Help with code for Position sizing

Hello i am new here. i have stock market experience but again new to amibroker. i was trying to adjust the position size but i could not do it. What i am trying to do is adjust the position size according to stop.
Stock price = $10000
Account capital = $10,000,000
Percent risk = 1% of account capital per trade = $1,00,000
Stop = 10 points.
Therefore position size = $1,00,000 / 10 pts = 10,000 shares per trade

i want to trade 10,000 shares at a time. How can we achieve this in backtest?
Stock buying price = $10,000

http://www.amibroker.com/kb/2014/10/12/position-sizing-based-on-risk/
i read the above link but could not understand it. In my case, i want to test for stoplosses 10 points, 20 points, 30, 40. How can this be done?

Buy = Cross( C, MA( C, 20 ) ); // some trading rules
Sell = Cross( MA( C, 20 ), C );
//
RiskPerShare =  10;
ApplyStop( stopTypeLoss, stopModePoint, RiskPerShare, True );
//
// risk 1% of entire equity on single trade
PositionRisk = 1;
//
// position size calculation
PctSize =  PositionRisk * BuyPrice / RiskPerShare;
SetPositionSize( PctSize, spsPercentOfEquity );

Pctsize = 1 * 10000/10;
setpositionsize(pctsize, spsPercentofequity);

Is this correct?

For testing 20 points stop, i have to change 10 points to 20 points in above code?

Writing this stuff is very difficult. Some help from seniors would be highly appreciated.

10,000 shares per trade you have arrived mathematically by plain division, but since you don't mention leverage, how do you expect this to work?

If you have $10M as Equity, at $10k per share, you'd only be allowed to buy 1K units and not 10K
that is why,

this will arrive to 1000 in spsPercentofequity

so try using Min() as in Min(100, PctSize ) so it takes the least of the values.

1 lot requires $80,000 margin. Lot size 75, futures trading.

Blockquote

Buy = Cross( C, MA( C, 20 ) ); // some trading rules
Sell = Cross( MA( C, 20 ), C );
//
RiskPerShare =  10;
ApplyStop( stopTypeLoss, stopModePoint, RiskPerShare, True );
//
// risk 1% of entire equity on single trade
PositionRisk = 1;
//
// position size calculation
PctSize =  PositionRisk * BuyPrice / RiskPerShare;
SetPositionSize( PctSize, spsPercentOfEquity );

Should i replace "Pctsize" above with "Min(100, Pctsize)" ?

PctSize =  PositionRisk * BuyPrice / RiskPerShare;
SetPositionSize( Min(100, PctSize), spsPercentOfEquity );

i googled but could not find anything on this

One more problem i am facing is that i have amibroker 1min data from 2011 till 2018. But when i run a backtest, it starts from April 2015 (even after selecting All Quotes). i have Amibroker 6.30 Professional. Do i have to change any settings to make it backtest on entire data?

Check if you did not accidentally turned on "pad and align" to symbol with shorter history, see: How do I debug my formula?

You would also want to read about Futures mode here
https://www.amibroker.com/guide/h_futbacktest.html

Because then you need to set the appropriate values (explained in the manual)

  • Futures mode check box (Settings-General page)
  • Margin deposit (Symbol-Information page)
  • Point value (Symbol-Information page)

_TRACE("This is a test");
_TRACE("This is selected value of close: " + Close );
_TRACE("This is first element of close array: " + Close[ 0 ] );

Can you give me an example of how to use trace function? And exactly what should i be tracing?

i am assuming that _trace(close) should be inserted somewhere in the afl, but again it is not clear where.

i downloaded Debugview also. Can you guide me to an example for using Trace() and debugview?

a

see my settings. Still it wont backtest on entire data from 2011 till 2018. You can see the start date also in the attached screenshots

see the link TJ posted, I think you just skimmed through it :slight_smile:

Use _TRACEF() https://www.amibroker.com/guide/afl/_tracef.html something like this will give you formatting and multi variable trace in one go

_TRACEF( "%s for %s is %g", "Barcount ", Name(), BarCount );

Pad and align is unticked.

