
#property copyright "Copyright © 2008, Leurn"
#property link      "leurnforex@mail.ru"

extern string FridayTimeToSet = "22:50";
extern bool WaitNewBarAtStart = TRUE;

 extern double  Risk           = 1;        // Процент использ. от макс.возм.лотa (от депозита) на одну сделку
                                           // если 0- работать фиксированным лотом Lot
 extern double  MaxLt          = 2.0;      // Максимальный допустимый лот при авторасчёте лота ( Risk>0 )                                        
 extern double  Lot            = 0.1;      // Фиксированный лот

extern int TakeProfit = 150;
extern int StopLoss = 5;
extern int TrailStop = 20;
extern int TrailStep = 5;
extern string OrdersComment = "Cerpiy";
int G_pos_120;
int G_magic_124;
int G_stoplevel_128;
int G_spread_132;
double G_price_144;
double G_price_152;
double Gd_160;
double Gd_168;
double G_price_184;
double G_price_192;
string G_comment_200;
bool Gi_208;
bool Gi_212;
bool Gi_216;
bool Gi_220;
bool Gi_224;
bool Gi_228;
int G_datetime_232;
int G_str2time_236;
double Lots,Max_Lot,Min_Lot,One_Lot,Free,Step,Balance,Credit,Equity;

int init() {
   Min_Lot=MarketInfo(_Symbol,MODE_MINLOT);
   Max_Lot=MarketInfo(_Symbol,MODE_MAXLOT);
   if(Lot<Min_Lot){Alert("Старт. лот установлен меньше минимального значения");return(0);}
   G_magic_124 = StringGetChar(Symbol(), 0) + 61008 + StringGetChar(Symbol(), 1) * 2 + 3 * StringGetChar(Symbol(), 3) + StringGetChar(Symbol(), 4) * 4;
   Gi_212 = FALSE;
   G_datetime_232 = 0;
   G_price_184 = 0;
   G_price_192 = 0;
   G_comment_200 = OrdersComment + " Magic#=" + G_magic_124;
   return (0);
}

int deinit(){Comment("");return (0);}
int start() {
   if (!IsTesting()) {
      if (!IsExpertEnabled()) {
         Comment("В торговом терминале запрещён запуск экспертов.");
         return (0);
      }
      if (!IsTradeAllowed()) {
         Comment("Торговля запрещена или торговый поток занят.");
         return (0);
      }
      
      Comment("");
   }
   G_stoplevel_128 = MarketInfo(Symbol(), MODE_STOPLEVEL);
   G_spread_132 = MarketInfo(Symbol(), MODE_SPREAD);
   G_str2time_236 = StrToTime(FridayTimeToSet);
   Step=MarketInfo(_Symbol,MODE_LOTSTEP);
   Balance=NormalizeDouble(AccountBalance(),2);
   Equity=NormalizeDouble(AccountEquity(),2);
   Credit=NormalizeDouble(AccountCredit(),2);
   Free=NormalizeDouble(AccountFreeMargin(),2);
   One_Lot=NormalizeDouble(MarketInfo(_Symbol,MODE_MARGINREQUIRED),_Digits);
   if(Risk>0){if((Balance+Credit)>0){
   if(One_Lot>0){Lots=MathFloor((Free/One_Lot)/Step)*Step/100.0*Risk;}}
   if(Lots>MaxLt)Lots=MaxLt;} else Lots=Lot;
   if(Lots>Max_Lot)Lots=Max_Lot;
   if (!WaitNewBarAtStart) Gi_208 = TRUE;
   else {
      if (DayOfWeek() == 5) {
         if (G_datetime_232 == 0) G_datetime_232 = iTime(NULL, PERIOD_D1, 0);
         if (G_datetime_232 < iTime(NULL, PERIOD_D1, 0)) Gi_208 = TRUE;
         else {
            if (G_datetime_232 == iTime(NULL, PERIOD_D1, 0) && TimeCurrent() >= G_str2time_236) Gi_208 = TRUE;
            else Gi_208 = FALSE;
         }
      } else {
         if (G_datetime_232 == 0) G_datetime_232 = iTime(NULL, PERIOD_D1, 0);
         if (G_datetime_232 < iTime(NULL, PERIOD_D1, 0)) Gi_208 = TRUE;
         else Gi_208 = FALSE;
      }
   }
   if (Gi_208 && (!Gi_212) && G_price_184 == 0.0 && G_price_192 == 0.0) {
      if (DayOfWeek() == 5 && TimeCurrent() >= G_str2time_236) {
         G_price_184 = NormalizeDouble(iHigh(NULL, PERIOD_D1, 0) + G_spread_132 * Point, Digits);
         G_price_192 = NormalizeDouble(iLow(NULL, PERIOD_D1, 0), Digits);
      } else {
         G_price_184 = NormalizeDouble(iHigh(NULL, PERIOD_D1, 1) + G_spread_132 * Point, Digits);
         G_price_192 = NormalizeDouble(iLow(NULL, PERIOD_D1, 1), Digits);
      }
   }
   if (!Gi_212 && Ask + G_stoplevel_128 * Point > G_price_184 && G_price_184 > 0.0) {
      Comment("УРОВЕНЬ ОРДЕРА BUYSTOP - ", DoubleToStr(G_price_184, Digits), " СЛИШКОМ БЛИЗОК К ТЕКУЩЕЙ ЦЕНЕ!!!");
      return (0);
   }
   if (!Gi_212 && Bid - G_stoplevel_128 * Point < G_price_192 && G_price_192 > 0.0) {
      Comment("УРОВЕНЬ ОРДЕРА SELLSTOP - ", DoubleToStr(G_price_192, Digits), " СЛИШКОМ БЛИЗОК К ТЕКУЩЕЙ ЦЕНЕ!!!");
      return (0);
   }
   Comment("");
   Gi_216 = FALSE;
   Gi_220 = FALSE;
   for (G_pos_120 = OrdersTotal() - 1; G_pos_120 >= 0; G_pos_120--) {bool mod;
      if(OrderSelect(G_pos_120, SELECT_BY_POS)){
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != G_magic_124 || OrderType()!= OP_SELL) continue;
      if (OrderType() == OP_SELL) {
         Gi_220 = TRUE;
         if (TrailStop >= G_stoplevel_128) {
            if (OrderOpenPrice() - Ask > TrailStop * Point && (OrderStopLoss() > OrderOpenPrice() || OrderStopLoss() == 0.0)) {
               mod=OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, CLR_NONE);
               continue;
            }
            if (OrderOpenPrice() - Ask > TrailStop * Point && OrderStopLoss() > Ask + (TrailStop + TrailStep) * Point && OrderStopLoss() <= OrderOpenPrice()) 
            mod=OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(Ask + TrailStop * Point, Digits), OrderTakeProfit(), 0, CLR_NONE);
         }
      } else {
         if (OrderType() == OP_BUY) {
            Gi_216 = TRUE;
            if (TrailStop >= G_stoplevel_128) {
               if (Bid - OrderOpenPrice() > TrailStop * Point && OrderStopLoss() < OrderOpenPrice()) {
                  mod=OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, CLR_NONE);
                  continue;
               }
               if (Bid - OrderOpenPrice() > TrailStop * Point && OrderStopLoss() < Bid - (TrailStop + TrailStep) * Point && OrderStopLoss() >= OrderOpenPrice()) 
              mod= OrderModify(OrderTicket(), OrderOpenPrice(), NormalizeDouble(Bid - TrailStop * Point, Digits), OrderTakeProfit(), 0, CLR_NONE);
            }
         }}
      }
   }
   Gi_224 = FALSE;
   Gi_228 = FALSE;
   for (G_pos_120 = OrdersTotal() - 1; G_pos_120 >= 0; G_pos_120--) {bool del;
      if(OrderSelect(G_pos_120, SELECT_BY_POS)){
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != G_magic_124 || OrderType() <= OP_SELL) continue;
      if (OrderType() == OP_SELLSTOP) {
         if (Gi_216) {
            del=OrderDelete(OrderTicket());
            continue;
         }
         Gi_228 = TRUE;
      } else {
         if (OrderType() == OP_BUYSTOP) {
            if (Gi_220) {
               del=OrderDelete(OrderTicket());
               continue;
            }
            Gi_224 = TRUE;
         }
      }
   }}
   if (Gi_228 && Gi_224) {
      Gi_212 = TRUE;
      G_datetime_232 = iTime(NULL, PERIOD_D1, 0);
   }
   if (Gi_212 && (!Gi_220) && (!Gi_228) && (!Gi_216) && (!Gi_224)) {
      Gi_212 = FALSE;
      G_price_184 = 0;
      G_price_192 = 0;
      return (0);
   }
   RefreshRates();
   if ((!Gi_216) && !Gi_224 && Gi_208 && (!Gi_212)) {int tic;
      if (StopLoss < G_stoplevel_128 + G_spread_132) G_price_144 = G_price_192;
      else G_price_144 = NormalizeDouble(G_price_184 - StopLoss * Point, Digits);
      if (TakeProfit < G_stoplevel_128 - G_spread_132 || TakeProfit == 0) G_price_152 = 0;
      else G_price_152 = NormalizeDouble(G_price_184 + TakeProfit * Point, Digits);
      tic=OrderSend(Symbol(), OP_BUYSTOP, Lots, G_price_184, 0, G_price_144, G_price_152, G_comment_200, G_magic_124, 0, Red);
   }
   if ((!Gi_220) && !Gi_228 && Gi_208 && (!Gi_212)) {
      if (StopLoss < G_stoplevel_128 + G_spread_132) G_price_144 = G_price_184;
      else G_price_144 = NormalizeDouble(G_price_192 + StopLoss * Point, Digits);
      if (TakeProfit < G_stoplevel_128 - G_spread_132 || TakeProfit == 0) G_price_152 = 0;
      else G_price_152 = NormalizeDouble(G_price_192 - TakeProfit * Point, Digits);
      tic=OrderSend(Symbol(), OP_SELLSTOP,Lots, G_price_192, 0, G_price_144, G_price_152, G_comment_200, G_magic_124, 0, Blue);
   }
   return (0);
}
