Hedging Blue Print for Auto Trading

There are two types of trading that may require hedging.
1. Investments
If you have long term holdings, your tolerance of draw down may be greater (I.e. conviction) and with this type of “trading” you may change direction and adjust your weighting accordingly. In this context overhedging does make sense, but graduality should still apply.
2. Short term trading
With short term trading, hedging is a last resort and one should try to avoid it.
Yet, it is something to prepare for and some parts of this additional system in place may contribute to your bottom line.
Auto trading is what I am engaging in. Every trade comes with stop losses, so what is this about?
The events to plan for are the following:
– How to handle a weekend gap prospect if you are still in an open position near the end of the week.
– What to do if the stop loss size was not selected well enough, and one individual position starts to put on too much drag (I.e. the draw down caused exceeds 5%).
– What to do if the simultaneously opened positions impose a greater draw down or even a margin call threat?
– How to prepare for possible human interactions such as waiving stop losses or opening positions without stop losses.
In order to prepare for auto-trade hedging, one has to figure out the final outcome first.
The final outcome is the reach of the maximum draw down.
I start with the following numbers:
Ratio hedging should happen in two steps;
When the total draw down exceeds 20%, which means that the equity to balance ratio drops below .8, half hedge should be clicked on at market and simultaneously all stop losses and targets should be eliminated  (except for the hedge itself) as well as all target prices and all trail stops and croppers should be suspended.
As additional protection measure, at .85% all orders placed in the more weighted direction should be halted.
Yet another measure would be at .75% all at market orders in the more weighted direction by auto trading routines to be halted (other than hedging of course).
When the equity to balance ratio drops to .7, a full hedge should be clicked on at market and all auto trading should be suspended asap.
This is where a human would have to salvage all positions at once and take the 30% loss.
To avoid ever getting into this situation, pro-active hedging could be made.
The automated version of this could do the following:
It could administer half hedges as follows:
In a bearish short term stance (below Mr. Maroon) upon reaching local peak overbought condition and showing excessive draw down (5%) a 50% short hedge could be put on with no target, but with a stop.
In a bullish short term stance (above Mr. Maroon) upon reaching local peak oversold condition and showing excessive draw down (5%) a 50% long hedge could be put on with no target, but with a stop.
The rationale behind this proactive hedging is “attempting” to gain rope by additional income, that in theory may result in increase of balance when closing it out and temporary margin relief.
If the Margin level goes dangerously close to the level where you are not allowed by your broker to open positions, you should put on half a hedge immediately (if it is at 100%, make your move at 150%).
The stop of the half hedge should be at 6% loss of balance.
I can entrust this function on a cropper.

// Ratio Hedger by Macdulio for Automated Trading

#include <stdlib.mqh>
extern int magic_number = 51;
extern int magic_number2 = 52;
extern double Ratio = .8;
extern double MarginCallPercentage = 100;
#property copyright “by Macdulio in 2018”
#property link “https://forexfore.blog&#8221;
#property description “Ratio Hedger”
#property description “Clicks on half a hedge upon the Equity/Balance ”
#property description “Ratio dropping below the set value (at market)”
#property description “and another half 10% lower(at market)”
#property description “1/2 hedge also triggered by 150% of the set”
#property description “margin call level (by your broker)”

int profits;

double nakedshorts[];
double nakedlongs[];

double open_price;
double stop_loss_price;
double take_profit_price;

double OrderOpenPrice;
double OrderProfit;
string symbol = Symbol();
int init() {
return(0);
}

int deinit() {
return(0);
}

int start() {
int i, counter;
int counted_bars=IndicatorCounted();
int longcount, shortcount;
double nlongs;
double nshorts;
double longaveragebuffer;
double shortaveragebuffer;
int order_type;

profits = 0;
int hstTotal=OrdersHistoryTotal();

counter = 0;

for(i=OrdersTotal()-1; i>=0 ; i–)
{

if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)
{
Print(“Access to orders list failed with error (“,GetLastError(),”)”);
break;
}
// if ( Symbol()==”EURUSD” && OrderStopLoss()==0 ) {
if (OrderType() == OP_BUY)
{
nlongs = nlongs+OrderLots();
longcount = longcount+1;
longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots());

}

if (OrderType() == OP_SELL )
{
nshorts = nshorts+OrderLots();
shortcount = shortcount+1;
shortaveragebuffer = shortaveragebuffer+(OrderOpenPrice()*OrderLots());
}
// }
}

double comparison = AccountEquity()/AccountBalance();

// Half Hedge for shorts
if (nlongs<nshorts && (comparison<Ratio || AccountMargin()<MarginCallPercentage*1.5) ) {

open_price = open_price = NormalizeDouble(Ask, Digits);
stop_loss_price = NormalizeDouble(0,Digits);
take_profit_price = NormalizeDouble(0,Digits);

for (i = OrdersTotal() – 1; i >= 0; i–)

if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number) {
order_type = OrderType();
if (order_type == ORDER_TYPE_BUY) {
if ((NormalizeDouble(OrderOpenPrice(), Digits) != open_price) || (NormalizeDouble(OrderStopLoss(), Digits) != stop_loss_price) || (NormalizeDouble(OrderTakeProfit(), Digits) != take_profit_price)) {
if (!OrderModify(OrderTicket(), open_price, stop_loss_price, take_profit_price, OrderExpiration()))
Print(“Error: “, ErrorDescription(_LastError));

}
break;
}
else if (order_type == ORDER_TYPE_BUY)
break;
}
if (i < 0)
if (OrderSend(symbol, OP_BUY, NormalizeDouble((nshorts-nlongs)/2,2), open_price, 3, stop_loss_price, take_profit_price, “RATIO HEDGER HALF BUY 0/0”, magic_number) < 0)

