Author: Ivan Katsko
Price Data Components
Series array that contains open time of each barSeries array that contains open prices of each barSeries array that contains close prices for 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 automatically opens orders when conditions are reachedIt Closes Orders by itself
Miscellaneous
It issuies visual alerts to the screenIt plays sound alerts
0 Views
0 Downloads
0 Favorites
iK_BD_3
//+------------------------------------------------------------------+
//|                                                                  |
//|       Ñîâåòíèê íà                                                |
//|       ïðîáîé ôëåòà                                               |
//|                             http://www.mql4.com/ru/users/ikatsko |
//+------------------------------------------------------------------+
#property copyright "Ivan Katsko"
#property link      "ICQ:372739628"

#include <stdlib.mqh>

extern double WantProfit   = 4;                 //Æåëàåìàÿ ïðèáûëü â %% äåïî
extern double OrdersMax    = 4;                 //Ìàêñèìàëüíîå ÷èñëî îðäåðîâ, êîòîðûå âûäåðæèò áàëàíñ
extern string Canal        = "Âûáîð êàíàëà";          
//extern int    BS  = 3;                          //×èñëî îòêðûòûõ îðäåðîâ, áîëüøå êîòîðîãî ïðèìåíÿåòñÿ StopProfit
//extern int    ES   = 9;                         //Âçÿòü %% íàìå÷åííîãî Ïðîôèòà 
extern string BeginSesion  = "03:00";           //Âðåìÿ íà÷àëà ñåññèè    |Åñëè íà÷àëî è êîíåö ñåññèè = "00:00",
extern string EndSesion    = "09:00";           //Âðåìÿ îêîí÷àíèÿ ñåññèè |òî êàíàë îïðåäåëÿåòñÿ ïî äâóì ïàðàìåòðàì íèæå
extern int    Flat         = 6;                 //Äëèòåëüíîñòü ôëåòà â ÷àñàõ. "0" - ôëåò ïî óðîâíþ àãðåññèè (Sielens)
extern double Aggress      = 23.6;              //Àãðåññèâíîñòü ðûíêà îò 0 äî 100 ïî Sielens
extern bool   LimitOnlyMin = false;             //Îãðàíè÷èòü êàíàë òîëüêî ïî ìèíèìóìó 
extern bool   Revers       = false;             //"false" - îáû÷íàÿ ðàáîòà, "true" - øèðîêèé êàíàë, ðàáîòà âíóòðè êàíàëà
extern string MM           = "MoneyManagement";          
extern double OrdersNoMore = 2;                 //Îòêðûòûõ îðäåðîâ äîëæíî áûòü íå áîëåå
extern double ProfitPercent= 1;                 //Âçÿòü %% áàëàíñà, åñëè îòêàò
extern int    OrdersLimit  = 2;                 //×èñëî îòêðûòûõ îðäåðîâ, áîëüøå êîòîðîãî ïðèìåíÿåòñÿ StopProfit
extern int    StopProfit   = 90;                //Âçÿòü %% íàìå÷åííîãî Ïðîôèòà 
extern int    StopOut      = 100;               //StopOut íå ìåíåå óêàçàííîãî â %% 
extern double StopBalance  = 475;               //Çàêîí÷èòü òîðãîâëþ íà ýòîì óðîâíå 
extern double NotUsedPart  = 500;               //Íå èñïîëüçóåìàÿ ÷àñòü áàëàíñà
extern string TimeRest     = "Îãðàíè÷åíèÿ ïî âðåìåíè";          
extern int    Jump         = 0;                 //Ïðîïóñòèòü äåíü íåäåëè
extern double Wait         = 0;                 //Îæèäàíèå ïðîáîÿ êàíàëà, â ìèíóòàõ 
extern int    GMT          = 1;                 //Ñèñòåìíîå âðåìÿ ïî îòíîøåíèþ ê Ãðèíâè÷ó (+/-)
extern int    magic        = 5928;

// Ïåðåìåííûå äëÿ îïðåäåëåíèÿ ôëåòà
int MyPeriod = 12;                 
int History = 288;
bool end, begin, middle, stop_revers, revers_work, flag_pp;
datetime time_begin, time_end, time_order;
double top;
double bottom;
              
double MinFactor = 0.382;                        //Êîýôôèöèåíò Ïðîôèòà ê Êàíàëó 
double MaxFactor = 1.75;                         //Êîýôôèöèåíò Ïðîôèòà ê Êàíàëó 
double TakeProfit = 47;                          //ÒÐ 
double Avalanche = 33;                           //Øèðèíà êàíàëà â ïóíêòàõ
double AvMax, AvMin;
int FirstTransaction;                            //Ïåðâàÿ ñäåëêà
double Profit;                                   //Ïðîôèò â âàëþòå áàëàíñà
double prots = 1.0;                              //Ïðîöåíòîâ ðèñêà
int Lot_Point;                                   //Çíàêîâ ïîñëå çàïÿòîé äëÿ ê-âà ëîòîâ
int gslippage = 3;
int shift;
int ord_count;
int attempt = 5;                                 //Ïîïûòîê íà îòêðûòèå/çàêðûòèå îðäåðîâ
string t_begin, t_end;
string ok_wav = "ok.wav";
string news_wav = "news.wav";
string expert_wav = "expert.wav";
int total;
int stoplevel;
int j, Spread;                                      //Ñïðåäà
int ShiftOfSL = 3;                               //Ñìåùåíèå SL (ðàç Ñïðåäà + Ñëèï)
int color_buy = MediumBlue;
int color_sell = DarkViolet;
int color_close_buy = MediumBlue;
int color_close_sell = DarkViolet;
bool comment_yes = TRUE;                         //Ðàçðåøèòü êîììåíòàðèé 
bool massege_yes = FALSE;                        //Ðàçðåøèòü ñîîáùåíèÿ
bool massege_profit = FALSE;                     //Ñîîáùèòü îá îñòàíîâêå
bool massege_loss = FALSE;                       //Ñîîáùèòü îá îñòàíîâêå
bool sound_yes = TRUE;                           //Ðàçðåøèòü çâóêè
bool massege_error = FALSE;                      //Ñîîáùèòü îá îøèáêå
bool New_Bar=false;                              // Ôëàã íîâîãî áàðà 
double StopLoss, Factor;
double lots_open;                                //Ðàáî÷åå ÷èñëî ëîòîâ äëÿ open
double level_set_buy;                            //Ðàáî÷èé óðîâåíü set äëÿ buy
double level_set_sell;                           //Ðàáî÷èé óðîâåíü set äëÿ sell
static datetime New_Time;

double lots_set[15], stop_profit[15];

