Dynamic position size in equity trading


Currently I am testing some codes on equity trading and trying to incorporate some position sizing on it. The following codes was posted by Howard before and i have made some amendments on it:

SetOption("MaxOpenPositions", 20);

Buy = Cross(MA(C, 5), MA(C, 10));
Sell = Cross(MA(C, 10), MA(C, 5));
Buy = ExRem(Buy,Sell);
e = Equity();
EquityMA = MA(e,20);
Pass = IIf(e>=EquityMA,1,0);
PassPS = IIf(Pass, 2, 1);
SetPositionSize (PassPS, spsShares);

The above code will buy 2 positions if current equity is higher than 20 days MA of equity, if not then it will buy 1.

However, i would like to ask how to add one position each time once Pass is true. For example, PassPS set to 1 for the first 20 trades. For the 21st trade, if current equity is higher than its MA(20), add one position to PassPS and so on. If current equity is lower than its MA(20), then PassPS remain unchanged.

Thank you!!

@jackcl I wanted to ask you to elaborate but first I just wanted to point out that your line

Pass = IIf(e>=EquityMA,1,0);

Is the equivalent to,

Pass = e>=EquityMA; which of course means the next line can be changed as well.

But in your post do you intend to continue to add positions? Every 20 trades to you plan on increasing to 3, 4, 5 etc shares if the Equity is above it’s MA(20)?

Also what is your plan if the Equity drops below the MA(20)? Decrease shares from 2 back to 1 (or if as above from 3 back to 2, or 4 back to 3 etc.)?
I may not have a solution but I wanted to clearly understand the objective before I give up and I like your question/idea.

Hi portfoliobuilder,

Thanks for your reply. Your point is correct. Pass = e>=EquityMA; is correct. I just forgot to change back it as the original code is to block signal when it is below MA20.

Actually my idea is to increase position size by 1 once my current equity is higher than its MA20 or reduce 1 if it is below MA20. Because of this, i have to wait until the 21st trade such that MA20 can be calculated. So, for the first 20 trades, the position size will be set at 1. After that, it will vary depending on the equity. It will add 1 if it is higher than MA 20 or reduce 1 if it is below MA20. The minimum size will be 1 while the max size will be 20.

Thank you!!

First recommended reading:

Once you read that you will clearly see that the approach you are using is incorrect.

Generally speaking you would need to evaluate your system performance and calculate equity bar by bar which means you need custom backtester.

1 Like

Hi Tomasz,

It will be a big challenge for me as i am not that strong in writing codes. Anyway, thanks for your advise and i will try to learn it.

1 Like