Australian (ASX) Stock Market Forum

Amibroker FAQ

.

I find this methodology to be beneficial in system testing / evaluation.

Mark

Hello. I noticed you have a trade management code which has a 'move stop to break even'. I am desperately :eek: seeking a simple AFL code for back testing that would set a stop at initial buy price (break even) after the stock price has moved x% up from buy price. Note - no initial stoploss. :)

So using day bars ...
a) 'set' stop at break even when high price is >= x% above buy price.
OR
b) sell stock at bar 30 if price close is below buy price.

some of your code:

PHP:
MSBE = Param("#DaysB4MoveStopBE", 10, 0,50,1) -1;

 // raise stop to BE after x days
  if(OpenPos == 1) {
    BES[i] = Max(BES[i], BES[i-1]);
    BESa[i] = BES[i];
  }
  if(OpenPos == 1 AND j == MSBE) {
    TS = Max(TS[i], BES[i]);
    TSa[i] = TS[i];
    BESa[i] = BES[i];
  }


Hope you don't mind me asking. I raised this question at Yahoo.group a while back.
 
Careful with my old code - I wasn't handling variables / arrays in the loop properly.

I need a general sell rule. eg. L < Ref(LLV(L,10),-1);
You want to specify one?

a) 'set' stop at break even when high price is >= x% above buy price.
Once this stop is triggered will the position exit at close or intra-day?

Sorry if I missed you at AmiYahoo, I find it can be "interesting".

Mark
 
Careful with my old code - I wasn't handling variables / arrays in the loop properly.

I need a general sell rule. eg. L < Ref(LLV(L,10),-1);
You want to specify one?

Sell = Cross(MACD(),Signal());

a) 'set' stop at break even when high price is >= x% above buy price.
Once this stop is triggered will the position exit at close or intra-day?
Mark

EOD system so close price will work with SetTradeDelays (1,1,0,0);

The stop set at break even will sell next day on open if triggered. (likely not right on the B.E. but that is okay)

Thanks. :)
 
From the amibroker guideline, it gives an example of the scaleout code. Can anyone please explain this code for me
"Sell[ i ] = exit + 1;". Although commented, I don't quite understand the meaning of "// mark appropriate exit code". As far as I know, the sell function is executed according to either 1(true) or 0(false). How does this code work to only sell when the exit is => 2 which is when secondprofit target (exit code=2) and trailing stop (exit code=3) are crossed.

Code:
Example 4: partial exit (scaling out) on profit target stops

Example of code that exits 50% on first profit target, 50% on next profit target and everything at trailing stop:

Buy = Cross( MA( C, 10 ), MA( C, 50 ) ); 
Sell = 0; 

// 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 = 10; // profit 
SecondProfitTarget = 20; // in percent 
TrailingStop = 10; // 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; 
         [COLOR="Red"]Sell[ i ] = exit + 1; // mark appropriate exit code [/COLOR]
         exit = 0; 
         priceatbuy = 0; // reset price 
         highsincebuy = 0; 
       } 
    } 
} 

SetPositionSize( 50, spsPercentOfEquity ); 
SetPositionSize( 50, spsPercentOfPosition * ( Buy == sigScaleOut ) ); // scale out 50% of position
 
Try this Wysiwg. The following code is probably longer than you expected, and indeed longer than it needs to be. I like to plot any / all variables, that way you can see exactly what is going on bar by bar. Apply Indicator, and you will be able to see / verify the results. I haven't exhaustively evaluated this, there may still be errors (let me know). I also hadn't used SetTradeDelays() before, it seems that if you want to buy / sell at any time other than the close you need to specify it outside the loop. At the moment it buys /sells at the open on the next bar. I didn't use your sell rule simply as I was getting lots of short trades (likely as a result of the buy rule not being in sync). Check it with your buy / sell rules, then you may want to trim the fat once you are happy.

Mark

Code:
SetPositionSize(1, spsPercentOfEquity);
SetTradeDelays(1,1,0,0);

Buy = H > Ref(HHV(H,50),-1);   // whatever entry
BuyPrice = O;                  // must be specified outside loop to work with trade delays?

Sell = L < Ref(LLV(L,50),-1);  // whatever exit
SellPrice = O;                 // must be specified outside loop to work with trade delays?

PctUp = Param("PctUp", 10, 1, 20, 1)/100;                     // percent above buyprice before shift stop to break even 
SellDays = Param("sell if not up # days", 30, 1, 50, 1) -1;  // after x days, we'll exit if not up
OpenPos = 0; Stop = 0;j = 0; be = 0; raise = 0; bp = 0;
bea = Null; bpa = Null; stopa = Null; ja = Null; raisea = Null;  // arrays filled with null values, these will be plotted