int init() {
   GetAvalanche(1440,30);
   double d1 = AvMax;
   GetAvalanche(240,30);
   double h4 = (AvMin+AvMax)/2;
   MaxFactor = (d1-h4)/2/h4;
   //Alert("MaxFactor=",(d1-h4)/2,"/",h4,"=",(d1-h4)/2/h4);
/*
   switch (BS) {
   case 0: BeginSesion  = "00:00"; break;
   case 1: BeginSesion  = "01:00"; break;
   case 2: BeginSesion  = "02:00"; break;
   case 3: BeginSesion  = "03:00"; break;
   case 4: BeginSesion  = "04:00"; break;
   case 5: BeginSesion  = "05:00"; break;
   }
   switch (ES) {
   case 0: EndSesion   = "00:00"; break;
   case 6: EndSesion   = "06:00"; break;
   case 7: EndSesion   = "07:00"; break;
   case 8: EndSesion   = "08:00"; break;
   case 9: EndSesion   = "09:00"; break;
   case 10: EndSesion  = "10:00"; break;
   case 11: EndSesion  = "11:00"; break;
   case 12: EndSesion  = "12:00"; break;
   }
*/
   stoplevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
   massege_error = FALSE;
   time_begin = Time[0];
   time_end = Time[0];
   end = false;
   begin = false;
   if (!IsTradeAllowed()) {                      //Åñëè ýêïåðòó íå ðàçðåøåíî òîðãîâàòü
      Message("Äëÿ íîðìàëüíîé ðàáîòû ñîâåòíèêà íåîáõîäèìî\n" + "Ðàçðåøèòü ñîâåòíèêó òîðãîâàòü");
      massege_error = TRUE;
      return;
   }
   if (!IsLibrariesAllowed()) {
      Message("Äëÿ íîðìàëüíîé ðàáîòû ñîâåòíèêà íåîáõîäèìî\n" + "Ðàçðåøèòü èìïîðò èç âíåøíèõ ýêñïåðòîâ");
      massege_error = TRUE;
      return;
   }
   if (!IsTesting()) {                           //Íå â òåñòå
      if (IsExpertEnabled()) Message("Ñîâåòíèê áóäåò çàïóùåí ñëåäóþùèì òèêîì");
      else Message("Îòæàòà êíîïêà \"Ðàçðåøèòü çàïóñê ñîâåòíèêîâ\"");
   }
   
   double i=MathMod(MarketInfo(Symbol(), MODE_LOTSTEP),1);
   Lot_Point = 0;
   while (i>0.0){
     Lot_Point++;
     i=MathMod(i*10,1);
   }
   
   Spread = MarketInfo(Symbol(), MODE_SPREAD);
   ord_count = 0;
   shift = (gslippage+Spread)*ShiftOfSL;
   StopLoss = (TakeProfit +  Avalanche + shift )* Point;
   stop_profit[0] = 100;
   for (j=1; j<=15; j++) {
      if (OrdersLimit == 0 || StopProfit == 0) 
         stop_profit[j] = 100;
      else {
         if (j >= OrdersLimit)
            stop_profit[j] = MathRound(stop_profit[j-1]*0.01*StopProfit);
         else
            stop_profit[j] = 100;
         if (stop_profit[j] < 10) stop_profit[j] = 10;
      }
   }
   double step = MarketInfo(Symbol(), MODE_LOTSTEP);
   double min_lot = MarketInfo(Symbol(),MODE_MINLOT);
   double max_lot = MarketInfo(Symbol(),MODE_MAXLOT);
   //Alert("Init: min_lot=",min_lot," max_lot=",max_lot," step=",step);
   j = 0;
   Factor = 0;
   MathSrand(TimeLocal());
   while (Factor < 0.1) {
      Factor = 0.00001*MathRand();
   }
   while ((OrdersMax > j-2 && Factor < MaxFactor) || lots_set[0]*Avalanche*Factor*MarketInfo(Symbol(),MODE_TICKVALUE) < 0.01*WantProfit*(AccountFreeMargin()-NotUsedPart)) {
   //if (Factor > MaxFactor) break;
   for (lots_open=min_lot; lots_open<=max_lot; lots_open=lots_open+step) {
      //Alert("lots_open=",lots_open);
      Profit = MathRound(TakeProfit*lots_open*MathPow(10,(5-Digits)));
      for (j=0; j<15; j++) {
        switch(j){
        case 0:
          lots_set[j] = lots_open;
          break;
        case 1:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        +lots_set[0]
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 2:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -lots_set[0]*(TakeProfit-Spread)
                        +lots_set[1]
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 3:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -lots_set[1]*(TakeProfit-Spread)
                        +(lots_set[0]+lots_set[2])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 4:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[0]+lots_set[2])*(TakeProfit-Spread)
                        +(lots_set[1]+lots_set[3])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 5:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[1]+lots_set[3])*(TakeProfit-Spread)
                        +(lots_set[0]+lots_set[2]+lots_set[4])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 6:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[0]+lots_set[2]+lots_set[4])*(TakeProfit-Spread)
                        +(lots_set[1]+lots_set[3]+lots_set[5])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 7:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[1]+lots_set[3]+lots_set[5])*(TakeProfit-Spread)
                        +(lots_set[0]+lots_set[2]+lots_set[4]+lots_set[6])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 8:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[0]+lots_set[2]+lots_set[4]+lots_set[6])*(TakeProfit-Spread)
                        +(lots_set[1]+lots_set[3]+lots_set[5]+lots_set[7])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 9:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[1]+lots_set[3]+lots_set[5]+lots_set[7])*(TakeProfit-Spread)
                        +(lots_set[0]+lots_set[2]+lots_set[4]+lots_set[6]+lots_set[8])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 10:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[0]+lots_set[2]+lots_set[4]+lots_set[6]+lots_set[8])*(TakeProfit-Spread)
                        +(lots_set[1]+lots_set[3]+lots_set[5]+lots_set[7]+lots_set[9])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 11:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[1]+lots_set[3]+lots_set[5]+lots_set[7]+lots_set[9])*(TakeProfit-Spread)
                        +(lots_set[0]+lots_set[2]+lots_set[4]+lots_set[6]+lots_set[8]+lots_set[10])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 12:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[0]+lots_set[2]+lots_set[4]+lots_set[6]+lots_set[8]+lots_set[10])*(TakeProfit-Spread)
                        +(lots_set[1]+lots_set[3]+lots_set[5]+lots_set[7]+lots_set[9]+lots_set[11])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 13:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[1]+lots_set[3]+lots_set[5]+lots_set[7]+lots_set[9]+lots_set[11])*(TakeProfit-Spread)
                        +(lots_set[0]+lots_set[2]+lots_set[4]+lots_set[6]+lots_set[8]+lots_set[10]+lots_set[12])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        case 14:
          lots_set[j] = NormalizeDouble((Profit/MathPow(10,(5-Digits))
                        -(lots_set[0]+lots_set[2]+lots_set[4]+lots_set[6]+lots_set[8]+lots_set[10]+lots_set[12])*(TakeProfit-Spread)
                        +(lots_set[1]+lots_set[3]+lots_set[5]+lots_set[7]+lots_set[9]+lots_set[11]+lots_set[13])
                        *(Avalanche+TakeProfit+Spread))/TakeProfit,Lot_Point);
          break;
        }
      }
      double sum_lot = 0;
      double maxx_lot = (AccountFreeMargin()-NotUsedPart) / MarketInfo(Symbol(), MODE_MARGINREQUIRED);
      for (j=0; j<OrdersMax+2; j++) 
         if (sum_lot < maxx_lot) {
            sum_lot = sum_lot + lots_set[j];
            //Alert("Äî sum_lot=",sum_lot,">",maxx_lot);
            }
         else {
            //Alert("Ìàêñèìàëüíî âîçìîæíîå ÷èñëî îðäåðîâ = ",j-2);
            break;
         }
      if (sum_lot > maxx_lot) {
         //Alert("Ïî sum_lot=",sum_lot,">",maxx_lot);
         break;
      }
   }
   if (Factor < MaxFactor) Factor = Factor*1.05;
   else break;
   //Alert("lots_set[0]*Avalanche*Factor*MarketInfo(Symbol(),MODE_TICKVALUE)=",lots_set[0],"*",Avalanche,"*",Factor,"*",MarketInfo(Symbol(),MODE_TICKVALUE),"=",lots_set[0]*Avalanche*Factor*MarketInfo(Symbol(),MODE_TICKVALUE)," < ",0.01*WantProfit*AccountFreeMargin());
   //Sleep(30000000);
   TakeProfit = NormalizeDouble(Avalanche * Factor,0);
   }
   if (OrdersMax > j-2)
      Alert("Ñðåäñòâ íå õâàòàåò äëÿ ïîääåðæàíèÿ ",OrdersMax," îðäåðîâ");
   Alert("Factor=",Factor," lots[",0,"]=",lots_set[0]," îðäåðîâ=",j-2," áóäåò ïðîôèò=",NormalizeDouble(100*lots_set[0]*Avalanche*Factor*MarketInfo(Symbol(),MODE_TICKVALUE)/(AccountFreeMargin()-NotUsedPart),2),"%");
   return (0);
}

