HMA Stochastic Divergence Trader
Download scriptThis script is an automated trading system designed to execute trades based on the identification of specific market price behaviors, specifically focusing on "divergence" and trend confirmation. It uses a combination of technical indicators to decide when to enter the market, manage existing risk, and determine when to exit a position.
Core Trading Logic
The system identifies entry points by looking for discrepancies between price action and momentum (Divergence). It primarily utilizes two main components to generate signals:
- Stochastic Divergence: The script monitors a specialized Stochastic oscillator. It looks for specific patterns where the price movement and the indicator movement are not aligned, signaling a potential shift in market direction.
- Trend Confirmation (HMA): To ensure the trades align with the current momentum, the system uses a Hull Moving Average (HMA). It checks if the HMA is trending in the desired direction before authorizing a trade, acting as a safety filter to avoid trading against a strong trend.
Advanced Filters
The script includes several optional "filters" to refine the entry logic and increase accuracy:
- Moving Average Filter: This allows the system to only take trades that align with a longer-term trend (e.g., only buying when the price is above a certain average).
- Time Filter: Users can restrict the bot to operate only during specific hours of the trading day, which is useful for avoiding low-liquidity periods or high-volatility news events.
- Reversal Mode: A setting that allows the user to flip the logic entirely, turning buy signals into sell signals and vice versa.
Trade & Money Management
Beyond just opening trades, the script handles the "lifecycle" of a position with professional management tools:
- Dynamic Lot Sizing: It includes a Money Management system that can automatically calculate trade sizes based on a percentage of your account balance. It also supports "Martingale" logic, which adjusts trade sizes based on previous performance.
- Trade Protection: The script features automated Take Profit (TP) and Stop Loss (SL) levels.
- Dynamic Movement: It includes a Trailing Stop, which moves the stop loss as the price moves in your favor to lock in profits, and a Breakeven function that moves the stop loss to the entry price once a certain profit threshold is reached.
Execution Behavior
The script is designed to manage multiple positions and can be configured to "cumulate" positions (adding more trades in the same direction) or limit the total number of open orders at one time. It also includes error handling for insufficient funds and ensures that it only interacts with specific currency pairs and "Magic Numbers" (unique IDs) to avoid interfering with other manual or automated trades.
//+------------------------------------------------------------------+
//| HMA Stochastic Divergence Trader.mq4 |
//| Copyright © 2008, TradingSytemForex |
//| http://www.tradingsystemforex.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, TradingSytemForex"
#property link "http://www.tradingsystemforex.com"
#define OrSt "HMA Stochastic Divergence Trader"
extern string SD="---------------- Stoch Div Settings";
extern int KPeriod=8;
extern int DPeriod=3;
extern int Slowing=3;
extern string HMA="---------------- HMA Settings";
extern bool UseHMAConfirmation=true;
extern int HMAPeriod=15;
extern int HMAMethod=3;
extern int HMAPrice=0;
extern string LM="---------------- Lot Management";
extern double Lots=0.1;
extern bool MM=false; //money management
extern double Risk=10; //risk in percentage
extern bool Martingale=false; //martingale
extern double Multiplier=1.5; //multiplier
extern double MinProfit=0; //minimum profit to apply the martingale
extern string TSTB="---------------- TP SL TS BE";
bool EnableRealSL=false;
int RealSL=5; //stop loss under 15 pîps
bool EnableRealTP=false;
int RealTP=10; //take profit under 10 pîps
extern int SL=0; //stop loss
extern int TP=0; //take profit
extern int TS=0; //trailing stop
int TSStep=1; //trailing step
extern int BE=0; //breakeven
extern string EXT="---------------- Extras";
extern bool Reverse=false;
extern bool AddPositions=false; //positions cumulated
extern int MaxOrders=100; //maximum number of orders
extern bool MAFilter=false; //moving average filter
extern int MAPeriod=20;
extern int MAMethod=1;
extern int MAPrice=0;
extern bool TimeFilter=false; //time filter
extern int StartHour=8;
extern int EndHour=21;
extern int Magic=0;
int Slip=3;static int TL=0;double Balance=0.0;int err=0;int TK;
// expert start function
int start(){int j=0,limit=1;double BV=0,SV=0;BV=0;SV=0;
if(CntO(OP_BUY,Magic)>0)TL=1;if(CntO(OP_SELL,Magic)>0)TL=-1;for(int i=1;i<=limit;i++){
string TIFI="false";
if(TimeFilter){if(!(Hour()>=StartHour && Hour()<=EndHour)){TIFI="true";}}
double MAF=iMA(Symbol(),0,MAPeriod,0,MAMethod,MAPrice,i);
string MAFIB="false";string MAFIS="false";
if(MAFilter){if(Bid>MAF)MAFIB="true";if(Ask<MAF)MAFIS="true";}
if(MAFilter==false){MAFIB="true";MAFIS="true";}
double STD1=iCustom(Symbol(),0,"Stochastic_Divergence V2",KPeriod,DPeriod,Slowing,0,i+1);
double STD2=iCustom(Symbol(),0,"Stochastic_Divergence V2",KPeriod,DPeriod,Slowing,1,i+1);
double STD3=iCustom(Symbol(),0,"Stochastic_Divergence V2",KPeriod,DPeriod,Slowing,0,i);
double STD4=iCustom(Symbol(),0,"Stochastic_Divergence V2",KPeriod,DPeriod,Slowing,1,i);
double HMA4=iCustom(Symbol(),0,"HMA",HMAPeriod,HMAMethod,HMAPrice,2,i+3);
double HMA3=iCustom(Symbol(),0,"HMA",HMAPeriod,HMAMethod,HMAPrice,2,i+2);
double HMA2=iCustom(Symbol(),0,"HMA",HMAPeriod,HMAMethod,HMAPrice,2,i+1);
double HMA1=iCustom(Symbol(),0,"HMA",HMAPeriod,HMAMethod,HMAPrice,2,i);
string HMABuy="false";string HMASell="false";string HMABuyClose="false";string HMASellClose="false";
if(UseHMAConfirmation){
if(HMA1>HMA2)HMABuy="true";
if(HMA1<HMA2)HMASell="true";
if(HMA1>HMA2)HMASellClose="true";
if(HMA1<HMA2)HMABuyClose="true";
}
if(UseHMAConfirmation==false){HMABuy="true";HMASell="true";}
string SBUY="false";string SSEL="false";
if(STD1<EMPTY_VALUE&&STD3>0)SBUY="true";
if(STD2<EMPTY_VALUE&&STD4>0)SSEL="true";
if(HMABuy=="true"&&MAFIB=="true"&&SBUY=="true"&&TIFI=="false"){if(Reverse)SV=1;else BV=1;break;}
if(HMASell=="true"&&MAFIS=="true"&&SSEL=="true"&&TIFI=="false"){if(Reverse)BV=1;else SV=1;break;}}
// expert money management
if(MM){if(Risk<0.1||Risk>100){Comment("Invalid Risk Value.");return(0);}
else{Lots=MathFloor((AccountFreeMargin()*AccountLeverage()*Risk*Point*100)/(Ask*MarketInfo(Symbol(),MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_MINLOT)))*MarketInfo(Symbol(),MODE_MINLOT);}}
if(MM==false){Lots=Lots;}
if(Balance!=0.0&&Martingale==True){if(Balance>AccountBalance())Lots=Multiplier*Lots;else if((Balance+MinProfit)<AccountBalance())Lots=Lots/Multiplier;else if((Balance+MinProfit)>=AccountBalance()&&Balance<=AccountBalance())Lots=Lots;}Balance=AccountBalance();
// expert init positions
int cnt=0,OP=0,OS=0,OB=0,CS=0,CB=0;OP=0;for(cnt=0;cnt<OrdersTotal();cnt++){OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if((OrderType()==OP_SELL||OrderType()==OP_BUY)&&OrderSymbol()==Symbol()&&((OrderMagicNumber()==Magic)||Magic==0))OP=OP+1;}
if(OP>=1){OS=0; OB=0;}OB=0;OS=0;CB=0;CS=0;
// expert conditions to open position
if(SV>0){OS=1;OB=0;}if(BV>0){OB=1;OS=0;}
// expert conditions to close position
if((SV>0)||(HMABuyClose=="true")||(TIFI=="true")||(EnableRealSL&&(OrderOpenPrice()-Bid)/Point>=RealSL)||(EnableRealTP&&(Ask-OrderOpenPrice())/Point>=RealTP)){CB=1;}
if((BV>0)||(HMASellClose=="true")||(TIFI=="true")||(EnableRealSL&&(Ask-OrderOpenPrice())/Point>=RealSL)||(EnableRealTP&&(OrderOpenPrice()-Bid)/Point>=RealTP)){CS=1;}
for(cnt=0;cnt<OrdersTotal();cnt++){OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
if(OrderType()==OP_BUY&&OrderSymbol()==Symbol()&&((OrderMagicNumber()==Magic)||Magic==0)){if(CB==1){OrderClose(OrderTicket(),OrderLots(),Bid,Slip,Red);return(0);}}
if(OrderType()==OP_SELL&&OrderSymbol()==Symbol()&&((OrderMagicNumber()==Magic)||Magic==0)){if(CS==1){OrderClose(OrderTicket(),OrderLots(),Ask,Slip,Red);return(0);}}}double SLI=0,TPI=0;int TK=0;
// expert open position value
if((AddP()&&AddPositions&&OP<=MaxOrders)||(OP==0&&!AddPositions)){
if(OS==0&&OB==0){Comment("no order opened");}
if(OS==1){if(TP==0)TPI=0;else TPI=Bid-TP*Point;if(SL==0)SLI=0;else SLI=Bid+SL*Point;TK=OrderSend(Symbol(),OP_SELL,Lots,Bid,Slip,SLI,TPI,OrSt,Magic,0,Red);OS=0;Comment("sell order opened","\n","magic number : ",Magic);return(0);}
if(OB==1){if(TP==0)TPI=0;else TPI=Ask+TP*Point;if(SL==0)SLI=0;else SLI=Ask-SL*Point;TK=OrderSend(Symbol(),OP_BUY,Lots,Ask,Slip,SLI,TPI,OrSt,Magic,0,Lime);OB=0;Comment("buy order opened","\n","magic number : ",Magic);return(0);}}
for(j=0;j<OrdersTotal();j++){if(OrderSelect(j,SELECT_BY_POS,MODE_TRADES)){if(OrderSymbol()==Symbol()&&((OrderMagicNumber()==Magic)||Magic==0)){TrP();}}}return(0);}
// expert number of orders
int CntO(int Type,int Magic){int _CntO;_CntO=0;
for(int j=0;j<OrdersTotal();j++){OrderSelect(j,SELECT_BY_POS,MODE_TRADES);if(OrderSymbol()==Symbol()){if((OrderType()==Type&&(OrderMagicNumber()==Magic)||Magic==0))_CntO++;}}return(_CntO);}
//expert breakeven
void TrP(){double pb,pa,pp;pp=MarketInfo(OrderSymbol(),MODE_POINT);if(OrderType()==OP_BUY){pb=MarketInfo(OrderSymbol(),MODE_BID);
if(BE>0){if((pb-OrderOpenPrice())>BE*pp){if((OrderStopLoss()-OrderOpenPrice())<0){ModSL(OrderOpenPrice()+0*pp);}}}
// expert trailing stop
if(TS>0){if((pb-OrderOpenPrice())>TS*pp){if(OrderStopLoss()<pb-(TS+TSStep-1)*pp){ModSL(pb-TS*pp);return;}}}}
if(OrderType()==OP_SELL){pa=MarketInfo(OrderSymbol(),MODE_ASK);if(BE>0){if((OrderOpenPrice()-pa)>BE*pp){if((OrderOpenPrice()-OrderStopLoss())<0){ModSL(OrderOpenPrice()-0*pp);}}}
if(TS>0){if(OrderOpenPrice()-pa>TS*pp){if(OrderStopLoss()>pa+(TS+TSStep-1)*pp||OrderStopLoss()==0){ModSL(pa+TS*pp);return;}}}}}
//expert stoploss
void ModSL(double ldSL){bool fm;fm=OrderModify(OrderTicket(),OrderOpenPrice(),ldSL,OrderTakeProfit(),0,CLR_NONE);}
//expert add positions function
bool AddP(){int _num=0; int _ot=0;
for (int j=0;j<OrdersTotal();j++){if(OrderSelect(j,SELECT_BY_POS)==true && OrderSymbol()==Symbol()&&OrderType()<3&&((OrderMagicNumber()==Magic)||Magic==0)){
_num++;if(OrderOpenTime()>_ot) _ot=OrderOpenTime();}}if(_num==0) return(true);if(_num>0 && ((Time[0]-_ot))>0) return(true);else return(false);
if(TK<0){if (GetLastError()==134){err=1;Print("NOT ENOGUGHT MONEY!!");}return (-1);}}
Comments