for(i=1; i<BarCount; i++)
{
  if(!OpenPos) {                           // not in an open position
    Sell[i] = False;                       // remove excess sell signals
      if(Buy[i]) {                         // buy signal
        OpenPos = 1;                       // now have an open position
        BuyPrice[i] = O[i];                // not necessary as specified outside loop - more for reference
        bp = BuyPrice[i];
        be = BuyPrice[i] * 1.005;          // break even = buyprice + commissions, interest, etc - you decide
        raise = (1+PctUp) * BuyPrice[i];   // calculated level to shift stop to break even  
        j = 0;                             // just a counter - used for 30 day exit
      }
    bpa[i] = bp; bea[i] = be; raisea[i] = raise; stopa[i] = stop; ja[i] = j; // storing variables in arrays so they can be plotted
  }
  else {                                   // we are in an open position
    Buy[i] = False;                        // remove excess buy signals
      if(H[i] > raise)                     // stock up, set stop at break even
        stop = be;                         // used "stop" to make it obvious when checking
      if(C[i] < stop) {                    // stop is at be, we're closing below it = exit
        Sell[i] = True;                    
        OpenPos = 0;
        SellPrice[i] = O[i];               // again not necessary as it is specified outside loop, there for reference
        bp = 0; be = 0; raise = 0; stop = 0; j = 0;  // reset all variables back to 0
      }  
      if(j == SellDays AND C[i] < bp) {    // sell after 30 bars if stock is below buyprice
        Sell[i] = True;
        OpenPos = 0;
        SellPrice[i] = O[i];
        bp = 0; be = 0; raise = 0; stop = 0; j = 0;
      }
      if(Sell[i]) {                        // normal sell 
        OpenPos = 0;
        SellPrice[i] = O[i];
        bp = 0; be = 0; raise = 0; stop = 0; j = 0;
      }
    bpa[i] = bp; bea[i] = be; raisea[i] = raise; stopa[i] = stop;
    j++; ja[i] = j;
  }
}

Plot(bpa, "buyprice", colorGreen, styleLine);
Plot(bea, "BE", colorRed, styleLine);
Plot(raisea, "raise level", colorBrightGreen, styleLine);
Plot(stopa, "stop level", colorBlue, styleLine);
Plot(ja, "J count", colorBlack, styleLine|styleOwnScale);

PlotShapes(Buy*shapeUpArrow, colorGreen, 0,L);
PlotShapes(Sell*shapeDownArrow, colorRed, 0,H);
Plot(L, "low", colorBlack, styleLine);
 
Hi all,

I have come across a line of code in amibroker referencing Positionsize in a manner I do not understand. Can anyone help?

1. How I am using it:
Risk = 0.02*Capital; //Only risk 2% for any given trade
TrailStopAmount = 3 * ATR( 10 ); //Define initial and trailing stop
PositionSize = (Risk/TrailStopAmount)*BuyPrice;

2. Another version I do not understand:
TrailStopAmount = 3 * ATR( 10 )
PositionSize= -2*BuyPrice/TrailStopAmount

In version 2 there is no reference to capital, does positionsize reference this dynamically/automically? Does this give the same result as version 1?

Cheers :)
S
 
PositionSize accesses portfolio equity automatically.

eg.
Positionsize = -10; //invest 10% of equity
Positionsize = 10000; //invest $10000 in trade.

Your 1st example gives a positive number as result therefore it would invest a dollar amount.

Your 2nd example gives a negative number therefore it would invest that percentage of equity.

I assume your first example should give a negative number and therefore both examples produce exactly the same result.
 
It is my understanding that any number greater than 1 will trigger a sell signal. People typically stick to 1 or 0 or true/false for clarity.

Mark


From the amibroker guideline, it gives an example of the scaleout code. Can anyone please explain this code for me
"Sell[ i ] = exit + 1;". Although commented, I don't quite understand the meaning of "// mark appropriate exit code". As far as I know, the sell function is executed according to either 1(true) or 0(false). How does this code work to only sell when the exit is => 2 which is when secondprofit target (exit code=2) and trailing stop (exit code=3) are crossed.

Code:
Example 4: partial exit (scaling out) on profit target stops

Example of code that exits 50% on first profit target, 50% on next profit target and everything at trailing stop:

Buy = Cross( MA( C, 10 ), MA( C, 50 ) ); 
Sell = 0; 

// 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 = 10; // profit 
SecondProfitTarget = 20; // in percent 
TrailingStop = 10; // 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; 
         [COLOR="Red"]Sell[ i ] = exit + 1; // mark appropriate exit code [/COLOR]
         exit = 0; 
         priceatbuy = 0; // reset price 
         highsincebuy = 0; 
       } 
    } 
} 

SetPositionSize( 50, spsPercentOfEquity ); 
SetPositionSize( 50, spsPercentOfPosition * ( Buy == sigScaleOut ) ); // scale out 50% of position
 
Hi another Amiboker newbee !

Can someone help me out I was wondering how to change timeframes from the preselected ones on Intraday? I am sure it must be obvious so excuse the stupid question although I fear this may be the first of a few! :confused:

Mant thanks
 
Thanks Captain for the Positionsize response!

Another one....

I want to have a trailing stop that sells at the open of the following morning. To help my understanding I am looking at how the sell signals would actually take place for the following cases-

Case 1.
ApplyStop( stopTypeTrailing, stopModePoint,TrailAmount, 0, True );

(I am thinking the sell would be at the close of that day - based on the 4th param)

Case 2.
ApplyStop( stopTypeTrailing, stopModePoint,TrailAmount, 0, True );
SellPrice = Open;

(Not sure?)

Case 3.
SetTradeDelays(1,1,1,1);
ApplyStop( stopTypeTrailing, stopModePoint,TrailAmount, 0, True );
SellPrice = Open;

(At the open of the next day?)

Many thanks :)
S
 
I want to have a trailing stop that sells at the open of the following morning.

Here's the help file for the Applystop function:

http://www.amibroker.com/guide/afl/afl_view.php?id=20

I'm off for some shuteye but happy to help you work through it tomorrow if there's anything you don't understand.

A trailing stop that sells at the open of the day after the stop is hit would be along the lines of Scenario 3 in the help file. Best way to see how each type of exit works is to run your formula with each different scenario and run through the trade list.
 
Thank Captain,

The possible options for the 4th param of the ApplyStop( stopTypeTrailing, stopModePoint,TrailAmount, 0, True ) function are -

ExitAtStop = 0 - means check stops using only trade price and exit at regular trade price
(if you are trading on close it means that only close price will be checked for exits and exit will be done at close price)
ExitAtStop = 1 - check High-Low prices and exit intraday on price equal to stop level on the same bar when stop was triggered
ExitAtStop = 2 - check High-Low prices but exit NEXT BAR on regular trade price.

I don't find the definitions particularly clear - if I want it to check today's close and sell on tomorrow's open I am not sure which to use...:eek:
 
Thank Captain,

The possible options for the 4th param of the ApplyStop( stopTypeTrailing, stopModePoint,TrailAmount, 0, True ) function are -

ExitAtStop = 0 - means check stops using only trade price and exit at regular trade price
(if you are trading on close it means that only close price will be checked for exits and exit will be done at close price)
ExitAtStop = 1 - check High-Low prices and exit intraday on price equal to stop level on the same bar when stop was triggered
ExitAtStop = 2 - check High-Low prices but exit NEXT BAR on regular trade price.

I don't find the definitions particularly clear - if I want it to check today's close and sell on tomorrow's open I am not sure which to use...:eek:

If you are using a trailing stop then ExitatStop = 2 will check to see if today's low price has crossed the trailing stop. If it has then the trade will be exited at the price you define for SellPrice the next day.

So if you have:

SellPrice = Open;

then the trade will be exited at tomorrows open if today's low crossed your trailing stop.
 
Hi;
I have just downloaded AmiBroker and it looks like an impressive package.For one of my stock analyis I am using trend bands, which is basically a trend line extended by a certain percentage to the to top and bottom.

I didn't see a tool for this in AmiBroker, has anyone done this before?

Thomas
 
Thanks again Captain,

I think that is as close as I will get.

Is there an easy way to verify your system is exiting when you expect it is? I am currently looking at the detailed trade log.

Cheers
 
Is there an easy way to verify your system is exiting when you expect it is? I am currently looking at the detailed trade log.

yeh, manually checking the results from the detailed trade list against actual prices is the way I check to make sure trades are entered and exited when I expect them to be, you'll soon discover any anomalies. I'm sure there are ways to include something in your formula to check that things are happening as you expect, using the _trace function would be one:

http://www.amibroker.com/guide/afl/afl_view.php?id=222

However for a basic system it's a bit of overkill, handy for debugging real-time or intraday systems.

Stops can be written using looping too if you find that applystop doesn't do what you want, there's an example in the knowledge base written by TJ to visualise stops but is a good starting point to play around with as well.

http://www.amibroker.com/kb/2007/03/24/how-to-plot-a-trailing-stop-in-the-price-chart/

From memory GP or GreatPig had a file here on ASF with some stops too but not sure where it is.
 
Top