//+------------------------------------------------------------------+
//|                                              Lentiaika by Maloma |
//+------------------------------------------------------------------+

#include <stdlib.mqh>
#include <stderror.mqh>

extern double Lots=0.1;
extern int    sl=20;
extern int    tp=30;
extern int    TimePeriod=0;
extern int    DemarkerPeriod=14;
extern double DemarkerUP=0.7;
extern double DemarkerDN=0.3;
       int    TP;       
       int    magic=98467356;
       int    i, Total=0;
       int    CBar,Spread;
       double D1,D2;

int WTP()

{
 switch (TimePeriod)
  {
   case 1:TP=1;
          break;
   case 2:TP=5;
          break;
   case 3:TP=15;
          break;
   case 4:TP=30;
          break;
   case 5:TP=60;
          break;
   case 6:TP=240;
          break;
   case 7:TP=1440;
          break;
   case 8:TP=10080;
          break;
   case 9:TP=43200;
          break;
   default:TP=0;
           break;
  }
 return(0);
}

int start()
{ 
 WTP();
// Spread=MarketInfo(Symbol(),MODE_SPREAD);
// Total=0;
 D1=iDeMarker(Symbol(),TP,DemarkerPeriod,1); 
 D2=iDeMarker(Symbol(),TP,DemarkerPeriod,2);
 if (CBar<Bars)
  {
   for(i=OrdersTotal()-1;i>=0;i--)
    {
     OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
     if ((OrderSymbol()==Symbol()) && (OrderMagicNumber()==magic))
      {
       if ((OrderType()==OP_BUY) && ((D2<DemarkerUP)&&(DemarkerUP<D1))) {OrderClose(OrderTicket(),OrderLots(),Bid,3,CLR_NONE);}
       if ((OrderType()==OP_SELL) && ((D2>DemarkerDN)&&(DemarkerDN>D1))) {OrderClose(OrderTicket(),OrderLots(),Ask,3,CLR_NONE);}
      }
    }
/*   if ((D2>DemarkerDN)&&(DemarkerDN>D1)) OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid-sl*Point,Bid+tp*Point,"",magic,0);
   if ((D2<DemarkerUP)&&(DemarkerUP<D1)) OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Ask+sl*Point,Ask-tp*Point,"",magic,0);*/
   if ((D2<DemarkerDN)&&(DemarkerDN<D1)) OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid-sl*Point,Bid+tp*Point,"",magic,0);
//   Print("D2=",D2," DemarkerDN=",DemarkerDN," D1=",D1," D2<DemarkerDN<D1=",((D2<DemarkerDN)&&(DemarkerDN<D1)));
   if ((D2>DemarkerUP)&&(DemarkerUP>D1)) OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Ask+sl*Point,Ask-tp*Point,"",magic,0);
//   Print("D2=",D2," DemarkerUP=",DemarkerUP," D1=",D1," D2>DemarkerUP>D1=",((D2>DemarkerUP)&&(DemarkerUP>D1)));
   CBar=Bars;
  }
 return(0);
}