User Guide – Hedging EA

User guide for Hedging EA for Metatrader (Mt4/Mt5)

Loading

Hedging EA is a Metatrader Expert Advisor that provides a correct framework for your trading activity. It provides proper risk calculations and a very smart position management strategy that will manage your trades automatically and recover your trading losses.

By properly using this expert advisor, your losing trades will be recovered automatically by the EA, and you’ll be able to trade again when the chart is flat.

Product Links

The Hedging EA for MT4 and MT5 can be found here.
It can also be downloaded from the mql5.com market.

1. What this EA is

Hedging EA is a Metatrader4 Expert Advisor that provides a correct framework for your trading activity. It provides proper risk calculations and a very smart position management strategy that will manage your trades automatically and recover your trading losses. By properly using this expert advisor, your losing trades will be recovered automatically.

Once the EA is attached to the chart and properly configured, all you need to do is take trades by clicking “buy” or “sell” on the chart buttons displayed at the top-right corner of the chart or enable one of the automated entry strategies the EA offers.

Once a trade is taken, the EA will then take over position management for you and all you have to do is wait until the chart is flat -no trades- to trade again. It is paramount not to meddle with the initial trade once a recovery trade has been placed.

This EA implements a hedging recovery strategy made simple for the average user. Input parameters are limited and understandable. Most inputs of the EA are drop-down menus which makes it almost impossible for the user to enter unreasonable values. Any parameter that can be auto-calculated by the EA has been removed from the inputs to avoid confusion. Others have been broken down into ratios based on others.

This expert advisor is, probably, the most effective loss recovery expert advisor you can find on the internet, but also the easiest one to use. I have spent a tremendous amount of time coding the visual elements of this tool, to make sure you understand how it works and to make the EA behave as you’d expect it to, in a predictable fashion.

This user guide will allow you to understand the EA and start trading in one hour.

2. What does it do?

Once a trade has been taken, one of the two scenarios will take place.

a) The trade is correct – if your trade goes into profits, the EA will apply a straightforward management comprised of a break-even in pips and a trailing-stop until the trade is stopped out at a profit. Optionally, you can set a take-profit in pips which is evaluated in stealth mode – without sending the take-profit order to the broker-

b) The trade goes straight into losses – If your initial trade is incorrect and goes into red, the EA will apply an imbalanced hedging strategy to exit the deal at a small profit, placing alternative pending orders -in opposite directions-, with increasing but not exponential lotsizes until an exit point is reached or until all the trade plan is allocated.

Occasionally, the trade plan will be fully allocated without reaching an exit point. If this happens, the EA will start cutting back exposure trade by trade searching for an exit point at a partial loss. As the EA closes old trades one by one, the break-even price comes closer to the current price.

And, very rarely, all the trade plan will be fully deconstructed without finding an exit point at a partial loss, in which case all trades will be closed at a loss, losing the predefined risk displayed on screen, allowing you to start over again.

3. Broker and account selection

The EA can be applied to any symbol offered by your broker. That being said, you should avoid…

  • Symbols with big spreads
  • Symbols with big swap costs
  • Futures with rollover fees

If you must trade symbols with high spreads or with low liquidity, make sure to increase the zone parameter to avoid spread hikes executing a large portion of your trade plan in a short period of time. We will review this further in the user guide.

You can trade with any broker of your choosing, but it is recommended to use a fixed spread account to avoid spread hikes triggering lots of pending orders in a short period of time. A fixed spread account will have the same spread all the time, no matter what, albeit a big higher than variable spread accounts.

4. Loading the EA to the chart

The download page of the product has straightforward download and install instructions which you will be able to follow easily. Once the EA has been installed in your Metatrader4 platform, load it to an empty chart from navigator->expert advisors.

The EA can be loaded to any timeframe without making any change in settings: since the EA does not use high-low-close-open data from the chart, the timeframe where it is loaded is irrelevant. You can change between timeframes, even if the recovery process is active, without problems and without need of changing the settings.

