Navigation´╝ÜHome > Content >

CrossMA-EA_v0.2.mq4

Time: 2010-07-08 | Download file:CrossMA-EA_v0.2.mq4

//===================================================================================================================//
// email: nikolaospantzos@gmail.com                                                                                  //       
//===================================================================================================================//
#property copyright "Copyright 2013 by PanNik"
//----------------------- Externals ----------------------------------------------------------------
extern string Money_Management  = "==== Money Management ====";
extern bool   MoneyManagement   = true;     // Auto lot size
extern bool   RiskBaseStopLoss  = false;    // Calculate risk factor base stop loss
extern double RiskFactor        = 10;       // Risk for money management (from 0.1 to 50)
extern double ManualLotSize     = 0.01;     // Manual lot size
extern bool   RecoveryLot       = false;    // Recovery lot if loss order
extern double MultiplierLot     = 2;        // Multiplier lot recovery
extern string SetOrders         = "==== Set Orders Parametre ====";
extern bool   UseTakeProfit     = true;     // Use take profit
extern double TakeProfit        = 20;       // Profit for all orders
extern bool   UseStopLoss       = true;     // Use stop loss
extern double StopLoss          = 10;       // Loss for all orders
extern bool   UseTrailingStop   = false;    // Use trailing stop loss
extern double TrailingStop      = 20;       // Pips for trailing stop
extern bool   UseBreakEven      = true;     // Use break even 
extern double BreakEven         = 5;        // Pips for break even
extern double BreakEvenAfter    = 0;        // Pips plus break even
extern string IndiParametre     = "==== Set Indicator Parametre ====";
extern int    PeriodFastMA      = 13;       // Parameter 1
extern int    PeriodSlowMA      = 200;      // Parameter 2
extern double PipsLimit         = 3;        // Parameter 3
extern int    BarsLimits        = 25;       // Parameter 4
extern string SignalsParametre  = "==== Set Signals Parametre ====";
extern string TypeSignalUseInf  = "1:normal signal, 2:reverse signal";
extern int    TypeSignalUse     = 1;        // Signal to open
extern string CloseOrders       = "==== Close Orders ====";
extern bool   AutoCloseOrders   = true;     // Auto close ordres
extern string TimeFilter        = "==== Time Filter ====";
extern bool   UseTimeFilter     = false;    //Start stop time
extern int    TimeStartTrade    = 0;        //Time to start trade expert
extern int    TimeEndTrade      = 0;        //Time to stop trade expert
extern string ManageOrders      = "==== Manage Orders Set ====";
extern double MaxSpread         = 0;        // Maximum spread in pips, 0:Not check spread
extern double Slippage          = 3;        // Maximum slipage in pips
extern int    MagicNumber       = 777;      // Identifier
extern int    MaxOpenPositions  = 1;        //Maximum opened orders
extern string SetGeneral        = "==== General Set ====";
extern bool   RunNDDbroker      = false;    // If broker not accept sl or tp in open order
extern int    SizeBackGround    = 156;      // Size for background
extern bool   SoundAlert        = true;     // Play sound if open, close or modify order
//===================================================================================================================//
string SoundFileAtOpen="alert.wav";
string SoundFileAtClose="alert2.wav";
string SoundModify="tick.wav";
string ExpertName;
string EASymbol;
double DigitPoint;
double StopLevel;
double LocalTrail;
double CurrentSpread;
double Spread;
double TotalProfitLoss=0;
double TotalPips=0;
int TotalTrades=0;
int WinsTrades=0;
int LossesTrades=0;
int OrderTime;
int MultiplierPoint;
int StartTime;
int OrdersOpened;
int RunOrders;
int Signal;
int BarsUp=0;
int BarsDn=0;
bool CheckSpread;
bool CountHistory=true;
bool BuyDir=false;
bool SellDir=false;
bool CloseBuy;
bool CloseSell;
//===================================================================================================================//
//init function
int init()
{
//------------------------------------------------------
//Started information
ExpertName=WindowExpertName();
EASymbol=Symbol();
StartTime=TimeLocal();
//------------------------------------------------------
//Broker 4 or 5 digits
DigitPoint=MarketInfo(Symbol(),MODE_POINT);
MultiplierPoint=1;
if(MarketInfo(Symbol(),MODE_DIGITS)==3||MarketInfo(Symbol(),MODE_DIGITS)==5)
{
MultiplierPoint=10;
DigitPoint*=MultiplierPoint;
}
//------------------------------------------------------
//Minimum trailing, take profit and stop loss
StopLevel=MathMax(MarketInfo(Symbol(),MODE_FREEZELEVEL)/MultiplierPoint,MarketInfo(Symbol(),MODE_STOPLEVEL)/MultiplierPoint);
if((TrailingStop>0)&&(TrailingStop0)&&(BreakEven0)&&(TakeProfit0)&&(StopLossMaxSpread)&&(MaxSpread>0))//for forward test warning message
{
CheckSpread=false;
Print("Spread is greater than MaxSpread!!! (Spread: "+DoubleToStr(Spread,1)+" || MaxSpread: "+DoubleToStr(MaxSpread,1)+")");
Print("Expert check again spread....");
CurrentSpread=Spread;
}
//---
if((SpreadMaxSpread)&&(MaxSpread>0))//for backtest warning message
{
CheckSpread=false;
Print("Spread is greater than MaxSpread!!! (Spread: "+DoubleToStr(Spread,1)+" || MaxSpread: "+DoubleToStr(MaxSpread,1)+")");
}
//------------------------------------------------------
//Do if there is opened orders
if(isMgNum(MagicNumber)>0)
{
RunOrders=1;//there is open order
//------------------------------------------------------
//Call modify orders functions
if((UseTrailingStop==true)||(UseBreakEven==true)) ModifyOrders();
//------------------------------------------------------
//Call close orders functions
if(AutoCloseOrders==true)
{
GetSignal();
CloseOrders();
}
}//End if(isMgNum(MagicNumber)>0)
//------------------------------------------------------
//Check time to trade
if(UseTimeFilter==true)
{
if((TimeStartTradeTimeEndTrade))) return(0);
else
if((TimeStartTrade>TimeEndTrade)&&((TimeHour(TimeCurrent())=TimeEndTrade))) return(0);
}
//------------------------------------------------------
//Start check signal
if(CheckSpread==true)
{
//------------------------------------------------------
//Buy
if(isMgNum(MagicNumber)0)&&(UseTakeProfit==true)) TP=NormalizeDouble(Ask+OrderTP,Digits);
if((StopLoss>0)&&(UseStopLoss==true)) SL=NormalizeDouble(Bid-OrderSL,Digits);
if((TrailingStop>0)&&(UseStopLoss==false)&&(UseTrailingStop==true)&&(SL==0)) SL=NormalizeDouble(Bid-TrailingSL,Digits);
TypeOfOrder="Buy";
}
//------------------------------------------------------
//Sell stop loss and take profit in price
if(PositionType==OP_SELL)
{
TP=0;
SL=0;
OpenPrice=NormalizeDouble(Bid,Digits);
OpenColor=Red;
if((TakeProfit>0)&&(UseTakeProfit==true)) TP=NormalizeDouble(Bid-OrderTP,Digits);
if((StopLoss>0)&&(UseStopLoss==true)) SL=NormalizeDouble(Ask+OrderSL,Digits);
if((TrailingStop>0)&&(UseStopLoss==false)&&(UseTrailingStop==true)&&(SL==0)) SL=NormalizeDouble(Ask+TrailingSL,Digits);
TypeOfOrder="Sell";
}
//------------------------------------------------------
//NDD broker, no sl no tp
if(RunNDDbroker==true)
{
TP=0;
SL=0;
}
//------------------------------------------------------
//Send orders
OpenOrderTicket=OrderSend(EASymbol,PositionType,CalcLots(),OpenPrice,Slippage,SL,TP,ExpertName,MagicNumber,0,OpenColor);
//---
if(OpenOrderTicket>0)
{
if(SoundAlert==true) PlaySound(SoundFileAtOpen);
Print(ExpertName+" M"+Period()+" "+TypeOfOrder);
break;
}
//---
else
{
Print(ExpertName+": receives new data and try again open order");
Sleep(100);
RefreshRates();
}
//---
}//End while(true)
//------------------------------------------------------
//NDD send stop loss and take profit
if((RunNDDbroker==true)&&(OpenOrderTicket>0))
{
if(OrderSelect(OpenOrderTicket,SELECT_BY_TICKET))
{
//------------------------------------------------------
//Modify stop loss and take profit buy order
if((OrderType()==OP_BUY)&&(OrderStopLoss()==0)&&(OrderTakeProfit()==0))
{
while(true) 
{
TP=0;
SL=0;
if((TakeProfit>0)&&(UseTakeProfit==true)) TP=NormalizeDouble(Ask+OrderTP,Digits);
if((StopLoss>0)&&(UseStopLoss==true)) SL=NormalizeDouble(Bid-OrderSL,Digits);
if((TrailingStop>0)&&(UseStopLoss==false)&&(UseTrailingStop==true)) SL=NormalizeDouble(Bid-TrailingStop,Digits);
//---
WasOrderModified=OrderModify(OrderTicket(),NormalizeDouble(OrderOpenPrice(),Digits),SL,TP,0,Blue);
//---
if(WasOrderModified>0)
{
if(SoundAlert==true) PlaySound(SoundModify);
Print(ExpertName+": modify buy by NDDmode, ticket: "+OrderTicket());
break;
}
//---
else
{
Print("Error: ",GetLastError()+" || "+ExpertName+": receives new data and try again modify order");
RefreshRates();
}
//---
}//End while(true)
}//End if((OrderType()
//------------------------------------------------------
//Modify stop loss and take profit sell order
if((OrderType()==OP_SELL)&&(OrderStopLoss()==0)&&(OrderTakeProfit()==0))
{
while(true) 
{
TP=0;
SL=0;
if((TakeProfit>0)&&(UseTakeProfit==true)) TP=NormalizeDouble(Bid-OrderTP,Digits);
if((StopLoss>0)&&(UseStopLoss==true)) SL=NormalizeDouble(Ask+OrderSL,Digits);
if((TrailingStop>0)&&(UseStopLoss==false)&&(UseTrailingStop==true)) SL=NormalizeDouble(Ask+TrailingStop,Digits);
//---
WasOrderModified=OrderModify(OrderTicket(),NormalizeDouble(OrderOpenPrice(),Digits),SL,TP,0,Red);
//---
if(WasOrderModified>0)
{
if(SoundAlert==true) PlaySound(SoundModify);
Print(ExpertName+": modify sell by NDDmode, ticket: "+OrderTicket());
break;
}
//---
else
{
Print("Error: ",GetLastError()+" || "+ExpertName+": receives new data and try again modify order");
RefreshRates();
}
//---
}//End while(true)
}//End if((OrderType()
//------------------------------------------------------
}//End OrderSelect(...
//------------------------------------------------------
}//End if(RunNDDbroker==true)
return(0);
}
//===================================================================================================================//
//modify orders
void ModifyOrders()
{
double PriceComad=0;
double LocalStopLoss=0;
bool WasOrderModified;
string CommentModify;
//------------------------------------------------------
//Select order
for(int i=0; i0)&&(UseBreakEven==true)&&(Bid-OrderOpenPrice()>=(BreakEven+BreakEvenAfter)*DigitPoint)&&(NormalizeDouble(OrderOpenPrice()+BreakEven*DigitPoint,Digits)<=Bid-(StopLevel*DigitPoint)))//&&(OrderStopLoss()0)&&(UseTrailingStop==true)&&(NormalizeDouble(Bid-LocalTrail*DigitPoint,Digits)>OrderStopLoss()))
{
PriceComad=NormalizeDouble(Bid-LocalTrail*DigitPoint,Digits);
LocalStopLoss=LocalTrail;
CommentModify="trailing stop";
}
//-----------------------
//Modify
if((LocalStopLoss>0)&&(PriceComad!=NormalizeDouble(OrderStopLoss(),Digits)))
WasOrderModified=OrderModify(OrderTicket(),0,PriceComad,NormalizeDouble(OrderTakeProfit(),Digits),0,Blue);
else break;
//---
if(WasOrderModified>0)
{
if(SoundAlert==true) PlaySound(SoundModify);
Print(ExpertName+": modify buy by "+CommentModify+", ticket: "+OrderTicket());
break;
}
//---
else
{
Print("Error: ",GetLastError()+" || "+ExpertName+": receives new data and try again modify order");
RefreshRates();
}
//---
}//End while(true)
}//End if(OrderType()
//------------------------------------------------------
//Modify sell
if(OrderType()==OP_SELL)
{
WasOrderModified=false;
LocalStopLoss=0.0;
while(true)
{
//-----------------------
//Break even
if((LocalStopLoss==0)&&(BreakEven>0)&&(UseBreakEven==true)&&(OrderOpenPrice()-Ask>=(BreakEven+BreakEvenAfter)*DigitPoint)&&(NormalizeDouble(OrderOpenPrice()-BreakEven*DigitPoint,Digits)>=Ask+(StopLevel*DigitPoint)))//&&(OrderStopLoss()>OrderOpenPrice()))
{
PriceComad=NormalizeDouble(OrderOpenPrice()-BreakEven*DigitPoint,Digits);
LocalStopLoss=BreakEven;
CommentModify="break even";
}
//-----------------------
//Trailing stop
if((LocalStopLoss==0)&&(LocalTrail>0)&&(UseTrailingStop==true)&&(NormalizeDouble(Ask+LocalTrail*DigitPoint,Digits)0)&&(PriceComad!=NormalizeDouble(OrderStopLoss(),Digits)))
WasOrderModified=OrderModify(OrderTicket(),0,PriceComad,NormalizeDouble(OrderTakeProfit(),Digits),0,Red);
else break;
//---
if(WasOrderModified>0)
{
if(SoundAlert==true) PlaySound(SoundModify);
Print(ExpertName+": modify sell by "+CommentModify+", ticket: "+OrderTicket());
break;
}
//---
else
{
Print("Error: ",GetLastError()+" || "+ExpertName+": receives new data and try again modify order");
RefreshRates();
}
//---
}//End while(true)
}//End if(OrderType()
//------------------------------------------------------
}//End if((OrderSymbol()...
}//End OrderSelect(...
}//End for(...
return(0);
}
//===================================================================================================================//
//close orders
void CloseOrders()
{
bool WasOrderClosed;
//------------------------------------------------------
for(int i=OrdersTotal()-1; i>=0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
if((OrderSymbol()==EASymbol)&&(OrderMagicNumber()==MagicNumber))
{
//------------------------------------------------------
//Close buy
if(OrderType()==OP_BUY)
{
WasOrderClosed=false;
while(true) 
{
//------------------------------------------------------
if(CloseBuy==true)
WasOrderClosed=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),Slippage,Yellow);
else break;
//---
if(WasOrderClosed>0)
{
if(SoundAlert==true) PlaySound(SoundFileAtClose);
Print(ExpertName+": close buy, ticket: "+OrderTicket());
break;
}
//---
else
{
Print("Error: ",GetLastError()+" || "+ExpertName+": receives new data and try again close order");
RefreshRates();
}
//---
}//End while(...
}//End if(OrderType()==OP_BUY)
//------------------------------------------------------
//Close sell
if(OrderType()==OP_SELL)
{
WasOrderClosed=false;
while(true) 
{
//------------------------------------------------------
if(CloseSell==true)
WasOrderClosed=OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),Slippage,Yellow);
else break;
//---
if(WasOrderClosed>0)
{
if(SoundAlert==true) PlaySound(SoundFileAtClose);
Print(ExpertName+": close sell, ticket: "+OrderTicket());
break;
}
//---
else
{
Print("Error: ",GetLastError()+" || "+ExpertName+": receives new data and try again close order");
RefreshRates();
}
//---
}//End while(...
}//End if(OrderType()==OP_SELL)
//------------------------------------------------------
}//End if((OrderSymbol()...
}//End OrderSelect(...
}//End for(...
return(0);
}
//===================================================================================================================//
//Get magic number orders
int isMgNum(int Magic)
{
int SumOrders=0;
for(int i=0; i=0)) Multiplier=1;
}
}
}
//------------------------------------------------------
//lot size
if(Multiplier>1) Lot=NormalizeDouble(MathMin(MathMax(LastLot*Multiplier,MinLot),MaxLot),LotDigit);
else
Lot=NormalizeDouble(MathMin(MathMax(LotSize*Multiplier,MinLot),MaxLot),LotDigit);
//------------------------------------------------------
return(Lot);
}
//===================================================================================================================//
//comment in chart
void CommentScreen()
{
string FirstOrderString="First Order Opened:  Not opened order yet";
string MMstring="";
string StringSpread="";
double PrintMaxSpread=MaxSpread;
//------------------------------------------------------
//Calculate total profit or loss, trades and pips
if(CountHistory==true)
{
for(int iCnt=OrdersHistoryTotal()-1; iCnt>=0; iCnt--)
{      
if(OrderSelect(iCnt,SELECT_BY_POS,MODE_HISTORY))
{
if((OrderType()<=OP_SELL)&&(OrderMagicNumber()==MagicNumber))
{
OrderTime=OrderOpenTime();//Calculate time to open first order
TotalTrades++;//Calculate total orders
//------------------------------------------------------
//wins orders
if(OrderProfit()>=0)
{
WinsTrades++;
TotalProfitLoss+=OrderProfit()+OrderCommission()+OrderSwap();
TotalPips+=(MathMax(OrderOpenPrice(),OrderClosePrice())-MathMin(OrderOpenPrice(),OrderClosePrice()))/
(MarketInfo(OrderSymbol(),MODE_POINT)*MultiplierPoint);
}
//------------------------------------------------------
//Losses orders
if(OrderProfit()<0)
{
LossesTrades++;
TotalProfitLoss-=MathAbs(OrderProfit()+OrderCommission()+OrderSwap());
TotalPips-=(MathMax(OrderOpenPrice(),OrderClosePrice())-MathMin(OrderOpenPrice(),OrderClosePrice()))/
(MarketInfo(OrderSymbol(),MODE_POINT)*MultiplierPoint);
}
//------------------------------------------------------
}//End if((...
}//End OrderSelect(...
}//End for(...
}
//------------------------------------------------------
//String first order
if(TimeToStr(OrderTime,TIME_DATE)>"2000") FirstOrderString="First Order Opened:  "+TimeToStr(OrderTime,TIME_DATE|TIME_SECONDS);
//------------------------------------------------------
//String money management
if(MoneyManagement==true) MMstring="AUTO";
if(MoneyManagement==false) MMstring="MANUAL";
//------------------------------------------------------
//String spread
if(MaxSpread==0) StringSpread="   EA NOT CHECK SPREAD,  Expert running";
if((Spread<=MaxSpread)&&(MaxSpread>0)) StringSpread="   SPREAD IS ACCEPT,  Expert is running";
if((Spread>MaxSpread)&&(MaxSpread>0)) StringSpread="SPREAD IS NOT ACCEPT. EA stop running";
//------------------------------------------------------
//Comment in chart
Comment("=============================","\n",
" ACCOUNT NUMBER : ",AccountNumber(),"\n",
" ACCOUNT NAME     : ",AccountName(),"\n",
"=============================","\n",
" MAXIMUM SPREAD: ",PrintMaxSpread,",  PAIR SPREAD: ",Spread,"\n",
StringSpread,"\n",
"=============================","\n",
" Money Management: ",MMstring,",  LOT : ",CalcLots(),"\n",
"=============================","\n",
FirstOrderString,"\n",
"=============================","\n",
"Magic Number: ",MagicNumber,",  Total_Trades: ",TotalTrades,"\n",
"WINS_TRADES : ",WinsTrades,",  LOSSES_TRADES: ",LossesTrades,"\n",
"TOTAL_PIPS  : ",TotalPips,",  TOTAL_P/L: ",TotalProfitLoss,"\n",
"=============================");
//------------------------------------------------------
return(0);
}
//===================================================================================================================//
//Orders signals
void GetSignal()
{
int ReverseSignals=0;
CloseBuy=false;
CloseSell=false;
Signal=0;
//------------------------------------------------------
//Reverse signal
if(TypeSignalUse==1) ReverseSignals=1;
if(TypeSignalUse==2) ReverseSignals=-1;
//------------------------------------------------------
//Indicator set
double FastMAhigh=iMA(NULL,0,PeriodFastMA,0,MODE_SMA,PRICE_HIGH,0);
double FastMAlow=iMA(NULL,0,PeriodFastMA,0,MODE_SMA,PRICE_LOW,0);
double SlowMA=iMA(NULL,0,PeriodSlowMA,0,MODE_SMA,PRICE_CLOSE,0);
double FastMAhigh1=iMA(NULL,0,PeriodFastMA,0,MODE_SMA,PRICE_HIGH,1);
double FastMAlow1=iMA(NULL,0,PeriodFastMA,0,MODE_SMA,PRICE_LOW,1);
double SlowMA1=iMA(NULL,0,PeriodSlowMA,0,MODE_SMA,PRICE_CLOSE,1);
//------------------------------------------------------
//Count bars
if((FastMAhigh>SlowMA)&&(FastMAlow>SlowMA)&&((FastMAhigh1SlowMA1)||(FastMAlow1>SlowMA1))) BarsDn=iBars(NULL,0);
//------------------------------------------------------
//Signals open close orders
if((FastMAhigh>SlowMA)&&(FastMAlow>SlowMA)&&(Ask-SlowMA>0)&&(Ask-SlowMA<=PipsLimit*DigitPoint))
{
if((isMgNum(MagicNumber)>0)&&(AutoCloseOrders==true)) CloseSell=true;
if((BuyDir==false)&&(isMgNum(MagicNumber)==0)&&(iBars(NULL,0)-BarsUp<=BarsLimits))
{
Signal=1;
BuyDir=true;
SellDir=false;
}
}
if((FastMAhigh0)&&(SlowMA-Bid<=PipsLimit*DigitPoint))
{
if((isMgNum(MagicNumber)>0)&&(AutoCloseOrders==true)) CloseBuy=true;
if((SellDir==false)&&(isMgNum(MagicNumber)==0)&&(iBars(NULL,0)-BarsDn<=BarsLimits))
{
Signal=-1;
BuyDir=false;
SellDir=true;
}
}
//------------------------------------------------------
//Reset direction
if((FastMAhigh>SlowMA)&&(FastMAlow>SlowMA)&&(SellDir==true)) SellDir=false;
if((FastMAhigh        

Recommend