Cbot not executing trades. trades not opening

Created at 12 Jun 2023, 10:42
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
BA

bakosadiq

Joined 23.07.2022

Cbot not executing trades. trades not opening
12 Jun 2023, 10:42


Hello please the code below is not working. It does not execute trade or open trade. can someone help me please

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class ClickAlgoSchoolSMA : Robot
    {
        #region User defined parameters

        private bool OpenBuyTrade;
        private bool OpenSellTrade;
        
      

        private DateTime _startTime;
        private DateTime _stopTime;
        private int ConsecutiveLosses;
        [Parameter("Start Hour", DefaultValue = 9.0)]
        public double StartTime { get; set; }

        [Parameter("Stop Hour", DefaultValue = 17.0)]
        public double StopTime { get; set; }

        [Parameter("Include Break-Even", DefaultValue = false)]
        public bool IncludeBreakEven { get; set; }

        [Parameter("Break-Even Trigger (pips)", DefaultValue = 10, MinValue = 1)]
        public int BreakEvenPips { get; set; }

        [Parameter("Break-Even Extra (pips)", DefaultValue = 2, MinValue = 1)]
        public int BreakEvenExtraPips { get; set; }

        [Parameter("PipsAway", DefaultValue = 10)]
        public double PipsAway { get; set; }

        [Parameter("Take Profit", Group = "Protection", DefaultValue = 1)]
        public int TakeProfit { get; set; }

        [Parameter("Stop Loss", Group = "Protection", DefaultValue = 0)]
        public int StopLoss { get; set; }

        [Parameter("Instance Name", DefaultValue = "001")]
        public string InstanceName { get; set; }

        // ADD THIS SECTION TO THE CBOT PARAMETERS
        [Parameter("Include Trailing Stop", DefaultValue = false)]
        public bool IncludeTrailingStop { get; set; }

        [Parameter("Trailing Stop Trigger (pips)", DefaultValue = 20)]
        public int TrailingStopTrigger { get; set; }

        [Parameter("Trailing Stop Step (pips)", DefaultValue = 10)]
        public int TrailingStopStep { get; set; }

        [Parameter("How Many Break Out Bars", DefaultValue = 2)]
        public int HowManyBars { get; set; }

        [Parameter("Lot Size", DefaultValue = 0.1)]
        public double LotSize { get; set; }

        [Parameter("Period EMA #50", DefaultValue = 1, MinValue = 1, MaxValue = 100)]
        public int PeriodsEma50 { get; set; }

        [Parameter("Calculate OnBar", DefaultValue = false)]
        public bool CalculateOnBar { get; set; }

        [Parameter("Number distance", DefaultValue = 5, MinValue = 5, MaxValue = 1000)]
        public double Numberdistance { get; set; }

        [Parameter("Use Martingale", DefaultValue = false)]
        public bool UseMartingale { get; set; }

        [Parameter("Martingale Multiplier", DefaultValue = 2.0, MinValue = 1.0)]
        public double MartingaleMultiplier { get; set; }

        [Parameter("Source")]
        public DataSeries Source { get; set; }

        [Parameter("Periods", DefaultValue = 14)]
        public int Periods { get; set; }

        #endregion

        #region Indicator declarations

        private ExponentialMovingAverage _ema50;
       

        #endregion

        protected override void OnStart()
        {
        
           Print("Robot started");
            Source = MarketSeries.Close;
            _ema50 = Indicators.ExponentialMovingAverage(Source, PeriodsEma50);
          

            _startTime = Server.Time.Date.AddHours(StartTime);
            _stopTime = Server.Time.Date.AddHours(StopTime);

            Positions.Closed += PositionsOnClosed;
        }

        protected override void OnTick()
        {
            if (!CalculateOnBar && IsInTradingTime())
            {
               
               Print("Tick event triggered");
               ManagePositions();
            }
        }

        protected override void OnBar()
        {
            if (CalculateOnBar && IsInTradingTime())
            {
               Print("Bar event triggered");
                ManagePositions();
            }
        }

        private bool IsInTradingTime()
        {
            return Server.Time >= _startTime && Server.Time <= _stopTime;
        }

        private void ManagePositions()
        {
        
             Print("Managing positions...");
            var currentBarIndex = MarketSeries.Close.Count - 1;

            if (Positions.Count == 0)
            {
                if (currentBarIndex >= HowManyBars && IsNewLow(currentBarIndex, HowManyBars))
           {
              OpenSellTrade = true;
              OpenBuyTrade = false; // Ensure only one trade is opened per bar
           }
         else if (currentBarIndex >= HowManyBars && IsNewHigh(currentBarIndex, HowManyBars))
             {
                OpenBuyTrade = true;
                OpenSellTrade = false; // Ensure only one trade is opened per bar
             }


                if (OpenSellTrade)
                {
                    var stopLoss = Symbol.Bid + PipsAway * Symbol.PipSize;
                    var takeProfit = Symbol.Bid - TakeProfit * Symbol.PipSize;

                    if (UseMartingale)
                    {
                        var adjustedVolume = LotSize * Math.Pow(MartingaleMultiplier, Positions.Count);

                        ExecuteMarketOrder(TradeType.Sell, Symbol, adjustedVolume, InstanceName, stopLoss, takeProfit, null);

                    }
                    else
                    {
                        ExecuteMarketOrder(TradeType.Sell, Symbol, LotSize, InstanceName, stopLoss, takeProfit);
                    }

                    OpenSellTrade = false;
                }
                else if (OpenBuyTrade)
                {
                    var stopLoss = Symbol.Ask - PipsAway * Symbol.PipSize;
                    var takeProfit = Symbol.Ask + TakeProfit * Symbol.PipSize;

                    if (UseMartingale)
                    {
                        var adjustedVolume = LotSize * Math.Pow(MartingaleMultiplier, Positions.Count);

                        ExecuteMarketOrder(TradeType.Buy, Symbol, adjustedVolume, InstanceName, stopLoss, takeProfit, null);

                    }
                    else
                    {
                        ExecuteMarketOrder(TradeType.Buy, Symbol, LotSize, InstanceName, stopLoss, takeProfit);
                    }

                    OpenBuyTrade = false;
                }
            }
        }

     private bool IsNewLow(int currentBarIndex, int howManyBars)
{
    for (int i = 1; i <= howManyBars; i++)
    {
        if (MarketSeries.Low[currentBarIndex - i] <= MarketSeries.Low[currentBarIndex])
        {
            return false;
        }
    }

    return true;
}

private bool IsNewHigh(int currentBarIndex, int howManyBars)
{
    for (int i = 1; i <= howManyBars; i++)
    {
        if (MarketSeries.High[currentBarIndex - i] >= MarketSeries.High[currentBarIndex])
        {
            return false;
        }
    }

    return true;
}



        private void PositionsOnClosed(PositionClosedEventArgs args)
        {
        
            
            Print("Position closed: " + args.Position.Label);
            if (args.Position.Label.Equals(InstanceName, StringComparison.OrdinalIgnoreCase))

            {
                if (args.Position.Pips > 0)
                {
                    // Profit, reset consecutive losses
                    ResetConsecutiveLosses();
                }
                else if (args.Position.Pips < 0)
                {
                    // Loss, increment consecutive losses
                    IncrementConsecutiveLosses();

                    if (IncludeBreakEven && ConsecutiveLosses >= BreakEvenPips)
                    {
                        ModifyPosition(args.Position);
                    }
                }
            }
        }

        private void ModifyPosition(Position position)
        {
            var stopLossPrice = position.TradeType == TradeType.Buy ? position.EntryPrice - BreakEvenExtraPips * Symbol.PipSize : position.EntryPrice + BreakEvenExtraPips * Symbol.PipSize;

            ModifyPosition(position, stopLossPrice, position.TakeProfit);
        }

        private void ResetConsecutiveLosses()
        {
            ConsecutiveLosses = 0;
        }

        private void IncrementConsecutiveLosses()
        {
            ConsecutiveLosses++;
        }

        private void ModifyPosition(Position position, double stopLoss, double takeProfit)
        {
            var positionType = position.TradeType == TradeType.Buy ? TradeType.Buy : TradeType.Sell;

          

            ExecuteMarketOrder(positionType, Symbol, position.Volume, InstanceName, stopLoss, takeProfit);
        }
    }
}


@bakosadiq
Replies

PanagiotisChar
13 Jun 2023, 08:17

Hi there,

Check your volume. You can't use lots as a volume parameter, you need to convert them to volume first.

Aieden Technologies

Need help? Join us on Telegram

 


@PanagiotisChar