int deinit() {
   if (!IsTesting()) Comment("");
   return (0);
}

bool EndOfFlat() {
  if (Flat == 0) {
     double s0 = Silense(0);
     double s1 = Silense(1);
     double s2 = Silense(2);
     double s3 = Silense(3);
     if (begin && (
         (s0 >= Aggress && s1 <  Aggress && s2 <  Aggress && s3 < Aggress) ||
         (s0 >= Aggress && s1 >= Aggress && s2 <  Aggress && s3 < Aggress) ||
         (s0 >= Aggress && s1 >= Aggress && s2 >= Aggress && s3 < Aggress))) {
        time_end = Time[0];
        if ((time_end - time_begin)/60/Period() > 12) {
          end = true;
        } else {
          begin = false; 
          end= false;
          if (s3 < Aggress) time_begin = Time[0];
          time_end = Time[0];
        }
     }
     if ((begin && end && (
          (s0 < Aggress && s1 > Aggress && s2 > Aggress && s3 > Aggress) ||
          (s0 < Aggress && s1 < Aggress && s2 > Aggress && s3 > Aggress) ||
          (s0 < Aggress && s1 < Aggress && s2 < Aggress && s3 > Aggress))) ||
         (begin && !end && s0 > Aggress)) {
        begin = false; 
        end= false;
     }   
     if (!begin && !end && (
         (s0 < Aggress && s1 > Aggress && s2 > Aggress && s3 > Aggress) ||
         (s0 < Aggress && s1 < Aggress && s2 > Aggress && s3 > Aggress) ||
         (s0 < Aggress && s1 < Aggress && s2 < Aggress && s3 > Aggress))) {
        begin = true;
        time_begin = Time[0];
        if (s0 > Aggress) time_end = Time[0];
     }
  } else {
     int BarsOfFlet = MathCeil(60*Flat/Period());
     int cur_bar = (Time[0] - StrToTime(TimeToStr(Time[0], TIME_DATE)))/60/Period();
     if (cur_bar < BarsOfFlet*2 && cur_bar > 2) {
        begin = true;
        double t = 0;
        double b = 100000;
        double t1 = 0;
        double b1 = 100000;
        for (int i = BarsOfFlet; i > 0; i--) {
           if (High[i] > t) t = High[i];
           if (Low[i] < b) b = Low[i];
        }
        for (i = BarsOfFlet; i > 0; i--) {
           if (High[i+1]>High[i] && High[i+1]>High[i+2])
              if (High[i+1] > t1) t1 = High[i+1];
           if (Low[i+1]<Low[i] && Low[i+1]<Low[i+2])
              if (Low[i+1] < b1) b1 = Low[i+1];
        }
        if (t!=t1 || b!=b1) {
           begin = false;
           end = false;
           time_begin = Time[0];
           time_end = Time[0];
        }
        double AvMaxx = NormalizeDouble((t - b)/Point,0);
        //Alert("AvMaxx =",AvMaxx);
        GetAvalanche();
        //Alert("AvMax =",AvMax," AvMin =",AvMin);
        if (AvMaxx <= AvMax && AvMaxx >= AvMin) {
           end = true;
           time_begin = iTime(0,0,BarsOfFlet);
           time_end = Time[0]/*+2*60*Period()*/;
           ObjectDelete("Begin");
           ObjectCreate("Begin",OBJ_VLINE,0,time_begin,0);
           ObjectSet("Begin",OBJPROP_COLOR,DarkOrchid);
           ObjectDelete("End");
           ObjectCreate("End",OBJ_VLINE,0,time_end,0);
           ObjectSet("End",OBJPROP_COLOR,DarkOrchid);
        } else {
           begin = false;
           end = false;
           time_begin = Time[0];
           time_end = Time[0];
        }
        //Alert("time_begin =",TimeToStr(time_begin,TIME_MINUTES)," time_end =",TimeToStr(time_end,TIME_MINUTES));
     }
  }return (end);
}