Congratulations! You have loaded the EA to the chart and it is displaying a lot of information which you’ll need to understand to make good decisions. Information is grouped and displayed in different corners of the chart.

  • The top-right corner holds risk allocation and displays the risk profile
  • The top-left corner holds current settings and the trade plan of the EA
  • The bottom of the chart holds information for the current symbol

You will also see two horizontal colored lines, which represent the break-even prices if the trade plan is fully allocated. Leave it at that for now, we will review all this information further in the user guide.

5. The risk settings

The risk allocation is directly related to the recovery inputs the EA mades available for you. It is your job to enter the recovery settings which best fit your trading activity, and to do so before taking a single trade. The maximum net exposure is the total exposure your account will have if all trade plan is allocated. The maximum drawdown is the maximum loss expressed as percentage of balance the EA has calculated you will suffer if all the trades of the recovery process must be closed at a loss. The EA will evaluate the maximum drawdown and display risk allocation as safe, aggressive or dangerous.

The risk responds to total exposure, and the total exposure depends directly of the recovery settings of the EA. This means that you can edit the settings of the EA to tailor the risk for each symbol to your liking. To do so, you’ll need to change the following parameters. As you read the guide, feel free to play around with them and see the impact on the risk and total exposure on the chart.

  • Recovery Trades: This parameter controls how many trades should be placed during the recovery process. More trades means the recovery process will be longer and implies more risk because it increases the final net exposure, but it also means less deals will incur in partial losses.

  • Zone in Pips: The zone is the distance in pips between the buy and sell orders. A bigger zone implies more risk because trades are allowed to run into losses more before being hedged, but it also shields you from spread hikes triggering a lot of trades of your recovery process in a short amount of time.

    As a rule of thumb, make sure the zone is at least 20-25 times bigger than the spread. For instance, if you trade EURUSD, which has a typical spread of 1.8 pips, you can safely set a zone of 50 pips. However, if you trade GPBJPY, which has a typical spread of 4 pips, you should set a zone of at least 100 pips to be safe from spread hikes.

    Setting a zone below 50 pips is not recommended, because during volatile times the broker might increase the spread wildly and you don’t want your trade plan to be executed without actual market movement. If you do, you do so at your own risk.

  • Behavior: The behavior controls how aggressively the EA increases lotsizes from one trade to the next. It ranges from very aggressive to very light, offering you the chance to adjust the risk level without changing the amount of trades, the zone, or the initial lotsize.

    A high aggression level means deals will be recovered faster, as the break-even price will be closer to your initial trade. However, it also implies more risk because margin will be allocated faster than with a lower aggression level.

  • Profit Target in Pips: The profit target only applies during the recovery process and is the amount of pips you want to earn before closing all trades. A higher profit target means that deals will take more time to close, and a small target means deals will close faster, allowing more rotation in your trades. This value can be changed in real time: for instance, as a deal grows larger you might want to decrease this value to accelerate the closing.

  • Lotsize for First Trade: The EA builds a trade plan for the recovery process using your recovery settings covered above and the initial lotsize of your trade. A higher initial lotsize increases the final net exposure and total risk. Select your initial lotsize here, and then use the chart buttons to trade.

The above explained risk settings allow for infinite combinations. For instance, if you don’t want to trade with 0.01 lots because your trades are often accurate, you can increase the initial lotsize and then decrease the amount of trades and attenuate the behavior, to lower the risk back to a safe level.

Play around with these settings until you find a reasonable risk for each pair you are trading.

In the EA input list, all parameters affecting the risk are highlighted with a ** in their name.

6. Multi-pair risk considerations

If you are going to trade several pairs, as we all do, it is imperative that you know that risks aggregate. For instance if you trade EURUSD, GBPUSD and USDJPY with a risk of 15% each and you take a trade in all those at the same time, the total risk is actually 45%, which is not good, even though the EA will say that the risk is safe for those pairs individually.

The above happens because you are setting into motion three trade plans which, god forbid, can be fully allocated at the same time, incurring into a combined loss on the three symbols at the same time.

