//+------------------------------------------------------------------+
//|                                                       Martin.mq4 |
//|                                                        By Foxonn |
//|                                          http://new.vk.com/lafei |
//+------------------------------------------------------------------+
#property copyright "By Foxonn"
#property link      "http://vk.com/51236663"
#property version   "1.00"
#property strict

extern double Lots       = 0.1;
extern int    TakeProfit = 5;
extern int    Step       = 10;
extern double Multipler  = 2.0;
extern int    Magic      = 123;
extern string MA       = "Настройка MA";
extern int    PeriodMA              = 100;
extern int    AVGShift        = 1;
extern int    Shift           = 1;

int ticket;
double tp, price, lastlot, maprice;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
    if( Digits == 3 || Digits == 5)
    {
      TakeProfit *= 10;
      Step       *= 10;
    }
      
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   
      maprice = iMA(Symbol(),0,PeriodMA,AVGShift,MODE_SMA,PRICE_CLOSE,Shift);
      
      Comment("Баланс: " + NormalizeDouble(AccountBalance(),3));
      
      if(CountTrades() == 0)
      {
      if(Ask > maprice)
      {
         tp = NormalizeDouble(Ask + TakeProfit * Point, Digits);
         ticket = OrderSend(Symbol(), OP_BUY, Lots, Ask, 5, 0, tp, "", Magic, 0, Blue);
      }
      else
      {
         tp = NormalizeDouble(Bid - TakeProfit * Point, Digits);
         ticket = OrderSend(Symbol(), OP_SELL, Lots, Bid, 5, 0, tp, "", Magic, 0, Red);
      }
     }
     else
     {
         int order_type = FindLastOrderType();
         if(order_type == OP_BUY)
         {
            price = FindLastOrderPrice(OP_BUY);
            if(Ask <= price - Step*Point)
            {
               lastlot = FindLastLots(OP_BUY);
               lastlot = NormalizeDouble(lastlot * Multipler, 2);
               ticket = OrderSend(Symbol(), OP_BUY, lastlot, Ask, 5, 0, 0, "", Magic, 0, Blue);
               if(ticket < 1)
                  Print("Ошибка открытия ордера на покупку");
               ModifyOrders(OP_BUY);
            }
         }
         if(order_type == OP_SELL)
         {
            price = FindLastOrderPrice(OP_SELL);
            if(Bid >= price + Step*Point)
            {
               lastlot = FindLastLots(OP_SELL);
               lastlot = NormalizeDouble(lastlot * Multipler, 2);
               ticket = OrderSend(Symbol(), OP_SELL, lastlot, Bid, 5, 0, 0, "", Magic, 0, Red);
               if(ticket < 1)
                  Print("Ошибка открытия ордера на продажу");
               ModifyOrders(OP_SELL);
            }
         }
     }
}
//+------------------------------------------------------------------+
int CountTrades()
{
   int count=0;
   for (int i=OrdersTotal()-1; i>=0; i--)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)
         if(OrderType() == OP_BUY || OrderType() == OP_SELL)
            count++;
      }
   }
   return(count);
}
//+------------------------------------------------------------------+
int FindLastOrderType()
{
   for (int i=OrdersTotal()-1; i>=0; i--)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic)
            return(OrderType());
      }
   }
   return(-1);
}
//+------------------------------------------------------------------+
double FindLastOrderPrice(int otype)
{
   int oldticket;
   double oldopenprice=0;
   ticket=0;
   for(int cnt = OrdersTotal() -1; cnt>=0; cnt--)
   {
      if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == otype)
         {
            oldticket = OrderTicket();
            if(oldticket > ticket)
            {
               ticket = oldticket;
               oldopenprice = OrderOpenPrice();
            }
         }
      }
   }
   return(oldopenprice);
}
//+------------------------------------------------------------------+
double FindLastLots(int otype)
{
   int oldticket;
   double oldlots=0;
   ticket=0;
   
   for(int cnt = OrdersTotal() -1; cnt>=0; cnt--)
   {
      if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == otype)
         {
            oldticket = OrderTicket();
            if(oldticket > ticket)
            {
               ticket = oldticket;
               oldlots = OrderLots();
            }
         }
      }
   }
   return(oldlots);
}
//+------------------------------------------------------------------+
void ModifyOrders(int otype)
{
   double avg_price, order_lots=0;
   price=0;
   for (int i=OrdersTotal()-1; i>=0; i--)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == otype)
         {
            price += OrderOpenPrice() * OrderLots();
            order_lots += OrderLots();
         }
      }
   }
   avg_price = NormalizeDouble(price / order_lots, Digits);
   
   if(otype == OP_BUY) tp = NormalizeDouble(avg_price + TakeProfit*Point, Digits);
   if(otype == OP_SELL) tp = NormalizeDouble(avg_price - TakeProfit*Point, Digits);
   
   for(int i=OrdersTotal()-1; i>=0; i--)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
      {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == otype)
            {
               if(OrderModify(OrderTicket(), OrderOpenPrice(), 0, tp, 0))
                  Print("Ордера успешно модифицированы");
                  else Print("Ошибка модификации ордеров");
            }
      }
   }
}
//+------------------------------------------------------------------+