Vous êtes sur la page 1sur 15

//+------------------------------------------------------------------+

//|
MTF_EA.mq4
|
//|
Copyright 2012
|
//|
Written by MrDharmesh from idea of Jason Robinson for Eric
|
|
//+------------------------------------------------------------------+
#property copyright "Copyright 2012, MrDharmesh"
#include <stdlib.mqh>
//---extern bool AccountIsMini=false;
// Change to true if trading mini account
extern bool MoneyManagement=false;
// Change to false to shutdown money mana
gement controls.
//---// Lots = 1 will be in effect and only 1
lot will be open regardless of equity.
extern double TradeSizePercent=5;
// Change to whatever percent of equity y
ou wish to risk.
extern double Lots=0.01;
// standard lot size.
extern double MaxLots=100;
//+---------------------------------------------------+
//|Indicator Variables
|
//| Change these to try your own system
|
//| or add more if you like
|
//+---------------------------------------------------+
//+---------------------------------------------------+
//|Money Management
|
//+---------------------------------------------------+
extern double StopLoss=25;
// Maximum pips willing to lose per positio
n.
extern bool UseTrailingStop=false;
extern int TrailingStopType=3;
// Type 1 moves stop immediately, Type 2 w
aits til value of TS is reached
extern double TrailingStop=40;
// Change to whatever number of pips you w
ish to trail your position with.
extern double TRStopLevel_1=20;
// Type 3 first level pip gain
extern double TrailingStop1=20;
// Move Stop to Breakeven
extern double TRStopLevel_2=30;
// Type 3 second level pip gain
extern double TrailingStop2=20;
// Move stop to lock is profit
extern double TRStopLevel_3=50;
// type 3 third level pip gain
extern double TrailingStop3=20;
// Move stop and trail from there
extern int TakeProfit=0;
// Maximum profit level achieved.
extern double Margincutoff=800;
// Expert will stop trading if equity leve
l decreases to that level.
extern int Slippage=10;
// Possible fix for not getting closed
//+---------------------------------------------------+
//|General controls
|
//+---------------------------------------------------+
int MagicNumber;
string setup;
bool YesStop;
double lotMM;
int TradesInThisSymbol;
int buyqty=0;
int sellqty=0;
double Highofall;
double Lowofall;

