Heiken315_EApk

Download script
Profit factor:
0.50

This automated trading script is designed to manage trades by combining trend-following indicators with strict risk management and time-based filters. It primary uses a "Smoothed Heikin Ashi" candlestick logic combined with an Exponential Moving Average (EMA) to determine when to enter and exit the market.

Core Trading Logic

Trend Identification The script primarily looks at two technical factors to decide on a trade:

  • Moving Average Filter: It uses a 24-period Exponential Moving Average. If the current price is above this average, it considers the trend "bullish" (potential for buying). If the price is below, it considers the trend "bearish" (potential for selling).
  • Heikin Ashi Signals: The script utilizes a specific variation of Heikin Ashi candles. It looks for specific patterns in these candles—specifically checking the relationship between current and previous candle heights and colors—to confirm that momentum is moving in the desired direction before opening a position.

Entry and Exit Rules

  • Buy Orders: A buy trade is triggered if the price is above the 24-period EMA and the Heikin Ashi candles show a confirmed upward momentum signal.
  • Sell Orders: A sell trade is triggered if the price is below the 24-period EMA and the Heikin Ashi candles show a confirmed downward momentum signal.
  • Exits: The script manages exits by looking for "reverse signals." If you are in a buy position and the Heikin Ashi indicators switch to a sell signal, the script will close the buy trade. This allows it to capture trends while exiting as soon as the momentum shifts.

Risk Management Features

Dynamic Positioning The script includes a risk management system that calculates the size of each trade based on your current account balance. Instead of using a fixed amount every time, it uses a percentage-based risk model to determine how many lots to trade.

Safety Measures

  • Stop Loss and Take Profit: Every trade is assigned a specific limit for potential losses (Stop Loss) and gains (Take Profit).
  • Trailing Stop: The script supports a trailing stop feature, which "follows" the price as it moves in your favor, locking in profits while allowing the trade to remain open if the price continues to move favorably.

Operational Constraints To protect the account from volatile market conditions or undesirable trading times, the script includes several filters:

  • Trading Sessions: You can define specific time windows (e.g., only trading during the London or New York sessions). The script will automatically pause if the current broker time falls outside these ranges.
  • Stop-Out Delay: If a trade is closed at a loss (a "stop out"), the script has an optional feature to wait for a specified number of minutes before opening a new trade. This prevents "revenge trading" or rapid consecutive losses during periods of high volatility.
  • Conflict Prevention: The script uses a "Magic Number" system, which ensures it only manages trades it opened itself and does not interfere with trades you might open manually or with other automated systems.
Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt Closes Orders by itself It can change open orders parameters, due to possible stepping strategy
Indicators Used
Moving average indicator
15 Views
0 Downloads
0 Favorites
Heiken315_EApk
//+------------------------------------------------------------------+
//|                                               Heiken299_EApk.mq4 |
//|                      Copyright © 2005, MetaQuotes Software Corp. |
//|                                       http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
// edits by P. Kubitzki, fxtogo4me@yahoo.com
// 9/09/07 PK changed iCustom Heiken Ashi to Heiken_Ashi_Smoothed
// change MA200 to MA24, running on 15M MA200 is too far out
// change signal candle from 0 to 1 on HA
// 9/10/07 2:50pm KC remove all Awesome Oscillator coding, it delays entry
// 9/11/07 BUG FOUND! This EA doen't work well with others. 
// If another EA opens a trade, this EA might close it. Possibly if only in the opposite direction.
// 09/12/07 added Magic Number coding when checking for close to fix former bug
//
// Edits by Robert Hill
// 9/15/07 Added code for trading sessions
//         Added code to check if last trade stopped out for delay of trading


#define MAGICMA  20050000

extern double Lots               = 0.1;
extern double MaximumRisk        = 0.5;
extern double TakeProfit = 2000; //TakeProfit in not really used, it closes at reverse direction
extern double TrailingStop = 0;
extern double Stoploss = 70; //changed from 60
extern double risk = 2; // changed from 10%
double lotMM;

