//+------------------------------------------------------------------+
//|                             BAV Parabolic_Hist StepMA_EA_nv1.mq4 |
//|                                  Nick Bilak, beluck[AT]gmail.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2007, Nick Bilak"
#property link      "http://www.mql4.info/"
#include <stdlib.mqh>

extern int expertId = 1;

extern int TakeProfit1=6;
extern int TakeProfit2=10;
extern int TakeProfit3=20;
extern int TakeProfit4=500;
extern int StopLoss=30;  
extern int TrailingStop = 30;  

extern bool   FixedLot = true; //trigger to use MM
extern double Lots = 0.1;
extern double MinLot = 0.1;    //minimum lot size
extern double MaximumRisk = 1; //% risk. lot size will be calculated so that stoploss was equal to risk% of balance

extern int shift=0;

extern string i0="-----Hist_StepMA_Stoch_KV1_Ex_03------";
extern int PeriodWATR=10;
extern double Kwatr=1.0000;
extern int HighLow=0;
extern int NumberOfBarsToCalculate = 500;

extern int    slippage=2;   	//slippage for market order processing

extern int    OrderTriesNumber=3; //to repeate sending orders when got some error

extern string    EAName="HistStepMA"; 

bool buysig,sellsig,closebuy,closesell; int lastsig,tries,co;


void start()  {


   //---- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false) return;

   CheckForSignals();
   co=CalculateCurrentOrders();
   if (co>0) CheckForClose();
   co=CalculateCurrentOrders();
   CheckForOpen();
   
   TrailStop();
        
}


//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders()
  {
   int ord;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==expertId) ord++;
     }
//---- return orders volume
   return(ord);
}

double LotsRisk(int StopLoss)  { 
   //MM lot size calculation
   double lot=Lots;
//---- select lot size
   if (!FixedLot)
      lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk*0.001/StopLoss,1);
//---- return lot size
   if(lot<MinLot) lot=MinLot;
   return(lot);
}

//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForSignals() {

      buysig=false;
      sellsig=false;
      closebuy=false;
      closesell=false;


      //indicators variables
      double hsms11 = iCustom(NULL,0,"Hist_StepMA_Stoch_KV1_Ex_03",PeriodWATR,Kwatr,HighLow,NumberOfBarsToCalculate,0,shift); //red
      double hsms12 = iCustom(NULL,0,"Hist_StepMA_Stoch_KV1_Ex_03",PeriodWATR,Kwatr,HighLow,NumberOfBarsToCalculate,0,shift+1); //red
      double hsms21 = iCustom(NULL,0,"Hist_StepMA_Stoch_KV1_Ex_03",PeriodWATR,Kwatr,HighLow,NumberOfBarsToCalculate,1,shift); //green
      double hsms22 = iCustom(NULL,0,"Hist_StepMA_Stoch_KV1_Ex_03",PeriodWATR,Kwatr,HighLow,NumberOfBarsToCalculate,1,shift+1); //green
   
	   if (hsms21>0 && hsms12<0 ) buysig=true;
	   if (hsms11<0 && hsms22>0 ) sellsig=true;
      closebuy=sellsig;
      closesell=buysig;
}

void CheckForOpen() {
   int    res,tr;
//---- sell conditions
   if(sellsig)  {
	   if (co==0 && lastsig!=Time[0]) {
	     res = OpenAtMarket(OP_SELL,LotsRisk(StopLoss),TakeProfit1);
	     res = OpenAtMarket(OP_SELL,LotsRisk(StopLoss),TakeProfit2);
	     res = OpenAtMarket(OP_SELL,LotsRisk(StopLoss),TakeProfit3);
	     res = OpenAtMarket(OP_SELL,LotsRisk(StopLoss),TakeProfit4);
	     if (res>0) lastsig=Time[0];
	   }
      return;
   }
//---- buy conditions
   if(buysig)  {
	   if (co==0 && lastsig!=Time[0]) {
	     res = OpenAtMarket(OP_BUY,LotsRisk(StopLoss),TakeProfit1);
	     res = OpenAtMarket(OP_BUY,LotsRisk(StopLoss),TakeProfit2);
	     res = OpenAtMarket(OP_BUY,LotsRisk(StopLoss),TakeProfit3);
	     res = OpenAtMarket(OP_BUY,LotsRisk(StopLoss),TakeProfit4);
	     if (res>0) lastsig=Time[0];
	   }
      return;
   }
}
  
  
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()  {
   bool bres; int tr;
   for(int i=0;i<OrdersTotal();i++)  {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)  break;
      if(OrderMagicNumber()!=expertId || OrderSymbol()!=Symbol()) continue;
      //---- check order type 
      if(OrderType()==OP_BUY)
         if (closebuy) {
            bres=CloseAtMarket(OrderTicket(),OrderLots());
            break;
         }
      if(OrderType()==OP_SELL) 
         if (closesell) {
            bres=CloseAtMarket(OrderTicket(),OrderLots());
            break;
         }
   }
}



int OpenAtMarket(int mode,double lot, int TP) {
   int    res,tr,col;
   double openprice,sl,tp;
   tries=0;
   while (res<=0 && tries<OrderTriesNumber) {
      tr=0; while (tr<5 && !IsTradeAllowed()) { tr++; Sleep(2000); }
      RefreshRates();
      if (mode==OP_SELL) {
         openprice=Bid; 
         sl=openprice+StopLoss*Point;
         if (TP>0) tp=openprice-TP*Point;
         col=Red;
      } else {
         openprice=Ask;
         sl=openprice-StopLoss*Point;
         if (TP>0) tp=openprice+TP*Point;
         col=Blue;
      }
      res=OrderSend(Symbol(),mode,lot,openprice,slippage,sl,tp,EAName+"_"+expertId,expertId,0,col);
      tries++;
   }
   return(res);
}


bool CloseAtMarket(int ticket,double lot) {
   bool bres=false; int tr;
   tries=0;
   while (!bres && tries<OrderTriesNumber) {
      tr=0; while (tr<5 && !IsTradeAllowed()) { tr++; Sleep(2000); }
      RefreshRates();
      bres=OrderClose(ticket,lot,OrderClosePrice(),slippage,White);
      tries++;
   }
   if (!bres) Print("Error closing order : ",ErrorDescription(GetLastError()));
}


void TrailStop() {
   bool bres;
   double StopLoss;
   if ( TrailingStop > 2 ) {
      for (int i = 0; i < OrdersTotal(); i++) {
         if ( OrderSelect (i, SELECT_BY_POS) == false )  continue;
         if ( OrderSymbol() != Symbol() || OrderMagicNumber() != expertId )  continue;
         if ( OrderType() == OP_BUY ) {
            if ( Bid < OrderOpenPrice()+TrailingStop*Point )  continue;
            StopLoss = Bid-TrailingStop*Point;
            if ( StopLoss > OrderStopLoss() ) {
                  bres=OrderModify (OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, White);
					   if (!bres) Print("Error Modifying BUY order : ",ErrorDescription(GetLastError()));
            }
         }
   
         if ( OrderType() == OP_SELL ) {
            if ( Ask > OrderOpenPrice()-TrailingStop*Point )  continue;
            StopLoss = Ask+TrailingStop*Point;
            if ( StopLoss < OrderStopLoss() ) {
                  bres=OrderModify (OrderTicket(), OrderOpenPrice(), StopLoss, OrderTakeProfit(), 0, Gold);
					   if (!bres) Print("Error Modifying SELL order : ",ErrorDescription(GetLastError()));
            }
         }
      }
   }
   return;
}

