Author: Copyright © 2008 Tor
Price Data Components
Orders Execution
Checks for the total of open ordersIt can change open orders parameters, due to possible stepping strategyIt automatically opens orders when conditions are reachedIt Closes Orders by itself
Indicators Used
MACD Histogram
0 Views
0 Downloads
0 Favorites
Mactor15
ÿþ//+------------------------------------------------------------------+

//|                           *  MacTor  *                           |

//|                           version  15                            |

//|            Copyright © 2008 Tor   izumov.juriy@gmail.com         |

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

#property copyright "Copyright © 2008 Tor"

#property link      "izumov.juriy@gmail.com"

#property strict

#property version   "15.00"



#include <stderror.mqh>

#include <stdlib.mqh>

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

//|                                                                  |

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

enum LanguageInt

  {

   RUS=1,    // Russian

   ENG=0     // English

  };

//--- input parameters

input LanguageInt Language=ENG;// Select Language



input datetime TimeStart=D'2008.09.30 12:58:18';// Trade start date

input datetime TimeEnd  =D'2035.09.30 12:58:29';// End date of trade

input int StopDeposit = 0;      // Stop deposit

input int holdHourStart = 0;    // Trade start hour

input int holdHourEnd = 0;      // End hour of trade



input double SpecProfit=2;       // Specific profitability, (USD / 0.01 lot)

input int MaxSpecProfit=10;      // Max orders with SpecProfit

input int TakeProfit = 700;

input int StepNxOrder=550;      // Step for next order

int    StopLoss   = 0;

int    OrderTotal = 4;          // The maximum number of pyramids for all currency pairs

int    ProfitUsr    = 500;      // Profit in pips with average positions

int    MaxUsr       = 40;       // Maximum number of averaged items

input double MaxLot   = 100;    // Max Lot

input bool   UseMM    = true;   // Use martingale?

input double    percLots = 1;   // Deposit percentage

bool   OnlyBuy  = false;

bool   OnlySell = false;

input int Magic=134554;

input int maxSpread=100;// Max Spread



input bool    OnOpenCandle=true;     // Deals on opening candles

input bool    CloseByCounter = false;    // Close counter transactions

input bool    CloseBySpecProfit = true;  // Close by specific profitability

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

//|                                                                  |

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

enum TypeTrend

  {

   AutoMACD=0,       // Auto MACD D1

   SellBuy = 1,      // Sell and Buy

   Sell = 2,         // Only Sell

   Buy  = 3,         // Only Buy

  };

//--- input parameters

input TypeTrend Trend= AutoMACD;         // Type graph

double MinusLot = 0.00;                  // So much reduce the lot



input int Slippage=20;                   // Slippage

input ENUM_TIMEFRAMES MACD_TF=PERIOD_D1; // Macd Trend TF 



color ColorBuy=Aqua;

color ColorSell=Gold;

bool OneWayTicket = true;          //true - calculate break-even level separately for buy and sell

                                   //false- to calculate the level of a loss without taking into account all open positions

double Profit=0.0;                 //The amount of funds in the deposit currency to be received after the closing of the positions



                                   // macd settings

int fastema = 12;                  //  fastema macd

int slowema = 26;                  //  slowema macd  

int sma = 9;                       //  sma macd



string           InpName="RectLabel";

color            InpBackColor=clrSkyBlue;

ENUM_BORDER_TYPE InpBorder=BORDER_FLAT;

ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER;

color            InpColor=clrDarkBlue;

ENUM_LINE_STYLE  InpStyle=STYLE_SOLID;

int              InpLineWidth=3;

bool             InpBack=false;

bool             InpSelection=false;

bool             InpHidden=true;

long             InpZOrder=0;



int shift,c,e,ticket,tiket;

double OBPrice,OSPrice,lotsib,lotsis,profb,profs,lasBuyLots,lasSellLots;

bool firstb=false,firsts=false,buy=false,sell=false;

datetime per;

string messs,val;

double firstOpBuyPrice=0; double firstOpSellPrice=0;

bool tradebuy=true; bool tradesell=true;

double buyProf,sellProf,buyLots,sellLots;

string Translate[2][100];

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

//|                                                                  |

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

