I will write an advisor free of charge - page 21

 
Vitalii Ananev:

Do you mean to open transactions at the opening of a D1 candle? If so, specify in the logic of the Expert Advisor the conditions to open transactions only at a given time.

I see. And one more question: I put two pending orders at +15 pips from the price, and a SellStop and a ByStop. And at every tick I move them to a new price. As soon as the price touches them during sharp price movements (most often during news events) the terminal hangs. (Why does it freeze?
 
MIR_KAZAN:
I see. And another question: I put two pending orders at +15 pips from price: buystop and sellstop. And at every tick I move them to a new price. As soon as the price touches them during sharp price movements (most often during news events) the terminal hangs. (Why does it freeze?

I can't say why it hangs up, I'm not a psychic, deal with the Expert Advisor's code. I can assume that after the order has been executed, your EA tries to move it to a new price, but because the pending order is already in the market, your EA hangs. Try to display in the log the state of key variables of the Expert Advisor for analyzing its operating logic.

 
Vitalii Ananev:

I can't say why it hangs up, I'm not a psychic, deal with the Expert Advisor's code. I can assume that after the order has been executed, your EA tries to move it to a new price, but because the pending order is already in the market, your EA hangs. Try to display in the log the state of key variables of the EA to analyze the logic of its work.

I think I have set all conditions correctly:

input int    Magic = 12;          // Магический номер ордеров
input int    Proskalzivanie = 5;  // Проскальзывание
input int    period = 200;        // Количество свечей для анализа волятильности
input int    tral = 20;           // Дистанция траллинга в пунктах
input int    tral_step = 3;       // Шаг срабатывания траллинга
input bool   use_step = true;     // Использовать шаг
input double Lot = 0.01;          // Лот
input double otstups = 0.0006;    // Отступ от цены
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  return;
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+

void Trailing_Stop(string _Simvol, int _Magic, double _Tral, double _Step, bool _Step_Use)
{
 int Dig=int(MarketInfo(_Simvol,MODE_DIGITS));
 for (int pos=OrdersTotal()-1; pos>=0; pos--)
 {
  if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==_Simvol &&
     OrderMagicNumber()==_Magic && OrderType()<2)
     {
      double SLPrice;
      if (OrderType()==OP_BUY)
      {
       if (_Step_Use)
       {
        RefreshRates();
        if(NormalizeDouble(Ask-OrderStopLoss(),Dig)>NormalizeDouble(_Tral+_Step,Dig))
        {
         SLPrice=NormalizeDouble(Ask-_Tral,Dig);
         if(!OrderModify(OrderTicket(),0,SLPrice,OrderTakeProfit(),OrderExpiration(),clrRed))
           Alert("Ошибка модификации ордера: ",GetLastError());
        }
       }
       else
       {
        RefreshRates();
        if(NormalizeDouble(Ask-OrderStopLoss(),Dig)>NormalizeDouble(_Tral,Dig))
         {
          SLPrice=NormalizeDouble(Bid+_Tral,Dig);
          if(!OrderModify(OrderTicket(),0,SLPrice,OrderTakeProfit(),OrderExpiration(),clrRed))
           Alert("Ошибка модификации ордера: ",GetLastError());
         }
       }
      }
    }
  }
}

void OnTick()
  {
//---
  double lot=Lot_Normalize(Symbol(),Lot,1);
  double sl= Dist_Normalize(Symbol(),tral);
  double step=Dist_Normalize(Symbol(),tral_step);
  double otstup=NormalizeDouble(otstups,Digits);
  int ord[8];
  Uchet_Orderov_Function(Symbol(),Magic,ord);
  if(ord[7]==2 && ord[6]==0 && Volume[0]==1)
   {
    Udalenie_Orderov_I_Sdelok(Symbol(),Magic, Proskalzivanie);
    if (OrderSend(Symbol(),OP_BUYSTOP,lot,Ask+otstup, Proskalzivanie,Ask+otstup-sl,0,NULL,Magic,0,clrBlue)==-1||
    OrderSend(Symbol(),OP_SELLSTOP,lot,Bid-otstup, Proskalzivanie,Bid-otstup+sl,0,NULL,Magic,0,clrRed)==-1)
    Print("Ошибка установки ордеров",GetLastError());
   }
  if (ord[6]==0 && ord[7]==0 && Volume[0]==1)
   {
    if (OrderSend(Symbol(),OP_BUYSTOP,lot,Ask+otstup, Proskalzivanie,Ask+otstup-sl,0,NULL,Magic,0,clrBlue)==-1||
    OrderSend(Symbol(),OP_SELLSTOP,lot,Bid-otstup, Proskalzivanie,Bid-otstup+sl,0,NULL,Magic,0,clrRed)==-1)
    Print("Ошибка установки ордеров",GetLastError());
   }
  if (ord[6]==1)
  {
   Trailing_Stop(Symbol(),Magic,sl,step,use_step);
   for(int i=OrdersTotal()-1; i>0; i++)
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderMagicNumber()==Magic && OrderSymbol()==Symbol() && OrderType()>1)
    if (!OrderDelete(OrderTicket(),clrNONE))
      Print("Ошибка удаления ордера!: ", GetLastError());
  }
}
//+------------------------------------------------------------------+
// Средняя волятильность свечей
//+------------------------------------------------------------------+
double Volatility(int _period)
{
 double summ=0;
 for (int i=1; i<=_period; i++)
  {
   summ+=MathAbs(High[i]-Low[i]);
  }
 return(NormalizeDouble(summ/_period,Digits));
}
//+------------------------------------------------------------------+
// Нормализация лота для любых брокеров
//+------------------------------------------------------------------+
double Lot_Normalize(string _Symvol, double _lot, double _mult)
{
 double minlot = MarketInfo(_Symvol,MODE_MINLOT);
 double maxlot = MarketInfo(_Symvol,MODE_MAXLOT);
 double steplot = MarketInfo(_Symvol,MODE_LOTSTEP);
 double lot=_lot*_mult;
 if (lot<=minlot)lot=minlot;
 else if(lot>=maxlot) lot=maxlot;
 else if (lot>minlot && lot<maxlot)
 {
  int k=int((lot-minlot)/steplot);
  lot=NormalizeDouble(minlot+k*steplot,2);
 }
 return(lot);
}

