grid MA ATR

Author: Copyright 2022, cmillion@narod.ru
Price Data Components
Series array that contains open time of each barSeries array that contains the highest prices of each barSeries array that contains the lowest prices of each bar
Orders Execution
Checks for the total of open ordersIt can change open orders parameters, due to possible stepping strategyChecks for the total of closed ordersIt automatically opens orders when conditions are reachedIt Closes Orders by itself
Indicators Used
Moving average indicator
0 Views
0 Downloads
0 Favorites
grid MA ATR
ÿþ//+------------------------------------------------------------------+

//|                                               grid_6_symbols.mq4 |

//|                                                                  |

//|                                                                  |

//+------------------------------------------------------------------+

#property copyright "Copyright 2022, cmillion@narod.ru"

#property link      "http://www.cmillion.ru"

#property strict

#property description "!>25B=8: 2KAB02;O5B A5B8 87 AB>? >@45@>2 2 =0?@02;5=88 . KH5 0 BuyStop =865  SellStop"

#property description "0: B>;L:> AC<<0@=K9 ?@>D8B ?> 2A5< ?>78F8O< ?@52KA8B C:070==K9 C@>25=L, A>25B=8: 70:@K205B 2A5 8 ?> =>2>9 ?5@5>B:@K205B A5B8"

#property description " ?@>F5AA5 B>@3>2;8 A>25B=8: ?5@52>48B 2 157C1KB>: ?@81K;L=K5 ?>78F88"

/*5A?;0B=K9 A>25B=8:



!>25B=8: B>@3C5B ?> AB@0B5388 A5B:0 ?> B@5=4C. KAB02;O5B A5B8 87 AB>? >@45@>2 2 =0?@02;5=88 . KH5  A5BL BuyStop =865  A5BL SellStop >@45@>2. 0:@KB85 ?>78F89 ?@>8AE>48B ?> AC<<0@=><C ?@>D8BC. 0: B>;L:> >1I89 ?@>D8B 2A5E ?>78F89 ?@52KA8B C:070==K9 C@>25=L 2 ?@>F5=B0E ATR, A>25B=8: 70:@K205B 2A5 A45;:8 8 ?> =>2>9 ?5@5>B:@K205B A5BL.  ?@>F5AA5 B>@3>2;8 A>25B=8: ?5@52>48B 2 157C1KB>: ?@81K;L=K5 ?>78F88 8 70 AG5B MB>3> B0: 65 =0:0?;8205BAO >?5@0B82=0O ?@81K;L 8 A=8605BAO =03@C7:0 =0 45?>78B.<br>A5 ?0@0<5B@K =0AB@0820NBAO 2 ?@>F5=B0E ATR B0:8< >1@07>< A>25B=8: <>65B B>@3>20BL A >4=8<8 8 B5<8 65 =0AB@>9:0<8 =0 @07;8G=KE 1@>:5@0E 8 @07=KE 8=AB@C<5=B0E.



0@0<5B@K:

Step % ATR - (03 A5B8 70405BAO 2 % >B A@54=54=52=>3> 42865=8O F5=K (2>;>B8;L=>AB8)

Orders - G8A;> >@45@>2 A5B8 :>B>@>5 ?>AB>O==> ?>445@68205BAO A>25B=8:><. 1I55 G8A;> >B:@KBKE ?>78F89 =5 >3@0=8G5=>.

NoLoss % ATR (0-off) - 5@52>4 @K=>G=>9 ?>78F88 2 157C1KB>: ?@8 4>AB865=88 59 ?@>D8B0 2 % ATR

Min profit % ATR - 8=8<0;L=K9 ?@>D8B ?@8 ?5@52>45 2 157C1KB>:. ".5. MB>B ?@>D8B <K ?>;CG05< ?@8 70:@KB88 ?>78F88 ?> 157C1KB:C. B0: 65 70405BAO 2 % >B 42865=8O F5=K 70 14 4=59.

Lot - >1J5< >B:@K205<KE ?>78F89 A5B8

Profit Close % ATR - !C<<0@=K9 ?@>D8B ?@8 :>B>@>< 70:@K205< 2A5 A45;:8.  0AG5B 53> 2545;AO 02B><0B8G5A:8 =0 >A=>20=88 AB>8<>AB8 B8:0 20;NBK 8 A@54=54=52=>3> 42865=8O F5=K 2 %

Magic - C=8:0;L=K9 =><5@ >@45@>2 A>25B=8:0

sleep- 045@6:0 ?>A;5 70:@KB8O 2 A5:C=40E. !>25B=8: >68405B 7040==>5 2@5<O ?>A;5 B>3> :0: 70:@>5B 2A5 A45;:8 4> >B:@KB8O =>2>9 A5B8.

period_Moving_Average 5@8>4 8=48:0B>@0  >B=>A8B5;L=> :>B>@>3> 2KAB@08205< A5B8.

//---*/