int init()

  {

   string Sym=Symbol();



   Translate[0][0] = "Trading is prohibited - Check button Autotrading \n";

   Translate[1][0] = "">@3>2;O 0?@5I5=0 - ?@>25@LB5 =060B0 ;8 :=>?:0 2B>B>@3>2;O \n";

   Translate[0][1] = "Please select TF = 5 min";

   Translate[1][1] = ":;NG8B5 5 <8=CB=K9 3@0D8:";

   Translate[0][2] = "Trade disabled by Time \n";

   Translate[1][2] = "5 B>@3C5< ?> 2@5<5=8 \n";

   Translate[0][3] = "Do not trade in order to avoid high leverage \n";

   Translate[1][3] = "5 B>@3C5< 2> 871560=88 ?>2KH5==>3> :@548B=>3> ?;5G0 \n";

   Translate[0][4] = "Advisor stopped on end date:time in the settings \n";

   Translate[1][4] = "!>25B=8: >AB0=>2;5= ?> 2@5<5=8 2 =0AB@>9:0E \n";

   Translate[0][5] = "Expert Advisor will run for ";

   Translate[1][5] = "!>25B=8: 1C45B @01>B0BL 5I5 ";

   Translate[0][6] = " days \n";

   Translate[1][6] = " 4=59 \n";

   Translate[0][7] = "We do not trade at midnight \n";

   Translate[1][7] = "5 B>@3C5< 2 ?>;=>GL \n";

   Translate[0][8] = "Do not trade by Deposit > ";

   Translate[1][8] = "5 B>@3C5< ?> 5?>78BC > ";

   Translate[0][9] = " - increase the limit or transfer the funds \n";

   Translate[1][9] = " - C25;8GLB5 ;8<8B 8;8 A=8<8B5 A@54AB20 \n";

   Translate[0][10] = "Deposit to stop need of ";

   Translate[1][10] = "5?>78BC 4> >AB0=>2:8 =5 E20B05B 5I5 ";

   Translate[0][11] = "You can open (lots) ";

   Translate[1][11] = "<>6=> >B:@KBL (;>B>2) ";

   Translate[0][12] = "enabled";

   Translate[1][12] = "B>@3C5<";

   Translate[0][13] = "disabled";

   Translate[1][13] = " B>@3C5<";

   Translate[0][14] = " Spread ";

   Translate[1][14] = " !?@54 ";

   Translate[0][15] = "Spread exceeded the maximum settings\n";

   Translate[1][15] = "=5 B>@3C5< ?> A?@54C\n";

   Translate[0][16] = "open transactions ";

   Translate[1][16] = ">B:@KB> A45;>: ";

   Translate[0][17] = "pp to last ";

   Translate[1][17] = "?? 4> ?>A;54=53> ";

   Translate[0][18] = "Last Price ";

   Translate[1][18] = ">A;54=OO F5=0 ";

   Translate[0][19] = "Last lots";

   Translate[1][19] = ">A;54=89 ;>B";

   Translate[0][20] = " next order ";

   Translate[1][20] = "  15@Q< ";

   Translate[0][21] = "Last price";

   Translate[1][21] = ">A;54=OO F5=0";

   Translate[0][22] = "profit";

   Translate[1][22] = "?@>D8B";

   Translate[0][23] = "target ";

   Translate[1][23] = "F5;L ";

   Translate[0][24] = "Profit for close (pp) : ";

   Translate[1][24] = "@>D8B 4;O 70:@KB8O (??) : ";

   Translate[0][25] = "TakeProfit";

   Translate[1][25] = ""59:?@>D8B";

   Translate[0][26] = " Step to next order";

   Translate[1][26] = " (03 CA@54=5=8O";

   Translate[0][27] = "Profit (pp)";

   Translate[1][27] = ""5:CI89 ?@>D8B (??) 4;O";

   Translate[0][28] = "Summary Profit $";

   Translate[1][28] = ""5:CI89 ?@>D8B 2 45=L30E ";

   Translate[0][29] = "Account Equity";

   Translate[1][29] = "-:28B8";

   Translate[0][30] = "Day trend";

   Translate[1][30] = "=52=>9 B@5=4";

   Translate[0][31] = "short signal";

   Translate[1][31] = ":@0B:>A@>G=K9 A83=0;";

   Translate[0][32] = "waiting";

   Translate[1][32] = ">68405< A83=0;0";

   Translate[0][33] = "Breakeven";

   Translate[1][33] = "57C1KB>:";

   Translate[0][34] = "Attempt #";

   Translate[1][34] = ">?KB:0 !";

   Translate[0][35] = "Order open error";

   Translate[1][35] = "H81:0 >B:@KB8O";

   Translate[0][36] = "Order close error";

   Translate[1][36] = "H81:0 70:@KB8O";

   Translate[0][37] = "Modify error";

   Translate[1][37] = "H81:0 <>48D8:0F88";

   Translate[0][38] = "";

   Translate[1][38] = "";



   shift=StepNxOrder;



   long x_distance;

   long y_distance;

   if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))

     {

      Print("str 172 ChartGetInteger Error, code = ",GetLastError());

     }

   if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))

     {

      Print("str 177 ChartGetInteger Error, code = ",GetLastError());

     }

   int x=(int)x_distance/4;

   int y=(int)y_distance/4;

   x=0; y=20;

   int width=(int)x_distance/3;

   int height=(int)y_distance/1;

   RectLabelCreate(0,InpName,0,x,y,width,height,InpBackColor,InpBorder,InpCorner,

                   InpColor,InpStyle,InpLineWidth,InpBack,InpSelection,InpHidden,InpZOrder);

   ChartRedraw();

   Sleep(1000);

