Hello @ slope game, I think you need to manage your positions correctly and ensure that the trailing stop is set for each position individually. Adjust the trailing stop logic to trail the stop loss correctly.
Here is the modified version of your code with corrections and improvements:
using System;using System.Linq;using cAlgo.API;using cAlgo.API.Indicators;namespace cAlgo.Robots{ [Robot(AccessRights = AccessRights.None)] public class RenkoTrader : Robot { [Parameter("Initial Quantity (Lots)", Group = "Volume", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)] public double InitialQuantity { get; set; } [Parameter("Include Trailing Stop", DefaultValue = true)] public bool IncludeTrailingStop { get; set; } [Parameter("Trailing Stop Trigger (pips)", DefaultValue = 0)] public int TrailingStopTrigger { get; set; } [Parameter("Trailing Stop Step (pips)", DefaultValue = 5)] public int TrailingStopStep { get; set; } private Position position = null; protected override void OnBarClosed() { var PositionCount = Positions.Where(p => p.Label == InstanceId).Count(); // Check for long entry condition if (Bars.Last(2).Close > Bars.Last(2).Open && Bars.Last(1).Close > Bars.Last(1).Open && Bars.Last(0).Close > Bars.Last(0).Open) { if (PositionCount == 0 && position == null) position = ExecuteMarketOrder(TradeType.Buy, SymbolName, 10, InstanceId).Position; } // Check for short entry condition if (Bars.Last(2).Close < Bars.Last(2).Open && Bars.Last(1).Close < Bars.Last(1).Open && Bars.Last(0).Close < Bars.Last(0).Open) { if (PositionCount == 0 && position == null) position = ExecuteMarketOrder(TradeType.Sell, SymbolName, 10, InstanceId).Position; } // Set trailing stop if (IncludeTrailingStop) { SetTrailingStop(); } } private void SetTrailingStop() { if (position == null) return; double distance; double newStopLossPrice; if (position.TradeType == TradeType.Sell) { distance = position.EntryPrice - Symbol.Ask; if (distance < TrailingStopTrigger * Symbol.PipSize) return; newStopLossPrice = Symbol.Ask + TrailingStopStep * Symbol.PipSize; } else // Buy { distance = Symbol.Bid - position.EntryPrice; if (distance < TrailingStopTrigger * Symbol.PipSize) return; newStopLossPrice = Symbol.Bid - TrailingStopStep * Symbol.PipSize; } if (position.StopLoss == null || newStopLossPrice < position.StopLoss && position.TradeType == TradeType.Sell || newStopLossPrice > position.StopLoss && position.TradeType == TradeType.Buy) { ModifyPosition(position, newStopLossPrice, position.TakeProfit); } } }}
joeanspach634
30 Sep 2024, 09:25 ( Updated at: 07 Oct 2024, 19:27 )
Hello @ slope game, I think you need to manage your positions correctly and ensure that the trailing stop is set for each position individually. Adjust the trailing stop logic to trail the stop loss correctly.
Here is the modified version of your code with corrections and improvements:
@joeanspach634