Skipping last n loss trades to take fresh long signal

Hi,
I am looking to write a code say simple moving average crossover.
and I want to skip last few number of loss trades say n.
means, trade long only when last n trades are loss trade.
looking for positive response from experts.
Regards,

You can use SumSince to track the number of simulated “losses” since the last “win” and then use that as an input to the Buy criteria.

Something like this should get you started:

LossesToSkipBeforeBuy = 3;

BuyPrice = SellPrice = C;

MA1 = MA(C, 5);
MA2 = MA(C, 20);

LongEntry = Cross(MA1, MA2);
LongExit = Cross(MA2, MA1);
ValueAtEntry = ValueWhen(LongEntry, BuyPrice);

Loss = LongExit AND SellPrice < ValueAtEntry;
Win = LongExit AND SellPrice >= ValueAtEntry;
TotalLossesSinceLastWin = SumSince(Win, Loss);

Buy = LongEntry AND TotalLossesSinceLastWin > LossesToSkipBeforeBuy;
Sell = LongExit;

Filter = LongExit OR Buy;
AddColumn(Win, "Win", 1);
AddColumn(Loss, "Loss", 1);
AddColumn(TotalLossesSinceLastWin, "TotalLossesSinceLastWin", 1);
AddColumn(Buy, "Buy", 1);
9 Likes

Hi Alan,

I’m trying to use this but without the SUMSINCE, because I have an older version of AB.

I tried the following but it’s not right. Could you suggest a fix please?

Thanks.

LossesToSkipBeforeBuy = Optimize("2",1,1,20,1);

BuyPrice = SellPrice = C;

LongEntry = C<O;
LongExit = C>O;
ValueAtEntry = ValueWhen(LongEntry, BuyPrice);

Loss = LongExit AND SellPrice < ValueAtEntry;
Win = LongExit AND SellPrice >= ValueAtEntry;

        x = Sum( loss, BarsSince( win ) );

TotalLossesSinceLastWin = x;

Buy = LongEntry AND TotalLossesSinceLastWin >= LossesToSkipBeforeBuy;
Sell = LongExit;

Filter = LongExit OR Buy;
AddColumn(Win, "Win", 1);
AddColumn(Loss, "Loss", 1);
AddColumn(TotalLossesSinceLastWin, "TotalLossesSinceLastWin", 1);
AddColumn(Buy, "Buy", 1);

It’s ok, worked it out thanks.

1 Like