//---

   return(0);

  }

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

//|                                                                  |

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

int start()

  {

   buy=false; sell=false; firstb=false; firsts=false; static datetime nt=0; bool modifysell=false;  bool modifybuy=false;

   lasBuyLots=0; lasSellLots=0; buyProf=0; sellProf=0; int todate=0;

   messs="\n";

   OBPrice=0;

   OSPrice=0;

   val=Symbol();



   if(IsTradeAllowed()){ tradebuy=true; tradesell=true; }else{  tradebuy=false; tradesell=false; messs=messs+Translate[Language][0]; }



   if(holdHourStart!=holdHourEnd)

     {

      if(holdHourStart<holdHourEnd && (Hour()<holdHourStart || Hour()>holdHourEnd))

        {

         tradebuy=false; tradesell=false; messs=messs+Translate[Language][2];

        }

      if(holdHourStart>holdHourEnd && (Hour()<holdHourStart && Hour()>holdHourEnd))

        {

         tradebuy=false; tradesell=false; messs=messs+Translate[Language][2];

        }

     }

   if(Hour()>=22 && (DayOfWeek()>=5 || DayOfWeek()==0)){ tradebuy=false; tradesell=false; messs=messs+Translate[Language][3]; }



   if(TimeCurrent()<TimeStart || TimeCurrent()>TimeEnd)

     {

      tradebuy=false; tradesell=false;

      messs=messs+Translate[Language][4];

        }else{

      todate=(int)(TimeEnd-TimeCurrent())/(60*60*24);

      messs=messs+Translate[Language][5]+(string)todate+Translate[Language][6];

     }



   if((Hour()==0 && Minute()<=5) || (Hour()==23 && Minute()>=55)){  tradebuy=false; tradesell=false;  messs=messs+Translate[Language][7];  }



   if(StopDeposit>0)

     {

      if(AccountBalance()>StopDeposit)

        {

         tradebuy=false; tradesell=false;

         messs=messs+Translate[Language][8]+(string)StopDeposit+Translate[Language][9];

           }else{

         messs=messs+Translate[Language][10]+(string)(StopDeposit-AccountBalance())+" $ \n";

        }

     }



   messs=messs+Translate[Language][11]+(string)NormalizeDouble((AccountFreeMargin())/(MarketInfo(Symbol(),MODE_MARGINREQUIRED)),2)+"\n";



   if(maxSpread<=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD)){ tradebuy=false; tradesell=false; messs=messs+Translate[Language][15]; }



   if(tradebuy){ messs=messs+"Buy - "+Translate[Language][12]+"   "; }else{ messs=messs+"Buy - "+Translate[Language][13]+"    "; }

   if(tradesell){ messs=messs+"Sell - "+Translate[Language][12]+"    "; }else{ messs=messs+"Sell - "+Translate[Language][13]+"    "; }

   messs=messs+Translate[Language][14]+(string)MarketInfo(Symbol(),MODE_SPREAD)+"\n";



   if(BuyOrders()==0){ firstb=false; } if(SellOrders()==0){ firsts=false; }



   if(Trend==0)

     { // macd

      if(MACDTrend()==1 && MACDEnter()==1){ buy=true; }

      if(MACDTrend()==2 && MACDEnter()==2){ sell=true; }

     }

   if(Trend==1)

     { // buy and sell simultaneously

      if(MACDEnter()==1){ buy=true; }

      if(MACDEnter()==2){ sell=true; }

     }

   if(Trend==2)

     { // sell

      if(MACDEnter()==2){ sell=true; }

     }

   if(Trend==3)

     { // buy

      if(MACDEnter()==1){ buy=true; }

     }



   if(CloseByCounter && BuyOrders()>0 && sell){ CloseBuy(); }

   if(CloseByCounter && SellOrders()>0 && buy){ CloseSell(); }



   if(OnlyBuy) sell=false;

   if(OnlySell) buy=false;



   SymbolOrders();



   if(BuyOrders()==0){ firstOpBuyPrice=0; }

   if(SellOrders()==0){ firstOpSellPrice=0; }



   datetime lastBOrder= 0; datetime lastSOrder = 0;

   double allBuyprice = 0; double allSellprice = 0;



   double LatestVal[22]; ArrayInitialize(LatestVal,0);

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

     {

      if(OrderSelect(c,SELECT_BY_POS))

        {

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

           {

            if(OrderType()==OP_BUY)

              {

               if(OrderComment()=="first")

                 {

                  LatestVal[2]=1;

                  LatestVal[20]=NormalizeDouble(OrderOpenPrice(),_Digits);

                 }

               if(LatestVal[8]==0)

                 { // 

                  LatestVal[4] = NormalizeDouble(OrderOpenPrice(),_Digits);

                  LatestVal[6] = OrderLots();

                  LatestVal[8] = (double)OrderOpenTime();

                    }else{

                  if(LatestVal[8]<OrderOpenTime())

                    { // 

                     LatestVal[4] = NormalizeDouble(OrderOpenPrice(),_Digits);

                     LatestVal[6] = OrderLots();

                     LatestVal[8] = (double)OrderOpenTime();

                    }



                 }

               LatestVal[10] = LatestVal[10]+1;

               LatestVal[16] = LatestVal[16]+OrderLots();

               LatestVal[14] = NormalizeDouble((LatestVal[14]+OrderProfit()),2);

               if(OrderTakeProfit()<0.00000000000001){ LatestVal[18]=1; } //  

              }

            if(OrderType()==OP_SELL)

              {

               if(OrderComment()=="first")

                 {

                  LatestVal[1]=1;

                  LatestVal[19]=NormalizeDouble(OrderOpenPrice(),_Digits); // 

                 }

               if(LatestVal[7]==0)

                 { // 

                  LatestVal[3] = NormalizeDouble(OrderOpenPrice(),_Digits);

                  LatestVal[5] = OrderLots();

                  LatestVal[7] = (double)OrderOpenTime();

                    }else{

                  if(LatestVal[7]<OrderOpenTime())

                    {

                     LatestVal[3] = NormalizeDouble(OrderOpenPrice(),_Digits);

                     LatestVal[5] = OrderLots();

                     LatestVal[7] = (double)OrderOpenTime();

                    }

                 }

               LatestVal[9]=LatestVal[9]+1;

               LatestVal[15] = LatestVal[15]+OrderLots();

               LatestVal[13] = NormalizeDouble((LatestVal[13]+OrderProfit()),2);

               if(OrderTakeProfit()<0.00000000000001){ LatestVal[17]=1; } // 

              }

           }

        }

     }



   if(LatestVal[10]>1 && profb>ProfitUsr){ CloseBuy(); }

   if(LatestVal[9]>1 && profs>ProfitUsr){ CloseSell(); }



   if(LatestVal[10]>0 && LatestVal[2]==0){ CloseBuy(); }

   if(LatestVal[9]>0 && LatestVal[1]==0){ CloseSell(); }



   double buyCel=0;

   double sellSel=0;



   if(CloseBySpecProfit)

     {

      if(LatestVal[10]>MaxSpecProfit || LatestVal[9]>MaxSpecProfit)

        {

         buyCel=LatestVal[16]*100*0.3;

         sellSel=LatestVal[15]*100*0.3;

           }else{

         buyCel=LatestVal[16]*100*SpecProfit;

         sellSel=LatestVal[15]*100*SpecProfit;

        }

     }



   if(CloseBySpecProfit && LatestVal[10]>1 && LatestVal[14]>=buyCel){ CloseBuy(); }

   if(CloseBySpecProfit && LatestVal[9]>1 && LatestVal[13]>=sellSel){ CloseSell(); }



   if(LatestVal[10]<1)

     {

      lotsib=MM();

        }else{

      if(UseMM)

        {

         lotsib=LatestVal[6]*2;

           }else{

         lotsib=LatestVal[6];

        }

     }

   if(LatestVal[9]<1)

     {

      lotsis=MM();

        }else{

      if(UseMM)

        {

         lotsis=LatestVal[5]*2;

           }else{

         lotsis=LatestVal[5];

        }

     }



   int ppToBuy=(int)((LatestVal[4]-Bid)/_Point);

   if(LatestVal[4]==0){ ppToBuy=0; }

   int ppToSell=(int)((Ask-LatestVal[3])/_Point);

   if(LatestVal[3]==0){ ppToSell=0; }



   messs=messs+"\n"+Translate[Language][16]+"  buy = "+(string)LatestVal[10]+"    sell = "+(string)LatestVal[9];

   if(LatestVal[10]>0 || LatestVal[9]>0){ messs = messs + "\n"+Translate[Language][17]+"  Buy = "+(string)ppToBuy+"      Sell = "+(string)ppToSell; }

   if(LatestVal[10]>0 || LatestVal[9]>0){ messs = messs + "\n"+Translate[Language][18]+"Buy = "+(string)LatestVal[4]+"  " + "     Sell = " + (string)LatestVal[3] + "\n"; }

   messs = messs + "\n"+Translate[Language][19]+" Buy = "+(string)LatestVal[6]+Translate[Language][20]+(string)lotsib + " ;    Sell = " + (string)LatestVal[5] + Translate[Language][20]+(string)lotsis;

   messs = messs + "\n"+Translate[Language][21]+" Buy " + (string)LatestVal[4]+"   "+Translate[Language][22]+" Buy "+DoubleToString(LatestVal[14],2)+" $   ";

   if(LatestVal[10]>1 || LatestVal[9]>1){ messs=messs+Translate[Language][23]+(string)buyCel+" $"; }

   messs=messs+"\n"+Translate[Language][21]+" Sell "+(string)LatestVal[3]+"   "+Translate[Language][22]+" Sell "+DoubleToString(LatestVal[13],2)+" $   ";

   if(LatestVal[10]>1 || LatestVal[9]>1){ messs=messs+Translate[Language][23]+(string)sellSel+" $"; }

   messs=messs+"\n";

   if(!CloseBySpecProfit){ messs=messs+Translate[Language][24]+(string)ProfitUsr+"    "; }

   messs = messs + Translate[Language][25]+" = "+(string)TakeProfit+Translate[Language][26]+" = "+(string)StepNxOrder;

   messs = messs + "\n"+Translate[Language][27]+" Buy: "+DoubleToString(profb,0)+"   "+Translate[Language][27]+" Sell: "+DoubleToString(profs,0);

   messs = messs + "\n"+Translate[Language][28] + DoubleToString((LatestVal[14]+LatestVal[13]),2)+"  "+Translate[Language][29]+"  " + (string)AccountEquity();



   string Naprav = "", Naprav2 = Translate[Language][32];

   if(MACDTrend()==1){ Naprav = "Buy"; }

   if(MACDTrend()==2){ Naprav = "Sell"; }

   if(MACDEnter()==1){ Naprav2 = "Buy"; }

   if(MACDEnter()==2){ Naprav2 = "Sell"; }



   messs=messs+"\n"+Translate[Language][30]+" = "+Naprav+"    "+Translate[Language][31]+" = "+Naprav2+"\n\n";



   Comment(messs);



   if(OnOpenCandle){ if(Time[0]==nt){ return 0; } }

   nt=Time[0];



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

   double PB = ProfitPrice(Symbol(), OP_BUY,  Magic, Profit);

   double PS = ProfitPrice(Symbol(), OP_SELL, Magic, Profit);

   if(OneWayTicket)

     {

      SetPriceLine(PB,Translate[Language][33]+" Buy",ColorBuy);

      SetPriceLine(PS,Translate[Language][33]+" Sell",ColorSell);

        }else{

      ProfitPrice2(Symbol(),Magic,Profit);

     }

   double PB2=0;  double PS2=0;

   if((buyCel>0 || sellSel>0) && (LatestVal[10]>1 || LatestVal[9]>1))

     {

      PB2 = ProfitPrice(Symbol(), OP_BUY,  Magic, buyCel);

      PS2 = ProfitPrice(Symbol(), OP_SELL, Magic, sellSel);

      if(OneWayTicket)

        {

         SetPriceLine(PB2,Translate[Language][23]+" Buy",ColorBuy);

         SetPriceLine(PS2,Translate[Language][23]+" Sell",Tomato);

           }else{

         //ProfitPrice2(Symbol(), Magic, NeedMoney);

        }

     }

   if(!CloseBySpecProfit)

     {

      if(LatestVal[10]>0){ PB2= PB+(MathCeil(ProfitUsr/LatestVal[10]))*Point; } // 

      if(LatestVal[9]>0){ PS2 = PS -(MathCeil(ProfitUsr/LatestVal[9]))*Point; } // 

     }



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

   double tmpBP,tmpSP;

   if(BuyOrders()<2){ ObjectDelete(Translate[Language][25]+" Buy"); }

   if(SellOrders()<2){ ObjectDelete(Translate[Language][25]+" Sell"); }

   if(BuyOrders()>1)

     {

      tmpBP=(allBuyprice/BuyOrders())+ProfitUsr/BuyOrders()*Point();

      SetPriceLine(tmpBP,Translate[Language][25]+" Buy",DeepPink);

     }

   if(SellOrders()>1)

     {

      tmpSP=(allSellprice/SellOrders())-ProfitUsr/SellOrders()*Point();

      SetPriceLine(tmpSP,Translate[Language][25]+" Sell",DeepPink);

     }

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