extern      int    StepATR                = 10; //Step % ATR

extern      int    Orders                 = 5;  //Orders

extern      int    NoLossATR              = 20; //NoLoss % ATR (0-off)

extern      int    MinProfitNoLossATR     = 1;  //Min profit  % ATR

extern      double Lot                    = 0.01;

extern      double ProfitCloseATR         = 5.0;//Profit Close % ATR

extern      int    Magic                  = 123;

extern      int    sleep                  = 0;  //045@6:0 ?>A;5 70:@KB8O 2 A5:C=40E

extern int     period_Moving_Average      = 100;

 ENUM_MA_METHOD ma_method_MA         = MODE_LWMA;

 ENUM_APPLIED_PRICE applied_price_MA = PRICE_OPEN;

 ENUM_TIMEFRAMES timeframe_MA        = 0;

//-------------------------------

string val;

double MaxSellPrice,MinBuyPrice;

double ordersB[500],ordersS[500];

datetime TimeATR=0;

int ATR=0,Step=0,NoLoss=0,MinProfitNoLoss=0;

double ProfitClose=0;

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

int OnInit()

  {

   val=" "+AccountCurrency();

   MaxSellPrice=0;MinBuyPrice=0;

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

   Comment("");

  }

//+------------------------------------------------------------------+

