Position Sizing in Futures using current equity not margin

I'm trying to code the position sizing in futures using current equity not margin.

My understanding is that I need to use the custom backtester as the SetPositionSize(10,spsPercentOfEquity) will use the Margin in futures mode. Although it is a clever way to do it, it will give unrealistic results in a long backtest as margins will changes a lot.

I want use a ATR dynamic position sizing based in the current equity. In the custom backtest I tried:

if( Status("action") == actionPortfolio )
bo = GetBacktesterObject();
for( bar = 0; bar < BarCount; bar++ )
CurrentPortfolioEquity = bo.Equity;
for( sig = bo.GetFirstSignal( bar ); sig; sig = bo.GetNextSignal( bar ) )
lotSize = int( CurrentPortfolioEquity
(PositionRisk/100) / dollarVol );


bo.ProcessTradeSignals( bar );

However, the lotsize is the number of contracts but sig.PosSize is the position size (positive numbers mean dollar value, negative values mean percent of portfolio equity).

So, how can I set the PosSize to the number of contracts/shares?

I figured it out without the CBT:

Buy = Cross( C, MA( C, 20 ) ); // some trading rules
Sell = Cross( MA( C, 20 ), C );
RiskPerContract = 2 * ATR( 20 );
ApplyStop( stopTypeLoss, stopModePoint, RiskPerContract, True );
// risk 1% of entire equity on single trade
PositionRisk = 1;
PctSize = PositionRisk * MarginDeposit / ( RiskPerContract * PointValue );
SetPositionSize( PctSize, spsPercentOfEquity );

At first glance, I thought that it use the margin to compute the position sizing, but no, It works with any value of the margin.

here the link


Using the position sizing based on risk above, how can I retrieve the number of contracts in the exploration for a multi-currency portfolio?

For instance:
AddColumn(PositionSize,"PosSize",1.0); returns the % of equity not the number of contracts

Contracts=int((PositionRiskEquity() / ( 100RiskPerContract * PointValue )));
returns the number of contract of the USD denominated symbols using the final equity value. This is not exactly what I want.

I just need the same number of contracts that is shown in the detailed log (Shares:). I'm sure there is a easy way to retrieve i but couldn't find it.

Moreover, is it possible to customize the backtest detailed log for, say, include the stop-loss level?



Risk-based position sizing requires the current equity to determine the number of contracts. Portfolio equity is not available from an Exploration. So no, you can't report number of contracts from the Exploration when using risk-based position sizing.

Also, please use code tags around your AFL snippets for better readability.

Ok. Got it. My objective in live trading is to place an order with the same number of contracts as the backtest. Therefore, I could use

CashB = StrToNum(ibc.GetAccountValue("TotalCashBalance"));

and compute the number of contract as:

ContractsIB=int((PositionRisk*CashB / ( 100*RiskPerContract * PointValue )));

It seems to work fine for USD denominated symbols. But I'm not sure how to do it for multi-currency.


If your futures contracts specify the currency and your database contains currency symbols that can be used to determine the exchange rate, you could make it work.

It does. Will I need to use the CBT? Otherwise how I can adjust the currency?

I have once made a tutorial on currency pairs years ago


Is it Possible to use Portfolio Equity in Calculating an array?For Eg I have written the following code:

SetOption("InitialEquity" , 1000000);
NiftyClose = Foreign("$NIFTY-NSE" , "C" ) ;
MarginPerLot = (NiftyClose * LotSize) / 15 ;
TotalLots = round(Foreign("~~~Equity", "C" )/ MarginPerLot) ;

But Foreign("~~~Equity", "C" ) doesn't change and always remains as 1000000.How do I use Custom Backtester here?

Foreign("~~~Equity", "C" ) returns the final equity.

You have to use

SetPositionSize( ..., spsPercentOfEquity );

see the help for the details

The margin per lot keeps on changing. For eg in year 1 the margin per lot was $1000. The margin per lot in year 2 was $2000. If the Initial equity is $100000, the position size using spspercentequity might not stay the same.The margin per lot is calculated using the underlying value of Nifty

sure, the closing price keeps changing as well. But the equity is fixed.

I want to calculate the Margin Per Lot on the Equity Value as of previous bar

There is something not right about the statement you have made.

Equity is the amount of Cash you have whereas as "Margin" or "Margin per Lot" is a value fixed by your Broker.

You have to calculate the Margin based on the Contract value or something on those lines and check if cash is sufficient to buy a lot or how many max. lots can be bought.

Ok. So the formula to calculate margin Per Lot
MarginPerLot = ( Current price of the Underlying * Lotsize ) / 15 . The max Number of Lots I can trade will be:
MaxLotsTraded = Current Equity Value / MarginPerLot
My question is How do I get the Current Equity Value?

Define initial Equity (Starting Capital), eg. $100,000

Freeze your trading system, run a backtest with the same.

It will populate the special symbol ~~~EQUITY with a value.
Hopefully you've not blown your account until then.

myLiveTradingCapital = Foreign( "~~~EQUITY",  "C");

From here you go Live.

Hi All, I read through this post, provided links and some other related topics, still have a bit of difficulty to understand how to do position sizing based on risk.
assume I have an SL distance (variable based on trade conditions) and I want to risk 1% of the total current equity in each trade.

RiskPerTrade = 1;
PctSize =  RiskPerTrade * MarginDeposit  / ( SL * PointValue );

This doesn't work as it won't consider the current equity.
What I want is to lose only x% of equality (at trade entry) if trade hit SL.

I think something like this works:

RiskPerTrade = 1;
PctSize =  RiskPerTrade * Current_Equity  / ( SL * PipValue);

any idea?

This is the way:

1 Like


I have mulled over the KB article that describes SetPositionSize() with futures:

Looking at the numbers in the example given in the article, if we denote MarginDeposit by M, we get:

PctSize = 1% * $M / (10 * $50) = M/500 %
M/500 % of $1,000,000 equity is $20 * M.
So with margin deposit of $M, we can buy $20 * M / $M = 20 contracts.

This is the same number in the example. So the number of contracts is independent of MarginDeposit (M). So it seems using any value of M will suffice for backtest purposes? Is my understanding correct?

There is one caveat: the backtest report has a column PositionValue = MarginDeposit * Qty. This is not independent of M. However, this seems to be an issue that can be ignored for most practical backtest purposes?