//+------------------------------------------------------------------+
//|                                                        Ticks.mq4 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

input double sensitive=1;
input double level=0.0035;
input int Magic=0;
input int a=3;
input int b = 3;
input int Tp = 30;
input int Sl = 100;
input double MaximumRisk=0.08;
input double Lot=0.01;
input int PerSec=1;
input int PerHigh=60;
datetime time=0,TimeMin=0;
int col=0, ColMax=0,MedInHigh=0,MedInHighW=0;
double oldbid=0;

double lastBid=0;
int countBuy=0;
int countSell=0;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   EventSetMillisecondTimer(1);
   time=TimeCurrent()+PerSec;
   //TimeMin=
   oldbid=Bid;
   col=1;
   ColMax=0;
   MedInHighW=1; MedInHigh=0;
   TimeMin=TimeCurrent()+PerHigh;
   return(INIT_SUCCEEDED);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   ObjectDelete("labelAskPercent");
   ObjectDelete("labelAskPercent");
   EventKillTimer();

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

   GetCountOrders();

   if(lastBid==0)
     {
      lastBid=Bid;
      return;
     }

   double s=sensitive;
   if(s<1)
      s=1;
   else if(s>100)
      s=100;

   double bidPercent=((Bid*100)/(Open[0]*s))-100;
   double bidPercent1 = bidPercent;
      if (bidPercent>bidPercent1)bidPercent1=bidPercent;
  

   if(NoOrders_ThisPair_Candle0())
   {
    if(bidPercent>level)
       OpenBuy();
    else if((bidPercent*-1)>level)
       OpenSell();
   } 
  // Trall();

   DrawText(bidPercent);
   lastBid=Bid;
   
   if (TimeCurrent()<TimeMin && Bid!=oldbid)
      {
      MedInHighW++;
      }
   if(TimeCurrent()<time && Bid!=oldbid)
     {
      col++;
      oldbid=Bid;
     }
   if(TimeCurrent()>=time)
     {
      time=TimeCurrent()+PerSec;
      oldbid=Bid;
      if (ColMax<col)ColMax=col;
      col=1;
     }
   if(TimeCurrent()>=TimeMin)
     {
      time=TimeCurrent()+PerHigh;
      MedInHigh=MedInHighW/PerHigh;
      MedInHighW=1;
     }
     // MedInHigh - среднее значение бидов за предыдущий старший период
     // ColMax - максимальное значение бидов в младший период
     // col - текущее количество бидов за младший период
      Comment ( "Максимальное отклонение " +  DoubleToStr( bidPercent1,5)+
               "\ncol   :" + col+
               "\nColMax   :" + ColMax + 
               "\nMedInHigh   :" + MedInHigh);
  }
//+------------------------------------------------------------------+

/*void Trall()
  {
   if(countBuy<1 && countSell<1)
      return;

   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol() == _Symbol && OrderMagicNumber()== Magic)
        {
         if(OrderType()==OP_BUY || OrderType()==OP_SELL)
           {
            Trall(OrderTicket());
           }
        }
     }

  }*/
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void GetCountOrders()
  {
   countBuy=0;
   countSell=0;
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol() == _Symbol && OrderMagicNumber()==Magic)
        {
         if(OrderType() == OP_BUY) countBuy++;
         if(OrderType() == OP_SELL) countSell++;
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DrawText(double bidPercent)
  {
   if((IsTesting() && !IsVisualMode()) || IsOptimization())
      return;


   ObjectCreate(0,"labelBidPercent",OBJ_TEXT,0,TimeCurrent(),lastBid -(150*Point));
   ObjectSetString(0,"labelBidPercent",OBJPROP_TEXT,"                    "+DoubleToStr(bidPercent,5)+"%");
   ObjectSetInteger(0,"labelBidPercent",OBJPROP_COLOR,bidPercent<0 ? clrHoneydew : clrOldLace);
   ObjectMove(0,"labelBidPercent",0,TimeCurrent(),Bid);
   ChartRedraw();
  }
//+------------------------------------------------------------------+
void OpenSell()
  {
   if(countBuy>0 || countSell > 0)
      return;
   double tp=NormalizeDouble(Ask+(Tp*Point),Digits);

   double sl=NormalizeDouble(Bid - (Sl * Point),Digits);
   int tiket= OrderSend(_Symbol,OP_BUY,LotsOptimized(),Ask,20,sl,tp,"Tika",Magic,0,clrBlue);
   if(tiket<0)
     {
      Print("OrderSend завершилась с ошибкой #",GetLastError());
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OpenBuy()
  {
   if(countBuy>0 || countSell > 0)
      return;
   double tp=NormalizeDouble(Bid -(Tp*Point),Digits);
   double sl=NormalizeDouble(Ask + (Sl * Point),Digits);
   int tiket =OrderSend(_Symbol,OP_SELL,LotsOptimized(),Bid,20,sl,tp,"Tika",Magic,0,clrBlue);
      if(tiket<0)
     {
      Print("OrderSend завершилась с ошибкой #",GetLastError());
     }

  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Trall(int ticket)
  {
   double StopLoss=OrderType()==OP_BUY ?  Low[b]: High[a];

   if(OrderOpenTime()<Time[1] && OrderStopLoss()!=StopLoss )
     {
      double TakePrice=0;//OrderType()==OP_BUY ?   NormalizeDouble(Ask+(Tp*Point),Digits) : NormalizeDouble(Bid -(Tp*Point),Digits);
     bool res = OrderModify(ticket,OrderOpenPrice(),NormalizeDouble(StopLoss,Digits),TakePrice,0,clrRed);
      if(!res)
               Print("Ошибка модификации ордера: " +IntegerToString(ticket)+ "  Код ошибки=",GetLastError());
            else
               Print("Цена Stop Loss ордера успешно модифицирована.");

     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=0.0;
   if(Lot>0) {lot=Lot; return(lot);}
   double MINLOT=MarketInfo(Symbol(),MODE_MINLOT);
   double LOTSTEP=MarketInfo(Symbol(),MODE_LOTSTEP);
   int ml=0;
   if(LOTSTEP == 0.01) ml =2;
   if(LOTSTEP == 0.1) ml =1;
   double MAXLOT=MarketInfo(Symbol(),MODE_MAXLOT);

//  if(OrdersTotal()==0)
   lot=NormalizeDouble(AccountBalance()/MarketInfo(Symbol(),MODE_MARGINREQUIRED)*MaximumRisk,ml);
//   else
//    lot=NormalizeDouble(AccountBalance()/MarketInfo(Symbol(),MODE_MARGINREQUIRED)*MaximumRisk/0.67,ml);
   if(lot>MAXLOT)      lot=MAXLOT;
   else if(lot<MINLOT) lot=MINLOT;

   return(lot);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool NoOrders_ThisPair_Candle0()
  {
   
   for(int i=OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol() == _Symbol && OrderMagicNumber()==Magic)
       {
         if(OrderOpenTime()>=iTime(_Symbol,0,0)) return(0);
   
         
       }
     }
  return(1);   
  }