[ARCHIVE]Any rookie question, so as not to clutter up the forum. Professionals, don't pass it by. Can't go anywhere without you - 5. - page 132

 
Roman.:

IMHO, not complicated, but very easy to "direct" or send,

Well it's certainly easier to "send" i.e. "send" than to suggest. And in fact, I didn't ask anything so as to poke me in a textbook. Wrote a duplicate in one place, true, but the essence does not change.

artmedia70:

Finally, tell me exactly what you want to do... For example: MAK so-and-so is going up and it is above MAK so-and-so and the price is at some point below/above MAK so-and-so and if it is true, then place a pending order at some distance. I will give you a rough algorithm. Because of all these code fragments, torn out of context, it's difficult to direct you in the right direction. After all the task is for the fifth grade (exaggeratedly)



Here I am attaching a test version of the code and publishing it in my post too.

//+-----------------------------------------------------------------------------------+
//|                                                                       test_Ma.mq4 |
//|                                                                               hoz |
//|                                                                                   |
//+-----------------------------------------------------------------------------------+
#property copyright "hoz"
#property link      ""

extern string ___H0 = " ___________ Параметры МА ____________ ";
extern int i_TF = 0,
           i_fastMaPeriod = 10,
           i_slowMaPeriod = 21;
extern string ___H1 = " _____ Параметры ордера _______";
extern int i_magic = 3333021;
extern double i_thresholdFromMa = 5;                           // Отступ от МА
// Машечки
double fastMa,
       slowMa;
double pt;
// Переменные рыночного окружения
double g_spread,
       g_stopLevel,
       g_tickSize;
// Идентификаторы положений машек
#define MA_DIRECT_TO_UP      0                                 // Машки направлены вверх
#define MA_DIRECT_TO_DOWN    1                                 // Машки направлены вниз
#define MA_DIRECT_TO_NONE   -1                                 // Машки во флете
#define SIGNAL_BUY           0                                 // Сигнал на покупку
#define SIGNAL_SELL          1                                 // Сигнал на продажу
#define SIGNAL_NO           -1                                 // Сигнала нет

