Stochastic Divergence Trader

Download script
Author: Ron Thompson
Profit factor:
0.37

Overview

The Stochastic Divergence Trader is an automated trading system designed to identify and capitalize on specific price movements by analyzing the relationship between two different technical indicators: the Stochastic Oscillator and the Hull Moving Average (HMA).

Instead of simply looking at where the price is going, this script looks for "divergence"—a situation where the momentum of the market (represented by the Stochastic indicator) disagrees with the actual price action.

Core Trading Logic

The system operates based on a multi-layered verification process before entering a trade:

1. Momentum Analysis (Stochastic Divergence) The script constantly calculates the difference between two lines of the Stochastic Oscillator (the Main and Signal lines). It looks for a specific "gap" or divergence value.

  • Buy Signal: Triggered when the divergence falls within a specific positive range.
  • Sell Signal: Triggered when the divergence falls within a specific negative range.

2. Trend Confirmation (HMA) To ensure the trades are moving in the right direction, the script includes an optional confirmation layer using the Hull Moving Average. This acts as a filter; even if a divergence is detected, the system can be configured to only execute the trade if the HMA confirms that the broader trend supports the move.

3. Trade Execution & Visual Feedback When the conditions are met, the script automatically places an order with a predefined lot size. It also provides real-time visual feedback on the chart by placing "B" (Buy) or "S" (Sell) markers at the exact moment an entry occurs.

Automated Money Management

Once a trade is live, the script actively manages the position to protect your capital and maximize profit:

  • Profit and Loss Limits: Every trade is governed by hard limits. It will automatically close a position if it hits a pre-defined profit target or a maximum allowable loss.
  • Break-Even Protection: The system includes a "Break-Even" feature. Once a trade reaches a certain amount of profit, the script moves the stop-loss to the entry price (plus a small cushion). This ensures that if the market turns around, you won't lose money on a winning trade.
  • Trailing Stop: For very profitable moves, the script can "trail" the price. As the market moves in your favor, the stop-loss follows behind it, locking in gains as they happen.
  • Basket Management: On a broader scale, the system monitors your total account equity. If your total open profit (or loss) hits a specific "Basket" target, it will automatically close all open positions to secure the funds.

Summary of Behavior

This script is designed for a trader who wants to automate the identification of momentum shifts while maintaining strict discipline over risk. It combines momentum detection (Stochastic), trend filtering (HMA), and dynamic trade management (Trailing Stops and Break-Even) into a single automated workflow.

Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategyIt Closes Orders by itself
Indicators Used
Stochastic oscillator
Miscellaneous
Uses files from the file systemIt writes information to fileIt issuies visual alerts to the screen
15 Views
0 Downloads
0 Favorites
Stochastic Divergence Trader
//+------------------------------------------------------------------+
//|                                 Stochastic Divergence Trader.mq4 |
//|                      Copyright © 2008, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"

/*
+--------+
|Divergence Trader
+--------+
*/


// variables declared here are GLOBAL in scope

#property copyright "Ron Thompson"
#property link      "http://www.lightpatch.com/forex"

// user input
extern double Lots=0.10;              // how many lots to trade at a time 
extern int KPeriod=8;
extern int DPeriod=3;
extern int Slowing=3;
extern bool   UseHMAConfirmation=true;
extern int HMAPeriod=15;
extern int HMAMethod=3;
extern int HMAPrice=0;
extern double DVBuySell=0.0011;
extern double DVStayOut=0.0073;
extern double ProfitMade=20;          // how much money do you expect to make
extern double LossLimit=115;          // how much loss can you tolorate
extern double TrailStop=9999;         // trailing stop (999=no trailing stop)
extern int    PLBreakEven=9999;       // set break even when this many pips are made (999=off)
extern int    BasketProfit=  10;      // if equity reaches this level, close trades
extern int    BasketLoss=9999;        // if equity reaches this negative level, close trades


// externals that don't need to be external
       int    Slippage=2;             // how many pips of slippage can you tolorate
       bool   FileData=false;         // write to file exery tick?

// naming and numbering
int      MagicNumber  = 200601182020; // allows multiple experts to trade on same account
string   TradeComment = "Divergence_07_";

// Bar handling
datetime bartime=0;                   // used to determine when a bar has moved
int      bartick=0;                   // number of times bars have moved
int      objtick=0;                   // used to draw objects on the chart
int      tickcount=0;

// Trade control
bool TradeAllowed=true;               // used to manage trades

// Min/Max tracking
double maxOrders;
double maxEquity;
double minEquity;



