October 17, 2014
Using price levels with ApplyStop function
ApplyStop function by default requires us to provide stop amount (expressed in either dollar or percentage distance from entry price). Therefore, if we want to place stop at certain price level, then we need to calculate the corresponding stop amount in our code.
This example shows how to place stops at previous bar Low (for long trades) and previous bar High (for short trades).
Stop amount parameter is simply the distance between entry price and desired trigger price (exit point). For long trade it is entry price minus stop level, while for short trade it is trigger (exit) price minus entry price. Additionally we may check if calculated distance is at least 1-tick large. We can distinguish between long and short entry by checking if one of entry signals is present (if a Buy signal is active then it is long entry, otherwise short). We only need to take care about the fact that if we are using trade delays we need to get delayed Buy signal as shown in the code below:
TradeDelay = 1; // set it to 0 for no delays
SetTradeDelays( TradeDelay, TradeDelay, TradeDelay, TradeDelay );
TickSize = 0.01;
// sample entry rules
Buy = Cross( MACD(), Signal() );
Short = Cross( Signal(), MACD() );
Sell = Cover = 0; // no other exit conditions, just stops
BuyPrice = SellPrice = ShortPrice = CoverPrice = Close;
// define stop level
stopLevelLong = Ref( L, -1 ); // use previous bar low
stopLevelShort = Ref( H, -1 ); // use previous bar high
// calculate stop amount
stopAmountLong = BuyPrice - stopLevelLong;
stopAmountShort = stopLevelShort - ShortPrice;
// make sure stop-amount is at least one tick
stopAmountLong = Max( TickSize, BuyPrice - stopLevelLong );
stopAmountShort = Max( TickSize, stopLevelShort - ShortPrice );
// assign stop amount conditionally by checking if there is a Buy signal on given bar
IsLong = Ref( Buy, -TradeDelay );
stopAmount = IIf( IsLong, stopAmountLong, stopAmountShort );
ApplyStop( stopTypeLoss, stopModePoint, stopAmount, True )
Filed by Tomasz Janeczko at 4:27 pm under Stops
Comments Off on Using price levels with ApplyStop function