//+-------------------------------------------------------------------------------------+
//| Функция иницилизации                                                                |
//+-------------------------------------------------------------------------------------+
int init()
{
   GetMarketInfo();
   
   if (Digits  == 2 || Digits == 4)
       pt = Point;
   if (Digits == 1 || Digits == 3 || Digits == 5)
       pt = Point * 10;
   if (Digits == 6)
       pt = Point * 100;
   if (Digits == 7)
       pt = Point * 1000;
   

  return (0);
}
//+-------------------------------------------------------------------------------------+
//| Функция деиницилизации                                                              |
//+-------------------------------------------------------------------------------------+
int deinit()
{
//----
   
//----
  return (0);
}
//+-------------------------------------------------------------------------------------+
//| Сбор рыночных данных                                                                |
//+-------------------------------------------------------------------------------------+
void GetMarketInfo()
{
  g_spread = MarketInfo(Symbol(),MODE_SPREAD);
  g_stopLevel = MarketInfo(Symbol(),MODE_STOPLEVEL);
  g_tickSize = MarketInfo(Symbol(),MODE_TICKSIZE);
}
//+-------------------------------------------------------------------------------------+
//| Функция нормализации                                                                |
//+-------------------------------------------------------------------------------------+
double ND(double A)
{
  return (NormalizeDouble(A, Digits));
}
//+-------------------------------------------------------------------------------------+
//| Открытие длинной позиции                                                            |
//+-------------------------------------------------------------------------------------+
bool OpenBuy(double fastMa, double slowMa)
{
   int ticket = -1;
   
   if ((fastMa + i_thresholdFromMa * pt) > Ask)           // Проверка что цена открытия выше Ask, т.к. у нас вход отложенником

       ticket = OrderSend(Symbol(), OP_BUYSTOP, 0.1, ND(fastMa + i_thresholdFromMa * pt), 3, 0, 0, NULL, i_magic, 0);
   
   if (ticket > 0)
 
   return (true);
}
//+-------------------------------------------------------------------------------------+
//| Открытие короткой позиции                                                           |
//+-------------------------------------------------------------------------------------+
bool OpenSell(double fastMa, double slowMa)
{
   int ticket = -1;
   
   if ((fastMa - i_thresholdFromMa * pt) < Bid)           // Проверка что цена открытия ниже Bid, т.к. у нас вход отложенником
   
       ticket = OrderSend(Symbol(), OP_SELLSTOP, 0.1, ND(fastMa - i_thresholdFromMa * pt), 3, 0, 0, NULL, i_magic, 0);
       
   if (ticket > 0)
    
   return (true);
}
//+-------------------------------------------------------------------------------------+
//| Получаем относительное положение машек                                              |
//+-------------------------------------------------------------------------------------+
int GetStateMa(double fastMa, double slowMa)
{
   if (fastMa > slowMa)                          // Если условия выполнены, то..
       return (MA_DIRECT_TO_UP);                 // ..машки направлены вниз
   
   if (fastMa < slowMa)                          // Если условия выполнены, то..
       return (MA_DIRECT_TO_DOWN);               // машки направлены вверх
   
   return (MA_DIRECT_TO_NONE);                   // Машки не имеют выраженного направления
}
//+-------------------------------------------------------------------------------------+
//| Открытие позиций                                                                    |
//+-------------------------------------------------------------------------------------+
bool Trade(int signal)
{
   if (signal == SIGNAL_BUY)                     // Если сигнал на покупку..
       if (!OpenBuy(fastMa, slowMa))             // ..покупаем
          return(false);
   
   if (signal == SIGNAL_SELL)                   // Если сигнал на продажу..
       if (!OpenSell(fastMa, slowMa))           // ..продаём
          return(false);
       
   return (true);
}
//+-------------------------------------------------------------------------------------+
//| Получаем общий сигнал на открытие позиции                                           |
//+-------------------------------------------------------------------------------------+
int GetSignal()
{
   if (GetStateMa(fastMa, slowMa) == MA_DIRECT_TO_UP)       // Если машки указывают вверх..
       if ( MathAbs(Ask - fastMa) <= i_thresholdFromMa * pt ) // ..зазор между ценой покупки и машки, <= i_thresholdFromMa..
           return(SIGNAL_BUY);                       // ..функция возвращает сигнал покупки

   if (GetStateMa(fastMa, slowMa) == MA_DIRECT_TO_DOWN)      // Если машки указывают вниз..
       if ( MathAbs(Bid - fastMa) <= i_thresholdFromMa * pt ) // ..зазор между ценой продажи и машки, <= i_thresholdFromMa..
       return(SIGNAL_SELL);                          // ..функция возвращает сигнал продажи
   
   return (SIGNAL_NO);
}
//+-------------------------------------------------------------------------------------+
//| Функция start                                                                       |
//+-------------------------------------------------------------------------------------+
int start()
{
   fastMa = iMA(NULL,i_TF,i_fastMaPeriod,0,MODE_EMA,MODE_CLOSE,1);
   slowMa = iMA(NULL,i_TF,i_slowMaPeriod,0,MODE_EMA,MODE_CLOSE,1);

// Отслеживание открытия нового бара
   static datetime lastBarTime = 0;    // Время проведения последних рассчётов
   
   if (lastBarTime == iTime(NULL, 0, 0))         // На текущем баре все необходимые действия..
       return (0);                      // ..уже были выполнены

// Рассчёт сигнала   
   int signal = GetSignal();
   
// Проведение торговых операций
   if (signal != SIGNAL_NO)
       if (!Trade(signal))
           return (0);
   
   lastBarTime = iTime(NULL, 0, 0);              // На текущем баре все необходимые действия..
                                       // .. успешно выполнены
  return (0);
}

The conditions clearly say that the price of the order is above (below) the MA+(-) offset from the MA.

Here it is:

if ( MathAbs(Ask - fastMa) <= i_thresholdFromMa * pt )

The signal should only be calculated when the price is inthe "gap" area of the MA +(-) indent.

In a buy function, for example:

