Navigation´╝ÜHome > Content >

Fryonarn_v0.9.5.mq4

Time: 2012-04-10 | Download file:Fryonarn_v0.9.5.mq4

//====================================================================================================================================================//
//                                                                                                                                    Fryonarn        //
//====================================================================================================================================================//
#import "Kernel32.dll"
void GetSystemTime(int& TimeArray[]);
#import
//====================================================================================================================================================//
extern string  Comment1         = "||========= Type Operation ==========||";
extern string  TypeOperationStr = "1:Market/Pending, 2:Market, 3:Pending";
extern int     TypeOperation    = 1;
extern string  Comment2         = "||========= Manage Market Positions ==========||";
extern double  Stoploss         = 1;
extern double  Takeprofit       = 10;
extern bool    UseDynamicTSL    = true;
extern double  MultiplierDSL    = 2;
extern double  PipsChangeDSL    = 1;
extern double  TrailingStop     = 0.3;
extern double  TrailingStart    = 0;
extern double  TrailingStep     = 0;
extern string  Comment3         = "||========= Manage Pending Orders ==========||";
extern bool    AddAfter_SL_TP   = true;
extern bool    ContinueSendPO   = false;
extern string  TypeOrdersSendStr= "1:stop orders, 2:limit orders";
extern int     TypeOrdersSend   = 1;
extern double  Step             = 0.3;
extern int     TimeModify       = 1;
extern string  Comment4         = "||========= Advance Trailing ==========||";
extern bool    FollowPriceSL    = true;
extern bool    AlwaysRunFPSL    = true;//true=like version 8.3, false=fixed that
extern double  Step_FPSL_Loss   = 0.5;
extern double  Pips_FPSL_Loss   = 1.5;
extern double  Max_FPSL_Loss    = 4;
extern double  Step_FPSL_Profit = 0.5;
extern double  Pips_FPSL_Profit = 1.5;
extern double  Max_FPSL_Profit  = 4;
extern string  Comment5         = "||========= Advance Settings ==========||";
extern bool    KeepOnePosition  = true;
extern bool    HideStopLoss     = false;
extern bool    HidePendingOrders= false;
extern string  Comment6         = "||========= Volatility set ==========||";
extern bool    UseVolatilityIndi= false;
extern bool    DeletePOandStop  = true;
extern int     MaPriod          = 34;
extern double  IndiValue        = 0.5;
extern double  LevelTrade       = 0.02;
extern string  TypeUseIndiInfo  = "1:over level, 2:under level";
extern int     TypeUseIndi      = 1;
extern string	NewsFilter		  = "||========= News Filter ==========||";
extern bool		Use_NewsFilter	  = false;
extern string  ImpactInfo       = "1:Low, 2:Medium, 3:High";
extern int     MinimumImpact    = 1;
extern int     MinsBeforeNews   = 5;
extern int     MinsAfterNews    = 5;
extern string  Comment7         = "||========= Money Management ==========||";
extern double  Lot              = 0.01;
extern int     risk             = 20;
extern int     DigitsLot        = 2;
extern string  Comment8         = "||========= General Sets ==========||";
extern string  SpreadLimitStr   = "0=Not check spread";
extern double  SpreadLimit      = 0;
extern bool    ClosePositions   = false;//market positions
extern bool    DeleteOrders     = true;//pending orders
extern string  MagicStr         = "0=Auto generate ID";
extern int     Magic            = 0;
extern int     slippage         = 3;
extern string  Comment9         = "||========= Session Window ==========||";
extern bool    UseTimeWindow    = true;
extern string  TimeStr          = "Hour Start/End in GMT";
extern int     Time_Start       = 0;
extern int     Time_End         = 18;
extern string  GMT_OffsetStr    = "Put GMT offset for backtest only";
extern int     GMT_Offset       = 99;
//====================================================================================================================================================//
string CommentOperation;
string OrderCom;
string SymbolName;
string ExpertName;
string MarketOp="";
double SPREADPOINT;
double MaxLot;
double MinLot;
double DigitPoint;
double STOPLEVEL;
double CurrentLevel;
double V_SL_Buy=-99999;
double V_SL_Sell=99999;
double V_PriceBuy=0;
double V_PriceSell=0;
int TimeBarB;
int TimeBarS;
int CountBuy;
int CountSell;
int CountBuyStop;
int CountSellStop;
int CountBuyLimit;
int CountSellLimit;
int CntCheck=0;
int StartHour;
int EndHour;
int MultiplierPoint;
bool SendBuy;
bool SendSell;