So, what can you do to keep risk in check? You should configure the EA in all the pairs you want to trade, which can be as many as you like, and then make sure not to trade more than 2 pairs simultaneously. For example, you can configure a 10% risk in all pairs and avoid having more than two active pairs, limiting the final exposure to a 20% of your account.

The amount of simultaneous pairs you want to trade call for different settings, regardless of the risk profile displayed on screen. If, on the other hand, you want to trade only EURUSD you can configure the EA to behave aggressively.

In the above example, we have the following risks for each pair:

  • 15,45% for EURUSD
  • 10,90% for GBPUSD
  • 10.41% for USDJPY

So, the total risk, if we were to start a trade on these pairs at the same time, would be 31,75%. A bit high for my taste, but these settings are wise if we were to have only two active pairs at any given moment.

7. Safety checks

Once you have configure the EA to have an acceptable individual and aggregated risk for the currencies wish to trade, it is time to trade! But before that, it is recommended to evaluate market conditions and review the trade plan, just like pilots review weather forecasts before taking off from the airport.

a) Make sure the exit prices are realistic: The EA displays two thick lines on the chart, a blue line and a red line. These are the break-even points and represent how far away from the current price the exit point will be if the complete trade plan is allocated. If these prices are non realistic, you should not trade under this settings. For example, if you are trading gold and the red line is at 650$/oz, you should not trade: since 650$/oz. is below mining costs, the EA would never be able to get out of a deal if all the trade plan is allocated. To bring the exit points closer, you’d have to decrease the amount of trades, decrease the zone and/or make the recovery process more aggressive, without incurring into extra risk.

b) Make sure the trade plan does not run out of margin: Margin hikes are not uncommon in the forex market if volatility is expected in the future. For example, at the time of writing, GPBUSD suffered a big margin hike due to the BREXIT referendum, which is due in a few days, and our previously feasible trade plan is not feasible anymore! See how trade 9 goes out of margin in the screenshot above! This is not good and it is imperative to adapt the trade plan so it stays inside the margin requirements. Else the broker will forcibly close your trades, at a loss, before the trade plan is allocated.

c) Make sure swaps are acceptable: Just as we pay monthly interest payments to the bank when we purchase a house with borrowed money, we have to pay daily carry costs to the broker when we trade on margin. Swaps reflect the cost to carry the trade from today to tomorrow. Some brokers artificially inflate the swap costs received from their liquidity provider while keeping a very low spread, which looks good on advertisements and brings in a lot of uninformed customers. But swap costs can pile up very quickly and delay the recovery process, because transaction costs must also be recovered. If you must trade a symbol with big swaps, try to make the recovery process shorter by decreasing the amount of trades and aggression level of the EA. But it is much better to trade only those pairs offering good swap costs relative to others. Swap costs are displayed at the bottom of the chart.

8. Position management settings

I know you are eager to trade now, but first let’s review the position management settings. The first thing you need to know is that the position management settings only apply to your first trade, and not during the recovery process.

The following parameters control how your initial trade is managed, if your initial trade is correct. Once the second trade of the trade plan is executed, the following settings are completely ignored and the recovery settings come into play.

  • Break-even in pips: This parameter controls how fast does the EA make the first trade risk free. Once the trade reaches the break-even level, the stop-loss is moved above the entry price, leaving equal distance between the entry price and the current price. For example, a break-even of 10 pips will move the stop-loss to +5 pips when the trade is +10 pips in profit. A small break-even value will cause more trades to be stopped out at a small profit prematurely, but on the flip side, less trades will fall into the recovery process. A big value aims for longer trades, but will cause more trades to fall into recovery before the break-even applies.

  • Trailing-Stop: The trailing stop is expressed as percentage of the maximum achieved trade profits. This particular trailing-stop method allows profits to run without neglecting the trailing-stop when profits are small. The actual trailing-stop value in pips will change according to the trade profit. A 50% trailing stop is a very wide one, leaving 50% of the trade profits as wiggle room for the market. On the other hand, a 10% trailing stop is very tight, leaving only 10% wiggle room for the market before the trailing-stop it hit. For example, assuming a 20% trailing-stop, values would change as exemplified below.

  • Trailing-Step in pips: The trailing step in pips represents the minimum increase from the last trailing-stop value. For instance, if you set a trailing-step of 5 pips, the trailing-stop won’t be moved unless the new value is at least 5 pips away from the current one, and 5 pips away from the current market price.

  • Take-Profit in pips: Optionally, you can set a take-profit level in pips for your first order. This take-profit level is not sent to the broker, but evaluated and executed in stealth mode instead. If set to zero, it is not used. Default settings are risk-averse and will break-even trades fast.