extern string  sm0="--Trading Hours Filter--";
extern string  sm1=" Times are Broker Chart times";
extern string  sm2="UseTradingHours - Enter 0 for false, 1 for true";
extern int     UseTradingHours = 0;
extern string  sm3="Trade Session 1 - Enter 0 for false, 1 for true";
extern int    TradeSession1 = 1;
extern int     Session1Start = 2200;       // Start trades after time
extern int     Session1Stop = 100;      // Stop trading after time
extern string  sm4="Trade Session 2 - Enter 0 for false, 1 for true";
extern int    TradeSession2 = 1;
extern int     Session2Start = 400;       // Start trades after time
extern int     Session2Stop = 600;      // Stop trading after time
extern string  sm5="Trade Session 3 - Enter 0 for false, 1 for true";
extern int    TradeSession3 = 0;
extern int     Session3Start = 700;       // Start trades after time
extern int     Session3Stop = 900;      // Stop trading after time
extern string  sm6="Trade Session 4 - Enter 0 for false, 1 for true";
extern int    TradeSession4 = 0;
extern int     Session4Start = 1330;       // Start trades after time
extern int     Session4Stop = 1500;      // Stop trading after time
extern string  sm7="Trade Session 5 - Enter 0 for false, 1 for true";
extern int    TradeSession5 = 0;
extern int     Session5Start = 1700;       // Start trades after time
extern int     Session5Stop = 1900;      // Stop trading after time

extern string  hd0 = " --Delay time--";
extern string  hd1 = " Enter 0 for false, 1 for true";
extern string  hd2 = " for useDelay and useDelayAfterWin";
extern int     useDelay = 1;
extern int     useDelayAfterWin = 1;
extern int     MinutesToDelay = 180;

bool     YesStop;
datetime StopTime;                 // Time to wait after a trade is stopped out
bool StoppedOut=false;

int init()
{
   return(0);
}

int deinit()
{
   return(0);
}
//+------------------------------------------------------------------+
//| Calculate open positions                                         |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
//      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)

// Since you pass the Symbol() you can use this

      if(OrderSymbol()==symbol && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//---- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
// =================================================================================
// PYRAMIDING - LINEAR
// Money Management risk exposure compounding
// =================================================================================
   
  
//+------------------------------------------------------------------+
//| Check Heikin Ashi for buy or sell signal                         |
//| Use OP_BUY to check for enter buy or exit sell                   |
//| Use OP_SELL to check for enter sell or exit buy                  |
//| Changes by Robert                                                |
//|  Added passing of boolean to determine check of                  |
//|  Bid < HA1 for Sell                                              |
//|  Bid > HA1 for Buy                                               |
//|  Modified code for faster backtesting                            |
//|  The checks are still done correctly                             |
//|  The iCustom call is only done when needed                       |
//+------------------------------------------------------------------+

bool CheckHeikenAshi(int cmd, bool checkBid)
{
   bool rule1;
   double HA0, HA1, HA2, HA3;
   
   HA1 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",1,1);
   if (cmd == OP_SELL)
   {
     rule1 = true;
     if (checkBid == true)
     {
       if (Bid > HA1) rule1 = false;  // reverse check for failure
     }
     
     if (rule1 == true)
     {
       HA0 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",0,1);
       if (HA1 < HA0)
       {
         HA2 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",2,1);
         HA3 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",3,1);
         if (HA2 > HA3) return(true);
       }
     }
   }
   if (cmd == OP_BUY)
   {
      rule1 = true;
     if (checkBid == true)
     {
       if (Bid < HA1) rule1 = false;  // reverse check for failure
     }
     
     if (rule1 == true)
     {
       HA0 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",0,1);
       if (HA1 > HA0)
       {
         HA2 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",2,1);
         HA3 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",3,1);
         if (HA2 < HA3) return(true);
       }
     }
   }
   return(false);
   
}


//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   int    res;
   
// Use Variables for speed
// Same values are used to check buy or sell so no need to get values twice
// also easier to read

//  double HA0, HA1, HA2, HA3;  // delete this line if you use CheckHeikenAshi function
   double Close1, MA24; //, AO;
   
   Close1 = Close[1];
//   MA200 = iMA(NULL,0,200,0,MODE_EMA,PRICE_CLOSE,0); previous
   MA24 = iMA(NULL,0,24,0,MODE_EMA,PRICE_CLOSE,1);
//   Comment ("\nUSE ON ANY CHART TIMEFRAME","\nEMA24[1] = ",MA24,"\nHA1: High of Blue OR Low of Red HA Candle","\nHA1 = ",HA1);

//   AO = iAO(NULL,0,0);
   
   
//---- sell conditions
//  if (CheckHeikenAshi(OP_SELL) && Close1 < MA24 && Bid < HA1) // && AO < 0) // Function version
// Change by Robert
// Also changed checks for speed of backtest
  if (Close1 < MA24) // && AO < 0) // If this is true then check HeikenAshi
  {
     // may need to change Bid< HA1 to Bid < Low[1] PK
     // If this change is made then modify the CheckHeikenAshi function to not check against HA1
  
     // if (HA2 > HA3 && HA1 < HA0 && Close1 < MA200 && AO < 0)
     if (CheckHeikenAshi(OP_SELL, true)) // && AO < 0) // New Function version
     {
      res=OrderSend(Symbol(),OP_SELL,MathCeil(AccountBalance() * risk / 100000),Bid,1,Bid+Stoploss*Point,Bid-TakeProfit*Point,"",MAGICMA,0,Red);
      return;
     }
  }
//---- buy conditions
//  if (CheckHeikenAshi(OP_BUY) && Close1 > MA24 && Bid > HA1) // && AO > 0)  // Function version
// Change by Robert
  if (Close1 > MA24) // && AO > 0)  // If this is true then check HeikenAshi
  {
       // may need to change Bid > HA1 to Bid > High[1] PK
       // If this change is made then modify the CheckHeikenAshi function to not check against HA1

       // if (HA2 < HA3 && HA1 > HA0 && Close1 > MA200 && AO > 0)
     if (CheckHeikenAshi(OP_BUY, true)) // && AO > 0)  // New Function version
     {
      res=OrderSend(Symbol(),OP_BUY,MathCeil(AccountBalance() * risk / 100000),Ask,1,Ask-Stoploss*Point,Ask+TakeProfit*Point,"",MAGICMA,0,Blue);
      return;
     }
  }
//----
}
  
