Author: Ivan Katsko
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 reachedChecks for the total of closed ordersIt Closes Orders by itself
Miscellaneous
It issuies visual alerts to the screenIt plays sound alerts
0 Views
0 Downloads
0 Favorites
iK_candle
//+------------------------------------------------------------------+
//|                                                                  |
//|       Ñîâåòíèê íà ðàçâîðîò ïî                                    |
//|       êîìáèíàöèè ñâå÷åé                                          |
//|                             http://www.mql4.com/ru/users/ikatsko |
//+------------------------------------------------------------------+
#property copyright "Ivan Katsko"
#property link      "ICQ:372739628"
#include <stdlib.mqh>
//----
//+---------------------------------------------------+
//|Money Management                                   |
//+---------------------------------------------------+
extern double Lots              = 0;    // 0 - âêëþ÷àåò MoneyManagement 
extern string MM                = "Åñëè Lots=0, òî";
extern double ProfitPercent     = 10;   // Profit â %% ê ñâîáîäíûì ñðåäñòâàì ñ ó÷åòîì TakeProfit
extern double LossPercent       = 20;   // Loss â %%  ê ñâîáîäíûì ñðåäñòâàì ñ ó÷åòîì StopLoss
extern double MaxRisk           = 50;   // Ìàêñèìàëüíûé Loss â %%  ê ñâîáîäíûì ñðåäñòâàì ñ ó÷åòîì StopLoss
extern string BL                = "Îòêðûòü åù¸ îäèí îðäåð íà óðîâíå (â %) îò SL";
extern double BackLevel         = 80;   // Óðîâåíü StopLoss â %% ïóíêòàì StopLoss íèæå êîòîðîãî íàäî îòêðûâàòü âòîðîé îðäåð
extern double TrendBars         = 3;    // Áàðîâ â òðåíäå ïåðåä ðàçâîðîòîì
extern int    TakeProfit        = 130;  // Maximum profit level achieved.
extern string PL                = "Âçÿòü Profit íå íèæå (â %) îò TP";
extern double ProfitLimit       = 5;    // Óðîâåíü TakeProfit â %% ïóíêòàì TakeProfit âûøå êîòîðîãî íàäî çàêðûâàòü ïîçèöèþ
extern double StopLoss          = 290;  // Maximum pips willing to lose per position.
extern string LL                = "Îãðàíè÷èòü StopLoss íà óðîâíå (â %) îò SL";
extern double LossLimit         = 50;   // Óðîâåíü StopLoss â %% ïóíêòàì StopLoss íèæå êîòîðîãî íàäî çàêðûâàòü ïîçèöèþ
extern int    variant           = 1;    // 1 - Ðàáîòàåò òîëüêî â îäíîì íàïðàâëåíèè, 2 - â äâóõ íàïðàâëåíèÿõ 
extern int   UseTrailingStop    = 0;
extern double MarginCutoff      = 300;  // Expert will stop trading if equity level decreases to that level.
extern int    Slippage          = 4;    // Possible fix for not getting closed Could be higher with some brokers    
//----
int    OpPozBUY, OpPozSELL;
int    MagicNumber;                     // Magic EA identifier. Allows for several co-existing EA with different input values
int    attempt                  = 5;                        //Ïîïûòîê íà îòêðûòèå/çàêðûòèå îðäåðîâ
int    color_close_buy          = MediumBlue;
int    color_close_sell         = DarkViolet;
string ExpertName;                      // To "easy read" which EA place an specific order and remember me forever :)
string news_wav                 = "news.wav";
double lotMM, balans, old_balans, loss,price_buy, price_sell;
double stimul;
double spread                   = 3.0;
bool   UseAddOrder;
bool   MoneyManagement;                 // Change to false to shutdown money management controls.
bool   sound_yes                = TRUE; //Ðàçðåøèòü çâóêè
bool   is_loss                  = false;
double Pnt;
static int prevtime             = 0;

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() {
   if (Time[0] == prevtime) {
      return(0);
   }
   prevtime = Time[0];

   if (100*MathPow(10,Digits-5) < MarketInfo(Symbol(), MODE_STOPLEVEL)) {
      Alert(Symbol(),":STOPLEVEL=",DoubleToStr(MarketInfo(Symbol(), MODE_STOPLEVEL), 2)," âåëèê. Æäåì ñëåäóþùåãî òèêà.");
      return;
   } 
   //for (int k=0; k<TrendBars; k++)
   //Alert();
   //   if (iCustom(Symbol(),0,"Silense",20,288,1,1) < 23.6)
   //      return(0);
   if(IsTradeAllowed()) {
      RefreshRates();
      spread = (Ask - Bid) / Point;
   } else {
      again();
      return(0);
   }
   
   HandleOpenPositions();
 
   OpPozBUY = openPositionsBUY();
   OpPozSELL = openPositionsSELL();
   int OpPzBUY = openPositionsBUY(false);
   int OpPzSELL = openPositionsSELL(false);

   if (!(UseTrailingStop == 2)) {
      if (CheckEntryCloseBUY() && OpPzBUY > 0) CloseAllPos(OP_BUY);
      if (CheckEntryCloseSELL() && OpPzSELL > 0) CloseAllPos(OP_SELL);
   }

   if (CheckEntryOpenBUY() && OpPzBUY < 1 && (variant == 2 || (variant == 1 && OpPzSELL < 1 ))) {
      if(AccountFreeMargin() < MarginCutoff) {
         Print("Not enough money for buy to trade Strategy:", ExpertName);
         return(0);
      }
      lotMM=GetLots();
      OpenBuy();
   }

   if (CheckEntryOpenSELL() && OpPzSELL < 1 && (variant == 2 || (variant == 1 && OpPzBUY < 1 ))) {
      if(AccountFreeMargin() < MarginCutoff) {
         Print("Not enough money for sell to trade Strategy:", ExpertName);
         return(0);
      }
      lotMM=GetLots();
      OpenSell();
   }
   
   if (UseTrailingStop >= 1) {
      int total = OrdersTotal();   
      for(int i = total - 1; i >= 0; i--) {
         OrderSelect(i, SELECT_BY_POS, MODE_TRADES); 
         if ((OrderSymbol() == Symbol()) && (OrderMagicNumber() == MagicNumber)) {
            int prevticket = OrderTicket();
            if (OrderType() == OP_BUY) {
               if (Bid > (OrderStopLoss() + (StopLoss*MathPow(10,Digits-4) + spread) * Point))                
                  if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - StopLoss * Pnt*10, 0, 0, Blue)) 
                     again();
            } else { 
               if (Ask < (OrderStopLoss() - (StopLoss*MathPow(10,Digits-4) + spread) * Point)) 
                  if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + StopLoss * Pnt*10, 0, 0, Blue)) 
                     again();
            }
            return(0);
         }
      }
   }
    
   return(0);
}

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   prevtime = Time[0];
   stimul = LossPercent*0.01;
   Pnt = Point*MathPow(10,Digits-5);
   if (BackLevel == 0)  UseAddOrder    = false; else UseAddOrder    = true;
   if (Lots == 0)       MoneyManagement=true;   else MoneyManagement=false;
   old_balans = AccountBalance();
   MagicNumber=3000 + func_Symbol2Val(Symbol())*100 + func_TimeFrame_Const2Val(Period());
   ExpertName="iK_candle: " + MagicNumber + " : " + Symbol() + "_" + func_TimeFrame_Val2String(func_TimeFrame_Const2Val(Period()));
   return(0);
}

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {
   return(0);
}

