Since I can't find a simple example of a trailing stop code on here I thought I would take the example set Break even stop loss code and try to code a trailing stop from it.
I'm not a real crash hot programmer more a hack really, learning as I go.
Here is the result. Assume the variables are declared as they are in the full strategy.
Comments about accuracy etc are welcomed.
// Resets the stop loss to the original value when all positions are closed
switch (Position.MarketPosition)
{
case MarketPosition.Flat:
SetStopLoss(CalculationMode.Ticks, stopLossTicks);
previousPrice = 0;
break;
case MarketPosition.Long:
// Once the price is greater than entry price+ breakEvenTicks ticks, set stop loss to breakeven
if (Close[0] > Position.AvgPrice + breakEvenTicks * TickSize
&& previousPrice == 0)
{
SetStopLoss(CalculationMode.Price, Position.AvgPrice);
previousPrice = Position.AvgPrice;
PrintWithTimeStamp("previousPrice = "+previousPrice);
}
// Once at breakeven wait till trailProfitTrigger is reached before advancing stoploss by trailStepTicks size step
else if (previousPrice != 0 ////StopLoss is at breakeven
&& GetCurrentAsk() > previousPrice + trailProfitTrigger * TickSize
)
{
newPrice = previousPrice + trailStepTicks * TickSize;
SetStopLoss(CalculationMode.Price, newPrice);
previousPrice = newPrice;
PrintWithTimeStamp("previousPrice = "+previousPrice);
}
break;
case MarketPosition.Short:
// Once the price is Less than entry price - breakEvenTicks ticks, set stop loss to breakeven
if (Close[0] < Position.AvgPrice - breakEvenTicks * TickSize
&& previousPrice == 0)
{
SetStopLoss(CalculationMode.Price, Position.AvgPrice);
previousPrice = Position.AvgPrice;
PrintWithTimeStamp("previousPrice = "+previousPrice);
}
// Once at breakeven wait till trailProfitTrigger is reached before advancing stoploss by trailStepTicks size step
else if (previousPrice != 0 ////StopLoss is at breakeven
&& GetCurrentAsk() < previousPrice - trailProfitTrigger * TickSize
)
{
newPrice = previousPrice - trailStepTicks * TickSize;
SetStopLoss(CalculationMode.Price, newPrice);
previousPrice = newPrice;
PrintWithTimeStamp("previousPrice = "+previousPrice);
}
break;
default:
break;
}
Regards
Chris

Comment