//    fix tp

   if(IsTradeAllowed())

     {

      if(LatestVal[18]>0 || LatestVal[17]>0)

        {

         PB2 = NormalizeDouble(PB2, _Digits);

         PS2 = NormalizeDouble(PS2, _Digits);

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

           {

            if(OrderSelect(c,SELECT_BY_POS))

              {

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

                 {

                  if(LatestVal[18]>0 && OrderType()==OP_BUY)

                    {

                     if((OrderTakeProfit()<0.0000000001 || OrderTakeProfit()>PB2) && PB2>0)

                       {

                        for(c=0; c<=2; c++)

                          {

                           tiket=OrderModify(OrderTicket(),OrderOpenPrice(),0,PB2,0);

                           e=GetLastError();

                           if(!e==0)

                             {

                              Print(Translate[Language][37],c+1," str 425 - Modify Buy ",OrderTakeProfit(),"->",PB2," : ",e,"  ",ErrorDescription(e));

                                }else{ break;

                             }

                          }

                       }

                    }

                  if(LatestVal[17]>0 && OrderType()==OP_SELL)

                    {

                     if((OrderTakeProfit()<0.0000000001 || OrderTakeProfit()<PS2) && PS2>0)

                       {

                        for(c=0; c<=2; c++)

                          {

                           tiket=OrderModify(OrderTicket(),OrderOpenPrice(),0,PS2,0);

                           e=GetLastError();

                           if(!e==0)

                             {

                              Print(Translate[Language][37],c+1," str 38 - Modify Sell ",OrderTakeProfit(),"->",PS2,": ",e,"  ",ErrorDescription(e));

                                }else{ break;

                             }

                          }

                       }

                    }

                 }

              }

           }

        }

     }

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

   if(IsTradeAllowed())

     {

      if(LatestVal[2]==0 && tradebuy && buy && IsTradeAllowed() && AccountFreeMarginCheck(Symbol(),OP_BUY,lotsib)>0 && TotOrders()<OrderTotal && TimeCurrent()-per>=Period()*60)

        {

         for(c=0; c<=2; c++)

           {

            RefreshRates();

            double stb=0;

            if(StopLoss>0){ stb=Ask-StopLoss*Point; }

            ticket=OrderSend(Symbol(),OP_BUY,lotsib,Ask,Slippage,stb,Ask+TakeProfit*Point,"first",Magic,0,Blue);

            e=GetLastError();

            if(e==0)

              {

               per=TimeCurrent();

               break;

              }

            else Print(Translate[Language][34],c+1," str 423 - Buy "+Translate[Language][35]+": ",ErrorDescription(e));

           }

        }



      if(LatestVal[1]==0 && tradesell && sell && IsTradeAllowed() && AccountFreeMarginCheck(Symbol(),OP_BUY,lotsis)>0 && TotOrders()<OrderTotal && TimeCurrent()-per>=Period()*60)

        {

         for(c=0; c<=2; c++)

           {

            RefreshRates();

            double sts=0;

            if(StopLoss>0){ sts=Bid+StopLoss*Point; }

            ticket=OrderSend(Symbol(),OP_SELL,lotsis,Bid,Slippage,sts,Bid-TakeProfit*Point,"first",Magic,0,Red);

            e=GetLastError();

            if(e==0)

              {

               per=TimeCurrent();

               break;

              }

            else Print(Translate[Language][34],c+1," str 440 - Sell "+Translate[Language][35]+": ",ErrorDescription(e));

           }

        }

      //  do averaging     

      if(LatestVal[2]==1 && tradebuy && MACDEnter()==1 && ppToBuy>=StepNxOrder && IsTradeAllowed() && AccountFreeMarginCheck(Symbol(),OP_BUY,lotsib)>0 && LatestVal[10]<(MaxUsr+1))

        {

         for(c=0; c<=2; c++)

           {

            RefreshRates();

            ticket=OrderSend(Symbol(),OP_BUY,lotsib,Ask,Slippage,0,0,"next",Magic,0,Blue);

            e=GetLastError();

            if(e==0)

              {

               per=TimeCurrent();

               break;

              }

            else Print(Translate[Language][34],c+1," ",Ask," str 461 - Next Buy "+Translate[Language][35]+" : ",ErrorDescription(e));

           }

        }



      if(LatestVal[1]==1 && tradesell && MACDEnter()==2 && ppToSell>=StepNxOrder && IsTradeAllowed() && AccountFreeMarginCheck(Symbol(),OP_SELL,lotsis)>0 && LatestVal[9]<(MaxUsr+1))

        {

         for(c=0; c<=2; c++)

           {

            RefreshRates();

            ticket=OrderSend(Symbol(),OP_SELL,lotsis,Bid,Slippage,0,0,"next",Magic,0,Red);

            e=GetLastError();

            if(e==0)

              {

               per=TimeCurrent();

               break;

              }

            else Print(Translate[Language][34],c+1," ",Bid," str 461 - Next Sell "+Translate[Language][35]+" : ",ErrorDescription(e));

           }

        }

     }



   return(0);

  }

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



