Navigation´╝ÜHome > Content >

Fryonarn_v0.8.4.mq4

Time: 2013-11-22 | Download file:Fryonarn_v0.8.4.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         = "||========= Advance Stop Loss ==========||";
extern bool    FollowPriceSL    = false;
extern double  StepFollowPriceSL= 0.5;
extern double  PipsFollowPriceSL= 1.5;
extern double  MaxFollowPriceSL = 4;
extern string  Comment3         = "||========= Orders Manage ==========||";
extern bool    AddAfter_SL_TP   = true;
extern double  Stoploss         = 1;
extern double  Takeprofit       = 5;
extern double  TrailingStop     = 0.3;
extern double  TrailingStart    = 0;
extern double  TrailingStep     = 0;
extern double  Step             = 0.3;
extern int     TimeModify       = 1;
extern string  Comment4         = "||========= Volatility set ==========||";
extern bool    UseVolatilityIndi= false;
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  Comment5         = "||========= Money Management ==========||";
extern double  Lot              = 0.01;
extern int     risk             = 20;
extern int     DigitsLot        = 2;
extern string  Comment6         = "||========= 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  Comment7         = "||========= 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;
int TimeBarB;
int TimeBarS;
int CountBuy;
int CountSell;
int CountBuyStop;
int CountSellStop;
int CntCheck=0;
int StartHour;
int EndHour;
int MultiplierPoint;
//====================================================================================================================================================//
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;
//-----------------------------------------------------------------
//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()  
{
  datetime TimeTek=TimeCurrent();
  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 MovedSL=0;
  CountBuy=0;
  CountSell=0;
  CountBuyStop=0;
  CountSellStop=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;
  //-----------------------------------------------------------------------------
  //modify buy
  if(OrderType()==OP_BUY)  
  {  
  CountBuy++;
  if((TypeOperation==1)||(TypeOperation==2))
  {
  //---trailing stop
  if((TrailingStop!=0)&&(Bid-(OOP-SPREADPOINT*DigitPoint)>=TrailingStart*DigitPoint))
  {
  StLo=NormalizeDouble(Bid-TrailingStop*DigitPoint,Digits); 
  if((StLo>=(OOP-SPREADPOINT*DigitPoint))&&((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=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++;
  if((TypeOperation==1)||(TypeOperation==2))
  {
  //---trailing stop
  if((TrailingStop!=0)&&((OOP+SPREADPOINT*DigitPoint)-Ask>=TrailingStart*DigitPoint))
  {
  StLo=NormalizeDouble(Ask+TrailingStop*DigitPoint,Digits); 
  if((StLo<=(OOP+SPREADPOINT*DigitPoint))&&((StLo",DoubleToStr(SL,Digits));
  }
  //---move back stop loss
  if((FollowPriceSL==true)&&(OSL>OOP))
  {
  MovedSL=0;
  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));
  }
  }
  //---
  }
  }
  //-----------------------------------------------------------------------------
  }
  }
  }
//-----------------------------------------------------------------------------
//Check orders and modify them (pending)
  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)
  {
  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 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)
  {
  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();
  } 
  }  
  }
  }
  }
  }
//-----------------------------------------------------------------------------
//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);//close market positions
  if((TypeOperation==1)||(TypeOperation==3)) CLOSEORDER(2);//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(CurrentLevelSpreadLimit)&&(SpreadLimit>0))
  {
  if((TypeOperation==1)||(TypeOperation==2)&&(ClosePositions==true)) CLOSEORDER(1);//close market positions
  if((TypeOperation==1)||(TypeOperation==3)&&(DeleteOrders==true)) CLOSEORDER(2);//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 buystop
  if(((TypeOperation==1)||(TypeOperation==3))&&(Trade==true))
  {
  if(CountBuy+CountBuyStop==0)
  {
  SL=0;
  TP=0;
  if(AddAfter_SL_TP==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 sellstop
  if(CountSell+CountSellStop==0)
  {
  SL=0;
  TP=0;
  if(AddAfter_SL_TP==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();
  }
  }
//-----------------------------------------------------------------------------
//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)
{
  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))
  {
  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)) 
  {
  error=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),slippage,Red);
  if(error) Comment("Closed Order: ",OrderTicket(),"  Profit: ",OrderProfit(),"  ",TimeToStr(TimeCurrent(),TIME_SECONDS));
  }
  //---delete buystop
  if((OT==OP_BUYSTOP)&&(TypeOperation==2))
  {
  error=OrderDelete(OrderTicket());
  if(error) Comment("Delete Order: ",OrderTicket(),"  ",TimeToStr(TimeCurrent(),TIME_SECONDS));
  }
  //---close sellstop
  if((OT==OP_SELLSTOP)&&(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";
  }
  }
  //---
  Comment("========================="+
  "\n"+CommentOperation+
  "\n========================="+
  "\nBuy Orders: "+CountBuy+
  "\nSell Orders : "+CountSell+
  "\nBuyStop Orders: "+CountBuyStop+
  "\nSellStop Orders : "+CountSellStop+
  "\n========================="+
  "\nTimeStart: "+StartSession+
  "\nTimeEnd : "+EndSession+
  "\nGMToffset : "+MarketOp+
  "\n========================="+
  "\n Levels: (Current/Limit): "+DoubleToStr(CurrentLevel,4)+" / "+DoubleToStr(LevelTrade,4)+
  "\n Info: "+LevelString,
  "\n========================="
  );
  return(0);
}
//====================================================================================================================================================//

Recommend