9. Starting trades

To take a trade, click on BUY or SELL button on the chart and the trade will be placed for you with the proper lot size automatically. These buttons, besides being awfully convenient, are only displayed on the chart when the EA is ready to manage new trade.

Once the initial trade is placed, the trade buttons disappear and a another to close all trades is displayed instead. If you click on it, a confirmation dialog will prompt you for confirmation and close all trades in the chart immediately after if you confirm.

Once the EA is properly configured, your trading activity becomes very simple. All you need to do is taking the initial trade clicking on BUY or SELL, and then wait until the chart is flat again -no trades- to start a new trade.

Once you have taken the initial trade, a pending order will be placed in the opposite side of the zone matching the second trade of the trade plan. This pending order will be deleted automatically by the EA when the initial trade is closed by you, or by the EA.

Please note that the EA does not support bidirectional trading: do not buy and sell at the same time. Place just one initial trade, buy or sell, and wait until the chart clears to take a new trade.

Do not add additional trades to the initial trade, as each additional trade would double the risk of the recovery process or make it unfeasible altogether. This ensures that the martingale risk is controlled and exactly the same all the time.

If you want to start the deal placing pending orders, you can do so. If you place multiple pending orders on the chart, the EA will delete all others when the first one is executed, and start the recovery process on a clean chart.

If you configure the EA on the computer and take trades from your phone or mobile device, it is ok. Just keep in mind that this EA will not manage trades without a stop-loss. If the trade has no stop-loss, the EA will not manage it.

10. Automated entry strategies

The EA provides many simple automated entry strategies as an alternative to manual trading. This provides a certain level of automation to your trading, but will never match the quality of your discretional entries, as no entry strategy is profitable in all market conditions. That being said, you can switch between them according to what you see on the market. The list of automated entry strategies available is the following. Eventually more entry strategies will be added, which might not be included in this list.

11. Starting trades reading a custom indicator

Hedging EA is equipped to take trades according to a custom indicator of your choosing, which must follow certain conventions. It must store one of the following constants into a non-drawing but accessible buffer. Please note that this feature is missing in the Metatrader5 version.

  • Buy: Store 0 in the buffer
  • Sell: Store 1 in the buffer
  • Do nothing: Store EMPTY_VALUE in the buffer

By storing one of the following values into a buffer in your indicator, and making Hedging EA to read from it, it will be able to buy, sell and close trades when your custom indicator wants to. Kindly note that, closing trades will only work if there are no recovery trades opened. The indicator is read upon bar closing and the trade session filters applied.

To make things simpler, consider the example below, named MyIndicator.mq4, which buys when a bar closes above the high of the last bar, and shorts when a bar closes below the low of the last bar.