void OnTick()

  {

   if (TimeATR!=iTime(NULL,PERIOD_D1,0) || ATR==0)

   {

      ATR=(int)ATR(14);

      Step = ATR/100*StepATR;

      NoLoss = ATR/100*NoLossATR;

      MinProfitNoLoss = ATR/100*MinProfitNoLossATR;

      ProfitClose=Lot*SymbolInfoDouble(NULL,SYMBOL_TRADE_TICK_VALUE)*(ATR/100*ProfitCloseATR);

      TimeATR=iTime(NULL,PERIOD_D1,0);

   }

   if (!IsDemo()) return;

   int OT,i,orders=0;

   double OSL,SL,StLo,OOP,profit=0;

   double ProfitB=0,ProfitS=0,STOPLEVEL=MarketInfo(Symbol(),MODE_STOPLEVEL);

   double MaxPrice=0,MinPrice=0;

   int bs=0,ss=0;

   int b=0,s=0;

   ArrayInitialize(ordersB,0);

   ArrayInitialize(ordersS,0);

   for(i=0; i<OrdersTotal(); i++)

     {

      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))

        {

         if(OrderMagicNumber()==Magic && Symbol()==OrderSymbol())

           {

            OT=OrderType();

            

            profit+=OrderProfit()+OrderSwap()+OrderCommission();

            orders++;

            OOP = NormalizeDouble(OrderOpenPrice(),Digits);

            OSL = NormalizeDouble(OrderStopLoss(),Digits);

            SL=OSL;

            if(OT==OP_BUYSTOP)

              {

               if(MaxPrice<OOP) MaxPrice=OOP;

               bs++;

               ordersB[b]=OOP;b++;

              }

            if(OT==OP_SELLSTOP)

              {

               if(MinPrice>OOP || MinPrice==0) MinPrice=OOP;

               ss++;

               ordersS[s]=OOP;s++;

              }

            if (OT==OP_BUY)             

            {  

               ProfitB+=OrderProfit()+OrderSwap()+OrderCommission();

               ordersB[b]=OOP;b++;

               if (OSL<OOP && NoLoss!=0 && NoLoss>=STOPLEVEL)

               {

                  StLo = NormalizeDouble(OOP+MinProfitNoLoss*Point,Digits); 

                  if (StLo > OSL && OOP <= NormalizeDouble(Bid - NoLoss * Point,Digits)) SL = StLo;

               }

               if (SL != OSL)

               {  

                  if (!OrderModify(OrderTicket(),OOP,SL,0,0,clrNONE)) Print("Error OrderModify <<",(GetLastError()),">> ");

               }

            }                                         

            if (OT==OP_SELL)        

            {

               ProfitS+=OrderProfit()+OrderSwap()+OrderCommission();

               ordersS[s]=OOP;s++;

               if ((OSL>OOP || OSL==0) && NoLoss!=0 && NoLoss>=STOPLEVEL)

               {

                  StLo = NormalizeDouble(OOP-MinProfitNoLoss*Point,Digits); 

                  if ((StLo < OSL || OSL==0) && OOP >= NormalizeDouble(Ask + NoLoss * Point,Digits)) SL = StLo;

               }

               if (SL != OSL)

               {  

                  if (!OrderModify(OrderTicket(),OOP,SL,0,0,clrNONE)) Print("Error OrderModify <<",(GetLastError()),">> ");

               }

            } 

           }

        }

     }

   if(sleep>0 && orders==0)

     {

      for(i=OrdersHistoryTotal()-1; i>=0; i--)

        {

         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))

           {

            if(OrderMagicNumber()==Magic && Symbol()==OrderSymbol())

              {

               if(TimeCurrent()-OrderCloseTime()<sleep) return;

               break;

              }

           }

        }

     }

     

   double price,maprice;

   

   maprice = iMA( Symbol(), timeframe_MA, period_Moving_Average, 0, ma_method_MA, applied_price_MA, 1);

   

   if (s==0) MaxSellPrice=0;

   if (b==0) MinBuyPrice =0;

   int nn=0,n=0;

   

   if (Ask > maprice)

   {

      n=0;nn=0;

      while (true)

      {

         if(MaxPrice==0) {price=NormalizeDouble(Ask+Step*Point,Digits);MinBuyPrice=price;MaxPrice=price;}

         else price=NormalizeDouble(MinBuyPrice+Step*n*Point,Digits);

         if (price>Ask) nn++;

         if (nn>=Orders) break;

         n++;

         if (NoOrder(OP_BUY,price,b))

         {

            if (price>Ask+STOPLEVEL*Point)

            {

               if(OrderSend(_Symbol,OP_BUYSTOP,Lot,price,30,0,0,"GRID ",Magic,0,clrBlue)==-1)

                  Comment("OrderSend ",_Symbol," Error ",GetLastError());

            }

         }

      }

   }

           

     

   //---

   

   if (Bid < maprice)

   {

      n=0;nn=0;

      while (true)

      {

         if(MinPrice==0) {price=NormalizeDouble(Bid-Step*Point,Digits);MaxSellPrice=price;MinPrice=price;}

         else price=NormalizeDouble(MaxSellPrice-Step*n*Point,Digits);

         if (price<Bid) nn++;

         if (nn>=Orders) break;

         n++;

         //if (price>MinPrice) break;

         if (NoOrder(OP_SELL,price,s))

         {

            if (price<Bid-STOPLEVEL*Point)

            {

               if(OrderSend(_Symbol,OP_SELLSTOP,Lot,price,30,0,0,"GRID ",Magic,0,clrRed)==-1)

                  Comment("OrderSend ",_Symbol," Error ",GetLastError());

            }

         }

      }

   }