ticket = OrderSend(Symbol(), OP_BUYSTOP, 0.1, ND(fastMa + i_thresholdFromMa * pt), 3, 0, 0, NULL, i_magic, 0);

Buy must be abovefastMa byi_thresholdFromMa * pt.

In fact, it's not there. Either it's a fault in the language or it's a bug in the waving. How else can I explain what I need? I have given the whole code without additional conditions and functions (only one bare signal and opening).

It's already written clearly(for a tester, I didn't check it for real!)

Here's how it opens:

Wrong place to open...

artmedia70:


Regardingthe highlighted: work on open prices, then there will be no MAs redrawing on the zero bar

I deliberately made a condition on 1st bar, so there is no confusion. The main thing is how to run it...
Files:
test_ma.mq4  8 kb
 
The start flag of e.g. the fourth five minutes of each hour must be defined in the indicator.
if( Minute()==15)
Nothing is missing. Push it in the right direction.
 

I have a question - if I use a moving average with a shift to the right when I formulate my trading criteria - i.e. the shift value is positive.

Then when forming the signal I should not use the value of the moving average on the zero or the first bar, but on the bar with the index corresponding to the value of the shift.

 
Operr:
The start flag of e.g. the fourth five minutes of each hour must be defined in the indicator.


if( Minute()==15)// так будет работать в течении 1 минуты (от 15 до 16)
if( Minute()>=15)// так от 15 минут и до конца текущего часа
 
Tincup:

I have a question - if I use a moving average with a shift to the right when I formulate my trading criteria - i.e. the shift value is positive.

Then when forming the signal I should not use the value of the moving average on the zero or the first bar, but on the bar with the index corresponding to the value of the shift.


Put the moving average on the chart and see what index you need. You can see it visually.
 
hoz:

Well no doubt it's easier to "send" i.e. "send" than to suggest. In fact, I didn't ask anything to poke me in a textbook. I wrote a duplicate of it in one place, but the essence does not change.

Here I am attaching the test code variant and I am publishing it in my post too.

The conditions clearly say that the price of the order is above (below) the MA+(-) offset from the MA.

Here it is:

The signal should only be calculated when the price is inthe "gap" area of the MA +(-) indent.

In a buy function, for example:

Buy must be abovefastMa byi_thresholdFromMa * pt.

Actually it is not there. Either it's a bug in my language or it's a bug in my mouse. How else can I explain what I need? I gave a whole code without additional conditions and functions (only one bare signal and opening).

It's already written clearly(for a tester, I didn't check it for real!)

Here's how it opens:

I deliberately made a condition on 1st bar, so there is no confusion. The main thing is how to run it...
Once again, I ask: When exactly do you want to place the order? Not your code answer (do not want to understand it - there are enough of their own codes for analysis), and just words,

For example: I want to place a pending order above/below a MA at a distance of ... bah, bah, bah, bah, bah, bah ...

For the second time, please explain, is it so hard? We would have solved your problem long ago.

 
Also: if you have fastMA and slowMA defined as global, why pass them to a function? All functions can see them anyway, without passing their parameters to the called function.
 

Good afternoon.

Can you please advise how to deal with GAPs in EAs?

I often get GEPs during the weekend, and after they occur the work with the orders hangs, how to fix it, thanks beforehand!

 

Artyom, what do you think will work faster, expression with MathMax or with if?

double dist = MathMax(MathMax(NormalizeDouble(Dist*Point,Digits),spread),MathMax(StopLevel,FreezeLevel));//это?
// или это?
double dist = NormalizeDouble(Dist*Point,Digits);
if(dist < spread) dist = spread;
if(dist < StopLevel) dist = StopLevel;
if(dist < FreezeLevel) dist = FreezeLevel;


I didn't explain in words, because it's clear that this expression serves me to avoid errors 130, and it serves me perfectly!

Thanks in advance!

 
hoz:

Put the average on the chart and see what index you need. You can see it visually.

I did. I don't quite understand your answer, so I'll ask you again. Did I understand you correctly that when formulating the trading conditions

You should use the MA value for the corresponding number of bars backwards, but not the value marked with a yellow arrow in the picture.

I drew the figure as I understood your answer.