//+------------------------------------------------------------------+
//| Check for close order conditions                                 |
//+------------------------------------------------------------------+
void CheckForClose()
  {
// Use Variables for speed
// Same values are used to check close buy or close sell so no need to get values twice
// also easier to read
//   double HA0, HA1, HA2, HA3, MA24;  // delete this line if you use CheckHeikenAshi function
   
//   HA0 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",0,1);  // delete this line if you use CheckHeikenAshi function
//   HA1 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",1,1);  // delete this line if you use CheckHeikenAshi function
//   HA2 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",2,1);  // delete this line if you use CheckHeikenAshi function
//   HA3 = iCustom(NULL,0,"Heiken_Ashi_Smoothed",3,1);  // delete this line if you use CheckHeikenAshi function
//   MA24 = iMA(NULL,0,24,0,MODE_EMA,PRICE_CLOSE,1);
//   Comment ("\nUSE ON ANY CHART TIMEFRAME","\nEMA24[1] = ",MA24,"\nHA1: High of Blue OR Low of Red HA Candle","\nHA1 = ",HA1);
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&   // check for opened position 
         OrderSymbol()==Symbol() &&  // check for symbol
         OrderMagicNumber()==MAGICMA) // Check Magic Number
        {
         if(OrderType()==OP_BUY)   // long position is opened
           {
            // should it be closed?
          if (CheckHeikenAshi(OP_SELL, false)) // Function version check Sell condition to exit Buy
        //    if(HA2 > HA3 && HA1 < HA0)
                {
                 OrderClose(OrderTicket(),OrderLots(),Bid,1,Violet); // close position
                 return(0); // exit
                }
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if(Bid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-Point*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
           }
         else // go to short position
           {
            // should it be closed?
         if (CheckHeikenAshi(OP_BUY, false)) // Function version check Buy condition to exit Sell
       //     if (HA2 < HA3 && HA0 > HA1)
              {
               OrderClose(OrderTicket(),OrderLots(),Ask,1,Violet); // close position
               return(0); // exit
              }
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
           }
        }
     }
   return(0);
  }

// Return true if time is not in session for trading
bool CheckOutsideSession(int SessionStart, int SessionStop, int ct)
{

   if (SessionStart < SessionStop)
   {
     if (ct >= SessionStart && ct <= SessionStop) return (false); else return(true);
   }
   else
   {
      if (ct > SessionStop && ct < SessionStart) return (true); else return(false);
   }
}