double UsePoint;
int UseSlippage;
int goforsell=0;
int goforbuy=0;
int lastbuy=0;
int lastsell=0;
double lastHighofall;
double lastLowofall;
double lowestofall;
double highestofall;
int TrendUp;
int TrendDown;
double em20;
//+------------------------------------------------------------------+
//| expert initialization function
|
//+------------------------------------------------------------------+
int init()
{
setup="50Pipi " + Symbol() + "_" + func_TimeFrame_Val2String(func_TimeFrame_C
onst2Val(Period()));
MagicNumber=3000 + func_Symbol2Val(Symbol())*100 + func_TimeFrame_Const2Val(P
eriod());
UsePoint = PipPoint(Symbol());
UseSlippage = GetSlippage(Symbol(),Slippage);
//---return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function
|
//+------------------------------------------------------------------+
int deinit()
{
}
//+------------------------------------------------------------------------+
//| LSMA - Least Squares Moving Average function calculation
|
//| LSMA_In_Color Indicator plots the end of the linear regression line
|
//| Modified to use any timeframe
|
//+------------------------------------------------------------------------+
//+------------------------------------------------------------------+
bool CheckExitCondition(string TradeType)
{
bool YesClose;
//---YesClose=false;
// Check for cross down
if (TradeType=="BUY" && buyqty==1 ) YesClose=true;
// Check for cross up

if (TradeType=="SELL" && sellqty==1 ) YesClose=true;


//---return(YesClose);
}
//+------------------------------------------------------------------+
//| CheckEntryCondition
|
//| Check if entry condition is met
|
//+------------------------------------------------------------------+
bool CheckEntryCondition(string TradeType)
{
bool YesTrade;
//---YesTrade=false;
double
double
double
double

Close1=Close[1];
Close2=Close[2];
Close3=Close[3];
Close4=Close[4];

double
double
double
double

Open1=Open[1];
Open2=Open[2];
Open3=Open[3];
Open4=Open[4];

double
double
double
double

low1=Low[1];
low2=Low[2];
low3=Low[3];
low4=Low[4];

double
double
double
double

High1=High[1];
High2=High[2];
High3=High[3];
High4=High[4];

int i=0;
int j=0;

if(Close1 > Open1)


{
i++;
}
else j++;
if(Close2 > Open2)
{
i++;
}
else j++;
if(Close3 > Open3)
{
i++;
}
else j++;

if(Close4 > Open4)


{
i++;
}
else j++;
// Buy Order
int Go=0;
int NoGo=0;

if(i==2 && j==2)


{
Go=1;
}
else NoGo=1;

Highofall=Close[iHighest(NULL,0,MODE_CLOSE,4,1)];
Lowofall=Close[iLowest(NULL,0,MODE_CLOSE,4,1)];
em20= iMA(NULL,PERIOD_H1,20,0,MODE_EMA,PRICE_CLOSE,0);
// Check for cross up
if (TradeType=="BUY" && Go==1 && Ask > Highofall && em20 ) YesTrade=true;
// Check for cross down
if (TradeType=="SELL" && Go==1 && Bid < Lowofall && em20 )YesTrade=true;
//---return(YesTrade);
}
//+------------------------------------------------------------------+
//| expert start function
|
//+------------------------------------------------------------------+
int start()
{
// Check for valid inputs
if (CheckValidUserInputs()) return(0);
lowestofall=Close[iLowest(NULL,0,MODE_LOW,45,4)];
highestofall=Close[iHighest(NULL,0,MODE_HIGH,45,4)];
lastHighofall=High[iHighest(NULL,0,MODE_HIGH,4,1)];
lastLowofall=Low[iLowest(NULL,0,MODE_LOW,4,1)];
double trend1=lastHighofall-lowestofall;
double trend2=highestofall-lastLowofall;
double po=200*UsePoint;
if(trend1 > po)
{
TrendUp=1;
TrendDown=0;
}
//Alert("last trend up");
if(trend2 > po)

{
TrendUp=0;
TrendDown=1;
}
//Alert("last trend down");
//+------------------------------------------------------------------+
//| Check for Open Position
|
//+------------------------------------------------------------------+
HandleOpenPositions();
TradesInThisSymbol=openPositions() + openStops();
//+------------------------------------------------------------------+
//| Check if OK to make new trades
|
//+------------------------------------------------------------------+
if(AccountFreeMargin() < Margincutoff)
{
return(0);
}
// Only allow 1 trade per Symbol
if(TradesInThisSymbol > 0)
{
return(0);
}
lotMM=GetLots();
if(CheckEntryCondition("BUY"))
{
OpenBuyStopOrder();
}
if(CheckEntryCondition("SELL"))
{
OpenSellStopOrder();
}
//---return(0);
}
//+------------------------------------------------------------------+
//| Functions beyond this point should not need to be modified
|
//| Eventually will be placed in include file
|
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Open BuyStop
|
//| Open a new trade using Buy Stop
|
//| If Stop Loss or TakeProfit are used the values are calculated
|
//| for each trade
|
//+------------------------------------------------------------------+
void OpenBuyStopOrder()
{
int err,ticket;
ticket=OrderSend(Symbol(),OP_BUY,lotMM,Ask,Slippage,0,0,setup,MagicNumber,0,G
reen);
buyqty=1;
lastbuy=1;
lastsell=0;
if(ticket<=0)
{
err=GetLastError();
Print("Error opening BUY STOP order [" + setup + "]: (" + err + ") " + Err
orDescription(err));

}
}
//+------------------------------------------------------------------+
//| Open SellStop
|
//| Open a new trade using Sell Stop
|
//| If Stop Loss or TakeProfit are used the values are calculated
|
//| for each trade
|
//+------------------------------------------------------------------+
void OpenSellStopOrder()
{
int err, ticket;
ticket=OrderSend(Symbol(),OP_SELL,lotMM,Bid,Slippage,0,0,setup,MagicNumber,0,
Red);
sellqty=1;
lastsell=1;
lastbuy=0;
if(ticket<=0)
{
err=GetLastError();
Print("Error opening Sell order [" + setup + "]: (" + err + ") " + ErrorDe
scription(err));
}
}
//+------------------------------------------------------------------------+
//| counts the number of open positions
|
//+------------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|
|
//+------------------------------------------------------------------+
int openPositions( )
{
int op =0;
for(int i=OrdersTotal()-1;i>=0;i--)
// scan al
l orders and positions...
{
OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if (OrderMagicNumber()!=MagicNumber) continue;
if(OrderSymbol()==Symbol() )
{
if(OrderType()==OP_BUY)op++;
if(OrderType()==OP_SELL)op++;
}
}
return(op);
}
//+------------------------------------------------------------------------+
//| counts the number of STOP positions
|
//+------------------------------------------------------------------------+
int openStops()
{ int op =0;
for(int i=OrdersTotal()-1;i>=0;i--)
// scan al
l orders and positions...
{
OrderSelect(i, SELECT_BY_POS,MODE_TRADES);
if (OrderMagicNumber()!=MagicNumber) continue;
if(OrderSymbol()==Symbol() )
{
if(OrderType()==OP_BUYSTOP)op++;

if(OrderType()==OP_SELLSTOP)op++;
}
}
return(op);
}
//+------------------------------------------------------------------+
//| Handle Open Positions
|
//| Check if any open positions need to be closed or modified
|
//+------------------------------------------------------------------+
int HandleOpenPositions()
{
int cnt;
bool YesClose;
double pt;
for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
{
OrderSelect (cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol()!=Symbol()) continue;
if(OrderMagicNumber()!=MagicNumber) continue;
if(OrderType()==OP_BUY)
{
//Alert("order select",cnt,"orderprofit",OrderProfit());
//if(buyqty==1)
///{
//OrderModify(OrderTicket(),OrderOpenPrice(),Lowofall,0,0,Blue);
// buyqty=2;
// }
double
double
double
double

op=OrderProfit();
oop=OrderOpenPrice();
osl=OrderStopLoss();
otp=OrderTakeProfit();

if(Ask-OrderOpenPrice() > (100*UsePoint))


{
//if(Ask-OrderStopLoss()> (120*UsePoint))
//{
OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+50*Us
ePoint,OrderOpenPrice()+400*UsePoint,0,Blue);
//}
}

if (CheckExitCondition("BUY"))
{
OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-50*UsePo
int,OrderOpenPrice()+150*UsePoint,0,Blue);
buyqty=2;
//goforbuy=2;
//CloseOrder(OrderTicket(),OrderLots(),Bid);
}
else
{
if (UseTrailingStop)
{

HandleTrailingStop("BUY",OrderTicket(),OrderOpenPrice(),OrderStop
Loss(),OrderTakeProfit());
}
}
}
if(OrderType()==OP_SELL)
{
//if(sellqty==1)
//{
//OrderModify(OrderTicket(),OrderOpenPrice(),Highofall,0,0,Blue);
//sellqty=2;
// }
////if(OrderOpenPrice()-Ask > (80*UsePoint) )
//{
// OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+40*UsePoi
nt,OrderOpenPrice()-200*UsePoint,0,Blue);
//sellqty=3;
//}
if(OrderOpenPrice()-Ask > (100*UsePoint) )
{
//if(OrderStopLoss()-Ask > (120*UsePoint))
OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-50*UsePoint
,OrderOpenPrice()-400*UsePoint,0,Blue);
}
if (CheckExitCondition("SELL"))
{
OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+50*UsePo
int,OrderOpenPrice()-150*UsePoint,0,Blue);
sellqty=2;
//goforsell=2;
//CloseOrder(OrderTicket(),OrderLots(),Ask);
}
else
{
if(UseTrailingStop)
{
HandleTrailingStop("SELL",OrderTicket(),OrderOpenPrice(),OrderSto
pLoss(),OrderTakeProfit());
}
}
}
//Close pending orders
if (OrderType()==OP_BUYSTOP && CheckExitCondition("BUY")) DeleteOrder( Ord
erTicket() );
if (OrderType()==OP_SELLSTOP && CheckExitCondition("SELL")) DeleteOrder( O
rderTicket() );
}
}
//+------------------------------------------------------------------+
//| Delete Open Position Controls
|
//| Try to close position 3 times
|
//+------------------------------------------------------------------+
void DeleteOrder(int ticket)
{

int CloseCnt, err;


// try to close 3 Times
CloseCnt=0;
while(CloseCnt < 3)
{
if (OrderDelete(ticket))
{
CloseCnt=3;
}
else
{
err=GetLastError();
Print(CloseCnt," Error deleting order : (", err , ") " + ErrorDescripti
on(err));
if (err > 0) CloseCnt++;
}
}
}
//+------------------------------------------------------------------+
//| Close Open Position Controls
|
//| Try to close position 3 times
|
//+------------------------------------------------------------------+
void CloseOrder(int ticket,double numLots,double close_price)
{
int CloseCnt, err;
// try to close 3 Times
CloseCnt=0;
while(CloseCnt < 3)
{
if (OrderClose(ticket,numLots,close_price,Slippage,Violet))
{
CloseCnt=3;
}
else
{
err=GetLastError();
Print(CloseCnt," Error closing order : (", err , ") " + ErrorDescriptio
n(err));
if (err > 0) CloseCnt++;
}
}
}
//+------------------------------------------------------------------+
//| Modify Open Position Controls
|
//| Try to modify position 3 times
|
//+------------------------------------------------------------------+
void ModifyOrder(int ord_ticket,double op, double price,double tp)
{
int CloseCnt, err;
CloseCnt=0;
while(CloseCnt < 3)
{
if (OrderModify(ord_ticket,op,price,tp,0,Aqua))
{
CloseCnt=3;
}
else
{
err=GetLastError();
Print(CloseCnt," Error modifying order : (", err , ") " + ErrorDescript

ion(err));
if (err>0) CloseCnt++;
}
}
}
//+------------------------------------------------------------------+
//| HandleTrailingStop
|
//| Type 1 moves the stoploss without delay.
|
//| Type 2 waits for price to move the amount of the trailStop
|
//| before moving stop loss then moves like type 1
|
//| Type 3 uses up to 3 levels for trailing stop
|
//|
Level 1 Move stop to 1st level
|
//|
Level 2 Move stop to 2nd level
|
//|
Level 3 Trail like type 1 by fixed amount other than 1
|
//| Possible future types
|
//| Type 4 uses 2 for 1, every 2 pip move moves stop 1 pip
|
//| Type 5 uses 3 for 1, every 3 pip move moves stop 1 pip
|
//+------------------------------------------------------------------+
int HandleTrailingStop(string type, int ticket, double op, double os, double tp)
{
double pt, TS=0;
double bos,bop,opa,osa;
if (type=="BUY")
{
switch(TrailingStopType)
{
case 1: pt=Point*StopLoss;
if(Bid-os > pt) ModifyOrder(ticket,op,Bid-pt,tp);
break;
case 2: pt=Point*TrailingStop;
if(Bid-op > pt && os < Bid - pt) ModifyOrder(ticket,op,Bid - pt,tp);
break;
case 3: if (Bid - op > TRStopLevel_1 * Point)
{
TS=op + TRStopLevel_1*Point - TrailingStop1 * Point;
if (os < TS)
{
ModifyOrder(ticket,op,TS,tp);
}
}
if (Bid - op > TRStopLevel_2 * Point)
{
TS=op + TRStopLevel_2*Point - TrailingStop2 * Point;
if (os < TS)
{
ModifyOrder(ticket,op,TS,tp);
}
}
if (Bid - op > TRStopLevel_3 * Point)
{
//
TS = op + TRStopLevel_3 * Point - TrailingSt
op3*Point;
TS=Bid - TrailingStop3*Point;
if (os < TS)
{
ModifyOrder(ticket,op,TS,tp);
}
}
break;
}

return(0);
}
if (type== "SELL")
{
switch(TrailingStopType)
{
case 1: pt=Point*StopLoss;
if(os - Ask > pt) ModifyOrder(ticket,op,Ask+pt,tp);
break;
case 2: pt=Point*TrailingStop;
if(op - Ask > pt && os > Ask+pt) ModifyOrder(ticket,op,Ask+pt,tp);
break;
case 3: if (op - Ask > TRStopLevel_1 * Point)
{
TS=op - TRStopLevel_1 * Point + TrailingStop1 * Point;
if (os > TS)
{
ModifyOrder(ticket,op,TS,tp);
}
}
if (op - Ask > TRStopLevel_2 * Point)
{
TS=op - TRStopLevel_2 * Point + TrailingStop2 * Point;
if (os > TS)
{
ModifyOrder(ticket,op,TS,tp);
}
}
if (op - Ask > TRStopLevel_3 * Point)
{
//
TS = op - TRStopLevel_3 * Point + TrailingSto
p3 * Point;
TS=Ask + TrailingStop3 * Point;
if (os > TS)
{
ModifyOrder(ticket,op,TS,tp);
}
}
break;
}
}
return(0);
}
//+------------------------------------------------------------------+
//| Get number of lots for this trade
|
//+------------------------------------------------------------------+
double GetLots()
{
double lot;
if(MoneyManagement)
{
lot=LotsOptimized();
}
else
{
lot=Lots;
if(AccountIsMini)
{
if (lot > 1.0) lot=lot/10;
if (lot < 0.1) lot=0.1;

}
}
return(lot);
}
//+------------------------------------------------------------------+
//| Calculate optimal lot size
|
//+------------------------------------------------------------------+
double LotsOptimized()
{
double lot=Lots;
//---- select lot size
lot=NormalizeDouble(MathFloor(AccountFreeMargin()*TradeSizePercent/10000)/10,
1);
// lot at this point is number of standard lots
// if (Debug) Print ("Lots in LotsOptimized : ",lot);
// Check if mini or standard Account
if(AccountIsMini)
{
lot=MathFloor(lot*10)/10;
// Use at least 1 mini lot
if(lot<0.1) lot=0.1;
if (lot > MaxLots) lot=MaxLots;
}
else
{
if (lot < 1.0) lot=1.0;
if (lot > MaxLots) lot=MaxLots;
}
return(lot);
}
//+------------------------------------------------------------------+
//| Time frame interval appropriation function
|
//+------------------------------------------------------------------+
int func_TimeFrame_Const2Val(int Constant)
{
switch(Constant)
{
case 1: // M1
return(1);
case 5: // M5
return(2);
case 15:
return(3);
case 30:
return(4);
case 60:
return(5);
case 240:
return(6);
case 1440:
return(7);
case 10080:
return(8);
case 43200:
return(9);
}
}
//+------------------------------------------------------------------+
//| Time frame string appropriation function
|

