Author: Müller Peter

This trading script is designed to automate a complex "hedging" strategy on the MetaTrader 5 platform. In simple terms, hedging involves opening positions in both directions (buying and selling) simultaneously to manage risk or capture price movements from multiple angles.

Here is a breakdown of how the logic operates:

Core Market Monitoring

The script constantly monitors the live market for every "tick" (price update). It performs several checks before taking action:

  • Market Status: It ensures the market is actually open before attempting any operations.
  • Price Detection: It identifies the current Bid and Ask prices to calculate potential entry points.
  • Volatility Recognition: It looks for "Huge Candles"—significant price movements that suggest a breakout or a strong trend shift.

Strategy Activation

The automation doesn't run constantly; it waits for a specific trigger. When the script detects a "breakout" (a significant move in price) and confirms that its internal strategy engine is not already active, it initializes the trading logic. During this setup, it defines:

  • Distance: How far apart to place orders.
  • Take Profit: The target goal for closing trades profitably.
  • Lot Size: The amount of capital/volume to risk on the initial trade.

"Build From The Inside" Logic

This is the most sophisticated part of the script. It looks for a specific market structure where there is sufficient price "room" to maneuver. Specifically, it checks for three conditions:

  1. Sufficient Distance: There must be enough space between existing long and short positions.
  2. Balanced Sides: It verifies that the volume on both the buy and sell sides is relatively balanced and small compared to the starting lot size.
  3. Central Positioning: It ensures the current market price is sitting comfortably "between" the previous long and short prices.

If these conditions are met during a breakout, the script calculates a specific volume based on the distance between the current price and the established boundaries. It then executes a "Build From The Inside" move, which essentially builds out a new position from the center of the existing price range.

Safety and Risk Management

To protect the user's capital, the script includes a built-in "emergency brake." It continuously monitors the account health. If the total equity (the current value of the account) drops below 80% of the actual balance, the script will automatically stop all operations to prevent further losses.

3 Views
0 Downloads
0 Favorites
HedgingEA
ÿþ//+------------------------------------------------------------------+

//|                                                    HedgingEA.mq5 |

//|                                  Copyright 2023, MetaQuotes Ltd. |

//|                                             https://www.mql5.com |

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

#property copyright "Müller Peter"

#property link      "https://www.mql5.com/en/users/mullerp04/seller"

#property version   "1.00"



#include <HedgeClass.mqh> // Include the header file for the hedging strategy class



input int OrderDistancePoints = 300; // Distance in points to place orders

input int TPPoints = 250; // Take profit points

input double Startlotsize = 0.1; // Initial lot size

input double Gainperlot = 10.0; // Gain per lot



HedgingStrategy* Strat = new HedgingStrategy(); // Create a new instance of the HedgingStrategy class



// Initialization function

int OnInit()

{

   return(INIT_SUCCEEDED); // Return initialization success

}



// Deinitialization function

void OnDeinit(const int reason)

{

   delete Strat; // Delete the strategy instance

}



// Main function that runs on each tick

void OnTick()

{

   // Check if the market is open

   if(!IsMarketOpen(_Symbol))

      return;



   double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID); // Get the current bid price

   double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK); // Get the current ask price



   bool Breakout = HugeCandle(_Symbol,PERIOD_CURRENT); // Check for a breakout using the HugeCandle function



   // If the strategy is not running and there is a breakout, initialize and run the strategy

   if(!Strat.Running() && Breakout)

   {

      Strat.SetParameters(TPPoints * _Point, Startlotsize, Gainperlot, ask + OrderDistancePoints * _Point, ask - OrderDistancePoints * _Point);

      Strat.Run();

   }



   Strat.onTick(); // Update the strategy with the current tick data



   // Check if the conditions to build from the inside are met

   bool EnoughDistance = Strat.LastLongPrice() - Strat.LastShortPrice() > 2.5 * OrderDistancePoints * _Point;

   bool BothSides = Strat.LongVolume() && Strat.ShortVolume() && (Strat.LongVolume() + Strat.ShortVolume()) < 3 * Startlotsize;

   bool Between = bid > Strat.LastShortPrice() + OrderDistancePoints * _Point && bid < Strat.LastLongPrice() - OrderDistancePoints * _Point;



   // If conditions are met, build from the inside

   if(EnoughDistance && BothSides && Between && Breakout)

   {

      double Vol = RoundtoLots(MathMin(ask - Strat.LastShortPrice(), Strat.LastLongPrice() - bid) / Strat.TargetProfit() * MathMin(Strat.LongVolume(), Strat.ShortVolume()));

      Strat.BuildFromTheInside(Vol, bid + OrderDistancePoints * _Point, bid - OrderDistancePoints * _Point);

   }



   // Stop the strategy if account equity drops below 80% of the balance

   if(AccountInfoDouble(ACCOUNT_EQUITY) / AccountInfoDouble(ACCOUNT_BALANCE) < 0.8)

      Strat.Stop();

}

Comments