Current portfolio equity and cash

How can I access current Equity and Cash in a portfolio backtest to get the following calculations:

Need -> Cash
Need -> Equity

max_portfolio_allowed = Equity*20/100; //20% of current Equity
max_loss_allowed = Equity*0.5/100; //5% of current Equity
not_trade_cash = 100000; //always leave this cash
maxinvestcap = 300000; //max value a position can be

CashBalance_current = Cash - not_trade_cash;

Later I use all of the above to calculate positions size, but I am not able to access current Equity and Cash.

I tried to put the following on top of AFL:

SetOption( "UseCustomBacktestProc", True );
if( Status( "action" ) == actionPortfolio ) {
	bo = GetBacktesterObject();
	PortEquity = Null;
	PortCash = Null;
	for( bar = 0; bar < BarCount; bar++ ) {
		bo.ProcessTradeSignals( bar );
		PortEquity[ bar ] = bo.Equity;     
		PortCash[ bar ] =;


Yet I cannot use PortEquity and PortCash outside of these brackets.

You do not need CBT code if you just want to call equity and cash "later".
Those ones are part of ~~~EQUITY symbol's array fields later (after analysis).

eq = Foreign("~~~EQUITY", "C");
cash = Foreign("~~~EQUITY", "L");

If you want to do some very special position size calculation based on equity then it is not done "later" but inside CBT. But is that required in your case? If you always want to keep aside 100k then why not subtracting it one time from initial equity?


Thank you for your suggestion. I tried this, but for some reason Foreign("~~~EQUITY", "C") and Foreign("~~~EQUITY", "L") do not match/make sense at all with the Equity and Cash plotted on the chart and checking its values via _TRACE.

I need to call Equity and Cash during the backtest and not later so it is used to calculate position sizes for every entry.

I need to call Equity and Cash during the backtest and not later.

  1. You wrote "later" and said "cannot" use them "outside" CBT. I responded exactly to that.. they can be called later.
  2. cash and equity fields of ~~~EQUITY symbol are correct. And again ~~~EQUITY is updated after backtest. You possibly compared apples to oranges.
  3. If you need to do calculation on position size then either do in first phase of backtest (SetPositionSize(...,...) function) or (if you want to do "special" stuff on current eq and cash) then during second phase (CBT) but not later.

You are correct- apologies for this. With "later", I meant after that code. Do you know how to do this during the second phase of CBT?

My max loss calculation as 5% of equity calculates shares from price and stop loss, but I cannot use price inside CBT and CBT values outside of it.

The formula is:

Shares = Max_loss_allowed / (price - stoploss);

But max_loss_allowed is based on current equity.

Read the manual and the Knowledge Base, ready-to-use solution is described here:

The thing that you are missing is that is you don't really need to access equity variable to achieve want you want. Once you read KB article you would know how to refer to current equity correctly using simple PositionSize variable (or SetPositionSize function)

The problem with your question was not describing your GOAL.
Should you described the goal first one would point you to correct place in KB in first reply

1 Like

I have looked in the KB, yet this does not apply to my problem, because my price and stop values come from a file that has all the trades and they are always different in terms of % and distance.

KB article APPLIES to everything. It took 5 seconds for you to reply after pointing the KB article. Really 5 seconds is NOT enough to actually read the article. Read it carefully and please give it not a second, but few minutes of thought, then you will find out that it can be easily applied in your case.

Thank you Tomasz. Unfortunately, the article did not help me. Any help from the community would be much appreciated.

The article also does not address how to access current Cash as I would like to substract 100k from current equity all the time and then use the equity result for position sizing.

@trongart, I agree with @Tomasz: your case is very nicely described in the article that he referenced. In particular, focus on the example using ATR(20), which potentially has a different value on every bar, just like your example of using an external file with stop prices that are not a constant $ value or percentage from the entry price.

As for manipulating the cash in the account, you can do that from the CBT with something like this:

bo.Cash = bo.Cash - 100000;

However, you need to do some more studying so that you understand the two-phase approach that AmiBroker uses to execute a portfolio backtest.


I was able to add both PositionRisk (5%) and maximum allowed % of Equity (20%) to the position size calculation:

PctSize = Min ( PositionRisk * BuyPrice / RiskPerShare, MaxEquity );

However, is there a way to also set a maximum position value such as $50000 (this value will be different for every ticker in the portfolio)?

There is a MinPosValue option in Amibroker, but no Max. and also no Max option for shares.

RiskPerShare = 10;// $ amount subtracted/added from/to price for long/short. So RiskPerShare is price - stoploss 
ApplyStop( stopTypeLoss, stopModePoint, RiskPerShare, True ); 
// risk 5% of entire equity on single trade 
PositionRisk = 5;
MaxEquity = 20;
// position size calculation 
PctSize = Min ( PositionRisk * BuyPrice / RiskPerShare, MaxEquity   );       
SetPositionSize( PctSize, spsPercentOfEquity );

As for the cash, I added the following, but it seems to remove 100000 at every bar instead of producing trade-able cash for every trade as "CASH = CASH - 100000":

if( Status( "action" ) == actionPortfolio ) {
	bo = GetBacktesterObject();
	bo.PreProcess(); // Initialize backtester
	for( bar = 0; bar < BarCount; bar++ ) 
		bo.ProcessTradeSignals( bar );
		bo.Cash = bo.Cash - 100000;

If you want to start doing very customized position sizing, you will need to learn how to use the CBT more effectively.

Of course it does, because you put it inside the loop that iterates through all the bars of the backtest. Since it appears that you are not very familiar with AmiBroker nor with general programming concepts, you may want to start by testing some simpler concepts to increase your comfort level with how things work. Otherwise, you have a high potential to code something incorrectly without realizing it, which could lead to inaccurate test results.

1 Like

It may also help you to review this post: How do I debug my formula?

The debugging techniques described there will go a long way towards helping you understand exactly how AmiBroker executes a backtest.

Thank you for your reply. So the only way to add a limit on the max position value for my case is through CBT?

Do you think you could help me with this example so I would know how to use CBT for this case and many others this way? Many people would be able to find this post and learn from it. I could not figure it out unfortunately looking through all the material here.