//====================================================================================================================================================//
int init()
{
  ExpertName=WindowExpertName();
  SymbolName=Symbol();
  OrderCom=ExpertName+" ["+SymbolName+"]";
//-----------------------------------------------------------------
//decimal broker
  DigitPoint=Point;
  MultiplierPoint=1;
  if((Digits==3)||(Digits==5))
  {
  MultiplierPoint=10;
  DigitPoint*=MultiplierPoint;
  }
//-----------------------------------------------------------------
//info broker
  STOPLEVEL=MarketInfo(Symbol(),MODE_STOPLEVEL)/MultiplierPoint;
  MaxLot=MarketInfo(Symbol(),MODE_MAXLOT);
  MinLot=MarketInfo(Symbol(),MODE_MINLOT);
//-----------------------------------------------------------------
//confirm
  slippage*=MultiplierPoint;
  if((Stoploss>0)&&(Stoploss0)&&(Takeprofit0)&&(TrailingStop0)&&(TrailingStart3)) TypeOperation=1;
  if((TrailingStop>0)&&(Takeprofit>0)&&(Takeprofit2)) TypeUseIndi=1;
  if((TypeOrdersSend<1)||(TypeOrdersSend>2)) TypeOrdersSend=1;
  if((Use_NewsFilter==true)&&(IsTesting())) Use_NewsFilter=false;
//-----------------------------------------------------------------
//ID and background
  if(Magic==0) Magic=333+UniqueMagic();
  if(ObjectFind("Background0")==-1) DisplayText("Background0","g",140,"Webdings",Black,0,16);
//-----------------------------------------------------------------
  start();
  return(0);
}
//====================================================================================================================================================//
int deinit()
{
  ObjectDelete("Background0");
  Comment("");
  return(0);
}
//====================================================================================================================================================//
int start()  
{
  bool Trade=true;
  double OSL=0;
  double OTP=0;
  double StLo=0;
  double PriceB=0;
  double PriceS=0;
  double OOP=0;
  double SL=0;
  double TP=0;
  double TSL=0;
  double MovedSL=0;
  double OOPbuy=0;
  double OOPsell=0;
  double V_TSLbuy=0;
  double V_TSLsell=0;
  double StepFollowPriceSL=0;
  double PipsFollowPriceSL=0;
  double MaxFollowPriceSL=0;
  CountBuy=0;
  CountSell=0;
  CountBuyStop=0;
  CountSellStop=0;
  CountBuyLimit=0;
  CountSellLimit=0;
//-----------------------------------------------------------------
//Comment operation type
  if(TypeOperation==1) CommentOperation="Expert Run || Pending and Market";
  if(TypeOperation==2) CommentOperation="Expert Run || Only Market";
  if(TypeOperation==3) CommentOperation="Expert Run || Only Pending";
//-----------------------------------------------------------------
//Count ticks for check Market operation
  if(UseTimeWindow==false) MarketOp="Non Time Filter";
  if(UseTimeWindow==true)
  {
  if(CntCheck<2) CntCheck++;
  if(CntCheck==1) MarketOp="Market is closed";
  if(CntCheck>1) MarketOp="";
//-----------------------------------------------------------------
//Time Offset
  if(((IsTesting())||(IsOptimization()))&&(GMT_Offset==99))
  {
  Alert("Please set GMT Offset in the EA inputs");
  Sleep(60000);
  return(0);
  }
  //---
  if((!IsTesting())&&(!IsOptimization())) GMT_Offset=GMTOffset();
  }
//-----------------------------------------------------------------------------
//Get spread 
  SPREADPOINT=MarketInfo(Symbol(),MODE_SPREAD)/MultiplierPoint;
//-----------------------------------------------------------------------------
//Check positions and modify them (market)
  for(int i=0; iOP_SELL) continue;
  if((OrderSymbol()==Symbol())&&(Magic==OrderMagicNumber()))
  { 
  OSL=NormalizeDouble(OrderStopLoss(),Digits);
  OTP=NormalizeDouble(OrderTakeProfit(),Digits);
  OOP=NormalizeDouble(OrderOpenPrice(),Digits);
  SL=OSL;
  TP=OTP;
  TSL=TrailingStop;
  //-----------------------------------------------------------------------------
  //modify buy
  if(OrderType()==OP_BUY)  
  {  
  CountBuy++;
  OOPbuy=OrderOpenPrice();
  if((TypeOperation==1)||(TypeOperation==2))
  {
  if(HideStopLoss==false)
  {
  //---trailing stop
  if((TrailingStop!=0)&&(Bid-OOP>=TrailingStart*DigitPoint))
  {
  //---dynamic trailing stop
  if(UseDynamicTSL) TSL=TrailingStop*MathMax(1,((NormalizeDouble((((Bid-OOP)/DigitPoint)/PipsChangeDSL)-0.5,0))*(MultiplierDSL/2)));
  //---
  StLo=NormalizeDouble(Bid-TSL*DigitPoint,Digits); 
  if((StLo>=OOP)&&((StLo>OSL+TrailingStep*DigitPoint)||(OSL==0))) SL=StLo;
  }
  //---put stop loss and take profit
  if(AddAfter_SL_TP==true)
  {
  if((OSL==0)&&(Stoploss!=0)) SL=NormalizeDouble(Bid-Stoploss*DigitPoint,Digits);
  if((OTP==0)&&(Takeprofit!=0)) TP=NormalizeDouble(Ask+Takeprofit*DigitPoint,Digits);
  }
  //---modify position by trailing sl
  if((SL>OSL)||((OSL==0)&&(SL!=0))||((OTP==0)&&(TP!=0)))
  {  
  if(!OrderModify(OrderTicket(),OOP,SL,TP,0,White))
  Print("Error ",GetLastError(),"  Order Modify Buy ticket:"+OrderTicket()+" || SL ",DoubleToStr(OSL,Digits),"->",DoubleToStr(SL,Digits));
  }
  //---move back stop loss
  if((FollowPriceSL==true)&&(((OSL<=OOP)&&(AlwaysRunFPSL==false))||((OSL<=OSL)&&(AlwaysRunFPSL==true))))
  {
  if(Bid>=OOP)//in profit
  {
  MovedSL=0;
  StepFollowPriceSL=Step_FPSL_Profit;
  PipsFollowPriceSL=Pips_FPSL_Profit;
  MaxFollowPriceSL=Max_FPSL_Profit;
  }
  else//in loss
  {
  StepFollowPriceSL=Step_FPSL_Loss;
  PipsFollowPriceSL=Pips_FPSL_Loss;
  MaxFollowPriceSL=Max_FPSL_Loss;
  }
  if((NormalizeDouble(Bid-OSL,Digits)<=NormalizeDouble((Stoploss-StepFollowPriceSL)*DigitPoint,Digits))||(NormalizeDouble(Bid-OSL,Digits)>=NormalizeDouble((Stoploss+StepFollowPriceSL)*DigitPoint,Digits))) MovedSL=NormalizeDouble(Bid-PipsFollowPriceSL*DigitPoint,Digits);
  if(MovedSLNormalizeDouble(OOP-Stoploss*DigitPoint,Digits)) MovedSL=NormalizeDouble(OOP-Stoploss*DigitPoint,Digits);
  //---modify position by move back sl
  if((MovedSL!=0)&&(MovedSL!=OSL))
  {  
  if(!OrderModify(OrderTicket(),OOP,MovedSL,TP,0,White))
  Print("Error ",GetLastError(),"  Order Modify Buy ticket:"+OrderTicket()+" || SL ",DoubleToStr(OSL,Digits),"->",DoubleToStr(MovedSL,Digits));
  }
  }
  }
  //---
  }
  }
  //-----------------------------------------------------------------------------
  //modify sell
  if(OrderType()==OP_SELL)  
  {
  CountSell++;
  OOPsell=OrderOpenPrice();
  if((TypeOperation==1)||(TypeOperation==2))
  {
  if(HideStopLoss==false)
  {
  //---trailing stop
  if((TrailingStop!=0)&&(OOP-Ask>=TrailingStart*DigitPoint))
  {
  //---dynamic trailing stop
  if(UseDynamicTSL) TSL=TrailingStop*MathMax(1,((NormalizeDouble((((OOP-Ask)/DigitPoint)/PipsChangeDSL)-0.5,0))*(MultiplierDSL/2)));
  //---
  StLo=NormalizeDouble(Ask+TSL*DigitPoint,Digits); 
  if((StLo<=OOP)&&((StLo",DoubleToStr(SL,Digits));
  }
  //---move back stop loss
  if((FollowPriceSL==true)&&(((OSL>=OOP)&&(AlwaysRunFPSL==false))||((OSL>=OSL)&&(AlwaysRunFPSL==true))))
  {
  MovedSL=0;
  if(Ask<=OOP)//in profit
  {
  StepFollowPriceSL=Step_FPSL_Profit;
  PipsFollowPriceSL=Pips_FPSL_Profit;
  MaxFollowPriceSL=Max_FPSL_Profit;
  }
  else//in loss
  {
  StepFollowPriceSL=Step_FPSL_Loss;
  PipsFollowPriceSL=Pips_FPSL_Loss;
  MaxFollowPriceSL=Max_FPSL_Loss;
  }
  if((NormalizeDouble(OSL-Ask,Digits)<=NormalizeDouble((Stoploss-StepFollowPriceSL)*DigitPoint,Digits))||(NormalizeDouble(OSL-Ask,Digits)>=NormalizeDouble((Stoploss+StepFollowPriceSL)*DigitPoint,Digits))) MovedSL=NormalizeDouble(Ask+PipsFollowPriceSL*DigitPoint,Digits);
  if(MovedSL>NormalizeDouble(OOP+MaxFollowPriceSL*DigitPoint,Digits)) MovedSL=NormalizeDouble(OOP+MaxFollowPriceSL*DigitPoint,Digits);
  if(MovedSL",DoubleToStr(MovedSL,Digits));
  }
  }
  }
  //---
  }
  }
  //-----------------------------------------------------------------------------
  }
  }
  }
//-----------------------------------------------------------------------------
//Close in virtual stop loss
  if(HideStopLoss==true)
  {
  if(CountBuy==0) V_SL_Buy=-99999;
  if(CountSell==0) V_SL_Sell=99999;
  //---
  if(CountBuy>0)
  {
  V_TSLbuy=TrailingStop;
  if(V_SL_Buy==-99999) V_SL_Buy=NormalizeDouble((OOPbuy-(SPREADPOINT*DigitPoint))-Stoploss*DigitPoint,Digits);//first stop loss
  if(UseDynamicTSL) V_TSLbuy=TrailingStop*MathMax(1,(NormalizeDouble((OOPbuy-Ask)/DigitPoint,0)-0.5));//dynamic trailing
  if((FollowPriceSL==true)&&(Bid-V_TSLbuy*DigitPoint=NormalizeDouble((Stoploss+StepFollowPriceSL)*DigitPoint,Digits))) V_SL_Buy=NormalizeDouble(Bid-PipsFollowPriceSL*DigitPoint,Digits);
  if(V_SL_BuyNormalizeDouble(OOPbuy-Stoploss*DigitPoint,Digits)) V_SL_Buy=NormalizeDouble(OOPbuy-Stoploss*DigitPoint,Digits);
  }
  if(Bid-V_TSLbuy*DigitPoint>=OOPbuy) V_SL_Buy=MathMax(V_SL_Buy,NormalizeDouble(Bid-V_TSLbuy*DigitPoint,Digits));//start trailing
  if((CountBuy>0)&&(Bid<=V_SL_Buy)) CLOSEORDER(1,1);//close buy
  }
  //---
  if(CountSell>0)
  {
  V_TSLsell=TrailingStop;
  if(V_SL_Sell==99999) V_SL_Sell=NormalizeDouble((OOPsell+(SPREADPOINT*DigitPoint))+Stoploss*DigitPoint,Digits);//first stop loss
  if(UseDynamicTSL) V_TSLsell=TrailingStop*MathMax(1,(NormalizeDouble((OOP-Ask)/DigitPoint,0)-0.5));//dynamic trailing
  if((FollowPriceSL==true)&&(Ask+V_TSLsell*DigitPoint>OOPsell)&&(V_SL_Sell!=99999))//follow price stop loss
  {
  if((NormalizeDouble(V_SL_Sell-Ask,Digits)<=NormalizeDouble((Stoploss-StepFollowPriceSL)*DigitPoint,Digits))||(NormalizeDouble(V_SL_Sell-Ask,Digits)>=NormalizeDouble((Stoploss+StepFollowPriceSL)*DigitPoint,Digits))) V_SL_Sell=NormalizeDouble(Ask+PipsFollowPriceSL*DigitPoint,Digits);
  if(V_SL_Sell>NormalizeDouble(OOPsell+MaxFollowPriceSL*DigitPoint,Digits)) V_SL_Sell=NormalizeDouble(OOPsell+MaxFollowPriceSL*DigitPoint,Digits);
  if(V_SL_Sell0)&&(Ask>=V_SL_Sell)) CLOSEORDER(1,-1);//close sell
  }
  //---
  }
//-----------------------------------------------------------------------------
//Check orders and modify them (pending)
  if(HidePendingOrders==false)
  {
  for(int cnt=OrdersTotal()-1; cnt>=0; cnt--)
  {  
  if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
  {
  if(OrderType()NormalizeDouble(TrailingStep*DigitPoint,Digits)))
  {
  //---add after stop loss and take profit
  if((AddAfter_SL_TP==false)&&(HideStopLoss==false))
  {
  if((Stoploss>=STOPLEVEL)&&(Stoploss!=0)) SL=NormalizeDouble(Bid-Stoploss*DigitPoint,Digits); else SL=0;
  if((Takeprofit>=STOPLEVEL)&&(Takeprofit!=0)) TP=NormalizeDouble(Ask+Takeprofit*DigitPoint,Digits); else TP=0;
  }
  //---
  if(OrderModify(OrderTicket(),NormalizeDouble(Ask+Step*DigitPoint,Digits),SL,TP,0,CLR_NONE)) TimeBarB=TimeCurrent();
  }
  }
  }
  //-----------------------------------------------------------------------------
  //modify buylimit 
  if(OrderType()==OP_BUYLIMIT)
  {
  CountBuyLimit++;
  SL=0;
  TP=0;
  if((TypeOperation==1)||(TypeOperation==3))
  {
  PriceB=OOP;
  if((TimeBarBNormalizeDouble(TrailingStep*DigitPoint,Digits)))
  {
  //---add after stop loss and take profit
  if((AddAfter_SL_TP==false)&&(HideStopLoss==false))
  {
  if((Stoploss>=STOPLEVEL)&&(Stoploss!=0)) SL=NormalizeDouble(Bid-Stoploss*DigitPoint,Digits); else SL=0;
  if((Takeprofit>=STOPLEVEL)&&(Takeprofit!=0)) TP=NormalizeDouble(Ask+Takeprofit*DigitPoint,Digits); else TP=0;
  }
  //---
  if(OrderModify(OrderTicket(),NormalizeDouble(Bid-Step*DigitPoint,Digits),SL,TP,0,CLR_NONE)) TimeBarB=TimeCurrent();
  }
  }
  }
  //-----------------------------------------------------------------------------
  //modify sellstop 
  if(OrderType()==OP_SELLSTOP)
  {
  CountSellStop++;
  SL=0;
  TP=0;
  if((TypeOperation==1)||(TypeOperation==3))
  {
  PriceS=OOP;
  if((TimeBarSNormalizeDouble(TrailingStep*DigitPoint,Digits)))
  {
  //---add after stop loss and take profit
  if((AddAfter_SL_TP==false)&&(HideStopLoss==false))
  {
  if((Stoploss>=STOPLEVEL)&&(Stoploss!=0)) SL=NormalizeDouble(Ask+Stoploss*DigitPoint,Digits); else SL=0;
  if((Takeprofit>=STOPLEVEL)&&(Takeprofit!=0)) TP=NormalizeDouble(Bid-Takeprofit*DigitPoint,Digits); else TP=0;
  }
  //---
  if(OrderModify(OrderTicket(),NormalizeDouble(Bid-Step*DigitPoint,Digits),SL,TP,0,CLR_NONE)) TimeBarS=TimeCurrent();
  } 
  }  
  }
  //-----------------------------------------------------------------------------
  //modify selllimit 
  if(OrderType()==OP_SELLLIMIT)
  {
  CountSellLimit++;
  SL=0;
  TP=0;
  if((TypeOperation==1)||(TypeOperation==3))
  {
  PriceS=OOP;
  if((TimeBarSNormalizeDouble(TrailingStep*DigitPoint,Digits)))
  {
  //---add after stop loss and take profit
  if((AddAfter_SL_TP==false)&&(HideStopLoss==false))
  {
  if((Stoploss>=STOPLEVEL)&&(Stoploss!=0)) SL=NormalizeDouble(Ask+Stoploss*DigitPoint,Digits); else SL=0;
  if((Takeprofit>=STOPLEVEL)&&(Takeprofit!=0)) TP=NormalizeDouble(Bid-Takeprofit*DigitPoint,Digits); else TP=0;
  }
  //---
  if(OrderModify(OrderTicket(),NormalizeDouble(Ask+Step*DigitPoint,Digits),SL,TP,0,CLR_NONE)) TimeBarS=TimeCurrent();
  } 
  }  
  }
  //---
  }
  }
  }
  }
