//+------------------------------------------------------------------+
//|                                              Expert ASCTrend.mq4 |
//+------------------------------------------------------------------+
#property copyright "© Maloma"

extern string _Parameters_Expert = "----- Параметры советника";
extern double Lots               = 0.1;
extern int    SL                 = 15;
extern int    TP                 = 30;
extern int    RISK               = 3; 
extern int    magic              = 55887799;
extern string _Parameters_Tral   = "----- Параметры трала";
extern bool   Tral               = false;
extern int    TStOp              = 10;
extern int    TStEp              = 5;
extern int    Bezubitok          = 0;
extern string _Parameters_MM     = "----- Параметры манимэнэджмента";
extern bool   MM                 = false;
extern double MaximumRisk        = 0.03;
extern double DecreaseFactor     = 3;

       double RLots;
       double SigUP=0, SigDN=0;
       int    CBars=0;
       bool   trend,old; 

double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/500,1);
//---- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         //----
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>0) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//---- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }
  
void Tral()
{
 for(int i=OrdersTotal()-1;i>=0;i--)
    {
     OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
     if ((OrderSymbol()==Symbol()) && (OrderMagicNumber()==magic))
      {
       if (OrderType()==OP_BUY && Bid-OrderOpenPrice()>TStOp*Point)
        {
         if (Bezubitok!=0 && Bid-OrderOpenPrice()>=Bezubitok*Point && OrderStopLoss()<OrderOpenPrice())
          {OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+1*Point,OrderTakeProfit(),0,CLR_NONE);}
         if (Bid-OrderStopLoss()>=(TStOp+TStEp)*Point)
          {OrderModify(OrderTicket(),OrderOpenPrice(),Bid-TStOp*Point,OrderTakeProfit(),0,CLR_NONE);}
        }
       if (OrderType()==OP_SELL && OrderOpenPrice()-Ask>TStOp*Point)
        {
         if (Bezubitok!=0 && OrderOpenPrice()-Ask>=Bezubitok*Point && OrderStopLoss()>OrderOpenPrice())
          {OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-1*Point,OrderTakeProfit(),0,CLR_NONE);}
         if (OrderStopLoss()-Ask>=(TStOp+TStEp)*Point)
          {OrderModify(OrderTicket(),OrderOpenPrice(),Ask+TStOp*Point,OrderTakeProfit(),0,CLR_NONE);}
        }
      }
    }
 return(0);
}


void GetSignal(int i)
{
 int Counter,i1,value10,value11; 
 double value1,x1,x2,value2,value3; 
 double TrueCount,Range,AvgRange,MRO1,MRO2; 
 double Table_value2[150];
 
 SigUP=0; 
 SigDN=0; 
 value10=3+RISK*2; 
 x1=67+RISK; 
 x2=33-RISK; 
 value11=value10; 
 for (int n=99;n>=0;n--)
  { 
   Range=0.0; 
   AvgRange=0.0; 
   for(Counter=i+n; Counter<=i+n+9; Counter++) AvgRange=AvgRange+MathAbs(High[Counter]-Low[Counter]); 
   
   Range=AvgRange/10; 
   Counter=i+n; 
   TrueCount=0; 
   while (Counter<i+n+9 && TrueCount<1) 
    { 
     if (MathAbs(Open[Counter]-Close[Counter+1])>=Range*2.0) TrueCount=TrueCount+1; 
     Counter=Counter+1; 
    } 
   if (TrueCount>=1) {MRO1=Counter;} else {MRO1=-1;} 
   Counter=i+n; 
   TrueCount=0; 
   while (Counter<i+n+6 && TrueCount<1) 
    { 
     if (MathAbs(Close[Counter+3]-Close[Counter])>=Range*4.6) TrueCount=TrueCount+1; 
     Counter=Counter+1; 
    } 
   if (TrueCount>=1) {MRO2=Counter;} else {MRO2=-1;} 
   if (MRO1>-1) {value11=3;} else {value11=value10;} 
   if (MRO2>-1) {value11=4;} else {value11=value10;} 
   value2=100-MathAbs(iWPR(NULL,0,value11,i+n)); // PercentR(value11=9) 
   Table_value2[n+i]=value2;  
//   Print(n+i," ",Table_value2[n+i]);
  }
   if (value2<x2) 
    { 
     i1=1; 
     while (Table_value2[i+i1]>=x2 && Table_value2[i+i1]<=x1)
      {
//       Print("------------------ i+i1=",i+i1," ------Table_value2[i+i1]=",Table_value2[i+i1]);
       i1++;
      } 
     if (Table_value2[i+i1]>x1) {SigDN=1;}
    } 
   if (value2>x1) 
    { 
     i1=1; 
     while (Table_value2[i+i1]>=x2 && Table_value2[i+i1]<=x1){i1++;} 
     if (Table_value2[i+i1]<x2) {SigUP=1;} 
    } 
//   Print("SigUP=",SigUP," SigDN=",SigDN);   
 
 return(0);
}

void Check4Close()
{
 int j=OrdersTotal();
 for (int i=j;i>=0;i--)
  {
   OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
   if (Symbol()==OrderSymbol() && magic==OrderMagicNumber())
    if (OrderType()==OP_BUY && SigDN==1)
     OrderClose(OrderTicket(),OrderLots(),Bid,3,CLR_NONE);
    if (OrderType()==OP_SELL && SigUP==1)
     OrderClose(OrderTicket(),OrderLots(),Ask,3,CLR_NONE);
  }
 return(0);
}

void start()
{
 if (Tral) Tral();
 if (Bars==CBars) {return(2);}
 GetSignal(0);
// Check4Close();
 if (MM) RLots=LotsOptimized(); else RLots=Lots;
 if (SigUP==1) OrderSend(Symbol(),OP_BUY,RLots,Ask,3,Ask-SL*Point,Ask+TP*Point,"e-ASCTrend",magic,0,Green);
 if (SigDN==1) OrderSend(Symbol(),OP_SELL,RLots,Bid,3,Bid+SL*Point,Bid-TP*Point,"e-ASCTrend",magic,0,Red);
 CBars=Bars;
 return(0);
}