//---

  

   if (profit > ProfitClose) 

   {

      double AB=AccountBalance();

      Print("--------------- 0:@K205< ?> B@0;C ?@>D8B0 ---------------    ",DoubleToString(profit,2),val);

      DeleteAllOrders();

      Print("--------------- @81K;L ?>;CG5==0O ?@8 70:@KB88 ---------------     ",DoubleToString(AccountBalance()-AB,2),val);

   }





   DrawLABEL("Balance",StringConcatenate("Balance ",DoubleToStr(AccountBalance(),2),val),5,35,clrGray);

   DrawLABEL("Equity",StringConcatenate("Equity ",DoubleToStr(AccountEquity(),2),val),5,55,clrGray);

   DrawLABEL("FreeMargin",StringConcatenate("FreeMargin ",DoubleToStr(AccountFreeMargin(),2),val),5,75,clrGray);

   DrawLABEL("Profit B",StringConcatenate("Profit ",b," Buy ",DoubleToStr(ProfitB,2),val),5,100,Color(ProfitB<0,clrRed,clrLimeGreen));

   DrawLABEL("Profit S",StringConcatenate("Profit ",s," Sell ",DoubleToStr(ProfitS,2),val),5,120,Color(ProfitS<0,clrRed,clrLimeGreen));

   DrawLABEL("Profit ",StringConcatenate("Profit ",DoubleToStr(profit,2),val," (close ",DoubleToStr(ProfitClose,2),")"),5,140,Color(profit<0,clrRed,clrLimeGreen));

}

//-------------------------------

color Color(bool P,color a,color b)

  {

   if(P) return(a);

   else return(b);

  }

//------------------------------------------------------------------

void DrawLABEL(string name,string Name,int x,int y,color clr)

  {

   if(ObjectFind(name)==-1)

     {

      ObjectCreate(name,OBJ_LABEL,0,0,0);

      ObjectSet(name,OBJPROP_CORNER,1);

      ObjectSet(name,OBJPROP_XDISTANCE,x);

      ObjectSet(name,OBJPROP_YDISTANCE,y);

     }

   ObjectSetText(name,Name,12,"Arial",clr);

  }

//--------------------------------------------------------------------

void DeleteAllOrders()

  {

   bool error=true;

   int i,nn=0;

   while(true)

     {

      for(i=OrdersTotal()-1; i>=0; i--)

        {

         if(OrderSelect(i,SELECT_BY_POS))

           {

            if(OrderMagicNumber()==Magic && Symbol()==OrderSymbol())

              {

                  int OT=OrderType();

                  int Ticket=OrderTicket();

                  if(OT==OP_BUY)

                    {

                     error=OrderClose(Ticket,OrderLots(),NormalizeDouble(Bid,Digits),50,clrBlue);

                    }

                  if(OT==OP_SELL)

                    {

                     error=OrderClose(Ticket,OrderLots(),NormalizeDouble(Ask,Digits),50,clrRed);

                    }

                  if(OT>1)

                     if(!OrderDelete(Ticket))

                        Comment("@45@ ",Ticket," >H81:0 C40;5=8O ",GetLastError());

                  //---

                  if(!error)

                    {

                     int err=GetLastError();

                     if(err<2) continue;

                     if(err==129)

                       {

                        Comment("5?@028;L=0O F5=0 ",TimeToStr(TimeCurrent(),TIME_SECONDS));

                        Sleep(500);

                        RefreshRates();

                        continue;

                       }

                     if(err==146)

                       {

                        if(IsTradeContextBusy()) Sleep(500);

                        RefreshRates();

                        continue;

                       }

                    }

              }

           }

        }

      int k=0;

      for(int j= 0; j<OrdersTotal(); j++)

        {

         if(OrderSelect(j,SELECT_BY_POS))

           {

            if(OrderMagicNumber()==Magic && Symbol()==OrderSymbol())

              {

               k++;

              }

           }

        }

      if(k==0) break;

      nn++;

      if(nn>10) break;

      Sleep(500);

      RefreshRates();

     }

  }

//-------------------------------

bool NoOrder(int type,double price,int n)

{

   for(int i=0; i<n; i++)

   {

      if (type==OP_SELL && MathAbs(ordersS[i]-price)/Point<5) return(false);

      if (type==OP_BUY && MathAbs(ordersB[i]-price)/Point<5) return(false);

   }

   return(true);

}

//+------------------------------------------------------------------+

double ATR(int period)

{

   double atr=0;

   for (int i = 1; i<=period; i++)

   {

      atr+=iHigh(NULL,PERIOD_D1,i)-iLow(NULL,PERIOD_D1,i);

   }

   atr=atr/SymbolInfoDouble(NULL,SYMBOL_POINT)/period;

   return(atr);

}

//------------------------------------------------------------------

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---