int MACDTrend()

  {

   int t=0;

   double macdm0,macds0;

   macdm0=iMACD(Symbol(),MACD_TF,fastema,slowema,sma,PRICE_CLOSE,MODE_MAIN,1);

   macds0=iMACD(Symbol(),MACD_TF,fastema,slowema,sma,PRICE_CLOSE,MODE_SIGNAL,1);



   if((macdm0>0 && macdm0>macds0) || (macdm0<0 && macdm0>macds0)) t=1;

   if((macdm0<0 && macdm0<macds0) || (macdm0>0 && macdm0<macds0)) t=2;



   return(t);

  }

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

//|                                                                  |

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

int MACDEnter()

  {

   int t=0;

   double macdm0,macds0,macdm1,macds1;

   macdm0=iMACD(Symbol(),0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);

   macds0=iMACD(Symbol(),0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);

   macdm1=iMACD(Symbol(),0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);

   macds1=iMACD(Symbol(),0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);



   double macdm2=iMACD(Symbol(),0,12,26,9,PRICE_CLOSE,MODE_MAIN,2);

   double macds2=iMACD(Symbol(),0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,2);



   if((macdm0<0 && macdm1<macds1 && macdm0>macds0) || 

      (macdm0>0 && macdm1<macds1 && macdm0>macds0)) t=1;



   if((macdm0>0 && macdm1>macds1 && macdm0<macds0) || 

      (macdm0<0 && macdm1>macds1 && macdm0<macds0)) t=2;



/*if(t==0 && ((macdm0<0 && macdm2<macds2 && macdm0>macds0) ||

      (macdm0>0 && macdm2<macds2 && macdm0>macds0))){  t=1;  }

      

  if(t==0 && ((macdm0>0 && macdm2>macds2 && macdm0<macds0) ||

      (macdm0<0 && macdm2>macds2 && macdm0<macds0))){  t=2;  }*/



   return(t);

  }

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

