Trailing Stop Loss
I have received good advice in this area however I could do with further help on the code below. When optimizing the code works well with history showing trades closing in either profit or loss and it is the same with the back testing. When I run it live there is never a stop loss set either initially or trailing. I could let the trade continue into negative GP but the stop loss always remains blank. Why does it work in back testing but not live?
protected override void OnBar()
{
var Volumn = Math.Floor(Account.Equity * (Percentage / 1000));
var VolumeInUnits = Symbol.NormalizeVolumeInUnits(Volumn, RoundingMode.Down);
if (double.IsNaN(_fractal1.UpFractal.Last(Period1)) == false && _stochastic.PercentK.Last(kLast1) > _stochastic.PercentD.Last(dLast1))
{
if (_stochastic.PercentD.Last(dLast3) > Up_Level && _stochastic.PercentK.Last(kLast3) > Up_Level)
{
ExecuteMarketOrder(TradeType.Sell, SymbolName, VolumeInUnits, "ZEEBOT1", StopLoss, TakeProfit, "newStopLossPrice", true);
}
}
else if (double.IsNaN(_fractal1.DownFractal.Last(Period1)) == false && _stochastic.PercentK.Last(kLast4) < _stochastic.PercentD.Last(dLast4))
{
if (_stochastic.PercentD.Last(dLast6) < Down_Level && _stochastic.PercentK.Last(dLast6) < Down_Level)
{
ExecuteMarketOrder(TradeType.Buy, SymbolName, VolumeInUnits, "ZEEBOT1", StopLoss2, TakeProfit2, "newStopLossPrice", true);
}
}
}
public void SetTrailingStop(Position p)
{
double newStopLossPrice = 0;
var positions = Positions.Where(x => x.SymbolName == this.SymbolName);
foreach (var position in positions)
{
SetTrailingStop(position);
}
try
{
if (p.TradeType == TradeType.Sell)
{
double distance = p.EntryPrice - Symbol.Ask;
if (distance < StopLoss * Symbol.PipSize)
return;
newStopLossPrice = Symbol.Ask + TrailingStop * Symbol.PipSize;
if (p.StopLoss == null || newStopLossPrice < p.StopLoss)
{
if (p.TakeProfit == null)
{
ModifyPosition(p, newStopLossPrice, null);
}
else
{
ModifyPosition(p, newStopLossPrice, p.TakeProfit);
}
}
}
if (p.TradeType == TradeType.Buy)
{
double distance = Symbol.Bid - p.EntryPrice;
if (distance < StopLoss2 * Symbol.PipSize)
return;
newStopLossPrice = Symbol.Bid - TrailingStop * Symbol.PipSize;
if (p.StopLoss == null || newStopLossPrice > p.StopLoss)
{
if (p.TakeProfit == null)
{
ModifyPosition(p, newStopLossPrice, null);
}
else
{
ModifyPosition(p, newStopLossPrice, p.TakeProfit);
}
}
}
} catch (Exception ex)
{
Print("SetTrailingStop: " + ex.Message);
Print("Entry price: " + p.EntryPrice.ToString());
Print("New stop loss price: " + newStopLossPrice.ToString());
}
}