How to back test with multiple entries and multiple exits?

I made a simple strategy that I would like to use MA_Fast and MA_Slow to determine the market is bull or bear. When the fast and slow MA indicate the bull market, there are two situations that I will enter my long position: 1. PDI cross MDI; 2. StochK cross StochD. I will enter 1 position each time when one of them appears, so the maximum position will be 2.

If it is bull market, there are three conditions will exit the long entries: 1. MDI cross PDI, exit 1 position; 2. StochD cross StochK; exit 1 position; 3. MA_Slow cross MAFast, exit ALL positions.

Bear market is vice versa.

My code is as below, please help me to modify the code to meet the rules. Thank you guys very much.


SetOption("commissionMode",1);
SetOption("commissionAmount",0.1);

SetTradeDelays(1,1,1,1);

BuyPrice = O;
SellPrice = O;
ShortPrice = CoverPrice = O;

BullMarket = MA(Close, 10) > MA(Close, 20);
BearMarket = MA(Close, 10) < MA(Close, 20);

DMI_BullCross = Cross(PDI(14), MDI(14));
DMI_BearCross = Cross(MDI(14), PDI(14));

Stoch_BullCross = Cross(StochK(14, 3), StochD(14, 3));
Stoch_BearCross = Cross(StochD(14, 3), StochK(14, 3));

TrendReverse_Bull = Cross(MA(Close, 10), MA(Close, 20));
TrendReverse_Bear = Cross(MA(Close, 20), MA(Close, 10));

LE_DMI = BullMarket AND DMI_BullCross;
LX_DMI = BullMarket AND DMI_BearCross;
SE_DMI = BearMarket AND DMI_BearCross;
SX_DMI = BearMarket AND DMI_BullCross;

LE_KD = BullMarket AND Stoch_BullCross;
LX_KD = BullMarket AND Stoch_BearCross;
SE_KD = BearMarket AND Stoch_BearCross;
SX_KD = BearMarket AND Stoch_BullCross;

Buy = LE_DMI;
Buy = LE_KD;
Sell = LX_DMI;
Sell = LX_KD;
Sell = TrendReverse_Bear;
Short = SE_DMI;
Short = SE_KD;
Cover = SX_DMI;
Cover = SX_KD;
Cover = TrendReverse_Bull;

Moderator comment: you forgot required code tags. I added them. Next time use code tags or post will be rejected

The Knowledge Base is huge vault of useful code and it answers most of questions. You should search Knowledge Base it really contains LOTS of information, including the answer to your question http://www.amibroker.com/kb/2014/09/24/how-to-identify-which-signal-triggers/

See also KB table of content: http://www.amibroker.com/kb/toc/

1 Like