double Dist_Normalize(string _Simvol, int _Distancia)
{
 int Dig=int(MarketInfo(_Simvol,MODE_DIGITS));
 double Pip=MarketInfo(_Simvol,MODE_POINT);
 if(Dig==3 || Dig==5)
  return NormalizeDouble(_Distancia*5*Pip,Dig);
 else return NormalizeDouble(_Distancia*Pip,Dig);
}
//+------------------------------------------------------------------+
// Учет ордеров
//+------------------------------------------------------------------+
void Uchet_Orderov_Function(string _Simvol, int _Magic, int &_Mas[8])
{
 ArrayInitialize(_Mas,0);
 int Ticket=-1;
 for (int pos=OrdersTotal()-1; pos>=0; pos--)
 {
  if(OrderSelect(pos,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==_Simvol &&
    OrderMagicNumber()==_Magic && OrderTicket()!=Ticket)
    {
     Ticket=OrderTicket();
     switch(OrderType())
     {
      case 0:{_Mas[0]++;_Mas[6]++;break;}
      case 1:{_Mas[1]++;_Mas[6]++;break;}
      case 2:{_Mas[2]++;_Mas[7]++;break;}
      case 3:{_Mas[3]++;_Mas[7]++;break;}
      case 4:{_Mas[4]++;_Mas[7]++;break;}
      case 5:{_Mas[5]++;_Mas[7]++;break;}
     }
    }
  }
}

void Udalenie_Orderov_I_Sdelok(string _Simvol, int _Magic, int _Proskalzivanie)
{
 for(int pos=OrdersTotal()-1; pos>=0; pos--)
 {
  if(OrderSelect(pos,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==_Simvol && OrderMagicNumber()== _Magic)
  {
   if(OrderType()>1)
   {
    if (!OrderDelete(OrderTicket(),clrNONE))
     Alert("Ошибка при удалении отложенного ордера!" , GetLastError());
   }
  else
   {
    if (OrderType()==OP_BUY)
    {
     if(!OrderClose(OrderTicket(),OrderLots(),Bid,_Proskalzivanie,clrNONE))
       Alert("Ошибка закрытия ордера! ",GetLastError());
    }
    else
    {
     if(!OrderClose(OrderTicket(),OrderLots(),Ask,_Proskalzivanie,clrNONE))
       Alert("Ошибка закрытия ордера! ",GetLastError());
    }
   }
  }
}

}

 
khorosh:
You don't take into account that buy limit can only be set below the price and sell limit above the price. For what you suggest you need to use stop orders.

Agreed, Thanks for understanding my confusing algorithm. I'm still confused about the names of the pendants...

Let them be stop ones, maybe we should try to build an EA?

I'll test it later and show what happens ?

... Or give me a link to one, it's not like I've discovered America ?

 
MIR_KAZAN:

I think I have set all the test conditions correctly:

input int    Magic = 12;          // Магический номер ордеров
input int    Proskalzivanie = 5;  // Проскальзывание
input int    period = 200;        // Количество свечей для анализа волятильности
input int    tral = 20;           // Дистанция траллинга в пунктах
input int    tral_step = 3;       // Шаг срабатывания траллинга
input bool   use_step = true;     // Использовать шаг
input double Lot = 0.01;          // Лот
input double otstups = 0.0006;    // Отступ от цены
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  return;
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+

void Trailing_Stop(string _Simvol, int _Magic, double _Tral, double _Step, bool _Step_Use)
{
 int Dig=int(MarketInfo(_Simvol,MODE_DIGITS));
 for (int pos=OrdersTotal()-1; pos>=0; pos--)
 {
  if (OrderSelect(pos,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==_Simvol &&
     OrderMagicNumber()==_Magic && OrderType()<2)
     {
      double SLPrice;
      if (OrderType()==OP_BUY)
      {
       if (_Step_Use)
       {
        RefreshRates();
        if(NormalizeDouble(Ask-OrderStopLoss(),Dig)>NormalizeDouble(_Tral+_Step,Dig))
        {
         SLPrice=NormalizeDouble(Ask-_Tral,Dig);
         if(!OrderModify(OrderTicket(),0,SLPrice,OrderTakeProfit(),OrderExpiration(),clrRed))
           Alert("Ошибка модификации ордера: ",GetLastError());
        }
       }
       else
       {
        RefreshRates();
        if(NormalizeDouble(Ask-OrderStopLoss(),Dig)>NormalizeDouble(_Tral,Dig))
         {
          SLPrice=NormalizeDouble(Bid+_Tral,Dig);
          if(!OrderModify(OrderTicket(),0,SLPrice,OrderTakeProfit(),OrderExpiration(),clrRed))
           Alert("Ошибка модификации ордера: ",GetLastError());
         }
       }
      }
    }
  }
}

void OnTick()
  {
//---
  double lot=Lot_Normalize(Symbol(),Lot,1);
  double sl= Dist_Normalize(Symbol(),tral);
  double step=Dist_Normalize(Symbol(),tral_step);
  double otstup=NormalizeDouble(otstups,Digits);
  int ord[8];
  Uchet_Orderov_Function(Symbol(),Magic,ord);
  if(ord[7]==2 && ord[6]==0 && Volume[0]==1)
   {
    Udalenie_Orderov_I_Sdelok(Symbol(),Magic, Proskalzivanie);
    if (OrderSend(Symbol(),OP_BUYSTOP,lot,Ask+otstup, Proskalzivanie,Ask+otstup-sl,0,NULL,Magic,0,clrBlue)==-1||
    OrderSend(Symbol(),OP_SELLSTOP,lot,Bid-otstup, Proskalzivanie,Bid-otstup+sl,0,NULL,Magic,0,clrRed)==-1)
    Print("Ошибка установки ордеров",GetLastError());
   }
  if (ord[6]==0 && ord[7]==0 && Volume[0]==1)
   {
    if (OrderSend(Symbol(),OP_BUYSTOP,lot,Ask+otstup, Proskalzivanie,Ask+otstup-sl,0,NULL,Magic,0,clrBlue)==-1||
    OrderSend(Symbol(),OP_SELLSTOP,lot,Bid-otstup, Proskalzivanie,Bid-otstup+sl,0,NULL,Magic,0,clrRed)==-1)
    Print("Ошибка установки ордеров",GetLastError());
   }
  if (ord[6]==1)
  {
   Trailing_Stop(Symbol(),Magic,sl,step,use_step);
   for(int i=OrdersTotal()-1; i>0; i++)
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderMagicNumber()==Magic && OrderSymbol()==Symbol() && OrderType()>1)
    if (!OrderDelete(OrderTicket(),clrNONE))
      Print("Ошибка удаления ордера!: ", GetLastError());
  }
}
//+------------------------------------------------------------------+
// Средняя волятильность свечей
//+------------------------------------------------------------------+
double Volatility(int _period)
{
 double summ=0;
 for (int i=1; i<=_period; i++)
  {
   summ+=MathAbs(High[i]-Low[i]);
  }
 return(NormalizeDouble(summ/_period,Digits));
}
//+------------------------------------------------------------------+
// Нормализация лота для любых брокеров
//+------------------------------------------------------------------+
double Lot_Normalize(string _Symvol, double _lot, double _mult)
{
 double minlot = MarketInfo(_Symvol,MODE_MINLOT);
 double maxlot = MarketInfo(_Symvol,MODE_MAXLOT);
 double steplot = MarketInfo(_Symvol,MODE_LOTSTEP);
 double lot=_lot*_mult;
 if (lot<=minlot)lot=minlot;
 else if(lot>=maxlot) lot=maxlot;
 else if (lot>minlot && lot<maxlot)
 {
  int k=int((lot-minlot)/steplot);
  lot=NormalizeDouble(minlot+k*steplot,2);
 }
 return(lot);
}

double Dist_Normalize(string _Simvol, int _Distancia)
{
 int Dig=int(MarketInfo(_Simvol,MODE_DIGITS));
 double Pip=MarketInfo(_Simvol,MODE_POINT);
 if(Dig==3 || Dig==5)
  return NormalizeDouble(_Distancia*5*Pip,Dig);
 else return NormalizeDouble(_Distancia*Pip,Dig);
}
//+------------------------------------------------------------------+
// Учет ордеров
//+------------------------------------------------------------------+
void Uchet_Orderov_Function(string _Simvol, int _Magic, int &_Mas[8])
{
 ArrayInitialize(_Mas,0);
 int Ticket=-1;
 for (int pos=OrdersTotal()-1; pos>=0; pos--)
 {
  if(OrderSelect(pos,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==_Simvol &&
    OrderMagicNumber()==_Magic && OrderTicket()!=Ticket)
    {
     Ticket=OrderTicket();
     switch(OrderType())
     {
      case 0:{_Mas[0]++;_Mas[6]++;break;}
      case 1:{_Mas[1]++;_Mas[6]++;break;}
      case 2:{_Mas[2]++;_Mas[7]++;break;}
      case 3:{_Mas[3]++;_Mas[7]++;break;}
      case 4:{_Mas[4]++;_Mas[7]++;break;}
      case 5:{_Mas[5]++;_Mas[7]++;break;}
     }
    }
  }
}

void Udalenie_Orderov_I_Sdelok(string _Simvol, int _Magic, int _Proskalzivanie)
{
 for(int pos=OrdersTotal()-1; pos>=0; pos--)
 {
  if(OrderSelect(pos,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==_Simvol && OrderMagicNumber()== _Magic)
  {
   if(OrderType()>1)
   {
    if (!OrderDelete(OrderTicket(),clrNONE))
     Alert("Ошибка при удалении отложенного ордера!" , GetLastError());
   }
  else
   {
    if (OrderType()==OP_BUY)
    {
     if(!OrderClose(OrderTicket(),OrderLots(),Bid,_Proskalzivanie,clrNONE))
       Alert("Ошибка закрытия ордера! ",GetLastError());
    }
    else
    {
     if(!OrderClose(OrderTicket(),OrderLots(),Ask,_Proskalzivanie,clrNONE))
       Alert("Ошибка закрытия ордера! ",GetLastError());
    }
   }
  }
}

}

I'm afraid I can't help you, because your code is not analyzable. Maybe you may add some comments to improve your understanding of it. It is not clear what the ord[] array is used for and what data it stores. I understood your code this way: every tick you write the order type in the array (Uchet_Orderov_Function(Symbol(),Magic,ord);) then check the condition if(ord[7]==2 && ord[6]==0 && Volume[0]==1) and if it is true, the pending orders will be deleted and all positions will be closed. Then we check the condition if (ord[6]==0 && ord[7]==0 && Volume[0]==1) and if it is true, two pending orders are opened. But the value of ord[] array will not be updated before checking the condition if (ord[6]==0 && ord[7]==0 && Volume[0]==1). And it will be updated only on the second tick.

So you need to log all values of ord[] array that affect its logic.

Note also this code fragment:

 if (ord[6]==1)
  {
   Trailing_Stop(Symbol(),Magic,sl,step,use_step);
   for(int i=OrdersTotal()-1; i>0; i++)
    if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderMagicNumber()==Magic && OrderSymbol()==Symbol() && OrderType()>1)
    if (!OrderDelete(OrderTicket(),clrNONE))
      Print("Ошибка удаления ордера!: ", GetLastError());
  } 

I think there are software parentheses missing { . It should be like this:

 if (ord[6]==1)
  {
   Trailing_Stop(Symbol(),Magic,sl,step,use_step);
   for(int i=OrdersTotal()-1; i>0; i++)
   {
     if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderMagicNumber()==Magic && OrderSymbol()==Symbol() && OrderType()>1)
       if (!OrderDelete(OrderTicket(),clrNONE))
          Print("Ошибка удаления ордера!: ", GetLastError());
   }
  } 
 
Vitalii Ananev:


Also note this piece of code:

I think it's missing brackets { . It's supposed to be like this:

In this case, the brackets do not affect the operation (logic). There is no error

 
Victor Nikolaev:

In this case, the brackets have no effect on the operation (logic). There is no error.

Maybe not, but it's easier to read.
 
akarustam:

Agreed, Thanks for understanding my confusing algorithm. I'm still confused about the names of the pendants...

Let them be stop ones, maybe we should try to build an EA?

I'll test it later and show what happens ?

... Or give me a link to one, it's not like I've discovered America ?

To suggest something, you should have at least basic knowledge. All simple ideas have long been tested and you really have not discovered America. But look for you to link through forums and kodobase unlikely who will. You need it, you look for it. Or do you think there are people who keep in their minds links to all kinds of Expert Advisors, scripts and indicators?
 
khorosh:
You have to have at least basic knowledge to suggest something. All the simple ideas have been tried for a long time and indeed you have not discovered America. But no one is likely to look for a link for you on forums and kodobase. You need it, you look for it. Or do you think there are people who keep in their minds links to all sorts of Expert Advisors, scripts and indicators?
...assumed.
 

(I have an idea, I need help)) Write an Expert Advisor for this

I am using it for trading for a long time. I get 1000 pips monthly on one currency pair. Ihave never been used to such kind of trading. There is practically no drawdown, maximum 5 pips.

Timeframe H4

1. MA4/simple\close

2. MA5/simple/open

The working principle should be like this
Without Take Profit and Stop Loss. Open and close trades only on crossovers. For example, cross from the bottom to the top, open an order up, close the order only when it is crossed back. If there is a reverse signal to close the buy order open the sell order. Generally, I hope you understand) in the strategy it is not even the profit that matters, but these fucking crossovers) Something like this) Trade on this strategy for a long time, the profit is good, but since I think to write this strategy expert advisor will not be difficult.

If you agree to help here is my MAIL: 4iterRrock@mail.ru

Below is my pattern that I have been trading for almost a year.

Files:
MAxi2r.tpl  2 kb
Reason: