Australian (ASX) Stock Market Forum

Amibroker Money Management/Position Sizing

Joined
18 January 2007
Posts
178
Reactions
0
guys, I have been testing a system with simple buy and sell rules and I was wondering how would the system perform with my Money Management and Position Sizing rules. So I looked in the help files and found the following code.

The rules I follow are:

For entry:
total fund: $100,000
every stock that will be bought will get $10,000 allocated fund (1 lot). Initial entry will be with 20% of the lot, if the stock moves in my favour then the rest of the 80% will be invested in.

For exit:
Close 50% of the position if 50% profit achieved.
Close 100% of the position if 100% profit acheived. (am I limiting my profits here ? should I let the profit run and let the trailing stop loss take care of it ?)
trailing stop loss is set to 5%.

Does the code below reflect the above rules :

Code:
//-----------------Money MGMT-----------------//

PyramidThreshold = 100; // percent equity change threshold when pyramiding is performed


e = Equity(1); // generate equity without pyramiding effect 

PcntProfit = 100 * ( e - ValueWhen( Buy, e ) )/ValueWhen( Buy, e ); 

InTrade = Flip( Buy, Sell ); 

// ExRem is used here to ensure that scaling-in/out occurs 
// only once since trade entry 
DoScaleIn = ExRem( InTrade AND PcntProfit > PyramidThreshold, Sell ); 
DoScaleOut = ExRem( InTrade AND PcntProfit < -PyramidThreshold, Sell ); 

// modify rules to handle pyramiding 
Buy = Buy + sigScaleIn * DoScaleIn + sigScaleOut * DoScaleOut; 

PositionSize = IIf( DoScaleOut, 5000, 5000 ); // enter and scale-in size $5000, scale-out size: $5000

//-----------------------sell---------------------------//


// the system will exit 
// 50% of position if FIRST PROFIT TARGET stop is hit 
// 50% of position is SECOND PROFIT TARGET stop is hit 
// 100% of position if TRAILING STOP is hit 

FirstProfitTarget = 50; // profit 
SecondProfitTarget = 100; // in percent 
TrailingStop = 5; // also in percent 

priceatbuy=0; 
highsincebuy = 0; 

exit = 0; 

for( i = 0; i < BarCount; i++ ) 
{ 
   if( priceatbuy == 0 AND Buy[ i ] ) 
    { 
       priceatbuy = BuyPrice[ i ]; 
    } 

   if( priceatbuy > 0 ) 
    { 
       highsincebuy = Max( High[ i ], highsincebuy ); 

      if( exit == 0 AND 
          High[ i ] >= ( 1 + FirstProfitTarget * 0.01 ) * priceatbuy ) 
       { 
         // first profit target hit - scale-out 
         exit = 1; 
         Buy[ i ] = sigScaleOut; 
       } 

      if( exit == 1 AND 
          High[ i ] >= ( 1 + SecondProfitTarget * 0.01 ) * priceatbuy ) 
       { 
         // second profit target hit - exit 
         exit = 2; 
         SellPrice[ i ] = Max( Open[ i ], ( 1 + SecondProfitTarget * 0.01 ) * priceatbuy ); 
       } 

      if( Low[ i ] <= ( 1 - TrailingStop * 0.01 ) * highsincebuy ) 
       { 
         // trailing stop hit - exit 
         exit = 3;    
         SellPrice[ i ] = Min( Open[ i ], ( 1 - TrailingStop * 0.01 ) * highsincebuy ); 
       } 

      if( exit >= 2 ) 
       { 
         Buy[ i ] = 0; 
         Sell[ i ] = exit + 1; // mark appropriate exit code 
         exit = 0; 
         priceatbuy = 0; // reset price 
         highsincebuy = 0; 
       } 
    } 
} 

SetPositionSize( 50, spsPercentOfEquity ); 
SetPositionSize( 50, spsPercentOfPosition * ( Buy == sigScaleOut ) ); // scale out 50% of position

//---------------------------------------//
 
For exit:
Close 50% of the position if 50% profit achieved.
Close 100% of the position if 100% profit acheived. (am I limiting my profits here ? should I let the profit run and let the trailing stop loss take care of it ?)
trailing stop loss is set to 5%.

Just my opinion.
Test the system with both 100% and 200% profit exits -- see which one works better.

Trailing stop loss, if you mean 5% below the previous days close, well you are not leaving enough room for the stock to move.

I suggest maybe a wide ATR stop OR a moving average based stop OR a "lowest low"-type stop would be more appropriate.