//+------------------------------------------------------------------+
string func_TimeFrame_Val2String(int Value)
{
switch(Value)
{
case 1: // M1
return("PERIOD_M1");
case 2: // M1
return("PERIOD_M5");
case 3:
return("PERIOD_M15");
case 4:
return("PERIOD_M30");
case 5:
return("PERIOD_H1");
case 6:
return("PERIOD_H4");
case 7:
return("PERIOD_D1");
case 8:
return("PERIOD_W1");
case 9:
return("PERIOD_MN1");
default:
return("undefined " + Value);
}
}
//+-----------------------------------------------------------------+
//|
|
//+-----------------------------------------------------------------+
int func_Symbol2Val(string symbol)
{
if(symbol=="AUDCAD")
{
return(1);
}
else if(symbol=="AUDJPY")
{
return(2);
}
else if(symbol=="AUDNZD")
{
return(3);
}
else if(symbol=="AUDUSD")
{
return(4);
}
else if(symbol=="CHFJPY")
{
return(5);
}
else if(symbol=="EURAUD")
{
return(6);
}
else if(symbol=="EURCAD")

{
return(7);
}
else if(symbol=="EURCHF")
{
return(8);
}
else if(symbol=="EURGBP")
{
return(9);
}
else if(symbol=="EURJPY")
{
return(10);
}
else if(symbol=="EURUSD")
{
return(11);
}
else if(symbol=="GBPCHF")
{
return(12);
}
else if(symbol=="GBPJPY")
{
return(13);
}
else if(symbol=="GBPUSD")
{
return(14);
}
else if(symbol=="NZDUSD")
{
return(15);
}
else if(symbol=="USDCAD")
{
return(16);
}
else if(symbol=="USDCHF")
{
return(17);
}
else if(symbol=="USDJPY")
{
return(18);
}
else
{
Comment("unexpected Symbol");
return(0);
}
}
//+-----------------------------------------------------------------+
//| CheckValidUserInputs
|
//| Check if User Inputs are valid for ranges allowed
|
//| return true if invalid input, false otherwise

|
//| Also display an alert for invalid input
|
//+-----------------------------------------------------------------+
bool CheckValidUserInputs()
{
if (CheckTrailingStopType(TrailingStopType))
{
Alert("TrailingStopType( 1 to 3) You entered ",TrailingS
topType);
return(true);
}
}
//+------------------------------------------------+
//| Check for valid TrailingStopType
|
//| |
//| return true if invalid, false if OK
|
//+------------------------------------------------+
bool CheckTrailingStopType(int stop_type)
{
if (stop_type < 0)return(true);
if (stop_type > 3) return(true);
return(false);
}
//+------------------------------------------------------------------+
// Pip Point Function
double PipPoint(string Currency)
{
int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
if(CalcDigits == 2 || CalcDigits == 3) double CalcPoint = 0.01;
else if(CalcDigits == 4 || CalcDigits == 5) CalcPoint = 0.0001;
return(CalcPoint);
}
// Get Slippage Function
int GetSlippage(string Currency, int SlippagePips)
{
int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
if(CalcDigits == 2 || CalcDigits == 4) double CalcSlippage = SlippagePips;
else if(CalcDigits == 3 || CalcDigits == 5) CalcSlippage = SlippagePips * 10;
return(CalcSlippage);
}

Vous aimerez peut-être aussi