//+------------------------------------------------------------------+
//| CheckEntryOpen                                              |
//| Check if rules are met for Buy trade                             |
//+------------------------------------------------------------------+
bool CheckEntryOpenBUY() {
   int j = 0;
   for (int i = 2; i < 2+TrendBars; i++) {
      if (Open[i] - Close[i] > Point) j++; else j = 0;
   }
   if (j == TrendBars) {
      if (Close[1] - Open[1] > Point) {
         if (NormalizeDouble(Close[1],Digits) - NormalizeDouble(Open[2],Digits) >= 0) {
            if (Close[1] - Open[1] > 1.382*(Open[2] - Close[2])) {
               if (NormalizeDouble(Close[2],Digits) - NormalizeDouble(Open[1],Digits) >= -Point) {
                  return(true);
               }
            }
         }
      } 
   }
   return(false);
}

//+------------------------------------------------------------------+
//| CheckEntryOpen                                              |
//| Check if rules are met for open of trade                         |
//+------------------------------------------------------------------+
bool CheckEntryOpenSELL() {
   int j = 0;
   for (int i = 2; i < 2+TrendBars; i++) {
      if (Close[i] - Open[i] > Point) j++; else j = 0;
   } 
   if (j == TrendBars) {
      if (Open[1] - Close[1] > Point) {
         if (NormalizeDouble(Open[2],Digits) - NormalizeDouble(Close[1],Digits) >= 0) {
            if (Open[1] - Close[1] > 1.382*(Close[2] - Open[2])) {
               if (NormalizeDouble(Open[1],Digits) - NormalizeDouble(Close[2],Digits) >= -Point) {
                  return(true);
               }
            }
         }
      } 
   }
   return(false);
}
 