//+-------------+
//| Custom init |
//|-------------+
// Called ONCE when EA is added to chart or recompiled

int init()
  {
   int    i;
   string o;
   
   //remove the old objects 
   for(i=0; i<Bars; i++) 
     {
      o=DoubleToStr(i,0);
      ObjectDelete("myx"+o);
      ObjectDelete("myz"+o);
     }
   objtick=0;

   ObjectDelete("Cmmt");
   ObjectCreate( "Cmmt", OBJ_TEXT, 0, Time[20], High[20]+(5*Point) );
   ObjectSetText("Cmmt","Divergence=X.XXXX",10,"Arial",White);

   Print("Init happened ",CurTime());
   Comment(" ");
  }

//+----------------+
//| Custom DE-init |
//+----------------+
// Called ONCE when EA is removed from chart

int deinit()
  {
   int    i;
   string o;
   //remove the old objects 
   
   for(i=0; i<Bars; i++) 
     {
      o=DoubleToStr(i,0);
      ObjectDelete("myx"+o);
      ObjectDelete("myz"+o);
     }

   objtick=0;
   
   Print("MAX number of orders ",maxOrders);
   Print("MAX equity           ",maxEquity);
   Print("MIN equity           ",minEquity);
      
   Print("DE-Init happened ",CurTime());
   Comment(" ");
  }


//+-----------+
//| Main      |
//+-----------+
// Called EACH TICK and each Bar[]