//-----------------------------------------------------------------------------
//Delete pending in KeepOnePosition
  if((KeepOnePosition==true)&&(CountBuy+CountSell!=0)) CLOSEORDER(2,0);//delete pending orders
//-----------------------------------------------------------------------------
//Out of time, close/delete orders
  if(UseTimeWindow==true)
  {
  StartHour=Time_Start+GMT_Offset;
  EndHour=Time_End+GMT_Offset;
  if(StartHour>=24) StartHour=StartHour-24;
  if(EndHour>=24) EndHour=EndHour-24;
  if((StartHour=EndHour))) Trade=false;
  if((StartHour>EndHour)&&(TimeHour(TimeCurrent())=EndHour)) Trade=false;
  if(Trade==false)
  {
  if((TypeOperation==1)||(TypeOperation==2)) CLOSEORDER(1,0);//close market positions
  if((TypeOperation==1)||(TypeOperation==3)) CLOSEORDER(2,0);//delete pending orders
  if(TypeOperation==1) CommentOperation="Out OF Session || Pending and Market";
  if(TypeOperation==2) CommentOperation="Out OF Session || Only Market";
  if(TypeOperation==3) CommentOperation="Out OF Session || Only Pending";
  ChartComment();
  return(0);
  }
  }
//-----------------------------------------------------------------------------
//indicator
  if(UseVolatilityIndi==true)
  {
  Trade=false;
  CurrentLevel=MathMin(iCustom(NULL,0,"volatility",MaPriod,IndiValue,0,0),iCustom(NULL,0,"volatility",MaPriod,IndiValue,1,0));
  if(TypeUseIndi==1) if(CurrentLevel>LevelTrade) Trade=true;
  if(TypeUseIndi==2) if(CurrentLevel=MinimumImpact)||(MinSinceNews<=MinsAfterNews&&ImpactSinceNews>=MinimumImpact))
  {
  if(TypeOperation==1) CommentOperation="Stop Of News || Pending and Market";
  if(TypeOperation==2) CommentOperation="Stop Of News || Only Market";
  if(TypeOperation==3) CommentOperation="Stop Of News || Only Pending";
  Trade=false;
  }
  }
  }
//-----------------------------------------------------------------------------
//Check spread
  if((SPREADPOINT>SpreadLimit)&&(SpreadLimit>0))
  {
  if((TypeOperation==1)||(TypeOperation==2)&&(ClosePositions==true)) CLOSEORDER(1,0);//close market positions
  if((TypeOperation==1)||(TypeOperation==3)&&(DeleteOrders==true)) CLOSEORDER(2,0);//delete pending orders
  if(TypeOperation==1) CommentOperation="Spread Too High || Pending and Market";
  if(TypeOperation==2) CommentOperation="Spread Too High || Only Market";
  if(TypeOperation==3) CommentOperation="Spread Too High || Only Pending";
  ChartComment();
  return(0);
  }
//-----------------------------------------------------------------------------
//send pending orders
  if(((TypeOperation==1)||(TypeOperation==3))&&(Trade==true))
  {
//-----------------------------------------------------------------------------
//Hide pending Order
  if(HidePendingOrders==true)
  {
  if(CountBuy==0) SendBuy=true;
  if(CountSell==0) SendSell=true;
  //---
  if(SendBuy==true)
  {
  if(V_PriceBuy==0)
  {
  TimeBarB=TimeCurrent();
  V_PriceBuy=NormalizeDouble(Ask+Step*DigitPoint,Digits);
  }
  if((TimeBarBNormalizeDouble(TrailingStep*DigitPoint,Digits)))
  {
  TimeBarB=TimeCurrent();
  V_PriceBuy=NormalizeDouble(Ask+Step*DigitPoint,Digits);
  }
  if(Ask>=V_PriceBuy)
  {
  OrderSend(Symbol(),OP_BUY,LOT(),Ask,slippage,SL,TP,OrderCom,Magic,0,CLR_NONE);
  SendBuy=false;
  V_PriceBuy=0;
  }
  }
  //---
  if(SendSell==true)
  {
  if(V_PriceSell==0)
  {
  TimeBarS=TimeCurrent();
  V_PriceSell=NormalizeDouble(Bid-Step*DigitPoint,Digits);
  }
  if((TimeBarSNormalizeDouble(TrailingStep*DigitPoint,Digits)))
  {
  TimeBarS=TimeCurrent();
  V_PriceSell=NormalizeDouble(Bid-Step*DigitPoint,Digits);
  }
  if(Bid<=V_PriceSell)
  {
  OrderSend(Symbol(),OP_SELL,LOT(),Bid,slippage,SL,TP,OrderCom,Magic,0,CLR_NONE);
  SendSell=false;
  V_PriceSell=0;
  }
  }
  //---
  }
//-----------------------------------------------------------------------------
//send buystop
  if(HidePendingOrders==false)
  {
  if(TypeOrdersSend==1)
  {
  if(((KeepOnePosition==true)&&(CountBuy+CountSell==0))||(KeepOnePosition==false))
  if((CountBuy+CountBuyStop==0)||((ContinueSendPO==true)&&(CountBuyStop==0)))
  {
  SL=0;
  TP=0;
  if((AddAfter_SL_TP==false)&&(HideStopLoss==false))
  {
  if((Stoploss>=STOPLEVEL)&&(Stoploss!=0)) SL=NormalizeDouble(Bid-Stoploss*DigitPoint,Digits); else SL=0;
  if((Takeprofit>=STOPLEVEL)&&(Takeprofit!=0)) TP=NormalizeDouble(Ask+Takeprofit*DigitPoint,Digits); else TP=0;
  }
  if(OrderSend(Symbol(),OP_BUYSTOP,LOT(),NormalizeDouble(Ask+Step*DigitPoint,Digits),slippage,SL,TP,OrderCom,Magic,0,CLR_NONE)!=-1) TimeBarB=TimeCurrent();
  }
  }
//-----------------------------------------------------------------------------
//send buylimit
  if(TypeOrdersSend==2)
  {
  if(((KeepOnePosition==true)&&(CountBuy+CountSell==0))||(KeepOnePosition==false))
  if((CountBuy+CountBuyLimit==0)||((ContinueSendPO==true)&&(CountBuyLimit==0)))
  {
  SL=0;
  TP=0;
  if((AddAfter_SL_TP==false)&&(HideStopLoss==false))
  {
  if((Stoploss>=STOPLEVEL)&&(Stoploss!=0)) SL=NormalizeDouble(Bid-Stoploss*DigitPoint,Digits); else SL=0;
  if((Takeprofit>=STOPLEVEL)&&(Takeprofit!=0)) TP=NormalizeDouble(Ask+Takeprofit*DigitPoint,Digits); else TP=0;
  }
  if(OrderSend(Symbol(),OP_BUYLIMIT,LOT(),NormalizeDouble(Bid-Step*DigitPoint,Digits),slippage,SL,TP,OrderCom,Magic,0,CLR_NONE)!=-1) TimeBarB=TimeCurrent();
  }
  }
//-----------------------------------------------------------------------------
//send sellstop
  if(TypeOrdersSend==1)
  {
  if(((KeepOnePosition==true)&&(CountBuy+CountSell==0))||(KeepOnePosition==false))
  if((CountSell+CountSellStop==0)||((ContinueSendPO==true)&&(CountSellStop==0)))
  {
  SL=0;
  TP=0;
  if((AddAfter_SL_TP==false)&&(HideStopLoss==false))
  {
  if((Stoploss>=STOPLEVEL)&&(Stoploss!=0)) SL=NormalizeDouble(Ask+Stoploss*DigitPoint,Digits); else SL=0;
  if((Takeprofit>=STOPLEVEL)&&(Takeprofit!=0)) TP=NormalizeDouble(Bid-Takeprofit*DigitPoint,Digits); else TP=0;
  }
  if(OrderSend(Symbol(),OP_SELLSTOP,LOT(),NormalizeDouble(Bid-Step*DigitPoint,Digits),slippage,SL,TP,OrderCom,Magic,0,CLR_NONE)!=-1) TimeBarS=TimeCurrent();
  }
  }
//-----------------------------------------------------------------------------
//send selllimit
  if(TypeOrdersSend==2)
  {
  if(((KeepOnePosition==true)&&(CountBuy+CountSell==0))||(KeepOnePosition==false))
  if((CountSell+CountSellLimit==0)||((ContinueSendPO==true)&&(CountSellLimit==0)))
  {
  SL=0;
  TP=0;
  if((AddAfter_SL_TP==false)&&(HideStopLoss==false))
  {
  if((Stoploss>=STOPLEVEL)&&(Stoploss!=0)) SL=NormalizeDouble(Ask+Stoploss*DigitPoint,Digits); else SL=0;
  if((Takeprofit>=STOPLEVEL)&&(Takeprofit!=0)) TP=NormalizeDouble(Bid-Takeprofit*DigitPoint,Digits); else TP=0;
  }
  if(OrderSend(Symbol(),OP_SELLLIMIT,LOT(),NormalizeDouble(Ask+Step*DigitPoint,Digits),slippage,SL,TP,OrderCom,Magic,0,CLR_NONE)!=-1) TimeBarS=TimeCurrent();
  }
  }
  //---
  }
  }
//-----------------------------------------------------------------------------
//show comments in chart
  ChartComment();
  return(0);
}
//====================================================================================================================================================//
double LOT()
{
  if(Lot>0) return(Lot);
  double LOT=NormalizeDouble(AccountFreeMargin()*risk/100/MarketInfo(Symbol(),MODE_MARGINREQUIRED),DigitsLot);
  return(MathMin(MathMax(LOT,MinLot),MaxLot));
}
//====================================================================================================================================================//
//close positions and delete orders
bool CLOSEORDER(int TypeOperation, int OrdrType)
{
  bool error=true;
  int err,nn,OT;
  for(int j=OrdersTotal()-1; j >= 0; j--)
  {
  if(OrderSelect(j,SELECT_BY_POS))
  {
  if((OrderSymbol()==Symbol())&&(OrderMagicNumber()==Magic))
  {
  OT=OrderType();
  //---close buy
  if((OT==OP_BUY)&&(TypeOperation==1)&&((OrdrType==1)||(OrdrType==0))) 
  {
  error=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),slippage,Blue);
  if(error) Comment("Closed Order: ",OrderTicket(),"  Profit: ",OrderProfit(),"  ",TimeToStr(TimeCurrent(),TIME_SECONDS));
  }
  //---close sell
  if((OT==OP_SELL)&&(TypeOperation==1)&&((OrdrType==-1)||(OrdrType==0))) 
  {
  error=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),slippage,Red);
  if(error) Comment("Closed Order: ",OrderTicket(),"  Profit: ",OrderProfit(),"  ",TimeToStr(TimeCurrent(),TIME_SECONDS));
  }
  //---delete pending
  if((OT>1)&&(TypeOperation==2))
  {
  error=OrderDelete(OrderTicket());
  if(error) Comment("Delete Order: ",OrderTicket(),"  ",TimeToStr(TimeCurrent(),TIME_SECONDS));
  }
  //---failure close
  if(!error) 
  {
  err=GetLastError();
  if(err<2) continue;
  if(err==129) 
  {
  Comment("Invalid price ",TimeToStr(TimeCurrent(),TIME_SECONDS));
  RefreshRates();
  continue;
  }
  if(err==146) 
  {
  if(IsTradeContextBusy()) Sleep(2000);
  continue;
  }
  Comment("Error: ",err,". Not close/delete ",OrderTicket()," || ",TimeToStr(TimeCurrent(),TIME_SECONDS));
  }
  }
  }
  }
  return(0);
}
//====================================================================================================================================================//
//Unique ID for orders
int UniqueMagic()
{
  int SymbolDigits=StringLen(SymbolName);
  int PairID=0;
  int cnt;
  for(cnt=0; cnt>16;
  nDay=TimeArray[1]>>16;
  nHour=TimeArray[2]&0x0000FFFF;
  nMin=TimeArray[2]>>16;
  nSec=TimeArray[3]&0x0000FFFF;
  nMilliSec=TimeArray[3]>>16;
  string LocalTimeS=FormatDateTime(nYear,nMonth,nDay,nHour,nMin,nSec);
  double GMTdiff=TimeCurrent()-StrToTime(LocalTimeS);
  return(MathRound(GMTdiff/3600.0));
}
//====================================================================================================================================================//
//Format hour
string FormatDateTime(int nYear,int nMonth,int nDay,int nHour,int nMin,int nSec)
{
  string sMonth,sDay,sHour,sMin,sSec;
  sMonth=100+nMonth;
  sMonth=StringSubstr(sMonth,1);
  sDay=100+nDay;
  sDay=StringSubstr(sDay,1);
  sHour=100+nHour;
  sHour=StringSubstr(sHour,1);
  sMin=100+nMin;
  sMin=StringSubstr(sMin,1);
  sSec=100+nSec;
  sSec=StringSubstr(sSec,1);
  return(StringConcatenate(nYear,".",sMonth,".",sDay," ",sHour,":",sMin,":",sSec));
}
//====================================================================================================================================================//
//Background in comments
void DisplayText(string StringName, string Image, int FontSize, string TypeImage, color FontColor, int Xposition, int Yposition)
{
  ObjectCreate(StringName,OBJ_LABEL,0,0,0);
  ObjectSet(StringName,OBJPROP_CORNER,0);
  ObjectSet(StringName,OBJPROP_BACK,FALSE);
  ObjectSet(StringName,OBJPROP_XDISTANCE,Xposition);
  ObjectSet(StringName,OBJPROP_YDISTANCE,Yposition);
  ObjectSetText(StringName,Image,FontSize,TypeImage,FontColor);
 return(0);
}
//====================================================================================================================================================//
//Comments in chart
void ChartComment()
{
  string StartSession="None";
  string EndSession="None";
  string LevelString="";
  //---
  if(UseVolatilityIndi==false) LevelString="Not Use Volatility";
  if((UseVolatilityIndi==true)&&(TypeUseIndi==1)) LevelString="Trade Over Limit";
  if((UseVolatilityIndi==true)&&(TypeUseIndi==2)) LevelString="Trade under Limit";
  //---
  if(UseTimeWindow==true)
  {
  if(StringLen(DoubleToStr(StartHour,0))==1) StartSession="0"+DoubleToStr(StartHour,0)+":00";
  else StartSession=DoubleToStr(StartHour,0)+":00";
  if(StringLen(DoubleToStr(EndHour,0))==1) EndSession="0"+DoubleToStr(EndHour,0)+":00";
  else EndSession=DoubleToStr(EndHour,0)+":00";
  if(MarketOp=="") MarketOp=DoubleToStr(GMT_Offset,0)+" (use for BT)";
  else
  {
  StartSession=DoubleToStr(Time_Start,0)+":00"+"+GMT offset";
  EndSession=DoubleToStr(Time_End,0)+":00"+"+GMT offset";
  if(StringLen(DoubleToStr(Time_Start,0))==1) StartSession="0"+DoubleToStr(Time_Start,0)+":00"+"+GMT offset";
  else StartSession=DoubleToStr(Time_Start,0)+":00"+"+GMT offset";
  if(StringLen(DoubleToStr(Time_End,0))==1) EndSession="0"+DoubleToStr(Time_End,0)+":00"+"+GMT offset";
  else EndSession=DoubleToStr(Time_End,0)+":00"+"+GMT offset";
  }
  }
  //---
  if(UseVolatilityIndi==false) LevelTrade=0;
  //---
  Comment("========================="+
  "\n"+CommentOperation+
  "\n========================="+
  "\nBuy Market Orders  : "+DoubleToStr(CountBuy,0)+
  "\nSell Market Orders   : "+DoubleToStr(CountSell,0)+
  "\nBuy Pending Orders : "+DoubleToStr(CountBuyStop+CountBuyLimit,0)+
  "\nSell Pending Orders  : "+DoubleToStr(CountSellStop+CountSellLimit,0)+
  "\n========================="+
  "\nTime Start  : "+StartSession+
  "\nTime End   : "+EndSession+
  "\nGMT offset : "+MarketOp+
  "\n========================="+
  "\n Levels: (Current/Limit): "+DoubleToStr(CurrentLevel,4)+" / "+DoubleToStr(LevelTrade,4)+
  "\n Info   : "+LevelString,
  "\n========================="
  );
  return(0);
}
//====================================================================================================================================================//

Recommend