extern double Exp = 1.3;
extern int Interval = 20;
extern int TakeProfit = 20;
extern int Equity_per_lot = 10000;
extern int MaxTrades = 40;
extern double Rub_per_Usd = 40.0;
extern bool Comment_for_cent = true;
int LimitOrders = 99999999;
int timeprev, In, Tp, OrdTot, DateTime;
double ordprof, l, bl, sl, b, s, PriceLot, Count, SwapCom, AverageBuyPrice, PriceBuyTarget, 
AverageSellPrice, PriceSellTarget, Balance, ordprof1, ordprof2, ordprof3, Deposit, Withdraw;

int start() {
   if (timeprev == Time[0]) return (0);
   timeprev = Time[0];
   In = Interval; Tp = TakeProfit;
   if (In < MarketInfo(Symbol(), 14)) In = MarketInfo(Symbol(), 14);
   if (Tp < MarketInfo(Symbol(), 14)) Tp = MarketInfo(Symbol(), 14);
   for (int cnt = 0; cnt<OrdersTotal(); cnt++) {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if (TimeCurrent() > OrderOpenTime() + 31557600) {
         if (OrderSymbol() == Symbol()) { 
            if (OrderType() == OP_BUY) {
               RefreshRates();
               OrderClose(OrderTicket(), OrderLots(), Bid, In, White);
            }
            if (OrderType() == OP_SELL) {
               RefreshRates();
               OrderClose(OrderTicket(), OrderLots(), Ask, In, White);
            }
         }
      }
      ordprof = 0;
      ordprof = OrderProfit() + OrderSwap() + OrderCommission();
      if (OrderMagicNumber() != In && ordprof > 0) {
         if (OrderSymbol() == Symbol()) { 
            if (OrderType() == OP_BUY) {
               RefreshRates();
               OrderClose(OrderTicket(), OrderLots(), Bid, In, White);
            }
            if (OrderType() == OP_SELL) {
               RefreshRates();
               OrderClose(OrderTicket(), OrderLots(), Ask, In, White);
            }
         }
      }
   }
   if (DayOfWeek() == 5 && Hour() == 21) {
      for (cnt = 0; cnt<OrdersTotal(); cnt++) {
         ordprof = 0;
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         ordprof = OrderProfit() + OrderSwap() + OrderCommission();
         if (ordprof > 0) {
            if (OrderSymbol() == Symbol()) { 
               if (OrderType() == OP_BUY) {
                  RefreshRates();
                  OrderClose(OrderTicket(), OrderLots(), Bid, In, White);
               }
               if (OrderType() == OP_SELL) {
                  RefreshRates();
                  OrderClose(OrderTicket(), OrderLots(), Ask, In, White);
               }
            }
         }
      }
   }
   l = MathFloor(AccountEquity() / Equity_per_lot) * MarketInfo(Symbol(), 24);
   if (l < MarketInfo(Symbol(), 23)) l = MarketInfo(Symbol(), 23);
   if (l > MarketInfo(Symbol(), 25)) l = MarketInfo(Symbol(), 25);
   bl = NormalizeDouble(l * MathPow(Exp, CountBuyTrades()), 2);
   if (bl < MarketInfo(Symbol(), 23)) bl = MarketInfo(Symbol(), 23);
   if (bl > MarketInfo(Symbol(), 25)) bl = MarketInfo(Symbol(), 25);
   sl = NormalizeDouble(l * MathPow(Exp, CountSellTrades()), 2);
   if (sl < MarketInfo(Symbol(), 23)) sl = MarketInfo(Symbol(), 23);
   if (sl > MarketInfo(Symbol(), 25)) sl = MarketInfo(Symbol(), 25);
   if (CountBuyTrades() > 0) b = FindLastBuyPrice() - In * Point;
   if (AccountFreeMarginCheck(Symbol(), OP_BUY, bl) >= 0) {
      if (CountBuyTrades() == 0) b = Ask;
      if (b >= Ask) {
         RefreshRates();
         OrderSend(Symbol(), OP_BUY, bl, Ask, In, 0, 0, "Martin ("+In+")", In, 0, Blue);
         b = FindLastBuyPrice() - In * Point;
      }
   }
   if (CountSellTrades() > 0) s = FindLastSellPrice() + In * Point;
   if (AccountFreeMarginCheck(Symbol(), OP_SELL, sl) >= 0) {
      if (CountSellTrades() == 0) s = Bid;
      if (s <= Bid) {
         RefreshRates();
         OrderSend(Symbol(), OP_SELL, sl, Bid, In, 0, 0, "Martin ("+In+")", In, 0, Red);
         s = FindLastSellPrice() + In * Point;
      }
   }
   if (CountBuyTrades() > 0) {
      PriceLot = 0;
      Count = 0; SwapCom = 0;
      for (cnt = OrdersTotal() - 1; cnt >= 0; cnt--) {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         if (OrderSymbol() == Symbol() && OrderType() == OP_BUY) {
            PriceLot += OrderOpenPrice() * OrderLots();
            SwapCom += OrderSwap() + OrderCommission();
            Count += OrderLots();
         }
      }
      AverageBuyPrice = NormalizeDouble(PriceLot / Count, Digits);
      for (cnt = OrdersTotal() - 1; cnt >= 0; cnt--) {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         if (OrderSymbol() == Symbol() && OrderType() == OP_BUY) {
            if (SwapCom >= 0 || MarketInfo(Symbol(), 16) == 0) PriceBuyTarget = AverageBuyPrice + Tp * Point;
            if (SwapCom < 0 && MarketInfo(Symbol(), 16) == 0) PriceBuyTarget = AverageBuyPrice + Tp * Point;            
            if (SwapCom < 0 && MarketInfo(Symbol(), 16) != 0) 
            PriceBuyTarget = AverageBuyPrice + Tp * Point - MathFloor(SwapCom / (MarketInfo(Symbol(), 16)))*Point;
            if (PriceBuyTarget <= Bid) {
               RefreshRates();
               OrderClose(OrderTicket(), OrderLots(), Bid, In, White);
            }
            if (OrderTakeProfit() != PriceBuyTarget)
            OrderModify(OrderTicket(), OrderOpenPrice(), 0, NormalizeDouble(PriceBuyTarget, Digits), 0, Yellow);
         }
      }
   }
   if (CountSellTrades() > 0) {
      PriceLot = 0;
      Count = 0; SwapCom = 0;
      for (cnt = OrdersTotal() - 1; cnt >= 0; cnt--) {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         if (OrderSymbol() == Symbol() && OrderType() == OP_SELL) {
            PriceLot += OrderOpenPrice() * OrderLots();
            SwapCom += OrderSwap() + OrderCommission();
            Count += OrderLots();
         }
      }
      AverageSellPrice = NormalizeDouble(PriceLot / Count, Digits);
      for (cnt = OrdersTotal() - 1; cnt >= 0; cnt--) {
         OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
         if (OrderSymbol() == Symbol() && OrderType() == OP_SELL) {
            if (SwapCom >= 0 || MarketInfo(Symbol(), 16) == 0) PriceSellTarget = AverageSellPrice - Tp * Point;
            if (SwapCom < 0 && MarketInfo(Symbol(), 16) == 0) PriceSellTarget = AverageSellPrice - Tp * Point;
            if (SwapCom < 0 && MarketInfo(Symbol(), 16) != 0) 
            PriceSellTarget = AverageSellPrice - Tp * Point + MathFloor(SwapCom / (MarketInfo(Symbol(), 16)))*Point;
            if (PriceSellTarget >= Ask) {
               RefreshRates();
               OrderClose(OrderTicket(), OrderLots(), Ask, In, White);
            }
            if (OrderTakeProfit() != PriceSellTarget)
            OrderModify(OrderTicket(), OrderOpenPrice(), 0, NormalizeDouble(PriceSellTarget, Digits), 0, Yellow);
         }
      }
   }
   if (CountTrades() > MaxTrades) {
      for (int pos = 0; pos < OrdersTotal(); pos++) {
         OrderSelect(pos, SELECT_BY_POS);
         if (OrderSymbol() == Symbol() && OrderType() == OP_BUY) {
            RefreshRates();
            OrderClose(OrderTicket(), OrderLots(), Bid, In, White);
            pos = OrdersTotal();
         }
         if (OrderSymbol() == Symbol() && OrderType() == OP_SELL) {
            RefreshRates();
            OrderClose(OrderTicket(), OrderLots(), Ask, In, White);
            pos = OrdersTotal();
         }                      
      }
   }      
   if (GetLastError() == 148) LimitOrders = OrdersTotal();
   if (OrdersTotal() >= LimitOrders) {
      for (pos = 0; pos < OrdersTotal(); pos++) {
         OrderSelect(pos, SELECT_BY_POS);
         if (OrderType() == OP_BUY) {
            RefreshRates();
            OrderClose(OrderTicket(), OrderLots(), Bid, In, White);
            pos = OrdersTotal();
         }
         if (OrderType() == OP_SELL) {
            RefreshRates();
            OrderClose(OrderTicket(), OrderLots(), Ask, In, White);
            pos = OrdersTotal();
         }                      
      }
   }
   if (Balance != AccountBalance() || OrdTot != OrdersTotal()) {
      DateTime = TimeCurrent(); ordprof1 = 0;
      ordprof2 = 0; ordprof3 = 0; 
      Deposit = 0; Withdraw = 0;
      for (cnt = 0; cnt<OrdersHistoryTotal(); cnt++) {
         OrderSelect(cnt, SELECT_BY_POS, MODE_HISTORY);
         if (OrderCloseTime() < TimeCurrent() - 2629800) continue;
         if (StringFind(OrderComment(),"Deposit") >= 0) Deposit += OrderProfit() + OrderCommission();
         if (StringFind(OrderComment(),"Withdraw") >= 0) Withdraw += OrderProfit() + OrderCommission();
         ordprof3 += OrderProfit() + OrderCommission() + OrderSwap();
         if (OrderCloseTime() < TimeCurrent() - 604800) continue;
         ordprof2 += OrderProfit() + OrderCommission() + OrderSwap();
         if (OrderCloseTime() < TimeCurrent() - 86400) continue;
         ordprof1 += OrderProfit() + OrderCommission() + OrderSwap();
      }
      Balance = AccountBalance(); OrdTot = OrdersTotal();
   }
   ObjectDelete(ChartID(), "buyline");         
   ObjectDelete(ChartID(), "sellline");         
   ObjectDelete(ChartID(), "fon1");         
   ObjectDelete(ChartID(), "fon2");         
   ObjectCreate(ChartID(), "buyline", OBJ_HLINE, 0, 0, b);
   ObjectSetInteger(ChartID(), "buyline", OBJPROP_COLOR, Blue);
   ObjectSetInteger(ChartID(), "buyline", OBJPROP_STYLE, STYLE_DASH);
   ObjectCreate(ChartID(), "sellline", OBJ_HLINE, 0, 0, s);
   ObjectSetInteger(ChartID(), "sellline", OBJPROP_COLOR, Red);
   ObjectSetInteger(ChartID(), "sellline", OBJPROP_STYLE, STYLE_DASH);
   ObjectCreate(ChartID(), "fon1", OBJ_RECTANGLE_LABEL, 0, 0, 0);
   ObjectSetInteger(ChartID(), "fon1", OBJPROP_XDISTANCE, 100);
   ObjectSetInteger(ChartID(), "fon1", OBJPROP_YDISTANCE, 12);
   ObjectSetInteger(ChartID(), "fon1", OBJPROP_XSIZE, 700);
   ObjectSetInteger(ChartID(), "fon1", OBJPROP_YSIZE, 30);
   ObjectSetInteger(ChartID(), "fon1", OBJPROP_BGCOLOR, Black);
   ObjectSetInteger(ChartID(), "fon1", OBJPROP_BACK, false);
   ObjectCreate(ChartID(), "fon2", OBJ_RECTANGLE_LABEL, 0, 0, 0);
   ObjectSetInteger(ChartID(), "fon2", OBJPROP_XDISTANCE, 100);
   ObjectSetInteger(ChartID(), "fon2", OBJPROP_YDISTANCE, 45);
   ObjectSetInteger(ChartID(), "fon2", OBJPROP_XSIZE, 300);
   ObjectSetInteger(ChartID(), "fon2", OBJPROP_YSIZE, 70);
   ObjectSetInteger(ChartID(), "fon2", OBJPROP_BGCOLOR, Black);
   ObjectSetInteger(ChartID(), "fon2", OBJPROP_BACK, false);
   ChartSetInteger(ChartID(), CHART_FOREGROUND, 0, false);
   if (Comment_for_cent == true) {
      Comment("                                  Баланс: ", NormalizeDouble(AccountBalance() * Rub_per_Usd / 100, 2), 
      "р., Средства: ", NormalizeDouble(AccountEquity() * Rub_per_Usd / 100, 2), "р., Прибыль: ", 
      NormalizeDouble(AccountProfit() * Rub_per_Usd / 100, 2), "р., Свободно: ", 
      NormalizeDouble(AccountFreeMargin() * Rub_per_Usd / 100, 2), "р., Lot: ", l, ", ", bl, ", ", sl, ", Всего ордеров: ", 
      OrdersTotal(), ", Ордеров по символу: ", CountTrades(), "\n                                  Дата обновления: ",
      TimeToStr(TimeCurrent()), "\n\n                                                                       История счета\n    ",
      "                              ------------------------------------------------------------------------------------------------",
      "\n                                    Сегодня: ", NormalizeDouble(ordprof1 * Rub_per_Usd / 100, 2),
      "р., Пополнение: ", NormalizeDouble(Deposit * Rub_per_Usd / 100, 2), "р.\n                                    Неделя: ", 
      NormalizeDouble(ordprof2 * Rub_per_Usd / 100, 2), "р., Снятие: ", NormalizeDouble(Withdraw * Rub_per_Usd / 100, 2), 
      "р.\n                                    Месяц: ", NormalizeDouble(ordprof3 * Rub_per_Usd / 100, 2), "р., Дата обновления: ", 
      TimeToStr(DateTime));
   }
   if (Comment_for_cent == false) {
      Comment("                                  Баланс: ", NormalizeDouble(AccountBalance() * Rub_per_Usd, 2), 
      "р., Средства: ", NormalizeDouble(AccountEquity() * Rub_per_Usd, 2), "р., Прибыль: ", 
      NormalizeDouble(AccountProfit() * Rub_per_Usd, 2), "р., Свободно: ", 
      NormalizeDouble(AccountFreeMargin() * Rub_per_Usd, 2), "р., Lot: ", l, ", ", bl, ", ", sl, ", Всего ордеров: ", 
      OrdersTotal(), ", Ордеров по символу: ", CountTrades(), "\n                                  Дата обновления: ",
      TimeToStr(TimeCurrent()), "\n\n                                                    История счета",
      "\n                                  --------------------------------------------------------------------------------------",
      "\n                                    Сегодня: ", NormalizeDouble(ordprof1 * Rub_per_Usd, 2),
      "р., Пополнение: ", NormalizeDouble(Deposit * Rub_per_Usd, 2), "р.\n                                    Неделя: ", 
      NormalizeDouble(ordprof2 * Rub_per_Usd, 2), "р., Снятие: ", NormalizeDouble(Withdraw * Rub_per_Usd, 2), 
      "р.\n                                    Месяц: ", NormalizeDouble(ordprof3 * Rub_per_Usd, 2), "р., Дата обновления: ", 
      TimeToStr(DateTime));
   }
   return(0);
}

