Risk-based position sizing on margin account

Hi, im using risk-based position sizing based on this page: https://www.amibroker.com/kb/2014/10/12/position-sizing-based-on-risk/

riskPerShare = 3*ATR(5); 
positionRisk = 3; 									
PctSize =  positionRisk * BuyPrice / riskPerShare; 
SetPositionSize(200 * (PctSize/100), spsPercentOfEquity ); //to use that leverage

Im using margin for trading portfolio of stocks.

SetBacktestMode(backtestRegular);				
SetOption("InitialEquity",30000);			
SetOption("accountmargin",50); 		
SetOption("AllowPositionShrinking", True);	
SetOption("AllowSameBarExit", False);  		
SetOption("FuturesMode", False);  				
SetOption("UsePrevBarEquityForPosSizing",True)
SetOption("MaxOpenPositions", maxPositions);		
SetTradeDelays( 1, 1, 1, 1);						
SetOption("ActivateStopsImmediately",False);

Is this correct setup to backtest with margin and risk-based position sizing ? What i thought is shoud have done - on hypothetical trade:
I have 30k USD account - 60k USD available with margin.
Buy signal on stock - PctSize 11% - PositionSize should be 22% so with margin there should be 60000 * 0,22 = 13200 USD big position.

Ive digged into trade list from backtest and its seems that with that setup, my backtest is using correct equity for margin - 60k. But it opens trades with size based on original PctSize (11% from example above, instead of 22%) and opens more trades (if there are enough signals and until 60k equity is used).

What am I doing wrong ?
Have a nice day
Petr

1 Like

To trade stocks on margin you have to use SetOption("AccountMargin", value);
Or Backtest setting - General tab - Account margin
9
As well as to increase buying power (increase position size).


(Your post does not contain full code, BTW.)

As you can see below it works!
Here is full code

/// modified from
/// @link https://www.amibroker.com/kb/2014/10/12/position-sizing-based-on-risk/
leverage = 2;
SetOption("InitialEquity", 30000);
SetOption("AccountMargin", 100/leverage);
SetOption("FuturesMode", False);  	

Buy = Cross( C, MA( C, 20 ) ); // some trading rules
Sell = Cross( MA( C, 20 ), C );
Short = Cover = 0;
//
RiskPerShare =  3 * ATR( 20 );
ApplyStop( stopTypeLoss, stopModePoint, RiskPerShare, exitatstop = 1 );
//
// risk 3% of entire equity on single trade
PositionRisk = 3;
//
//buying_power = 1;
// or 
buying_power = leverage;
//
// position size calculation
PctSize = PositionRisk * BuyPrice / RiskPerShare;
SetPositionSize( buying_power*PctSize, spsPercentOfEquity );

Margin account disabled
10

Now leveraged.. sizes increase
12