Print(“Error: “, ErrorDescription(_LastError));
}
else
for (i = OrdersTotal() – 1; i >= 0; i–)

if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number )
if (OrderType() == ORDER_TYPE_BUY_STOP)
if (!OrderDelete(OrderTicket()))
Print(“Error: “, ErrorDescription(_LastError));

// Full Hedge for shorts
if (nlongs<nshorts && comparison<Ratio-.1 ) {

open_price = open_price = NormalizeDouble(Ask, Digits);
stop_loss_price = NormalizeDouble(0,Digits);
take_profit_price = NormalizeDouble(0,Digits);

for (i = OrdersTotal() – 1; i >= 0; i–)

if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number2) {
order_type = OrderType();
if (order_type == ORDER_TYPE_BUY) {
if ((NormalizeDouble(OrderOpenPrice(), Digits) != open_price) || (NormalizeDouble(OrderStopLoss(), Digits) != stop_loss_price) || (NormalizeDouble(OrderTakeProfit(), Digits) != take_profit_price)) {
if (!OrderModify(OrderTicket(), open_price, stop_loss_price, take_profit_price, OrderExpiration()))
Print(“Error: “, ErrorDescription(_LastError));

}
break;
}
else if (order_type == ORDER_TYPE_BUY)
break;
}
if (i < 0)
if (OrderSend(symbol, OP_BUY, NormalizeDouble(nshorts-nlongs,2), open_price, 3, stop_loss_price, take_profit_price, “RATIO HEDGER BUY 0/0”, magic_number2) < 0)

Print(“Error: “, ErrorDescription(_LastError));
}
else
for (i = OrdersTotal() – 1; i >= 0; i–)

if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number2 )
if (OrderType() == ORDER_TYPE_BUY_STOP)
if (!OrderDelete(OrderTicket()))
Print(“Error: “, ErrorDescription(_LastError));

// Half Hedge For Longs
if (nshorts<nlongs && (comparison<Ratio || AccountMargin()<MarginCallPercentage*1.5)) {

open_price = NormalizeDouble(Bid, Digits);
stop_loss_price = NormalizeDouble(0,Digits);
take_profit_price = NormalizeDouble(0,Digits);
for (i = OrdersTotal() – 1; i >= 0; i–)
if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number) {
order_type = OrderType();
if (order_type == ORDER_TYPE_SELL) {
if ((NormalizeDouble(OrderOpenPrice(), Digits) != open_price) || (NormalizeDouble(OrderStopLoss(), Digits) != stop_loss_price) || (NormalizeDouble(OrderTakeProfit(), Digits) != take_profit_price)) {
if (!OrderModify(OrderTicket(), open_price, stop_loss_price, take_profit_price, OrderExpiration()))
Print(“Error: “, ErrorDescription(_LastError));
}
break;
}
else if (order_type == ORDER_TYPE_SELL)
break;
}
if (i < 0)
if (OrderSend(symbol, OP_SELL, NormalizeDouble((nlongs-nshorts)/2,2), open_price, 3, stop_loss_price, take_profit_price, “RATIO HEDGER HALF SELL 0/0”, magic_number) < 0)
Print(“Error: “, ErrorDescription(_LastError));
}
else
for (i = OrdersTotal() – 1; i >= 0; i–)
if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number)
if (OrderType() == ORDER_TYPE_SELL_STOP)
if (!OrderDelete(OrderTicket()))
Print(“Error: “, ErrorDescription(_LastError));

// Full Hedge For Longs
if (nshorts<nlongs && comparison<Ratio-.1) {

open_price = NormalizeDouble(Bid, Digits);
stop_loss_price = NormalizeDouble(0,Digits);
take_profit_price = NormalizeDouble(0,Digits);
for (i = OrdersTotal() – 1; i >= 0; i–)
if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number2) {
order_type = OrderType();
if (order_type == ORDER_TYPE_SELL) {
if ((NormalizeDouble(OrderOpenPrice(), Digits) != open_price) || (NormalizeDouble(OrderStopLoss(), Digits) != stop_loss_price) || (NormalizeDouble(OrderTakeProfit(), Digits) != take_profit_price)) {
if (!OrderModify(OrderTicket(), open_price, stop_loss_price, take_profit_price, OrderExpiration()))
Print(“Error: “, ErrorDescription(_LastError));
}
break;
}
else if (order_type == ORDER_TYPE_SELL)
break;
}
if (i < 0)
if (OrderSend(symbol, OP_SELL, NormalizeDouble(nlongs-nshorts,2), open_price, 3, stop_loss_price, take_profit_price, “RATIO HEDGER SELL 0/0”, magic_number2) < 0)
Print(“Error: “, ErrorDescription(_LastError));
}
else
for (i = OrdersTotal() – 1; i >= 0; i–)
if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number2)
if (OrderType() == ORDER_TYPE_SELL_STOP)
if (!OrderDelete(OrderTicket()))
Print(“Error: “, ErrorDescription(_LastError));

return(0);
}