int CountTrades() {
   int count = 0;
   for (int trade = OrdersTotal() - 1; trade >= 0; trade--) {
      OrderSelect(trade, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() == Symbol()) count++;
   }
   return (count);
}

int CountBuyTrades() {
   int count = 0;
   for (int trade = OrdersTotal() - 1; trade >= 0; trade--) {
      OrderSelect(trade, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() == Symbol() && OrderType() == OP_BUY) count++;
   }
   return (count);
}

int CountSellTrades() {
   int count = 0;
   for (int trade = OrdersTotal() - 1; trade >= 0; trade--) {
      OrderSelect(trade, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() == Symbol() && OrderType() == OP_SELL) count++;
   }
   return (count);
}

double FindLastBuyPrice() {
   double oldorderopenprice;
   int oldticketnumber;
   int ticketnumber = 0;
   for (int cnt = OrdersTotal() - 1; cnt >= 0; cnt--) {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() == Symbol() && OrderType() == OP_BUY) {
         oldticketnumber = OrderTicket();
         if (oldticketnumber > ticketnumber) {
            oldorderopenprice = OrderOpenPrice();
            ticketnumber = oldticketnumber;
         }
      }
   }
   return (oldorderopenprice);
}

double FindLastSellPrice() {
   double oldorderopenprice;
   int oldticketnumber;
   int ticketnumber = 0;
   for (int cnt = OrdersTotal() - 1; cnt >= 0; cnt--) {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() == Symbol() && OrderType() == OP_SELL) {
         oldticketnumber = OrderTicket();
         if (oldticketnumber > ticketnumber) {
            oldorderopenprice = OrderOpenPrice();
            ticketnumber = oldticketnumber;
         }
      }
   }
   return (oldorderopenprice);
}