int start()
  {

   double p=Point;
   double spread=Ask-Bid;
   double spread2=(Ask-Bid)+2*Point; // for setting unattended stoploss and takeprofit
   
   int      cnt=0;
   int      gle=0;
   int      OrdersPerSymbol=0;
   
   int      iFileHandle;
  
   // stoploss and takeprofit and close control
   double SL=0;
   double TP=0;
   double CurrentProfit=0;
   double CurrentBasket=0;
   
   // direction control
   bool BUYme=false;
   bool SELLme=false;
   
   
   // Trade stuff
   double diverge;
   double maF1, maS1;

   // bar counting
   if(bartime!=Time[0]) 
     {
      bartime=Time[0];
      bartick++; 
      objtick++;
      TradeAllowed=true;
     }

   OrdersPerSymbol=0;
   for(cnt=OrdersTotal();cnt>=0;cnt--)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
        {
         OrdersPerSymbol++;
        }
     }
   if(OrdersPerSymbol>maxOrders) maxOrders=OrdersPerSymbol;

   double HMA1=iCustom(Symbol(),0,"HMA",HMAPeriod,HMAMethod,HMAPrice,0,1);
   double HMA2=iCustom(Symbol(),0,"HMA",HMAPeriod,HMAMethod,HMAPrice,2,1);
   string HMABuyUse="false";string HMASellUse="false";
   if(UseHMAConfirmation){if(HMA1<EMPTY_VALUE)HMABuyUse="true";if(HMA2<EMPTY_VALUE)HMASellUse="true";}

   //+-----------------------------+
   //| Insert your indicator here  |
   //| And set either BUYme or     |
   //| SELLme true to place orders |
   //+-----------------------------+

   maF1=iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MODE_SMA,0,MODE_MAIN,0);

   maS1=iStochastic(NULL,0,KPeriod,DPeriod,Slowing,MODE_SMA,0,MODE_SIGNAL,0);

   diverge=(maF1-maS1);
   
   ObjectDelete("Cmmt");
   ObjectCreate("Cmmt", OBJ_TEXT, 0, Time[20], High[20]+(10*p));
   ObjectSetText("Cmmt","Divergence="+DoubleToStr(diverge,4),10,"Arial",White);
   if( diverge>= DVBuySell       && diverge<= DVStayOut       && (UseHMAConfirmation==false||HMABuyUse=="true")) BUYme=true;
   if( diverge<=(DVBuySell*(-1)) && diverge>=(DVStayOut*(-1)) && (UseHMAConfirmation==false||HMASellUse=="true")) SELLme=true;
   
   if(FileData)
     {
      tickcount++;
      iFileHandle = FileOpen("eaDivergence07", FILE_CSV|FILE_READ|FILE_WRITE, ",");
      FileSeek(iFileHandle, 0, SEEK_END);
      FileWrite(iFileHandle, bartick, " ", tickcount, " ", diverge);
      FileFlush(iFileHandle);
      FileClose(iFileHandle);
     }

   //+------------+
   //| End Insert |
   //+------------+

   //ENTRY LONG (buy, Ask) 
   if(TradeAllowed && BUYme)
      {
       //Ask(buy, long)
      if(LossLimit ==0) SL=0; else SL=Ask-( (LossLimit +7)*Point );
      if(ProfitMade==0) TP=0; else TP=Ask+( (ProfitMade+7)*Point );
      OrderSend(Symbol(),OP_BUY,Lots,Ask,Slippage,SL,TP,TradeComment,MagicNumber,White);
      gle=GetLastError();
      if(gle==0)
        {
         Print("BUY  Ask=",Ask," bartick=",bartick);
         ObjectCreate("myx"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], High[0]+(5*p));
         ObjectSetText("myx"+DoubleToStr(objtick,0),"B",15,"Arial",Red);
         bartick=0;
         TradeAllowed=false;
        }
         else 
        {
         Print("-----ERROR----- BUY  Ask=",Ask," error=",gle," bartick=",bartick);
        }
     }
        
   //ENTRY SHORT (sell, Bid)
   if(TradeAllowed && SELLme)
     {
      //Bid (sell, short)
      if(LossLimit ==0) SL=0; else SL=Bid+((LossLimit+7)*Point );
      if(ProfitMade==0) TP=0; else TP=Bid-((ProfitMade+7)*Point );
      OrderSend(Symbol(),OP_SELL,Lots,Bid,Slippage,SL,TP,TradeComment,MagicNumber,Red);
      gle=GetLastError();
      if(gle==0)
        {
         Print("SELL Bid=",Bid," bartick=",bartick); 
         ObjectCreate("myx"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], High[0]+(5*p));
         ObjectSetText("myx"+DoubleToStr(objtick,0),"S",15,"Arial",Red);
         bartick=0;
         TradeAllowed=false;
        }
         else 
        {
         Print("-----ERROR----- SELL Bid=",Bid," error=",gle," bartick=",bartick);
        }
     }

     
   //Basket profit or loss
   CurrentBasket=AccountEquity()-AccountBalance();
   
   if(CurrentBasket>maxEquity) maxEquity=CurrentBasket;
   if(CurrentBasket<minEquity) minEquity=CurrentBasket;
   
   // actual basket closure
   if( CurrentBasket>=BasketProfit || CurrentBasket<=(BasketLoss*(-1)) )
     {
      CloseEverything();
     }

 
   // CLOSE order if profit target made
   for(cnt=OrdersTotal();cnt>=0;cnt--)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber )
        {
        
         if(OrderType()==OP_BUY)
           {
            CurrentProfit=Bid-OrderOpenPrice() ;

            // modify for break even
            if (CurrentProfit >= PLBreakEven*p && OrderOpenPrice()>OrderStopLoss())
              {
               SL=OrderOpenPrice()+(spread*2);
               TP=OrderTakeProfit();
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, White);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print("MODIFY BREAKEVEN BUY  Bid=",Bid," bartick=",bartick); 
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"BE",15,"Arial",White);
                 }
                  else 
                 {
                  Print("-----ERROR----- MODIFY BREAKEVEN BUY  Bid=",Bid," error=",gle," bartick=",bartick);
                 }
              }

            // modify for trailing stop
            if(CurrentProfit >= TrailStop*p )
              {
               SL=Bid-(TrailStop*p);
               TP=OrderTakeProfit();
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, White);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print ("MODIFY TRAILSTOP BUY  StopLoss=",SL,"  bartick=",bartick,"OrderTicket=",OrderTicket()," CurrProfit=",CurrentProfit); 
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"TS",15,"Arial",White);
                 }
                  else 
                 {
                  Print("-----ERROR----- MODIFY TRAILSTOP BUY  Bid=",Bid," error=",gle," bartick=",bartick);
                 }
              }

            // did we make our desired BUY profit
            // or did we hit the BUY LossLimit
            if((ProfitMade>0 && CurrentProfit>=(ProfitMade*p)) || (LossLimit>0 && CurrentProfit<=((LossLimit*(-1))*p))  )
              {
               OrderClose(OrderTicket(),Lots,Bid,Slippage,White);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print("CLOSE BUY  Bid=",Bid," bartick=",bartick); 
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"C",15,"Arial",White);
                 }
                  else 
                 {
                  Print("-----ERROR----- CLOSE BUY  Bid=",Bid," error=",gle," bartick=",bartick);
                 }
              }
              
           } // if BUY


         if(OrderType()==OP_SELL)
           {

            CurrentProfit=OrderOpenPrice()-Ask;
            
            // modify for break even
            if (CurrentProfit >= PLBreakEven*p && OrderOpenPrice()<OrderStopLoss())
              {
               SL=OrderOpenPrice()-(spread*2);
               TP=OrderTakeProfit();
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, Red);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print("MODIFY BREAKEVEN SELL Ask=",Ask," bartick=",bartick);
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"BE",15,"Arial",Red);
                 }
                  else 
                 {
                  Print("-----ERROR----- MODIFY BREAKEVEN SELL Ask=",Ask," error=",gle," bartick=",bartick);
                 }
              }

            // modify for trailing stop
            if(CurrentProfit >= TrailStop*p)
              {
               SL=Ask+(TrailStop*p);
               TP=OrderTakeProfit();
               OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP, Red);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print ("MODIFY TRAILSTOP SELL StopLoss=",SL,"  bartick=",bartick,"OrderTicket=",OrderTicket()," CurrProfit=",CurrentProfit); 
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"TS",15,"Arial",Red);
                 }
                  else 
                 {
                  Print("-----ERROR----- MODIFY TRAILSTOP SELL Ask=",Ask," error=",gle," bartick=",bartick);
                 }
              }

            // did we make our desired SELL profit?
            if( (ProfitMade>0 && CurrentProfit>=(ProfitMade*p)) || (LossLimit>0 && CurrentProfit<=((LossLimit*(-1))*p))  )
              {
               OrderClose(OrderTicket(),Lots,Ask,Slippage,Red);
               gle=GetLastError();
               if(gle==0)
                 {
                  Print("CLOSE SELL Ask=",Ask," bartick=",bartick);
                  ObjectCreate("myz"+DoubleToStr(objtick,0), OBJ_TEXT, 0, Time[0], Low[0]-(7*p));
                  ObjectSetText("myz"+DoubleToStr(objtick,0),"C",15,"Arial",Red);
                 }
                  else 
                 {
                  Print("-----ERROR----- CLOSE SELL Ask=",Ask," error=",gle," bartick=",bartick);
                 }
                 
              }

           } //if SELL
           
        } // if(OrderSymbol)
        
     } // for

  } // start()



//+-----------------+
//| CloseEverything |
//+-----------------+
// Closes all OPEN and PENDING orders

int CloseEverything()
  {
   double myAsk;
   double myBid;
   int    myTkt;
   double myLot;
   int    myTyp;

   int i;
   bool result = false;
    
   for(i=OrdersTotal();i>=0;i--)
     {
      OrderSelect(i, SELECT_BY_POS);

      myAsk=MarketInfo(OrderSymbol(),MODE_ASK);            
      myBid=MarketInfo(OrderSymbol(),MODE_BID);            
      myTkt=OrderTicket();
      myLot=OrderLots();
      myTyp=OrderType();
            
      switch( myTyp )
        {
         //Close opened long positions
         case OP_BUY      :result = OrderClose(myTkt, myLot, myBid, Slippage, Red);
         break;
      
         //Close opened short positions
         case OP_SELL     :result = OrderClose(myTkt, myLot, myAsk, Slippage, Red);
         break;

         //Close pending orders
         case OP_BUYLIMIT :
         case OP_BUYSTOP  :
         case OP_SELLLIMIT:
         case OP_SELLSTOP :result = OrderDelete( OrderTicket() );
       }
    
      if(result == false)
        {
         Alert("Order " , myTkt , " failed to close. Error:" , GetLastError() );
         Print("Order " , myTkt , " failed to close. Error:" , GetLastError() );
         Sleep(3000);
        }  

      Sleep(1000);

     } //for
  
  } // closeeverything---------------------------------------------------------+

Profitability Reports

PERFORMANCE BY SYMBOL

Expected payoff

Average expected payoff across the available backtests for each symbol.

Positive Negative
3 reports
AUD/USD Oct 2024 - Jan 2025
0.41
Total Trades 59
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -2.07
Gross Profit 86.10
Gross Loss -208.50
Total Net Profit -122.40
-100%
-50%
0%
50%
100%
GBP/USD Oct 2024 - Jan 2025
0.37
Total Trades 89
Won Trades 60
Lost trades 29
Win Rate 67.42 %
Expected payoff -2.37
Gross Profit 126.00
Gross Loss -336.90
Total Net Profit -210.90
-100%
-50%
0%
50%
100%
USD/CAD Oct 2024 - Jan 2025
0.33
Total Trades 68
Won Trades 44
Lost trades 24
Win Rate 64.71 %
Expected payoff -1.94
Gross Profit 65.55
Gross Loss -197.46
Total Net Profit -131.91
-100%
-50%
0%
50%
100%

Comments