Topics

Forum Topics not found

Replies

ianmackers
21 Jan 2024, 21:13 ( Updated at: 22 Jan 2024, 06:38 )

RE: Re: Trailing Stop Loss TRIGGERED ONLY AFTER X pips gained (Advanced Protection)

ismaeltrade said: 

This resource would be GREAT!

See below where the stop loss is only triggered once the “Trailing Stop Trigger (pips)” is reached.

        [Parameter("Stop Loss (pips)", Group = "Risk Management", DefaultValue = 0.0, MinValue = 0.0, Step = 1)]
        public int StopLossPips { get; set; }
        
        [Parameter("Take Profit (pips)", Group = "Risk Management", DefaultValue = 0.0, MinValue = 0.0, Step = 1)]
        public double TakeProfitPips { get; set; }
        
        [Parameter("Trailing Stop Trigger (pips)", Group = "Risk Management", DefaultValue = 0.0, MinValue = 0, Step = 1)]
        public int TrailingStopTrigger { get; set; }

        [Parameter("Trailing Stop Step (pips)", Group = "Risk Management", DefaultValue = 0.0, MinValue = 0, Step = 1)]
        public int TrailingStopStep { get; set; }

        protected override void OnTick()
        {   
            // Update the trailing stops
            MaintainTrailingStops();
        }

        private void MaintainTrailingStops()
        {
            // Are trailing stops enabled?
            if (StopLossType == EnumStopLossType.TrailingStop)
            {
                var sellPositions = Positions.FindAll(cBotLabel, SymbolName, TradeType.Sell);
                foreach (var position in sellPositions)
                {
                    double distance = position.EntryPrice - Symbol.Ask;
                    if (distance < TrailingStopTrigger * Symbol.PipSize)
                        continue;
    
                    double newStopLossPrice = Symbol.Ask + TrailingStopStep * Symbol.PipSize;
                    if (position.StopLoss == null || newStopLossPrice < position.StopLoss)
                    {
                        position.ModifyStopLossPrice(newStopLossPrice);
                    }
                }
    
                var buyPositions = Positions.FindAll(cBotLabel, SymbolName, TradeType.Buy);
                foreach (var position in buyPositions)
                {
                    double distance = Symbol.Bid - position.EntryPrice;
                    if (distance < TrailingStopTrigger * Symbol.PipSize)
                        continue;
    
                    double newStopLossPrice = Symbol.Bid - TrailingStopStep * Symbol.PipSize;
                    if (position.StopLoss == null || newStopLossPrice > position.StopLoss)
                    {
                        position.ModifyStopLossPrice(newStopLossPrice);
                    }
                }
            }
        }


@ianmackers