//|                                                                  |

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

int SymbolOrders()

  {

   int ci,t=0;

   profb=0; profs=0;

   buyProf = 0; sellProf = 0;

   buyLots = 0; sellLots = 0;

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

     {

      if(OrderSelect(ci,SELECT_BY_POS))

         if(OrderSymbol()==Symbol())

            if(OrderMagicNumber()==Magic)

              {

               t++;

               if(OrderType()==OP_BUY)

                 {

                  profb=profb+((Close[0]-OrderOpenPrice())/Point);

                  buyProf = buyProf + OrderProfit();

                  buyLots = buyLots + OrderLots();

                 }

               if(OrderType()==OP_SELL)

                 {

                  profs=profs+((OrderOpenPrice()-Close[0])/Point);

                  sellProf = sellProf + OrderProfit();

                  sellLots = sellLots + OrderLots();

                 }

              }

     }

   return(t);

  }

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

//|                                                                  |

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

int BuyOrders()

  {

   int co,t=0;

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

     {

      if(OrderSelect(co,SELECT_BY_POS))

         if(OrderSymbol()==Symbol())

            if(OrderMagicNumber()==Magic)

              {

               if(OrderType()==OP_BUY) t++;

              }

     }

   return(t);

  }

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

//|                                                                  |

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

int SellOrders()

  {

   int cp,t=0;

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

     {

      if(OrderSelect(cp,SELECT_BY_POS))

         if(OrderSymbol()==Symbol())

            if(OrderMagicNumber()==Magic)

              {

               if(OrderType()==OP_SELL) t++;

              }

     }

   return(t);

  }

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

//|                                                                  |

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

int TotOrders()

  {

   int cq,t=0;

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

     {

      if(OrderSelect(cq,SELECT_BY_POS))

         if(OrderMagicNumber()==Magic)

            if(OrderComment()=="first")

              {

               t++;

              }

     }

   return(t);

  }

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

//|                                                                  |

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

void CloseBuy()

  {

   int t=0;

   if(IsTradeAllowed())

     {

      while(BuyOrders()>0)

        {

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

           {

            if(OrderSelect(c,SELECT_BY_POS,MODE_TRADES))

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

                 {

                  if(OrderType()==OP_BUY)

                    {

                     for(t=0; t<=5; t++)

                       {

                        RefreshRates();

                        ticket=OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Red);

                        e=GetLastError();

                        if(e==0) break; else Print(Translate[Language][34],c+1," str 653 - Buy "+Translate[Language][36]+": ",ErrorDescription(e));

                       }

                    }

                 }

           }

        }

     }

   return;

  }

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

//|                                                                  |

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

void CloseSell()

  {

   int t=0;

   if(IsTradeAllowed())

     {

      while(SellOrders()>0)

        {

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

           {

            if(OrderSelect(c,SELECT_BY_POS,MODE_TRADES))

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

                 {

                  if(OrderType()==OP_SELL)

                    {

                     for(t=0; t<=5; t++)

                       {

                        RefreshRates();

                        ticket=OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);

                        e=GetLastError();

                        if(e==0) break; else Print(Translate[Language][34],c+1," str 653 - Sell "+Translate[Language][36]+": ",ErrorDescription(e));

                       }

                    }

                 }

           }

        }

     }

   return;

  }

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

//|                                                                  |

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

double MM()

  {

   double lts;

   double Lots=NormalizeDouble((AccountFreeMargin()*percLots/100)/(MarketInfo(Symbol(),MODE_MARGINREQUIRED)),2);

   lts=Lots-MinusLot;//

   if(lts>MaxLot) lts=MaxLot;

   if(lts>MarketInfo(_Symbol, MODE_MAXLOT)){ lts = MarketInfo(_Symbol, MODE_MAXLOT); }

   if(lts<MarketInfo(_Symbol, MODE_MINLOT)){ lts = MarketInfo(_Symbol, MODE_MINLOT); }



   return(lts);

  }

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

bool RectLabelCreate(const long            chart_ID=0,

                     const string           name="RectLabel",

                     const int              sub_window=0,

                     const int              x=400,

                     const int              y=400,

                     const int              width=50,

                     const int              height=18,

                     const color            back_clr=C'236,233,216',

                     const ENUM_BORDER_TYPE border=BORDER_SUNKEN,

                     const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER,

                     const color            clr=clrRed,

                     const ENUM_LINE_STYLE  style=STYLE_SOLID,

                     const int              line_width=1,

                     const bool             back=false,

                     const bool             selection=false,

                     const bool             hidden=true,

                     const long             z_order=0)

  {

   ResetLastError();

   if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE_LABEL,sub_window,0,0))

     {

      Print(__FUNCTION__,

            ": str719 OBJ_RECTANGLE error code = ",GetLastError());

      return(false);

     }

   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);

   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);

   ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);

   ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);

   ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);

   ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_TYPE,border);

   ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);

   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);

   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);

   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,line_width);

   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);

   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);

   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);

   return(true);

  }

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

double ProfitPrice(string fSymbol,int fType,int fMagic=0,double MyProfit=0.0)

  {

   double SummPrice=0.0,SummLots=0.0,Formula=0.0,SummLoss=0.0;

   int k=0;

   int total=OrdersTotal();

   for(int i=total-1; i>=0; i--)

     {

      int chk=OrderSelect(i,SELECT_BY_POS,MODE_TRADES);

      if(OrderSymbol()==fSymbol)

        {

         if(OrderMagicNumber()==fMagic || fMagic==0)

           {

            if(OrderType()==fType)

              {

               k++;

               SummLots=SummLots+OrderLots();

               SummPrice=SummPrice+OrderOpenPrice()*OrderLots();

               SummLoss=SummLoss+OrderCommission()+OrderSwap();

              }

           }

        }

     }



   if(k>0)

     {

      if(fType==OP_BUY)

        {

         Formula=SummPrice/SummLots+

                 (MyProfit-SummLoss)*MarketInfo(fSymbol,MODE_POINT)/

                 (MarketInfo(fSymbol,MODE_TICKVALUE)*SummLots);

           } else {

         Formula=SummPrice/SummLots -

                 (MyProfit-SummLoss)*MarketInfo(fSymbol,MODE_POINT)/

                 (MarketInfo(fSymbol,MODE_TICKVALUE)*SummLots);

        }

     }



   return(Formula);

  }

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

void ProfitPrice2(string fSymbol,int fMagic=0,double MyProfit=0.0)

  {

   double BuyLots=0.0,SellLots=0.0,BuyProfit=0.0,SellProfit=0.0,BuyPrice=0.0,SellPrice=0.0;

   int total=OrdersTotal();

   for(int i=total-1; i>=0; i--)

     {

      int chk2=OrderSelect(i,SELECT_BY_POS,MODE_TRADES);

      if(OrderSymbol()==fSymbol)

        {

         if(OrderMagicNumber()==fMagic || fMagic==0)

           {

            if(OrderType()==OP_BUY)

              {

               BuyLots=BuyLots+OrderLots();

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

                 }else if(OrderType()==OP_SELL){

               SellLots=SellLots+OrderLots();

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

              }

           }

        }

     }

   double TickValue=MarketInfo(fSymbol,MODE_TICKVALUE);

   if((BuyLots-SellLots)>0)

     {

      BuyPrice=Bid -((BuyProfit+SellProfit-MyProfit)/(TickValue *(BuyLots-SellLots))*Point);

     }

   if((SellLots-BuyLots)>0)

     {

      SellPrice=Ask+((BuyProfit+SellProfit-MyProfit)/(TickValue *(SellLots-BuyLots))*Point);

     }

   if((BuyLots-SellLots)==0.0)

     {

      if(BuyLots>0) BuyPrice=Bid -((BuyProfit+SellProfit-MyProfit)/(TickValue*BuyLots)*Point);

      if(SellLots>0) SellPrice=Ask+((SellProfit+BuyProfit-MyProfit)/(TickValue*SellLots)*Point);

     }

   SetPriceLine(BuyPrice,Translate[Language][33]+" Buy",ColorBuy);

   SetPriceLine(SellPrice,Translate[Language][33]+" Sell",ColorSell);

  }

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

void SetPriceLine(double Price=0.0,string NameLine="MyLine",color ColorLine=DarkOliveGreen)

  {

   int indWnd=0;

   if(ObjectFind(NameLine)==-1) ObjectCreate(NameLine,OBJ_HLINE,indWnd,0,Price);

   if(Price==0.0)

     {

      ObjectDelete(NameLine);

        }else{

      ObjectSet(NameLine,OBJPROP_PRICE1,Price);

      ObjectSet(NameLine,OBJPROP_COLOR,ColorLine);

     }

  }

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

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 ---