The really long trends (several years) like PDN and ZFX had 30-40% corrections during their uptrends. Are these the exceptions though?? We dont know. THats why we test :)
 
Nizar, the trailing stop is 5 % of the highest the SP has gone from the time of my entry.

This is a short term system with average position being held for 20 bars. I'll test it with 100% and 200% percent as well. ATR based stop does look good to me at this stage.
 
For entry:
total fund: $100,000
every stock that will be bought will get $10,000 allocated fund (1 lot). Initial entry will be with 20% of the lot, if the stock moves in my favour then the rest of the 80% will be invested in.

For exit:
Close 50% of the position if 50% profit achieved.
Close 100% of the position if 100% profit acheived. (am I limiting my profits here ? should I let the profit run and let the trailing stop loss take care of it ?)
trailing stop loss is set to 5%.

Firstly your doubling your Broker fees which will become important if you choose more trading than more time in the trade.
While I do the same thing in discretionary trading its important to get your full position set as soon as possible.I never place less than 50% on the initial buy as I dont wish to average down to much on the final buy.

As for exits your not using any technical reason to exit,other than your trailing stop.5% drop from your high means that the stock only has 5% wiggle room during its rise to 50% or 100% profit.
Cant say Ive seen to many trends like that.Wish I did!

You need to work on this.
(1) More trades and less profit/trade so shorter timeframe
OR
(2) Less trades wider trailing stops and greater profit/trade.
OR a mixture of both.
Right now you have a conflict.

50-100% profit targets and a 5% trailing stop.
You want profit but you want loss of profit even more!
Rule of thumb is the bigger the profit the wider the wiggle room will need to be.
Lots more trades with less profit each trade CAN nett greater profit than letting it run.
Provided winning trades far outweigh losing trades .Takes more work to look after though.

You could look also at parabolic SAR. Or an M/A version of it.
 
For exit:
Close 50% of the position if 50% profit achieved.
Close 100% of the position if 100% profit acheived. (am I limiting my profits here ? should I let the profit run and let the trailing stop loss take care of it ?)
trailing stop loss is set to 5%.

The answer is always; it depends.

In equities I expect that profit targets work best when a lot of price is covered in little time. When the speculative component of a share price is at its highest, when everyone wants to get on for risk of missing out. There fore cutting all winners short because they doubled in price is probably bad. Tightening the stop on a stock that has done so very quickly is probably good.

Does the code below reflect the above rules :

A cursory glance suggests that your code looks okay. To be sure test it on a single intrument, calculate the entry price, pyramid price, position sizes etc. and make sure they add up to the dollar.

ASX.G
 
Tightening the stop on a stock that has done so very quickly is probably good.

You could turn this into an extra exit condition.

Condition 1
Or Condition 2
2 being X % rise in say <5 periods.
 
I never place less than 50% on the initial buy as I dont wish to average down to much on the final buy.

good idea. I might test it for my plan and see if it suits, although I tend to be wrong more than I am right.


You need to work on this.
(1) More trades and less profit/trade so shorter timeframe
OR
(2) Less trades wider trailing stops and greater profit/trade.
OR a mixture of both.
Right now you have a conflict.

Tech can you give bit more info on the Mixture of Both . Do you mean more trades with more wiggle room ?


Lots more trades with less profit each trade CAN nett greater profit than letting it run.

Wont the broker fee kill me ?


ASXG
In equities I expect that profit targets work best when a lot of price is covered in little time. When the speculative component of a share price is at its highest, when everyone wants to get on for risk of missing out. There fore cutting all winners short because they doubled in price is probably bad. Tightening the stop on a stock that has done so very quickly is probably good.

This would probably be a more discritionary based system then a mechinical system. But I see your point, why leave dollars on the table when you can take them.
 
Tech can you give bit more info on the Mixture of Both . Do you mean more trades with more wiggle room ?

Yes.(Wiggle room)
And thats the difficult part.I think having alternate exit rules IE more than one helps.Its a balance of shorter trades and greater profit each trade.Not holding stock that doesnt perform.Having an exit rule for stagnent stock.
Tight initial stops and loser trailing stops but not to loose.
Use price action as entry and exits rather than oscillators.Radge had some good ideas that could be expanded on the "Developing a system" thread.
Like count backlines.Darvas type boxes or some of Joe Ross's work (google it).
Some VSA stuff would also be good.
Volume and Range.

Wont the broker fee kill me ?

Could do if there isnt enough profit and enough winning trades.
shorter term should have you seaching out cheapest brokerage.
Longer term doesnt matter as much.
CFD's even cheaper again, you dont have to trade the leverage!

This would probably be a more discritionary based system then a mechinical system. But I see your point, why leave dollars on the table when you can take them.

No it can be coded and ASX makes a good point.I find over 30% in a single day or 50% or more in 2 days generally sees that stock sold off heavily.You can code this as a condition (an extra one) of sale.
 
HI all

I need some hhelp in coding stop loss and position sizing. I hve a simple trading system to be used in 15 mins time frame.

// EMA Cross
Buy=Cross(EMA( C,10),EMA( C,30));
Sell=Cross(EMA( C,30),EMA( C,30));
Short=Sell;
Cover=Buy;


Filter=Buy OR Sell ;
AddColumn( IIf( Buy, 66, 83 ), "Signal", formatChar );
AddColumn(Close, "close" );


Manually I hv checked the system. I need to code to get the maximum drawdown of the system and then decide on stop loss.

Any help will be highly appreciated
Thanks
 
Im not sure if such a thing exists. I have got a trailing stop. Is there another stop that would work in conjunction with the trailing stop to protect your initial purchase by a set amount.

Example: Assume that a trailing stop is set at 10%. I want an initial stop to take me out of the trade at a level that can be entered hopefully in Parameters or else in the editor. I then want the trailing stop to take over once it the higher of the two. Is this possible?

This is my trailing stop code.

Code:
_SECTION_BEGIN("Buy MACD Cross");
StopLevel = 1 - Param("trailing stop %", 3, 0.1, 10, 0.1)/100;

Buy = Cross( MACD(), Signal() );
Sell = 0;
trailARRAY = Null;
trailstop = 0;

for( i = 1; i < BarCount; i++ )
{

   if( trailstop == 0 AND Buy[ i ] ) 
   { 
      trailstop = High[ i ] * stoplevel;
   }
   else Buy[ i ] = 0; // remove excess buy signals

   if( trailstop > 0 AND Low[ i ] < trailstop )
   {
      Sell[ i ] = 1;
      SellPrice[ i ] = trailstop;
      trailstop = 0;
   }

   if( trailstop > 0 )
   {   
      trailstop = Max( High[ i ] * stoplevel, trailstop );
      trailARRAY[ i ] = trailstop;
   }

}

PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);
PlotShapes(Sell*shapeDownArrow,colorRed,0,High);

Plot( Close,"Price",colorBlack,styleCandle);
Plot( trailARRAY,"trailing stop level", colorRed );


_SECTION_END();
 
Thanks Capt.Black.

Can you please tell me how to adjust this formula so that the values are all weekly. 150 week ema and 15/3 weekly stochastic.


Thank you
 
Better put up the formula eh!


Buy = StochK( 15, 3 ) > 20
AND Ref( StochK( 15, 3 ) , -1 ) < 20
OR Close > EMA( C , 150 );

Sell = Close < EMA( C , 150 );
 
You can set a max. loss stop and trailing stop easily using the ApplyStop function.

http://www.amibroker.com/guide/afl/applystop.html

Scroll down to the comments section to see how to display/visualise the stops on your chart.

I still need some help here. Im trying to get a sell indicator on my chart so that if price falls the following day after a purchase I get a sell signal on the chart. (Preferably a different looking down arrow) Ive tried a few things but still no good :confused:

HTML:
MA1 = MA(C,5);
MA2 = MA(C,25);
Buy = Cross(MA1,MA2);
Sell =0;




 	 /* max loss stop optimization */

ApplyStop(stopTypeLoss,
         stopModePercent,
         Optimize( "max. loss stop level", 2, 2, 30, 1 ),
         True );

_SECTION_BEGIN("Trailing Stop");
StopLevel = 1 - Param("trailing stop %", 3, 0.1, 10, 0.1)/100;


Sell = 0;
trailARRAY = Null;
trailstop = 0;

for( i = 1; i < BarCount; i++ )
{

   if( trailstop == 0 AND Buy[ i ] ) 
   { 
      trailstop = High[ i ] * stoplevel;
   }
   else Buy[ i ] = 0; // remove excess buy signals

   if( trailstop > 0 AND Close[ i ] < trailstop )
   {
      Sell[ i ] = 1;
      SellPrice[ i ] = trailstop;
      trailstop = 0;
   }

   if( trailstop > 0 )
   {   
      trailstop = Max( High[ i ] * stoplevel, trailstop );
      trailARRAY[ i ] = trailstop;
   }

}

PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);
PlotShapes(Sell*shapeDownArrow,colorRed,0,High);


Plot( trailARRAY,"trailing stop level", colorRed );

Stop.png
 

Attachments

  • Stop.png
    Stop.png
    50 KB · Views: 0
Here's a quickie to play around with:

Code:
MA1 = MA(C,5);
MA2 = MA(C,25);
Buy = Cross(MA1,MA2);
Sell =0;




 



_SECTION_BEGIN("Trailing Stop");
StopLevel = 1 - Param("trailing stop %", 3, 0.1, 10, 0.1)/100;


Sell = 0;
trailARRAY = Null;
trailstop = 0;

for( i = 1; i < BarCount; i++ )
{

   if( trailstop == 0 AND Buy[ i ] ) 
   { 
      trailstop = High[ i ] * stoplevel;
   }
   else Buy[ i ] = 0; // remove excess buy signals

   if( trailstop > 0 AND Close[ i ] < trailstop )
   {
      Sell[ i ] = 1;
      SellPrice[ i ] = trailstop;
      trailstop = 0;
   }

   if( trailstop > 0 )
   {   
      trailstop = Max( High[ i ] * stoplevel, trailstop );
      trailARRAY[ i ] = trailstop;
   }

}

     /* max loss stop optimization */


PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);
//PlotShapes(Sell*shapeDownArrow,colorRed,0,High);

ApplyStop(stopTypeLoss,
         stopModePercent,
         Param( "max. loss stop level", 2, 2, 30, 1 ),
         True );

PlotShapes( IIf(Sell==1, shapeDownArrow, shapeNone), colorRed,0,H);//trailstop
Equity(1);



PlotShapes( IIf(Sell==2, shapeDownArrow, shapeNone), colorWhite,0,H);//maxloss
Equity(1);



Plot( trailARRAY,"trailing stop level", colorRed );

_SECTION_BEGIN("Price1");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();
Not checked for accuracy, don't use for backtesting.
White arrow shows max loss exit.
 
Thanks heaps again :)

Just one query. Have I got something duplicated here. When I open up parameters Ive got price listed 4 times and stops 5 times.

Parameters.png
[/IMG]


HTML:
_SECTION_BEGIN("Price1");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();


Buy = Cross(MA(C,5),MA(C,25));
Sell =0;



_SECTION_BEGIN("Trailing Stop");
StopLevel = 1 - Param("My Trailing Stop %", 3, 0.1, 10, 0.1)/100;


Sell = 0;
trailARRAY = Null;
trailstop = 0;

for( i = 1; i < BarCount; i++ )
{

   if( trailstop == 0 AND Buy[ i ] ) 
   { 
      trailstop = High[ i ] * stoplevel;
   }
   else Buy[ i ] = 0; // remove excess buy signals

   if( trailstop > 0 AND Close[ i ] < trailstop )
   {
      Sell[ i ] = 1;
      SellPrice[ i ] = trailstop;
      trailstop = 0;
   }

   if( trailstop > 0 )
   {   
      trailstop = Max( High[ i ] * stoplevel, trailstop );
      trailARRAY[ i ] = trailstop;
   }

}

     /* max loss stop optimization */




ApplyStop(stopTypeLoss,
         stopModePercent,
         Param( "My Max Stop", 2, 2, 30, 1 ),
         True );

PlotShapes( IIf(Sell==1, shapeDownArrow, shapeNone), colorRed,0,H);//trailstop
Equity(1);



PlotShapes( IIf(Sell==2, shapeDownArrow, shapeNone), colorOrange,0,H);//maxloss
Equity(1);

PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);
//PlotShapes(Sell*shapeDownArrow,colorRed,0,High);

Plot( trailARRAY,"trailing stop level", colorRed );
 
Just one query. Have I got something duplicated here. When I open up parameters Ive got price listed 4 times and stops 5 times.

yeh, the joys of modifying charts in AB, if you get time then a read of the various ways of inserting chart formulas makes for a great sleep... ummm.. read ;)

Haven't time to look for the tutorial but it would be in the charting section of the help guide.

Simplest solution for now would be to start with a new pane and apply your indicator there.
 
OK - So long as it isnt me, thats great.

Will the "max stop loss line " plot on the chart as a static horizontal line? Something like?

Plot( stopline, "trailing stop line", colorOrange );
 
Top