int start() {
   //Alert("Ñòàðò");
   if (DayOfWeek() > 5 || DayOfWeek() < 1) {
      Message("Ñåãîäíÿ âûõîäíîé");
      return;
   }
   if (DayOfWeek() == Jump && total == 0) {
      Message("Ñåãîäíÿ íå ðàáîòàåì");
      return;
   }
   Fun_New_Bar();
   double SL;                                 //Óðîâåíü SL
   double TP;                                 //Óðîâåíü ÒÐ
   string ls148;
   if (massege_profit) {
      Message("Ñîâåòíèê ÎÑÒÀÍÎÂËÅÍ! Ñíèìàé äåíüãè!!");
      return;
   }
   if (massege_loss) {
      Message("Ñîâåòíèê ÎÑÒÀÍÎÂËÅÍ! Äîáàâëÿé äåíüãè...");
      return;
   }
   if (massege_yes) {
      Message("Êðèòè÷åñêàÿ îøèáêà! Ñîâåòíèê ÎÑÒÀÍÎÂËÅÍ!");
      return;
   }
   if (massege_error) {
      Message("Íå óäàëîñü èíèöèàëèçèðîâàòü ñîâåòíèê!");
      return;
   }
   
   if (stoplevel*10 < MarketInfo(Symbol(), MODE_STOPLEVEL)) {
      Alert(Symbol(),":STOPLEVEL=",DoubleToStr(MarketInfo(Symbol(), MODE_STOPLEVEL), 2)," âåëèê. Æäåì ñëåäóþùåãî áàðà.");
      return;
   } else stoplevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
   
   total = 0;                                //Ê-âî buy/sell îðäåðîâ
   int total_post = 0;                           //Ê-âî îòëîæåííûõ îðäåðîâ
   for (int i = 0; i <= OrdersTotal() - 1; i++) {//Äëÿ êàæäîãî îòêðûòîãî îðäåðà
      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){ //ñðåäè îòêðûòûõ îðäåðîâ
         if (OrderSymbol() == Symbol() && OrderMagicNumber() == magic) {
            if (OrderType()<=1)                  //åñëè îí buy/sell
               total++;                          //ïîñ÷èòàåì åãî
            if (OrderType()>1)                   //åñëè îí îòëîæåííûé
               total_post++;                     //ïîñ÷èòàåì åãî
         }
      }
   }
   
   if (total == OrdersMax) {
      double ab = AccountBalance();
      double ae = AccountEquity();
      if (ab-ae < 0.1*ab) {
         CloseAllPos();
         flag_pp = false;
         reset();
         Alert("Çàêðûëè : ïî ìèíèìàëüíîìó óáûòêó");
         return;
      }
   }
   
   if (total == 1) {
      ab = AccountBalance();
      ae = AccountEquity();
      if (ab-ae > 0.5*lots_open*Avalanche*MarketInfo(Symbol(),MODE_TICKVALUE))
         flag_pp = true;
      if (flag_pp)
         if (ae-ab > 0.01*ProfitPercent*ab) {
            CloseAllPos();
            flag_pp = false;
            reset();
            Alert("Çàêðûëè : ïî ProfitPercent");
            return;
         }
   }
   
   if (total >= ord_count) {
      if (Revers && revers_work && total > ord_count) {
         time_order = Time[0];
      }
      ord_count=total;
   }
   else {
      CloseAllPos();
      flag_pp = false;
      reset();
      Alert("Çàêðûëè : ïî Profit");
      return;
   }
   
   if (total > 0 && StopOut > 0) {
      if (100*(AccountEquity()-NotUsedPart)/AccountMargin() < StopOut) {
         CloseAllPos();
         flag_pp = false;
         reset();
         Alert("Çàêðûëè : ïî StopOut");
         return;
      }
   }
      
   if (Revers && revers_work) {
      if ((total_post == 2) || (total == 1 && total_post == 0)) return;
      if (total == 1 && total_post > 0) {
         stop_revers = true;
         DelPostPos();
      }
      
   }
   
   //Alert("Time[0]+GMT=", TimeToStr(Time[0]-GMT*60*60,TIME_SECONDS)," > ",TimeToStr(StrToTime(TimeToStr(time_order + 24*60*60, TIME_DATE)),TIME_MINUTES));
   if (time_end > 1000000 &&
       total > 0 && 
       Time[0]-GMT*60*60 > StrToTime(TimeToStr(time_order + 24*60*60, TIME_DATE))) {
      if (AccountEquity() > AccountBalance() + MathRound(0.1*TakeProfit*lots_open*MathPow(10,(5-Digits)))) {
         CloseAllPos();
         flag_pp = false;
         reset();
         Alert("Çàêðûëè : ñïóñòÿ ñóòêè");
      }
      //return;
   }
   
   if (total >= OrdersLimit) {
      if (AccountEquity()-AccountBalance() > 0.01*stop_profit[total]*TakeProfit*lots_open*MathPow(10,(5-Digits))) {
         Alert("AccountEquity()-AccountBalance()=", AccountEquity()-AccountBalance()," > ",0.01*stop_profit[total]*TakeProfit*lots_open*MathPow(10,(5-Digits)));
         CloseAllPos();
         flag_pp = false;
         reset();
         Alert("Çàêðûëè : íà óìåíüøåíèè ïðîôèòà");
         return;
      }
   }
      
   if (total_post == 0 && AccountBalance() > StopBalance) massege_profit = true;
   
   if (total == 0) {
      if (comment_yes) {
         ls148 = " SPREAD=" + DoubleToStr(Spread, 2) + "   STOPLEVEL=" + DoubleToStr(MarketInfo(Symbol(), MODE_STOPLEVEL), 2) 
            + "\n Êàíàë=" + DoubleToStr(Avalanche,0) + " ä.á. > " + DoubleToStr(AvMin,0) +  " è < " + DoubleToStr(AvMax,0)
            + "\n Ìèíèìàëüíûé ëîò=" + DoubleToStr(MarketInfo(Symbol(),MODE_MINLOT), 2) 
            + "\n Äîñòóïíûå ëîòû  =" + DoubleToStr((AccountFreeMargin()-NotUsedPart) / MarketInfo(Symbol(), MODE_MARGINREQUIRED), 2) 
            + "\n 쑌֔   =" + AccountLeverage()  
            + "\n Áàëàíñ  =" + DoubleToStr(AccountBalance(), 2) + "$" 
            + "\n StopOut=" + DoubleToStr(MathMax(AccountStopoutLevel(),StopOut), 0) + "%"
            + "\n+-------------------------+" 
            + "\n Íîìåð òåêóùåãî ñ÷åòà=" + DoubleToStr(AccountNumber(), 0) 
            + "\n Íàçâàíèå êîìïàíèè=" + AccountCompany() 
            + "\n+-------------------------+";
         Comment(ls148);
      } else Comment("");
      if (New_Bar){
         //Alert("Äî begin=",begin," end=",end," top=",top," bottom=",bottom);
         if(BeginSesion == "00:00" && EndSesion == "00:00") {
            if (!EndOfFlat()) {
              //Alert("Ïî begin=",begin," end=",end," top=",top," bottom=",bottom);
              //Alert("Æäåì");
              if (!begin && !end) 
                 if ((Ask <= top) && (Bid >= bottom))
                    Message("Æäåì ïðîáîÿ êàíàëà!");
                 else Message("Æäåì íà÷àëî ôëåòà! Êàíàë =" + Avalanche + " Ñïðåä=" + Spread);
              if (begin && !end) Message("Æäåì îêîí÷àíèÿ ôëåòà!");
              return;
            }
         } else {
            if (Time[0] == StrToTime(TimeToStr(Time[0], TIME_DATE)+" "+BeginSesion)) {
               ObjectDelete("Begin");
               ObjectCreate("Begin",OBJ_VLINE,0,Time[0],0);
               ObjectSet("Begin",OBJPROP_COLOR,DarkOrchid);
            }
            if (Time[0] == StrToTime(TimeToStr(Time[0], TIME_DATE)+" "+EndSesion)) {
               ObjectDelete("End");
               ObjectCreate("End",OBJ_VLINE,0,Time[0],0);
               ObjectSet("End",OBJPROP_COLOR,DarkOrchid);
            }
            while (Time[0] < StrToTime(TimeToStr(Time[0], TIME_DATE)+" "+EndSesion)) return;
              if (StrToTime(TimeToStr(Time[0], TIME_DATE)+" "+BeginSesion) > 
                  StrToTime(TimeToStr(Time[0], TIME_DATE)+" "+EndSesion))
                 time_begin = StrToTime(TimeToStr(Time[0]-24*60*60, TIME_DATE)+" "+BeginSesion);
                 else time_begin = StrToTime(TimeToStr(Time[0], TIME_DATE)+" "+BeginSesion);
              time_end = StrToTime(TimeToStr(Time[0], TIME_DATE)+" "+EndSesion);
         }
         //Alert("Ïåðåä time_begin=",TimeToStr(time_begin,TIME_MINUTES)," time_end=",TimeToStr(time_end,TIME_MINUTES));
         if (time_begin <= Time[0] && time_end >= Time[0]) {
            top = 0;
            bottom = 100000;
            for (i = iBarShift(0,0,time_begin); i > 0; i--) {
               if (High[i] > top) top = High[i];
               if (Low[i] < bottom) bottom = Low[i];
               ObjectDelete("Top");
               ObjectCreate("Top",OBJ_HLINE,0,0,top);
               ObjectSet("Top",OBJPROP_COLOR,DarkOrchid);
               ObjectDelete("Bottom");
               ObjectCreate("Bottom",OBJ_HLINE,0,0,bottom);
               ObjectSet("Bottom",OBJPROP_COLOR,DarkOrchid);
            }
         }
         t_begin = TimeToStr(time_begin,TIME_MINUTES);
         t_end = TimeToStr(time_end,TIME_MINUTES);
   //Alert(TimeToStr(StrToTime(t_end) + Wait*60*60,TIME_MINUTES),"<",TimeToStr(Time[0],TIME_MINUTES));
         if (Wait >0)
            if (StrToTime(t_end) + Wait*60 < Time[0]) {
               reset();
               return;
            }
         //if (top > 0)
            Avalanche = NormalizeDouble(MathAbs(top-bottom)/Point,0);
         GetAvalanche();
         if (Avalanche < AvMin) {
            reset();
            return;
         }
         //if (Avalanche < AvMin || (!LimitOnlyMin && Avalanche > AvMax) || (LimitOnlyMin && Avalanche > 1.236*AvMax)) {
         if (time_end == Time[0]) {
            stop_revers = false;
            revers_work = false;
         }
         if ((!LimitOnlyMin && Avalanche > AvMax) || (LimitOnlyMin && Avalanche > 1.236*AvMax)) {
            if (!Revers) {
               reset();
               return;
            } else {
               if (top != 0) {
                  revers_work = true;
                  //Alert("total_post=",total_post," total=",total," stop_revers=",stop_revers);
                  if (total_post < 2 && total == 0 && !stop_revers) {
                     if (MathAbs(bottom - Bid) < MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
                        level_set_buy = bottom - MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;
                     else level_set_buy = bottom;
                     if (MathAbs(top - Bid) < MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
                        TP = top + MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;
                     else TP = top;
                     SetOrder(Symbol(), OP_BUYLIMIT, lots_set[0],level_set_buy , bottom - StopLoss, TP, magic);
                     if (MathAbs(top - Bid) < MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
                        level_set_sell = top + MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;
                     else level_set_sell = top;
                     if (MathAbs(bottom - Bid) < MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
                        TP = bottom - MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;
                     else TP = bottom;
                     SetOrder(Symbol(), OP_SELLLIMIT, lots_set[0],level_set_sell , top + StopLoss, TP, magic);
                  }
               }
               return;
            }
         }
         init();
      } else { 
         if (top == 0) return; 
      }
   }
   if (OrdersMax > j-2) {
      //Alert("OrdersMax=", OrdersMax," j-2=",j-2);
      return;
   }
   if (total < OrdersNoMore)
      if (total_post == 0) {
         if (total == 0) {
            if ((Ask <= top) && (Bid >= bottom)) return;
            if (Ask > top) FirstTransaction = OP_BUY;
            if (Bid < bottom) FirstTransaction = OP_SELL;
         }
         if (FirstTransaction == OP_BUY) {
           if (total == 0) {
               level_set_buy = Ask;
               level_set_sell = Ask - Avalanche*Point;
               SL = Bid - StopLoss;
               TP = Ask + TakeProfit*Point;
               OpenPosition(Symbol(), OP_BUY, lots_set[total], SL, TP, magic);
           } else {
               if (New_Bar) 
                  if (MathMod(total,2) == 1) {
                    SL = level_set_sell + Spread*Point + StopLoss;
                    TP = level_set_sell - TakeProfit*Point;
                    SetOrder(Symbol(), OP_SELLSTOP, lots_set[total],level_set_sell , SL, TP, magic);
                  } else {
                    SL = level_set_buy - Spread*Point - StopLoss;
                    TP = level_set_buy + TakeProfit*Point;
                    SetOrder(Symbol(), OP_BUYSTOP, lots_set[total],level_set_buy , SL, TP, magic);
                  }
           }
         } else {
           if (total == 0) {
               level_set_buy = Bid + Avalanche*Point;
               level_set_sell = Bid;
               SL = Ask + StopLoss;
               TP = Bid - TakeProfit*Point;
               OpenPosition(Symbol(), OP_SELL, lots_set[total], SL, TP, magic);
           } else {
               if (New_Bar) 
                  if (MathMod(total,2) == 1) {
                    SL = level_set_buy - Spread*Point - StopLoss;
                    TP = level_set_buy + TakeProfit*Point;
                    SetOrder(Symbol(), OP_BUYSTOP, lots_set[total],level_set_buy , SL, TP, magic);
                  } else {
                    SL = level_set_sell + Spread*Point + StopLoss;
                    TP = level_set_sell - TakeProfit*Point;
                    SetOrder(Symbol(), OP_SELLSTOP, lots_set[total],level_set_sell , SL, TP, magic);
                  }
           }
         }
      }
   
   if (comment_yes) {
      ls148 = " Avalanche=" + DoubleToStr(Avalanche,0) + "   TakeProfit=" + DoubleToStr(TakeProfit,0) + "   SPREAD=" + DoubleToStr(Spread, 2) + "   STOPLEVEL=" + DoubleToStr(MarketInfo(Symbol(), MODE_STOPLEVEL), 2) 
         + "\n Ñåññèÿ ñ " + t_begin + " äî " + t_end 
         + "\n Îòêðûòî îðäåðîâ=" + ord_count
         + "\n Ïåðâûé ëîò=" + DoubleToStr(lots_open, 2) + ",  Äîñòóïíûå ëîòû=" + DoubleToStr((AccountFreeMargin()-NotUsedPart) / MarketInfo(Symbol(), MODE_MARGINREQUIRED), 2) 
         + "\n Ìàðæà îòêðûòûõ ïîçèöèé=" + DoubleToStr(AccountMargin(), 0) 
         + "\n+-------------------------+" 
         + "\n Áàëàíñ=" + DoubleToStr(AccountBalance(), 2) + "$" 
         + "\n Ýêâèòè=" + DoubleToStr(AccountEquity(), 2) + "$" 
         + "\n Ìèíèìàëüíûé ëîò=" + DoubleToStr(MarketInfo(Symbol(),MODE_MINLOT), 2)
         + "\n 쑌֔=" + AccountLeverage()  
         + "\n StopOut=" + DoubleToStr(MathMax(AccountStopoutLevel(),StopOut), 0) + "%" 
         + "\n Íîìåð òåêóùåãî ñ÷åòà=" + DoubleToStr(AccountNumber(), 0) 
         + "\n Íàçâàíèå êîìïàíèè=" + AccountCompany() 
         + "\n+-------------------------+";
      Comment(ls148);
   } else Comment("");
   return (0);
}

//+------------------------------------------------------------------+
void Fun_New_Bar()                              // Ô-èÿ îáíàðóæåíèÿ íîâîãî áàðà
  {                                             
   New_Bar=false;                               // Íîâîãî áàðà íåò
   if(New_Time!=Time[0])                        // Ñðàâíèâàåì âðåìÿ
     {
      New_Time=Time[0];                         // Òåïåðü âðåìÿ òàêîå
      New_Bar=true;                             // Ïîéìàëñÿ íîâûé áàð  
     }
  }

bool ExistPositions(string as0 = "", int acmd_8 = -1, int amagic_12 = -1, int ai16 = 0) {
   int lord_total_24 = OrdersTotal();
   if (as0 == "0") as0 = Symbol();
   for (int lpos_20 = 0; lpos_20 < lord_total_24; lpos_20++) {
      if (OrderSelect(lpos_20, SELECT_BY_POS, MODE_TRADES)) {
         if (OrderSymbol() == as0 || as0 == "") {
            if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
               if (acmd_8 < OP_BUY || OrderType() == acmd_8) {
                  if (amagic_12 < 0 || OrderMagicNumber() == amagic_12)
                     if (ai16 <= OrderOpenTime()) return (TRUE);
               }
            }
         }
      }
   }
   return (FALSE);
}

void OpenPosition(string asymbol_0, int acmd_8, double ad_12, double aprice_20 = 0.0, double aprice_28 = 0.0, int amagic_36 = 0) {
   color lcolor_40;
   int ldatetime_44;
   double lprice_48;
   double lask_56;
   double lbid_64;
   int ldigits_72;
   int lerror_76;
   int lticket_84 = 0;
   string lcomment_88 = WindowExpertName() + " " + GetNameTF(Period());
   if (asymbol_0 == "" || asymbol_0 == "0") asymbol_0 = Symbol();
   if (acmd_8 == OP_BUY) lcolor_40 = color_buy;
   else lcolor_40 = color_sell;
   for (int li80 = 1; li80 <= attempt; li80++) {
      if (!IsTesting() && IsStopped()) {
         Print("OpenPosition(): Îñòàíîâêà ðàáîòû ôóíêöèè");
         return;
      }
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      ldigits_72 = MarketInfo(asymbol_0, MODE_DIGITS);
      lask_56 = MarketInfo(asymbol_0, MODE_ASK);
      lbid_64 = MarketInfo(asymbol_0, MODE_BID);
      if (acmd_8 == OP_BUY) lprice_48 = lask_56;
      else lprice_48 = lbid_64;
      lprice_48 = NormalizeDouble(lprice_48, ldigits_72);
      ldatetime_44 = TimeCurrent();
      if (AccountFreeMarginCheck(Symbol(), acmd_8, ad_12) <= 0.0 || GetLastError() == 134/* NOT_ENOUGH_MONEY */) {
         Alert(Symbol(),":Äëÿ îòêðûòèÿ ïîçèöèè ", GetNameOP(acmd_8), ", Ëîòîì=", ad_12, ", ñâîáîäíûõ ñðåäñòâ íå õâàòàåò.");
         return;
      }
      lticket_84 = OrderSend(asymbol_0, acmd_8, ad_12, lprice_48, gslippage, aprice_20, aprice_28, lcomment_88, amagic_36, 0, lcolor_40);
      if (lticket_84 > 0) {
         //Alert(Symbol(),":Îòêðûëè îðäåð ", GetNameOP(acmd_8), " Ëîòîì=",ad_12);
         time_order = Time[0];
         if (!(sound_yes)) break;
         PlaySound(ok_wav);
         return;
      }
      lerror_76 = GetLastError();
      if (lask_56 == 0.0 && lbid_64 == 0.0) Message("Ïðîâåðüòå â Îáçîðå ðûíêà íàëè÷èå ñèìâîëà " + asymbol_0);
      Print("Error(", lerror_76, ") opening position: ", ErrorDescription(lerror_76), ", try ", li80);
      Print("Ask=", lask_56, " Bid=", lbid_64, " sy=", asymbol_0, " ll=", ad_12, " op=", GetNameOP(acmd_8), " pp=", DoubleToStr(lprice_48,5), " sl=", aprice_20, " tp=", aprice_28, " mn=", amagic_36);
      if (lerror_76 == 2/* COMMON_ERROR */ || lerror_76 == 64/* ACCOUNT_DISABLED */ || lerror_76 == 65/* INVALID_ACCOUNT */ || lerror_76 == 133/* TRADE_DISABLED */) {
         massege_yes = TRUE;
         return;
      }
      if (lerror_76 == 4/* SERVER_BUSY */ || lerror_76 == 131/* INVALID_TRADE_VOLUME */ || lerror_76 == 132/* MARKET_CLOSED */) {
         Sleep(300000);
         return;
      }
      if (lerror_76 == 128/* TRADE_TIMEOUT */ || lerror_76 == 142 || lerror_76 == 143) {
         Sleep(66666.0);
         if (ExistPositions(asymbol_0, acmd_8, amagic_36, ldatetime_44)) {
            if (!(sound_yes)) break;
            PlaySound(ok_wav);
            return;
         }
      }
      if (lerror_76 == 140/* LONG_POSITIONS_ONLY_ALLOWED */ || lerror_76 == 148/* ERR_TRADE_TOO_MANY_ORDERS */ || lerror_76 == 4110/* LONGS__NOT_ALLOWED */ || lerror_76 == 4111/* SHORTS_NOT_ALLOWED */) break;
      if (lerror_76 == 141/* TOO_MANY_REQUESTS */) Sleep(100000);
      if (lerror_76 == 145/* TRADE_MODIFY_DENIED */) Sleep(17000);
      if (lerror_76 == 146/* TRADE_CONTEXT_BUSY */) while (IsTradeContextBusy()) Sleep(11000);
      if (lerror_76 != 135/* PRICE_CHANGED */) Sleep(7700.0);
   }
}

string GetNameOP(int ai0) {
   switch (ai0) {
   case 0:
      return ("Buy");
   case 1:
      return ("Sell");
   case 2:
      return ("BuyLimit");
   case 3:
      return ("SellLimit");
   case 4:
      return ("BuyStop");
   case 5:
      return ("SellStop");
   }
   return ("Unknown Operation");
}

string GetNameTF(int atimeframe_0 = 0) {
   if (atimeframe_0 == 0) atimeframe_0 = Period();
   switch (atimeframe_0) {
   case PERIOD_M1:
      return ("M1");
   case PERIOD_M5:
      return ("M5");
   case PERIOD_M15:
      return ("M15");
   case PERIOD_M30:
      return ("M30");
   case PERIOD_H1:
      return ("H1");
   case PERIOD_H4:
      return ("H4");
   case PERIOD_D1:
      return ("Daily");
   case PERIOD_W1:
      return ("Weekly");
   case PERIOD_MN1:
      return ("Monthly");
   }
   return ("UnknownPeriod");
}

void Message(string as0) {
   Comment(as0);
}
void CloseAllPos() {
   int lord_total_22 = OrdersTotal();
   int lord_total_24 = lord_total_22;
   for (int lpos_18 = lord_total_22 - 1; lpos_18 >= 0; lpos_18--) {
      if (OrderSelect(lpos_18, SELECT_BY_POS, MODE_TRADES)) {
         if (OrderType()>1) DeleteOrders();
         else {
           ClosePosBySelect();
           lord_total_24--;
         }
      }
   }
   if (lord_total_24 == 0) return;
} 
void DelPostPos() {
   int lord_total_22 = OrdersTotal();
   int lord_total_24 = lord_total_22;
   for (int lpos_18 = lord_total_22 - 1; lpos_18 >= 0; lpos_18--)
      if (OrderSelect(lpos_18, SELECT_BY_POS, MODE_TRADES))
         if (OrderType()>1) DeleteOrders();
   if (lord_total_24 == 0) return;
} 

void ClosePosBySelect() {
   bool lord_close_0;
   color lcolor_4;
   double lord_lots_8;
   double ld16;
   double ld24;
   double lprice_32;
   int lerror_40;
   if (OrderType() == OP_BUY || OrderType() == OP_SELL) {
      for (int li44 = 1; li44 <= attempt; li44++) {
         if (!IsTesting() && !IsExpertEnabled() || IsStopped()) break;
         while (!IsTradeAllowed()) Sleep(5000);
         RefreshRates();
         ld16 = NormalizeDouble(MarketInfo(OrderSymbol(), MODE_ASK), Digits);
         ld24 = NormalizeDouble(MarketInfo(OrderSymbol(), MODE_BID), Digits);
         if (OrderType() == OP_BUY) {
            lprice_32 = ld24;
            lcolor_4 = color_close_buy;
         } else {
            lprice_32 = ld16;
            lcolor_4 = color_close_sell;
         }
         lord_lots_8 = OrderLots();
         lord_close_0 = OrderClose(OrderTicket(), lord_lots_8, lprice_32, gslippage, lcolor_4);
         if (lord_close_0) {
            if (!(sound_yes)) break;
            PlaySound(news_wav);
            return;
         }
         lerror_40 = GetLastError();
         if (lerror_40 == 146/* TRADE_CONTEXT_BUSY */) while (IsTradeContextBusy()) Sleep(11000);
         Print("Error(", lerror_40, ") Close ", GetNameOP(OrderType()), " ", ErrorDescription(lerror_40), ", try ", li44);
         Print(OrderTicket(), "  Ask=", ld16, "  Bid=", ld24, "  pp=", lprice_32);
         Print("sy=", OrderSymbol(), "  ll=", lord_lots_8, "  sl=", OrderStopLoss(), "  tp=", OrderTakeProfit(), "  mn=", OrderMagicNumber());
         Sleep(5000);
      }
   } else Print("Íåêîððåêòíàÿ òîðãîâàÿ îïåðàöèÿ. Close ", GetNameOP(OrderType()));
}

bool ExistOrders(string as0 = "", int acmd_8 = -1, int amagic_12 = -1, int ai16 = 0) {
   int lcmd_28;
   int lord_total_24 = OrdersTotal();
   if (as0 == "0") as0 = Symbol();
   for (int lpos_20 = 0; lpos_20 < lord_total_24; lpos_20++) {
      if (OrderSelect(lpos_20, SELECT_BY_POS, MODE_TRADES)) {
         lcmd_28 = OrderType();
         if (lcmd_28 > OP_SELL && lcmd_28 < 6) {
            if (OrderSymbol() == as0 || as0 == "" && acmd_8 < OP_BUY || lcmd_28 == acmd_8) {
               if (amagic_12 < 0 || OrderMagicNumber() == amagic_12)
                  if (ai16 <= OrderOpenTime()) return (TRUE);
            }
         }
      }
   }
   return (FALSE);
}

void SetOrder(string asymbol_0, int acmd_8, double ad_12, double aprice_20, double aprice_28 = 0.0, double aprice_36 = 0.0, int amagic_44 = 0, int adatetime_48 = 0) {
   color lcolor_52;
   int ldatetime_56;
   double lask_60;
   double lbid_68;
   double lpoint_76;
   int ldigits_72;
   int lerror_84;
   int lticket_92;
   int lcmd_100;
   string lcomment_104 = WindowExpertName() + " " + GetNameTF(Period());
   if (asymbol_0 == "" || asymbol_0 == "0") asymbol_0 = Symbol();
   int lstoplevel_96 = MarketInfo(asymbol_0, MODE_STOPLEVEL);
   if (acmd_8 == OP_BUYLIMIT || acmd_8 == OP_BUYSTOP) {
      lcolor_52 = RoyalBlue;
      lcmd_100 = 0;
   } else {
      lcolor_52 = MediumOrchid;
      lcmd_100 = 1;
   }
   if (adatetime_48 > 0 && adatetime_48 < TimeCurrent()) adatetime_48 = 0;
   for (int li_88 = 1; li_88 <= attempt; li_88++) {
      if (!IsTesting() && !IsExpertEnabled() || IsStopped()) {
         Print("SetOrder(): Îñòàíîâêà ðàáîòû ôóíêöèè");
         return;
      }
      while (!IsTradeAllowed()) Sleep(5000);
      RefreshRates();
      ldigits_72 = MarketInfo(asymbol_0, MODE_DIGITS);
      ldatetime_56 = TimeCurrent();
      if (AccountFreeMarginCheck(Symbol(), lcmd_100, ad_12) <= 0.0 || GetLastError() == 134/* NOT_ENOUGH_MONEY */) {
         Alert(Symbol(),":Äëÿ îòêðûòèÿ îòëîæåííîé ïîçèöèè ", GetNameOP(acmd_8), ", Ëîòîì=", DoubleToStr(ad_12,2), ", ñâîáîäíûõ ñðåäñòâ íå õâàòàåò.");
         CloseAllPos();
         flag_pp = false;
         reset();
         return;
      }
      aprice_20 = NormalizeDouble(aprice_20, ldigits_72);
      lticket_92 = OrderSend(asymbol_0, acmd_8, ad_12, aprice_20, gslippage, aprice_28, aprice_36, lcomment_104, amagic_44, adatetime_48, lcolor_52);
      if (lticket_92 > 0) {
         //Alert(Symbol(),":Îòêðûëè îòëîæåííûé îðäåð ", GetNameOP(acmd_8), " Ëîòîì=",ad_12);
         if (!(sound_yes)) break;
         PlaySound(expert_wav);
         return;
      }
      lerror_84 = GetLastError();
      if (lerror_84 == 128/* TRADE_TIMEOUT */ || lerror_84 == 142 || lerror_84 == 143) {
         Sleep(66000);
         if (ExistOrders(asymbol_0, acmd_8, amagic_44, ldatetime_56)) {
            if (!(sound_yes)) break;
            PlaySound(expert_wav);
            return;
         }
         Print("Error(", lerror_84, ") set order: ", ErrorDescription(lerror_84), ", try ", li_88);
      } else {
         lpoint_76 = MarketInfo(asymbol_0, MODE_POINT);
         lask_60 = MarketInfo(asymbol_0, MODE_ASK);
         lbid_68 = MarketInfo(asymbol_0, MODE_BID);
         if (lerror_84 == 130/* INVALID_STOPS */) {
            switch (acmd_8) {
            case OP_BUYLIMIT:
               if (aprice_20 > lask_60 - lstoplevel_96 * lpoint_76) aprice_20 = lask_60 - lstoplevel_96 * lpoint_76;
               if (aprice_28 > aprice_20 - (lstoplevel_96 + 1) * lpoint_76) aprice_28 = aprice_20 - (lstoplevel_96 + 1) * lpoint_76;
               if (aprice_36 > 0.0 && aprice_36 < aprice_20 + (lstoplevel_96 + 1) * lpoint_76) aprice_36 = aprice_20 + (lstoplevel_96 + 1) * lpoint_76;
               break;
            case OP_BUYSTOP:
               if (aprice_20 < lask_60 + (lstoplevel_96 + 1) * lpoint_76) aprice_20 = lask_60 + (lstoplevel_96 + 1) * lpoint_76;
               if (aprice_28 > aprice_20 - (lstoplevel_96 + 1) * lpoint_76) aprice_28 = aprice_20 - (lstoplevel_96 + 1) * lpoint_76;
               if (aprice_36 > 0.0 && aprice_36 < aprice_20 + (lstoplevel_96 + 1) * lpoint_76) aprice_36 = aprice_20 + (lstoplevel_96 + 1) * lpoint_76;
               break;
            case OP_SELLLIMIT:
               if (aprice_20 < lbid_68 + lstoplevel_96 * lpoint_76) aprice_20 = lbid_68 + lstoplevel_96 * lpoint_76;
               if (aprice_28 > 0.0 && aprice_28 < aprice_20 + (lstoplevel_96 + 1) * lpoint_76) aprice_28 = aprice_20 + (lstoplevel_96 + 1) * lpoint_76;
               if (aprice_36 > aprice_20 - (lstoplevel_96 + 1) * lpoint_76) aprice_36 = aprice_20 - (lstoplevel_96 + 1) * lpoint_76;
               break;
            case OP_SELLSTOP:
               if (aprice_20 > lbid_68 - lstoplevel_96 * lpoint_76) aprice_20 = lbid_68 - lstoplevel_96 * lpoint_76;
               if (aprice_28 > 0.0 && aprice_28 < aprice_20 + (lstoplevel_96 + 1) * lpoint_76) aprice_28 = aprice_20 + (lstoplevel_96 + 1) * lpoint_76;
               if (aprice_36 > aprice_20 - (lstoplevel_96 + 1) * lpoint_76) aprice_36 = aprice_20 - (lstoplevel_96 + 1) * lpoint_76;
            }
            Print("SetOrder(): Ñêîððåêòèðîâàíû öåíîâûå óðîâíè");
         }
         Print("Error(", lerror_84, ") set order: ", ErrorDescription(lerror_84), ", try ", li_88);
         Print("Ask=", lask_60, "  Bid=", lbid_68, "  sy=", asymbol_0, "  ll=", ad_12, "  op=", GetNameOP(acmd_8), "  pp=", aprice_20, "  sl=", aprice_28, "  tp=", aprice_36, "  mn=", amagic_44);
         if (lask_60 == 0.0 && lbid_68 == 0.0) Message("SetOrder(): Ïðîâåðüòå â îáçîðå ðûíêà íàëè÷èå ñèìâîëà " + asymbol_0);
         if (lerror_84 == 2/* COMMON_ERROR */ || lerror_84 == 64/* ACCOUNT_DISABLED */ || lerror_84 == 65/* INVALID_ACCOUNT */ || lerror_84 == 133/* TRADE_DISABLED */) {
            massege_yes = TRUE;
            return;
         }
         if (lerror_84 == 4/* SERVER_BUSY */ || lerror_84 == 131/* INVALID_TRADE_VOLUME */ || lerror_84 == 132/* MARKET_CLOSED */) {
            Sleep(300000);
            return;
         }
         if (lerror_84 == 8/* TOO_FREQUENT_REQUESTS */ || lerror_84 == 141/* TOO_MANY_REQUESTS */) Sleep(100000);
         if (lerror_84 == 139/* ORDER_LOCKED */ || lerror_84 == 140/* LONG_POSITIONS_ONLY_ALLOWED */ || lerror_84 == 148/* ERR_TRADE_TOO_MANY_ORDERS */) break;
         if (lerror_84 == 146/* TRADE_CONTEXT_BUSY */) while (IsTradeContextBusy()) Sleep(11000);
         if (lerror_84 == 147/* ERR_TRADE_EXPIRATION_DENIED */) adatetime_48 = 0;
         else
            if (lerror_84 != 135/* PRICE_CHANGED */ && lerror_84 != 138/* REQUOTE */) Sleep(7700.0);
      }
   }
}

void DeleteOrders(string as0 = "", int acmd_8 = -1, int amagic_12 = -1) {
   bool lord_delete_16;
   int lerror_20;
   int lcmd_36;
   int l_ord_total_32 = OrdersTotal();
   if (as0 == "0") as0 = Symbol();
   for (int lpos_24 = l_ord_total_32 - 1; lpos_24 >= 0; lpos_24--) {
      if (OrderSelect(lpos_24, SELECT_BY_POS, MODE_TRADES)) {
         lcmd_36 = OrderType();
         if (lcmd_36 > OP_SELL && lcmd_36 < 6) {
            if (OrderSymbol() == as0 || as0 == "" && acmd_8 < OP_BUY || lcmd_36 == acmd_8) {
               if (amagic_12 < 0 || OrderMagicNumber() == amagic_12) {
                  for (int li_28 = 1; li_28 <= attempt; li_28++) {
                     if (!IsTesting() && !IsExpertEnabled() || IsStopped()) break;
                     while (!IsTradeAllowed()) Sleep(5000);
                     lord_delete_16 = OrderDelete(OrderTicket(), MediumAquamarine);
                     if (lord_delete_16) {
                        if (!(sound_yes)) break;
                        PlaySound(expert_wav);
                        break;
                     }
                     lerror_20 = GetLastError();
                     Print("Error(", lerror_20, ") delete order ", GetNameOP(lcmd_36), ": ", ErrorDescription(lerror_20), ", try ", li_28);
                     Sleep(5000);
                  }
               }
            }
         }
      }
   }
}

void GetAvalanche(int per=240, int hist=30) {
  double x = 0;
  double n = 0;
  for (int i=hist; i>0; i--) {
    n+=MathAbs(iOpen(0,per,i)-iClose(0,per,i));
    x+=iHigh(0,per,i)-iLow(0,per,i);
  }
  AvMin=NormalizeDouble(n/hist/Point,0);
  AvMax=NormalizeDouble(x/hist/Point,0);
}

double Silense(int bar, int per=12, int hist=288) {
  double MAX=0,
         MIN=1000, B;
  for (int i=hist; i>=0; i--) {
    B=0;
    for(int x=i+per-1+bar; x>=i+bar; x--) { 
       if(Close[x]>Open[x]) {
          //áåëàÿ ñâå÷à
          B=B+(Close[x]-Close[x+1]);
       } else {
          //÷¸ðíàÿ ñâå÷à
          B=B+(Close[x+1]-Close[x]);
       }
    }
    B=B/Point/MyPeriod;
    if (B > MAX) MAX=B;
    if (B < MIN) MIN=B;
    if (i==0) B=Èíòåðïîëÿöèÿ(MAX,MIN,100,0,B);
  }
  return(B);
}

double Èíòåðïîëÿöèÿ (double a,double b,double c,double d,double X) {
//a; X; b - ñòîëáåö èçâåòíûõ ÷èñåë, c; d; - ñòîëáåö ñî ñòîðîíû íåèçâåñòíîé.
  if (b - a == 0)
     return(10000000); //áåñêîíå÷íîñòü
  else
     return(d - (b - X) * (d - c) / (b - a));
}//Èíòåðïîëÿöèÿ

void reset() {
   ord_count=0;
   end = false;
   begin = false;
   top = 0;
   bottom = 100000;
}

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