#property copyright   "Arthur Lopez"
#property link        "http://www.pointzero-trading.com"
#property description "Indicator example for the custom indicator feature."
#property version     "1.0"
#property strict
//---- indicator settings
#property indicator_chart_window
#property indicator_buffers 0
//---- constants
#define ShortName       "My Indicator"
#define OP_CLOSE_BUY    3
#define OP_CLOSE_SELL   4
#define OP_CLOSE_ALL    5
//---- indicator buffers
double SignalBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
{
   IndicatorBuffers(1);             // We only need one buffer
   SetIndexBuffer(0,SignalBuffer);  // This is the signal buffer (0)
   return(0);
}
int deinit()
{
   return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
{
   int start = 1;
   int limit;
   int counted_bars = IndicatorCounted();
   // check for possible errors
   if(counted_bars < 0)
      return(-1);
   // Iteration Limit
   limit = Bars - 1 - counted_bars;
   // Iterate all bars from past to present
   for(int i = limit; i >= start; i--)
   {
      // Ignore first bar
      if(i >= Bars-1) continue;
      // Store empty value first, no action by default
      SignalBuffer[i] = EMPTY_VALUE;
      // If bullish breakout
      if(Close[i] > High[i+1]) SignalBuffer[i] = OP_BUY;
      // If bearish breakout
      if(Close[i] < Low[i+1]) SignalBuffer[i] = OP_SELL;
   }
   return(0);
}

Please copy the above code into your MetaEditor, and click compile.



The compiler should compile the indicator without errors, making the indicator usable.  To use it in Stop Reverse EA, select “Custom Indicator” as entry strategy, type the indicator name (MyIndicator) in the Custom Indicator parameter and set the signal buffer number to 0.



As you work with other indicators to make them compatible with Hedging EA, the signal buffer number will change. For instance if you edit an indicator which has 5 buffers used, you’ll have to add an additional buffer and enter the correct buffer number in the input parameters of Hedging EA. You can make unlimited indicators, as complex as you want.

12. Trading sessions

To avoid starting trades in sessions you don’t want to trade, you can enable or disable the following sessions in the indicator inputs. These sessions are evaluated only to take the initial trade, not to perform recovery trades. The session filter is evaluated when you are using a custom indicator too.

13. The recovery process

The recovery process starts when the second trade of the trade plan is executed. When this happens, the EA displays two lines on the chart, which weren’t there before. The thick green line is the current break-even price: the price at which your deal can be closed without losing a cent. The dotted green line, on the other hand, represents the profit target for the recovery process.

As soon as the price touches the dotted green line, the EA will close the deal completely.

Other interesting thing to pay attention to is the amount of trades executed and the transaction costs incurred to far, both present on the chart comment you see at the left side of the chart. The EA converts accumulated transaction costs into pips, and accounts for them in the recovery process. As mentioned previously, swap costs can pile up very quickly, so make sure to pay attention to them before trading.

14. Changing the recovery process

The recovery process will follow the recovery settings to the letter, and you should not change them on the fly. Therefore you must be completely sure about your risk settings before trading. The only thing you can do on the fly during a recovery process is stopping it, and forbid the EA from taking additional trades. If you do so, the EA will stop adding trades and will start closing trades one by one looking for an exit point at a partial loss.

Doing this makes sense only if you made a mistake calculating your aggregated risk and over-traded several pairs. To forbid the EA from taking further recovery trades, you should set the Behavior parameter to Do_Not_Add_Trades as exemplified below.

However, you can change the amount of trades on the fly if less trades have been taken so far: for example if the original trade plan was to trade 12 trades and so far the EA has taken 6, you can change recovery trades to any value above 6. Other thing you can change is the profit target for recovery. As the deal grows larger you might want to decrease it, increasing the odds of closing the deal faster and start trading fresh trades again.

15. Closing deals manually

The EA displays a button labeled “Close All” on the top-right corner of the chart. If you click on it, the deal will be completely closed right away, regardless of the profit or loss result of the trades at the current moment.

16. Backtesting

I have intentionally left the backtest of the expert advisor for the end of the user guide, because you must understand the relationship between the recovery settings and the execution risk of the EA before you can run any meaningful backtest. It makes no sense to judge the performance of an EA based on a backtest with dangerous recovery settings, as the EA will surely over-leverage your account or go into a margin call and stop the test at a loss.

To perform a backtest, first you have to find the desired risk profile for the balance of the account you wish to test. To do that, you’ll have to first launch the test in visual mode. The visual mode will show you information on the chart as the EA trades, and you’ll be able to stop the test and change the settings if the settings are undesirable.

To start the test, select an entry strategy from the EA inputs and click on Start. The EA will either start trading or inform you that the risk allocation is dangerous. If the risk allocation is dangerous, the EA won’t trade and you’ll be forced to change the recovery settings to start a new backtest.

Once you launch a safe or aggressive test, the EA will take completely random trades until the test stops. It won’t reflect true trading activity because in live trading, you will be deciding the trades, but it will give you information about how the recovery process is handled and the expected equity curve you can expect.

You can test any timeframe above M30 or H1 in control points mode. The control points mode generates 8 ticks for each bar in the test, which is more than enough to test this particular expert advisor.

Hopefully you’ll test will look very similar to mine. That being said backtests are not the best way to measure the performance of this expert because it needs human decisions to operate: only you can decide what to trade, when to trade it, what settings to use, what symbols to avoid and when and many other things which a machine can never decide for a human being.

17. Input Parameters

  • Lotsize for first trade: This parameter controls the size of the initial trade. A smaller lotsize decreases the net exposure of the deal.
  • Break-even in pips: This parameter controls at which profit in pips the EA moves the stop-loss above/below the open price securing profits. This parameter only affects the first trade, not during the recovery process.
  • Break-even Behavior: Upon break-even, the EA can secure half the profits of the trade or move the SL to the open price, as you wish. If you want to let profits run and maximize the first trade, choose the latter.
  • Trailing Stop: Percentage of the max. favorable excursion (MFE) used as trailing-stop. A small value is a tight stop, and a big value is a wide stop. This parameter only affects the first trade, not during the recovery process.
  • Trailing Step in pips: Minimum increase in pips for the trailing stop value and, at the same time, the minimum distance from the new stoploss and the current market price. This parameter only affects the first trade, not during the recovery process.
  • Take Profit in pips: Steath take-profit for the first trade. Not used during the recovery process.
  • Entry Strategy: The EA implements a set of automated entry strategies to provide some degree of automation. Not all entry strategies will greatly perform in all market conditions, but you can switch between them as you see fit. Supported entry strategies are CCI, ADX, RSI, Bollinger Bands, AC, AO, Alligator, Fractal Breakouts, MACD, PSAR, RVI, Stochastic, Heiken Ashi, Turtle Trading, Breakouts, Buy Constantly, Sell Constantly and Random Trades..
  • Custom Indicator Name: If you choose to trade using your own custom indicator, type the indicator name in this parameter. The EA will call it via iCustom() internally. For more information about this, read the user guide.
  • Custom Indicator Signal Buffer: If you choose to trade using your own custom indicator, type the signal buffer number in this parameter. The EA will call it via iCustom() internally. For more information about this, read the user guide.
  • Recovery Trades: Maximum amount of trades to place during the recovery process.
  • Zone In Pips: Distance in pips between buy stop and sell stop orders. A higher value will decrease trading frequency but will make deals to last longer. If the spread is below one pip, you can use a zone of 50 pips. If the spread is between 2 and 3 pips, you should set a zone over 75 pips. If the spread is above 3 pips, you need a zone of at least 100 pips.
  • Behavior: The behavior parameter instructs the EA how aggressive to behave during the recovery process. More aggression will close deals faster but use more free margin to do so. If this parameter is set to Do_Not_Add_Trades during live trading, the EA will stop adding trades and start to cut back exposure.
  • Profit Target in pips: Overall profit at which we wish to close deals. A bigger value will cause deals to last longer in time. Please note this is not the take-profit for the first trade.
  • Trade Assian Session: If enabled, the EA will start trades during the Assian Session.
  • Trade European Session: If enabled, the EA will start trades during the European Session.
  • Trade American Session: If enabled, the EA will start trades during the American Session.
  • Magic Number: The magic number allows the EA to identify its own trades when reloaded or the platform restarts. As a rule of thumb, never change it.
  • Custom Comment: Enter your custom comment for all trades here.

18. Questions

Feel free to post your questions below. Thank you!

Loading

Author: Arthur Lopez

Private investor and speculator, software engineer and founder of PZ Trading Solutions.

5 thoughts on “User Guide – Hedging EA”

    1. This particular robot is not meant to trade indices, but it will load and work fine if you wish to use it that way. It can also read and trade using any of my indicators, using the signal buffer.

  1. Hello, is it possible to get the code to copy for the custom indicator with MT5? I want to buy the full version but I want to backtest first.
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *