Inside Bar – Rewrite Compo

At times out of nostalgia I browse among my older routines for a current back test to see if any of them holds up well in the current environment.

Hundreds of ideas came and went, but some were on cue all along. I used to have a chess team with not much in common but the idea to exploit an edge.

Now I am thinking more of in terms of a complete, well rounded system, and I expect just as much from the management part as from the “excuses”, the trade initiator routines.

I am happy when I see something with a back test like this:

This is treasure. Something with a great edge. All you need to do is sell instead of buy and vica versa.

I would like you to follow on my path in redoing the piece of code I have coming up here.

I made a few modifications and this is what I ended up with.



Out of the total, 17 “bad turned good” trades I only lost 5 when I applied one 4-hour filter per direction – to eliminate the losing trades.

Can you do this? Could you even better?

Feel free to show me your insights and your results!

The testing period is from the 1st of October, 2018 to the 25th of November, 2018. Tested on EUR/USD with 2 points average spread.


// Inside Trader

#property copyright “by Macdulio”
#property link “https://forexfore.blog
#property description “Inside Trader”
#property description “V1.0”

#include <stdlib.mqh>
extern int ClosePendingInSeconds = 10800;
extern int magic_number = 999;
extern int magic_number2 = 998;
extern int StopLoss = 25;

double RSI2[],stoch[];
int profits;
double nakedshorts[];
double nakedlongs[];
extern double Leverage = 1.5;
extern double AF=1.3;
extern double LT=333;
double open_price;
double stop_loss_price;
double take_profit_price;

int dhdcount;
double OrderOpenPrice;
double OrderProfit;
string symbol = Symbol();
int init() {
ArrayResize(RSI2, 1100);
ArrayInitialize(RSI2, EMPTY_VALUE);
ArrayResize(stoch, 1100);
ArrayInitialize(stoch, EMPTY_VALUE);

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;
double account = AccountEquity();
double longsize, shortsize;
double MaxLots = NormalizeDouble(LT/3000000*account*AF*Leverage/StopLoss*260/4,2);
profits = 0;

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 (OrderType() == OP_BUY && OrderSymbol()==Symbol())
{
nlongs = nlongs+OrderLots();
longcount = longcount+1;
longaveragebuffer = longaveragebuffer+(OrderOpenPrice()*OrderLots());

}

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

for (i=1; i<=3; i++)
{
stoch[i]=iStochastic(NULL,30,10,3,3,MODE_SMA,1 ,MODE_SIGNAL,i);
RSI2[i]=iRSI(NULL,30,2,PRICE_MEDIAN,i);
}

double dmulti=1;
double umulti=1;

if (Close[0]>iMA(Symbol(),60,1656,0,MODE_EMA, PRICE_HIGH,0) && Close[0]>iMA(Symbol(),30,414,0,MODE_EMA, PRICE_HIGH,0) && iMA(Symbol(),30,414,0,MODE_EMA, PRICE_HIGH,0)iMA(Symbol(),30,414,0,MODE_EMA, PRICE_HIGH,0) && iMA(Symbol(),30,414,0,MODE_EMA, PRICE_HIGH,0)iMA(Symbol(),30,414,0,MODE_EMA, PRICE_HIGH,0) ) {umulti=1.48; dmulti=1;}
else if (Close[0]<ima(symbol(),60,1656,0,mode_ema, price_low,0)=”” &&=”” close[0]iMA(Symbol(),30,135,0,MODE_EMA, PRICE_HIGH,0) ) {umulti=1; dmulti=2.1;}
else if (Close[0]iMA(Symbol(),30,135,0,MODE_EMA, PRICE_HIGH,0) ) {umulti=1; dmulti=1.77;}
else if (Close[0]<ima(symbol(),30,414,0,mode_ema, price_low,0))=”” {umulti=”1;” dmulti=”1.48;}” s=”” #1=”” if=”” (=”” (mathabs(nlongs)=”=0″ ||=”” nlongs<nshorts)=”” &&=”” ihigh(symbol,60,1)-ilow(symbol,60,1).0013 && iHigh(symbol,60,1)<=iHigh(symbol,60,2) && iLow(symbol,60,1)>=iLow(symbol,60,2) && iRSI(NULL,60,8,PRICE_MEDIAN,1)>23 && iStochastic(NULL,60,10,3,3,MODE_SMA,1 ,MODE_SIGNAL,1)<istochastic(null,60,10,3,3,mode_sma,1 ,mode_signal,2)=”” &&=”” istochastic(null,60,10,3,3,mode_sma,1=”” ,mode_signal,0)<istochastic(null,60,10,3,3,mode_sma,1=”” ,mode_signal,1)=”” close[0]<ima(symbol(),30,135,0,mode_ema,=”” price_high,0)=”” close[0]= 0; i–)

if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number) {
order_type = OrderType();
if (order_type == ORDER_TYPE_SELL_STOP) {
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_SELLSTOP, longsize, open_price, 3, stop_loss_price, take_profit_price, magic_number+” I.T. SSTP “, magic_number) < 0)

Print(“Error: “, ErrorDescription(_LastError));
}
else
for (i = OrdersTotal() – 1; i >= 0; i–)
if (TimeCurrent()-OrderOpenTime()>=ClosePendingInSeconds)
if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number)
// if (OrderType() == ORDER_TYPE_BUY_LIMIT)
if (!OrderDelete(OrderTicket()))
Print(“Error: “, ErrorDescription(_LastError));

// L #1
if ((MathAbs(nshorts)==0 || nlongs>nshorts) &&
iHigh(symbol,60,1)-iLow(symbol,60,1)<(iHigh(symbol,60,2)-iLow(symbol,60,2))*.75 && iHigh(symbol,60,2)-iLow(symbol,60,2)>.0013 && iHigh(symbol,60,1)<=iHigh(symbol,60,2) && iLow(symbol,60,1)>=iLow(symbol,60,2) && iRSI(NULL,60,8,PRICE_MEDIAN,1)<82 && iStochastic(NULL,60,10,3,3,MODE_SMA,1 ,MODE_SIGNAL,1)>iStochastic(NULL,60,10,3,3,MODE_SMA,1 ,MODE_SIGNAL,2) && iStochastic(NULL,60,10,3,3,MODE_SMA,1 ,MODE_SIGNAL,0)>iStochastic(NULL,60,10,3,3,MODE_SMA,1 ,MODE_SIGNAL,1)

&& Close[0]>iMA(Symbol(),30,414,0,MODE_EMA, PRICE_LOW,0)
&& Close[0]>iMA(Symbol(),30,135,0,MODE_EMA, PRICE_LOW,0)
) {

if (nshorts==0) shortsize =MathAbs(NormalizeDouble(MaxLots*.7,2));
else shortsize =NormalizeDouble(MaxLots-nshorts,2);

open_price = NormalizeDouble((iHigh(symbol,60,1)+10*Point),5);
stop_loss_price = NormalizeDouble(iHigh(symbol,60,1)-(iHigh(symbol,60,1)-iLow(symbol,60,1))/2-40*Point, 6);
take_profit_price = NormalizeDouble(iHigh(symbol,60,1)+(iHigh(symbol,60,1)-iLow(symbol,60,1))*umulti, 6);

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_STOP) {
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_BUYSTOP, shortsize, open_price, 3, stop_loss_price, take_profit_price, magic_number+” I.T. BSTP “, magic_number) < 0)
Print(“Error: “, ErrorDescription(_LastError));
}
else
for (i = OrdersTotal() – 1; i >= 0; i–)
if (TimeCurrent()-OrderOpenTime()>=ClosePendingInSeconds)
if (OrderSelect(i, SELECT_BY_POS))
if (OrderMagicNumber() == magic_number)
// if (OrderType() == ORDER_TYPE_SELL_LIMIT)
if (!OrderDelete(OrderTicket()))
Print(“Error: “, ErrorDescription(_LastError));

return(0);
}

Just for the heck of it, what if I didn’t limit the number of orders that can be opened simultaneously?

Not that bad return for 2 months…

The 3 Genders of Hedging (Humanitica)

The need of hedging comes from the presence of human error.
Human error is for instance opening a position without a reason, not having / eliminating stop losses, and you cannot blame an EA for opening a trade at the wrong place/ time, only the maker who failed to factor in all possibilities and failed to include / find the necessary / right filters.

I have started a video series on hedging, called 4-step Auto Hedging in Forex.

In my opinion, there are three different hedging systems, and they all have their use.

1. Ratio Hedging

The fore-mentioned videos talk about a 4-step hedging system that is meant to prevent you from the equity/balance ratio dropping below a certain level. The weakness of ratio hedging is that it only relies on the equity drop and does not consider other factors, so you may end up with a hedge at a wrong place/time especially when you are opening larger sizes that you may be tempted for especially when having larger leverage at your disposal. The 4 steps as a reminder are: 33% hedge (the rope trade), 5% equity drop later 1/2 hedge, 5% equity drop later overhedge, and if for some reason push comes to shove, 5% later a full hedge gets clicked on – after which manual close outs mean the resolution.

2. Break Out Hedging

Break out hedging may be too far out to be accommodating, and would not eliminate the possibility of a margin call. This is where my good old, “re-calculate needed size, post pending order, wait, delete order” sequence can be utilized. To not be allocating to much bandwidth, it is sensible to to only start posting orders when price is within stone throw distance. I use my Forest model for this kind of hedging which by now includes the hedging line. This, roll-out, automatic hedging can be done with over size as well, and the routines can close out the hedges when the next mile stone was made.

3. Proactive hedging

I know, all hedging genders are proactive, they try to prevent from losses, but this particular kind is the early bird of the tree. If you were a human, this would be your place to chip in. The opened hedge sizes do not exceed the open position sizes (in the opposite direction), so if nothing is open, nothing happens. Since there is a place and a need to catering for the trading robots, Humanitica would have to define for the human what he/she is allowed to do in order not to cause any harm to the robots and the account balance. A lot of the human role can and should be handed over to the Human-Substitute Bots, for a human is not capable to carry out a 24-hour service, nor can they make emotionless judgements. Yet, they must be trained in order to aid their chances of survival.

11110000001010100000000000000101010111111111111111110101010

Humanitica2

My First 25%+ Gainer Auto-Trading Day

Well, would had been if I did not touch the phone all day.

Here is how it shaped up after all:

Statement151118LQD

Yeah, this is only 15.65%, I am fully aware.

Statement151118LQD_

I cancelled 4 trades.

The orange, buy limit would had been cropped at 2.5% gains potentially, if I did not touch it.

The next yellow box, the 96 EL potentially would had made it to 7% gains, for it is a high privilege trade, just like the first trade of the day was with “93” magic number (my weight breaker routine).

The other two yellow – at least one of those should had made it to the 2.5% crop.

I left 12% on the table due to having a cell phone at my disposal and too much time to interfere unnecessarily.

There were no trades opened manually, and none of the stop losses were danger of being hit.

 

 

 

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);
}