//+------------------------------------------------------------------+
//| CheckEntryClose                                                  |
//| Check if rules are met for Buy trade                             |
//+------------------------------------------------------------------+
bool CheckEntryCloseBUY() {
   if (Open[0] > price_buy + 0.01*ProfitLimit*TakeProfit*10*Pnt) {
      if (Close[2] - Open[2] > Point) {                                                                // Áåëàÿ ñâå÷à
         if (NormalizeDouble(Open[1],Digits) - NormalizeDouble(Close[1],Digits) >= 0) {                // ×åðíàÿ ñâå÷à
            if (Close[2] - Open[2] > Open[1] - Close[1]) {                                             // Áàëàÿ áîëüøå ÷åðíîé
               if (NormalizeDouble(Close[1],Digits) - NormalizeDouble(Open[2],Digits) >= -Point) {     // ×åðíàÿ çàêðûëàñü íå íèæå 1ï. ÷åì áåëàÿ îòêðûëàñü
                  if (NormalizeDouble(Close[2],Digits) - NormalizeDouble(Open[1],Digits) >= -Point) {  // Áåëàÿ çàêðûëàñü íå íèæå 1ï. ÷åì ÷åðíàÿ çàêðûëàñü
                     return(true);
                  }
               }
            }
         } 
      }
   }
   if (Open[0] < price_buy-0.01*LossLimit*StopLoss*10*Pnt) {
      if (Open[2] - Close[2] > Point) {
         if (NormalizeDouble(Close[1],Digits) - NormalizeDouble(Open[1],Digits) >= 0) {
            if (Open[2] - Close[2] > Close[1] - Open[1]) {
               if (NormalizeDouble(Open[2],Digits) - NormalizeDouble(Close[1],Digits) >= -Point) {
                  if (NormalizeDouble(Open[1],Digits) - NormalizeDouble(Close[2],Digits) >= -Point) {
                     return(true);
                  }
               }
            }
         } 
      }
   }
   return(false);
}

//+------------------------------------------------------------------+
//| CheckEntryClose                                                  |
//| Check if rules are met for open of trade                         |
//+------------------------------------------------------------------+
bool CheckEntryCloseSELL() {
   if (Open[0] < price_sell - 0.01*ProfitLimit*TakeProfit*10*Pnt) {
      if (Open[2] - Close[2] > Point) {
         if (NormalizeDouble(Close[1],Digits) - NormalizeDouble(Open[1],Digits) >= 0) {
            if (Open[2] - Close[2] > Close[1] - Open[1]) {
               if (NormalizeDouble(Open[2],Digits) - NormalizeDouble(Close[1],Digits) >= -Point) {
                  if (NormalizeDouble(Open[1],Digits) - NormalizeDouble(Close[2],Digits) >= -Point) {
                     return(true);
                  }
               }
            }
         } 
      }
   }
   if (Open[0] > price_sell+0.01*LossLimit*StopLoss*10*Pnt) {
      if (Close[2] - Open[2] > Point) {  
         if (NormalizeDouble(Open[1],Digits) - NormalizeDouble(Close[1],Digits) >= 0) {                // ×åðíàÿ ñâå÷à
            if (Close[2] - Open[2] > Open[1] - Close[1]) {                                             // Áàëàÿ áîëüøå ÷åðíîé
               if (NormalizeDouble(Close[1],Digits) - NormalizeDouble(Open[2],Digits) >= -Point) {     // ×åðíàÿ çàêðûëàñü íå íèæå 1ï. ÷åì áåëàÿ îòêðûëàñü
                  if (NormalizeDouble(Close[2],Digits) - NormalizeDouble(Open[1],Digits) >= -Point) {  // Áåëàÿ çàêðûëàñü íå íèæå 1ï. ÷åì ÷åðíàÿ çàêðûëàñü
                     return(true);
                  }
               }
            }
         } 
      }
   }
   return(false);
}

//+------------------------------------------------------------------+
//| OpenBuy                                                          |
//+------------------------------------------------------------------+
int OpenBuy() {
   int err, ticket;
   color myColor = Green;
   
   if (MarketInfo(Symbol(), MODE_STOPLEVEL) > 2*spread) double shift = MarketInfo(Symbol(), MODE_STOPLEVEL);
   else shift = 2*spread;

   double myPrice      = NormalizeDouble(Ask/* - shift*Point*/,Digits);
   double myTakeProfit = NormalizeDouble(myPrice + TakeProfit*Pnt*10,Digits);                                                     //
   double myStopLoss   = NormalizeDouble(myPrice - StopLoss * Pnt*10,Digits);
   ticket=OrderSend(Symbol(),OP_BUY,lotMM,myPrice,Slippage,myStopLoss,myTakeProfit,ExpertName, MagicNumber,0,myColor);
 
   string MyTxt;
   MyTxt = " for " + DoubleToStr(myPrice,4); 
         
   if(ticket<=0) {
      err=GetLastError();
      return(0);
   }
   return(1);
}

//+------------------------------------------------------------------+
//| OpenSell                                                         |
//+------------------------------------------------------------------+
int OpenSell() {
   int err, ticket;
   color myColor = Red;
   
   if (MarketInfo(Symbol(), MODE_STOPLEVEL) > 2*spread) double shift = MarketInfo(Symbol(), MODE_STOPLEVEL);
   else shift = 2*spread;
   
   double myPrice      = NormalizeDouble(Bid/* + shift*Point*/,Digits);         
   double myTakeProfit = NormalizeDouble(myPrice - TakeProfit*Pnt*10,Digits);                                                           //
   double myStopLoss   = NormalizeDouble(myPrice + StopLoss * Pnt*10,Digits);
  
   ticket=OrderSend(Symbol(),OP_SELL,lotMM,myPrice,Slippage,myStopLoss,myTakeProfit,ExpertName, MagicNumber,0,myColor);
   
   string MyTxt;
   MyTxt = " for " + DoubleToStr(myPrice,4); 
         
   if(ticket<=0) {
      err=GetLastError();
      return(0);
   }
   return(1);
}

//+------------------------------------------------------------------------+
//| counts the number of open positions BUY                                    |
//+------------------------------------------------------------------------+
int openPositionsBUY(bool limit = true) {  
   int op =0;
   for(int i=OrdersTotal()-1;i>=0;i--) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()==Symbol()) {
         if(OrderType()==OP_BUY) {
            op++;
            price_buy = OrderOpenPrice();
         }
         if(limit && OrderType()==OP_BUYLIMIT)op++;
      }
   }
   return(op);
}

//+------------------------------------------------------------------------+
//| counts the number of open positions SELL                                   |
//+------------------------------------------------------------------------+
int openPositionsSELL(bool limit = true) {  
   int op =0;
   for(int i=OrdersTotal()-1;i>=0;i--) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()==Symbol())  {
         if(OrderType()==OP_SELL) {
            op++;
            price_sell = OrderOpenPrice();
         }
         if(limit && OrderType()==OP_SELLLIMIT)op++;
      }
   }
   return(op);
}

//+------------------------------------------------------------------+
//| Get number of lots for this trade                                |
//+------------------------------------------------------------------+
double GetLots() {
   double lot;
   if(MoneyManagement) {
      RefreshRates();                              // Îáíîâëåíèå äàííûõ
      double
      TickValue = MarketInfo(Symbol(),MODE_TICKVALUE),
      Min_Lot=MarketInfo(Symbol(),MODE_MINLOT),        // Ìèíèì. êîëè÷. ëîòîâ 
      Max_Lot=MarketInfo(Symbol(),MODE_MAXLOT),        // Ìèíèì. êîëè÷. ëîòîâ 
      Free   =AccountFreeMargin(),                     // Ñâîáîäí ñðåäñòâà
      balans =AccountBalance(),
      One_Lot=MarketInfo(Symbol(),MODE_MARGINREQUIRED),// Ñòîèìîñòü 1 ëîòà
      Step   =MarketInfo(Symbol(),MODE_LOTSTEP);       // Øàã èçìåíåí ðàçìåðà
      
      if (balans >= old_balans) {
         old_balans = balans;
         stimul = LossPercent*0.01;
         is_loss = true;
      } else {
         if (is_loss) {
            loss = GetProfitLastClosePos();
            if (3*LossPercent > MaxRisk) stimul = 0.01*MaxRisk;
            else stimul = 3*LossPercent*0.01;
            is_loss = false;
         }
      }
      if (old_balans - balans > 0.5*StopLoss*lot*TickValue) {
         lot = stimul*MathPow(10,4-Digits)*Free/(StopLoss*TickValue);
         if (stimul == 3*LossPercent*0.01) Comment("Ïîñëå óáûòêà ËÎÒ â ïðåäåëàõ % óòðîåííîãî ðèñêà îò SL è ðàâåí ",MathCeil(lot/Step)*Step," èëè ",100*stimul,"% áàëàíñà");
           else Comment("Ïîñëå óáûòêà ËÎÒ â ïðåäåëàõ % ìàêñèìëüíîãî ðèñêà îò SL è ðàâåí ",MathCeil(lot/Step)*Step," èëè ",100*stimul,"% áàëàíñà");
      } else {
         lot=Free*ProfitPercent*0.01/(TakeProfit*MathPow(10,Digits-5)*10*TickValue); 
         Comment("Ñòàíäàðòíà ñèòóàöèÿ ËÎÒ ðàâåí ",MathCeil(lot/Step)*Step);
      }
      if (lot > Max_Lot) {
         lot = Max_Lot;
         Comment("ËÎÒ îãðàíè÷åí ìàêñèìóìîì è ðàâåí ",MathCeil(lot/Step)*Step);
      }
      if (lot*One_Lot > Free) {
         lot = Free/One_Lot;
         Comment("ËÎÒ îãðàíè÷åí ñâîáîäíûìè ñðåäñòâàìè è ðàâåí ",MathCeil(lot/Step)*Step);
      }
      if (lot < Min_Lot) {
         lot=Min_Lot;               // Íå ìåíüøå ìèíèìàëüí
         Comment("ËÎÒ îãðàíè÷åí ìèíèìóìîì è ðàâåí ",MathCeil(lot/Step)*Step);
      }
   } else lot=Lots;
   if(MoneyManagement && 
      StopLoss*lot*TickValue > stimul*MathPow(10,4-Digits)*Free) {
      lot = stimul*MathPow(10,4-Digits)*Free/(StopLoss*TickValue);
      if (stimul == LossPercent*0.01) Comment("ËÎÒ â ïðåäåëàõ % ìèíèìàëüíîãî ðèñêà îò SL è ðàâåí ",MathCeil(lot/Step)*Step," èëè ",100*stimul,"% áàëàíñà");
      else if (stimul == 3*LossPercent*0.01) Comment("ËÎÒ â ïðåäåëàõ % óòðîåííîãî ðèñêà îò SL è ðàâåí ",MathCeil(lot/Step)*Step," èëè ",100*stimul,"% áàëàíñà");
           else Comment("ËÎÒ â ïðåäåëàõ % ìàêñèìëüíîãî ðèñêà îò SL è ðàâåí ",MathCeil(lot/Step)*Step," èëè ",100*stimul,"% áàëàíñà");
   }
   RefreshRates();                              // Îáíîâëåíèå äàííûõ
   Step = MarketInfo(Symbol(),MODE_LOTSTEP);       // Øàã èçìåíåí ðàçìåðà
   lot = MathCeil(lot/Step)*Step;
   return(lot);
}

//+------------------------------------------------------------------+
int GetProfitLastClosePos(string sy="", int mn=-1) {
  datetime t;
  int      i, k=OrdersHistoryTotal(), r=0;
  
  if (sy=="0") sy=Symbol();
  for (i=0; i<k; i++) {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
      if ((OrderSymbol()==sy || sy=="") && (mn<0 || OrderMagicNumber()==mn)) {
        if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
          if (t<OrderCloseTime()) {
            t=OrderCloseTime();
            r=OrderProfit();
          }
        }
      }
    }
  }
  return(r);
}

//+------------------------------------------------------------------+
//| Time frame interval appropriation  function                      |
//+------------------------------------------------------------------+
int func_TimeFrame_Const2Val(int Constant) {
     switch(Constant) {
         case     1: return(1);
         case     5: return(2);
         case    15: return(3);
         case    30: return(4);
         case    60: return(5);
         case   240: return(6);
         case  1440: return(7);
         case 10080: return(8);
         case 43200: return(9);
     }
}

//+------------------------------------------------------------------+
//| Time frame string appropriation  function                        |
//+------------------------------------------------------------------+
string func_TimeFrame_Val2String(int Value) {
    switch(Value) {
        case 1: return("PERIOD_M1");
        case 2: return("PERIOD_M5");
        case 3: return("PERIOD_M15");
        case 4: return("PERIOD_M30");
        case 5: return("PERIOD_H1");
        case 6: return("PERIOD_H4");
        case 7: return("PERIOD_D1");
        case 8: return("PERIOD_W1");
        case 9: return("PERIOD_MN1");
        default: return("undefined " + Value);
    }
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int func_Symbol2Val(string symbol)  {
     if(symbol=="AUDCAD")  {
        return(1);
     } else if(symbol=="AUDJPY") {
        return(2);
     } else if(symbol=="AUDNZD") {
        return(3);
     } else if(symbol=="AUDUSD") {
        return(4);
     } else if(symbol=="CHFJPY") {
        return(5);
     } else if(symbol=="EURAUD") {
        return(6);
     } else if(symbol=="EURCAD") {
        return(7);
     } else if(symbol=="EURCHF") {
        return(8);
     } else if(symbol=="EURGBP") {
        return(9);
     } else if(symbol=="EURJPY") {
        return(10);
     } else if(symbol=="EURUSD") {
        return(11);
     } else if(symbol=="GBPCHF") {
        return(12);
     } else if(symbol=="GBPJPY") {
        return(13);
     } else if(symbol=="GBPUSD") {
        return(14);
     } else if(symbol=="NZDUSD") {
        return(15);
     } else if(symbol=="USDCAD") {
        return(16);
     } else if(symbol=="USDCHF") {
        return(17);
     } else if(symbol=="USDJPY") {
        return(18);
     } else {
        Comment("unexpected Symbol");
        return(0);
     }
}

void CloseAllPos(int typ=2) {
   int l_ord_total_22 = OrdersTotal();
   int l_ord_total_24 = l_ord_total_22;
   for (int l_pos_18 = l_ord_total_22 - 1; l_pos_18 >= 0; l_pos_18--) {
      if (OrderSelect(l_pos_18, SELECT_BY_POS, MODE_TRADES)) {
         ClosePosBySelect(typ);
         l_ord_total_24--;
      }
   }
   if (l_ord_total_24 == 0) return;
} 

void ClosePosBySelect(int typ) {
   bool l_ord_close_0;
   color l_color_4;
   double l_ord_lots_8;
   double ld_16;
   double ld_24;
   double l_price_32;
   int l_error_40;
   if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
      for (int li_44 = 1; li_44 <= attempt; li_44++) {
         if (!IsTesting() && !IsExpertEnabled() || IsStopped()) break;
         while (!IsTradeAllowed()) Sleep(5000);
         RefreshRates();
         ld_16 = NormalizeDouble(MarketInfo(OrderSymbol(), MODE_ASK), Digits);
         ld_24 = NormalizeDouble(MarketInfo(OrderSymbol(), MODE_BID), Digits);
         if (OrderType() == OP_BUY) {
            l_price_32 = ld_24;
            l_color_4 = color_close_buy;
         } else {
            l_price_32 = ld_16;
            l_color_4 = color_close_sell;
         }
         l_ord_lots_8 = OrderLots();
         
         if (typ == 2) l_ord_close_0 = OrderClose(OrderTicket(), l_ord_lots_8, l_price_32, Slippage, l_color_4);
         else if (typ == OrderType()) l_ord_close_0 = OrderClose(OrderTicket(), l_ord_lots_8, l_price_32, Slippage, l_color_4);
         
         if (l_ord_close_0) {
            if (!(sound_yes)) break;
            PlaySound(news_wav);
            return;
         }
         l_error_40 = GetLastError();
         if (l_error_40 == 146/* TRADE_CONTEXT_BUSY */) while (IsTradeContextBusy()) Sleep(11000);
         Print("Error(", l_error_40, ") Close ", OrderType(), " ", ErrorDescription(l_error_40), ", try ", li_44);
         Sleep(5000);
      }
   } else Print("Íåêîððåêòíàÿ òîðãîâàÿ îïåðàöèÿ. Close ", OrderType());
}

//+------------------------------------------------------------------+
//| HandleUseAddOrder                                               |
//+------------------------------------------------------------------+

int HandleUseAddOrder(string type, int ticket, double op, double os, double tp)
 {
     int x; bool IsGoHi;
     int err, ticketNew;
     double myPrice;
     string MyTxt;
 
     if (type== "SELL" && OpPozSELL == 1 && OpPozBUY == 0)
     {
      if(op < Ask - 0.01*BackLevel*StopLoss*10*Pnt) 
        {
        myPrice = NormalizeDouble(Bid,Digits);
        ticketNew=OrderSend(Symbol(),OP_SELL,lotMM,myPrice,Slippage,os,op  - 10*Pnt,ExpertName,MagicNumber,0,Red);
   
        MyTxt = " for " + DoubleToStr(myPrice,4); 
         
        if(ticketNew<=0)
          {
           err=GetLastError();
           Print("iK_candle: Error opening Add Sell order [" + ExpertName + "]: (" + err + ") " + ErrorDescription(err) + " /// " + MyTxt);
           return(0);
          }
        //ModifyOrder(ticket,op,os,op  - 10*Pnt );
        }
      }
    
    if (type== "BUY" && OpPozBUY == 1 && OpPozSELL == 0)
     {
       if(op > Bid + 0.01*BackLevel*StopLoss*10*Pnt) 
        {
        myPrice = NormalizeDouble(Ask,Digits);
        ticketNew=OrderSend(Symbol(),OP_BUY,lotMM,myPrice,Slippage,os,op  + 10*Pnt,ExpertName,MagicNumber,0,Green);
   
        MyTxt = " for " + DoubleToStr(myPrice,4); 
         
        if(ticketNew<=0)
          {
           err=GetLastError();
           Print("iK_candle: Error opening Add Sell order [" + ExpertName + "]: (" + err + ") " + ErrorDescription(err) + " /// " + MyTxt);
           return(0);
          }
        //ModifyOrder(ticket,op,os,op  + 10*Pnt );
        }
     }

   return(0);

  }

//+------------------------------------------------------------------+
//|  Modify Open Position Controls                                   |
//|  Try to modify position 3 times                                  |
//+------------------------------------------------------------------+
void ModifyOrder(int ord_ticket,double op, double price,double tp)
  {
   int CloseCnt, err;
   CloseCnt=0;
   while(CloseCnt < 3)
     {
      if (OrderModify(ord_ticket,op,price,tp,0,Aqua))
        {
         CloseCnt=3;
        }
      else
        {
         err=GetLastError();
         Print(CloseCnt," Error modifying order : (", err , ") " + ErrorDescription(err));
         if (err>0) CloseCnt++;
        }
     }
  } 
  
//+------------------------------------------------------------------+
//| Handle Open Positions                                            |
//| Check if any open positions need to be closed or modified        |
//+------------------------------------------------------------------+
int HandleOpenPositions()
  {
   int cnt;
   bool YesClose;
   double pt;
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
     {
      OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()!=Symbol()) continue;
      if(OrderMagicNumber()!=MagicNumber)  continue;
      if(OrderType()==OP_BUY)
         if (UseAddOrder)
            HandleUseAddOrder("BUY",OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
      if(OrderType()==OP_SELL)
         if (UseAddOrder)
            HandleUseAddOrder("SELL",OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
     }
  }

//+------------------------------------------------------------------+
void again() {
   prevtime = Time[1];
   Sleep(30000);
}

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