i pasted the code line you gave me and it returned the following Trace log. Check attached screenshottrace

does 688861 bars mean the backtest is running on entire 1min data from 2011 till 2018? Yet it still shows results from 2015 till 2018. How to get it fixed

Coming back to my original question. Can we enter a value like
SetPositionSize(106, spsPercentOfEquity);

It seems too high number to test on 106% of equity for a 1% risk per trade in this case(Equity = $10,000,000). But that is the only solution i found to get it working. Point value = 75

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 );

RiskPerContract = 10 points.
PositionRisk = 1%.
Pctsize = 106%
Setpositionsize(106, spsPercentOfEquity).

Is the calculation proper for Futures trading?

I am trying to plot the scalein entries but not getting it. Some help in modifying the code below would be appreciated:

x = SumSince(sellsig1, buysig1);
xsigs = x <= 30;

Buy =  IIf(buysig1 AND xsigs, sigScaleIn, 0);
PlotShapes( sigScaleIn, shapeUpTriangle, shapeNone );

//PlotShapes(IIf(buysig1 AND xsigs, shapeSmallUpTriangle, shapeNone),colorBlue, 0, L, Offset=-45);
//PlotShapes(IIf(InitialEntry, shapeupTriangle, shapeNone),colorGreen, 0, L, Offset=-45);

Sell =  sellsig1;
Short = IIf(sellsig1 AND xsigs, sigScaleIn, 0);
//PlotShapes( sigScaleIn, shapeDownTriangle, shapeNone );
Cover = buysig1;

Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);

Big thanks to asxmarketwatch for the code :slight_smile:

Read the manual already pointed to you. You are not setting margin deposit (you should) and not following the manual
http://www.amibroker.com/guide/h_futbacktest.html (if you are trading futures). Read slowly and carefully. Follow ALL steps. Don't skip.

Knowledge Base has everything you need. You might need to (re-)read it a couple of times.
http://www.amibroker.com/kb/2014/10/12/position-sizing-based-on-risk/
This article already has ALL the explanations required, including calculations and all the math required. Nothing else beyond explicit and very detailed information already given in KB is available.

If you are getting PosSize of more than 100% it is obviously incorrect. You are supposed to do your math on your own. Again KB article has all the details.

Also you are once talking about stocks then you start talking about futures, so at this point no one really knows what you are after. You need to formulate your questions crystal clear, see: How to ask a good question

@dmbull9, welcome to the AmiBroker Forum. This is the DEEP end of a deep pool. AB is an amazing body of work and can do anything you can program it to do. Therein lies the problem: you have to know the programming environment in order to make it work.
Think of it like this: you go to a car dealership to buy a car. You pay your money and walk out with a car that drives. With AmiBroker, you're walking into the car factory and designing your own car. You need to know how to build the car but you can have it any way you want.
That's why you're being redirected to the User Guide and the Tutorials in nearly every reply. There is no shortcut, you have to study the material.

3 Likes

Thanks for your replies guys. i have spent the last few weeks in studying afl programming. Sometimes i get stuck. For e.g., i am not able to plot the sigscalein entries on the chart. How can it be done?

PlotShapes(IIf(Buy==1 || Buy == sigScaleIn, shapeUpArrow ,Null),colorBlue, 0, H);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0, H);

What am i missing here? If i have 5 sigscalein entries then how to get all 5 entries plotted on the chart?

If i use If statement instead of sigscalein, then does amibroker consider both as same? What is the difference between both(if with loops for scalein or sigscalein)?

Hi @dmbull9,
I dont know about the backtest stuff but in
PlotShapes(IIf(Buy==1 || Buy == sigScaleIn, shapeUpArrow ,Null),colorBlue, 0, H);
you should have a 'logical or' operator - OR.
In AFL | is 'bitwise or' and AFAIK || is not defined but may be valid - but other languages do use it.

@JohnHT AB has its roots deep inside C++ :slight_smile:
|| and && are logical operators that are supported in AB (and do work) but the preferred convention tends to be OR and AND

1 Like

Ahh, Thanks for that @travick.
Always a learner.

1 Like