bool CheckTradingTimes()
{
   bool StopTrading;
   int ct;
   ct = Hour() * 100 + Minute();
   
     StopTrading = true;

     if (TradeSession1 == 1)
     {
        StopTrading = CheckOutsideSession(Session1Start, Session1Stop, ct);
     }
     if (StopTrading == true)
     {

       if (TradeSession2 == 1)
       {
         StopTrading = CheckOutsideSession(Session2Start, Session2Stop, ct);
       }
     }
     if (StopTrading == true)
     {

       if (TradeSession3 == 1)
       {
         StopTrading = CheckOutsideSession(Session3Start, Session3Stop, ct);
       }
     }
     if (StopTrading == true)
     {

       if (TradeSession4 == 1)
       {
         StopTrading = CheckOutsideSession(Session4Start, Session4Stop, ct);
       }
     }
     if (StopTrading == true)
     {

       if (TradeSession5 == 1)
       {
         StopTrading = CheckOutsideSession(Session5Start, Session5Stop, ct);
       }
     }
     
     return(StopTrading);
}

//+------------------------------------------------------------------+
//| LastTradeStoppedOut                                              |
//| Check History to see if last trade stopped out                   |
//| Return Time for next trade                                       |
//+------------------------------------------------------------------+
  
datetime LastTradeStoppedOut()
{
   int cnt, total;
   datetime NextTime;
   bool Stopped;
   
   NextTime = 0;
   
   total = HistoryTotal();
   for (cnt = total - 1; cnt >= 0; cnt--)
   {
      OrderSelect (cnt, SELECT_BY_POS, MODE_HISTORY);
      
      if(OrderSymbol()==Symbol() && OrderMagicNumber() == MAGICMA)
      {
        Stopped = false;
        if (OrderType() == OP_BUY)
        {
          if (OrderClosePrice() - OrderOpenPrice() < 0)
          {
             Stopped = true;
          }
          if(useDelayAfterWin == 1) Stopped = true;
          cnt = 0;
        }
        if (OrderType() == OP_SELL)
        {
          if (OrderOpenPrice() - OrderClosePrice() < 0)
          {
             Stopped = true;
          }
          if(useDelayAfterWin == 1) Stopped = true;
          cnt = 0;
        }
      }
   }
   
   if (Stopped)
   {
      StopTime = OrderCloseTime() + MinutesToDelay*60;
   }
   
   return (Stopped);
}

// the end.
//----

//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
  {
  
//---- check for history and trading
   if(Bars<100 || IsTradeAllowed()==false) return;
//---- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0)
   {
//+------------------------------------------------------------------+
//| Check if OK to make new trades                                   |
//+------------------------------------------------------------------+

// Check if last trade stopped out

   if (useDelay == 1)
   {
     StoppedOut = LastTradeStoppedOut();
     if  (CurTime() < StopTime)
     {
//    Comment("No Trades Until : " + TimeToStr(StopTime,TIME_DATE|TIME_MINUTES));
      return(0);
     }
   }
     YesStop = false;
     if (UseTradingHours == 1)
     {
        YesStop = CheckTradingTimes();
   
        if (YesStop == true)
        {
          Comment ("Trading has been stopped - wrong time of day");
        }
        else
        {
          Comment ("Trading has resumed - time is OK");
        }
     }
     if (YesStop == false) CheckForOpen();
   }
   else CheckForClose();
//----
  }
//+--------------------------------------------------------------

Profitability Reports

PERFORMANCE BY SYMBOL

Expected payoff

Average expected payoff across the available backtests for each symbol.

Positive Negative
3 reports
USD/CAD Oct 2024 - Jan 2025
0.51
Total Trades 196
Won Trades 20
Lost trades 176
Win Rate 10.20 %
Expected payoff -21.83
Gross Profit 4366.56
Gross Loss -8645.69
Total Net Profit -4279.13
-100%
-50%
0%
50%
100%
NZD/USD Oct 2024 - Jan 2025
0.50
Total Trades 178
Won Trades 24
Lost trades 154
Win Rate 13.48 %
Expected payoff -30.01
Gross Profit 5262.00
Gross Loss -10603.00
Total Net Profit -5341.00
-100%
-50%
0%
50%
100%
AUD/USD Oct 2024 - Jan 2025
0.49
Total Trades 186
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -30.57
Gross Profit 5448.00
Gross Loss -11134.00
Total Net Profit -5686.00
-100%
-50%
0%
50%
100%

Comments