When i Put trades and select time for trades it is not working can someone fix

Created at 14 Sep 2022, 14:06
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!
MO

moiz.forex

Joined 05.09.2022

When i Put trades and select time for trades it is not working can someone fix
14 Sep 2022, 14:06


HI,

I created this bot with help of someone. Infact it was my strategy and i just informed the coder this is what i want. the problem i am facing is the Trade sessions timming start and stop i select doesnt work. i mean the ot still buys trade in off timmings..Can someone fix this plz

 

 

using System;
using System.Net;
using System.Net.Mail;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace cAlgo.Robots
{

    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class CandleScalper : Robot
    {

        [Parameter("Order Identification Label", Group = "Settings", DefaultValue = "")]
        public string TheLabel { get; set; }

        [Parameter("Trade Direction", Group = "Settings", DefaultValue = DirectionSelector.Both)]
        public DirectionSelector TheDirection { get; set; }

        [Parameter("Close trades on new bar", Group = "Trade Close", DefaultValue = false)]
        public bool EndAtCandle { get; set; }

        [Parameter("Minutes before market close", Group = "Trade Close", DefaultValue = 15, MinValue = 0, Step = 1)]
        public int MinutesToClose { get; set; }
        
        [Parameter("Volume (in lots)", Group = "Volume Settings", DefaultValue = 0.01, MinValue = 0.01, Step = 0.01)]
        public double Volume { get; set; }

        [Parameter("Stop Loss", Group = "Stop Loss Settings", DefaultValue = SLSelector.Pips)]
        public SLSelector TheStopLoss { get; set; }
        
        [Parameter("Pips", Group = "Stop Loss Settings", DefaultValue = 0, MinValue = 0, Step = 0.1)]
        public double SLPips { get; set; }
                
        [Parameter("Take Profit", Group = "Take Profit Settings", DefaultValue = TPSelector.Pips)]
        public TPSelector TheTakeProfit { get; set; }
        
        [Parameter("Pips", Group = "Take Profit Settings", DefaultValue = 0, MinValue = 0, Step = 0.1)]
        public double TPPips { get; set; }
                                
        [Parameter("Active", Group = "Trade Session", DefaultValue = false)]
        public bool TradeTime { get; set; }

        [Parameter("Start Hour", Group = "Trade Session", DefaultValue = 0, MinValue = 0, MaxValue = 23, Step = 1)]
        public int StartTimeHour { get; set; }

        [Parameter("Start Minute", Group = "Trade Session", DefaultValue = 0, MinValue = 0, MaxValue = 59, Step = 1)]
        public int StartTimeMinutes { get; set; }

        [Parameter("Stop Hour", Group = "Trade Session", DefaultValue = 0, MinValue = 0, MaxValue = 23, Step = 1)]
        public int StopTimeHour { get; set; }

        [Parameter("Stop Minute", Group = "Trade Session", DefaultValue = 0, MinValue = 0, MaxValue = 59, Step = 1)]
        public int StopTimeMinutes { get; set; }

        [Parameter("UTC adjustment", Group = "Trade Session", DefaultValue = 0, MinValue = -12, MaxValue = 14, Step = 1)]
        public int UTC { get; set; }
        
        [Parameter("Enable", Group = "Optimization", DefaultValue = false)]
        public bool Optimizing { get; set; }

        private string _label, _longlabel, _shortlabel;
        private double _lots, _sl, _tp;

        public enum DirectionSelector
        {
            Both,
            LongOnly,
            ShortOnly
        }

        public enum SLSelector
        {
            Pips,
            Dynamic
        }
 
        public enum TPSelector
        {
            Pips
        }
        
        public enum ColorSelector
        {
            Blue,
            Cyan,
            Red,
            Pink,
            Green,
            Orange,
            Yellow,
            Purple
        }

        protected override void OnStart()
        {
            Initialize();

            Positions.Opened += Position_Opens;
            Positions.Closed += Position_Closes;
        }

        private void Initialize()
        {
            _label = SymbolName + "|" + this.TimeFrame + "|" + TheLabel;
            _longlabel = "Long" + "|" + _label;
            _shortlabel = "Short" + "|" + _label; 
        }
   
        protected override void OnTick()
        {
            int mins = Symbol.MarketHours.TimeTillClose().Minutes;
            int hours = Symbol.MarketHours.TimeTillClose().Hours;            
            if(hours == 0 && mins <= MinutesToClose)
            {
                foreach(var pos in Positions)
                {
                    if(pos.Label == _shortlabel || pos.Label == _longlabel)
                    {
                        pos.Close();
                    }                
                }
                
            }
        }
        
        protected override void OnBar()
        {    

            if(EndAtCandle)
            {
                foreach(var pos in Positions)
                {
                    if(pos.Label == _shortlabel || pos.Label == _longlabel)
                    {
                        pos.Close();
                    }
                } 
            }
            
            foreach(var ord in PendingOrders)
            {
                if(ord.Label.Contains(_label))
                {
                    CancelPendingOrder(ord);    
                }
            }
            
            bool tradetime = !TradeTime ? true : TimeManagement(StartTimeHour, StartTimeMinutes, StopTimeHour, StopTimeMinutes) ? true : false;
            int index = Bars.Count - 1;

            if (tradetime)
            {                
                if(Bars.ClosePrices.Last(1) - Bars.OpenPrices.Last(1) > 0) 
                {
                    TradeParameterCalculations("Long","Any");
                    var ordstop = PlaceStopOrder(TradeType.Buy, SymbolName, _lots, Bars.HighPrices.Last(1)+ (Symbol.PipSize * 10),_longlabel, _sl, _tp);

                    TradeParameterCalculations("Short","Any");
                    var ordlimit = PlaceStopOrder(TradeType.Sell, SymbolName, _lots, Bars.LowPrices.Last(1)- (Symbol.PipSize * 10), _shortlabel, _sl, _tp);
                }
                else
                {
                    TradeParameterCalculations("Short","Any");
                    var ordstop = PlaceStopOrder(TradeType.Sell, SymbolName, _lots, Bars.LowPrices.Last(1)- (Symbol.PipSize * 10) ,_shortlabel, _sl, _tp);

                    TradeParameterCalculations("Long","Any");
                    var ordlimit = PlaceStopOrder(TradeType.Buy, SymbolName, _lots, Bars.HighPrices.Last(1)+ (Symbol.PipSize * 10), _longlabel, _sl, _tp);
                }
            }
        }
        
        void Position_Opens(PositionOpenedEventArgs obj)
        {

        }

        void Position_Closes(PositionClosedEventArgs obj)
        {

        }

        private void TradeParameterCalculations(string direction, string barColor)
        {

            if (direction.Equals("Long"))
            {
                if(TheStopLoss == SLSelector.Pips)
                {
                    _sl = SLPips;
                }
                else
                {
                    if(barColor == "Any")
                    {
                        double sllevel = Bars.OpenPrices.Last(1);
                        _sl = Math.Round(Math.Abs(Symbol.Ask - sllevel)/Symbol.PipSize,1);
                    }
                    else
                    {
                        double sllevel = Bars.LowPrices.Last(1);
                        _sl = Math.Round(Math.Abs(Symbol.Ask - sllevel)/Symbol.PipSize,1);
                    }
                }
            }

            if (direction.Equals("Short"))
            {
                if(TheStopLoss == SLSelector.Pips)
                {
                    _sl = SLPips;
                }
                else
                {
                    if(barColor == "Any")
                    {
                        double sllevel = Bars.HighPrices.Last(1); 
                        _sl = Math.Round(Math.Abs(Symbol.Ask - sllevel)/Symbol.PipSize,1);
                    }
                    else
                    {
                        double sllevel = Bars.OpenPrices.Last(1);
                       _sl = Math.Round(Math.Abs(Symbol.Ask - sllevel)/Symbol.PipSize,1);
                    }
                }
            }

            if(TheTakeProfit == TPSelector.Pips)
                _tp = TPPips;
            
            _lots = CalculateRisk(_sl);

        }

        protected double CalculateRisk(double stoploss)
        {
            double exactVolume = Symbol.QuantityToVolumeInUnits(Volume);
            return Symbol.NormalizeVolumeInUnits(exactVolume, RoundingMode.ToNearest);
        }
           
        private Color GetColor(ColorSelector color)
        {

            switch (color)
            {
                case ColorSelector.Blue:
                    {
                        return Color.Blue;
                    }
                 case ColorSelector.Cyan:
                    {
                        return Color.Cyan;
                    }
                 case ColorSelector.Red:
                    {
                        return Color.Red;
                    }
                 case ColorSelector.Pink:
                    {
                        return Color.Pink;
                    }
                 case ColorSelector.Green:
                    {
                        return Color.Green;
                    }
                 case ColorSelector.Yellow:
                    {
                        return Color.Yellow;
                    }
                 case ColorSelector.Purple:
                    {
                        return Color.Purple;
                    }
                 case ColorSelector.Orange:
                    {
                        return Color.Orange;
                    }
                 default:
                    return Color.White;
             }

        }

        private bool TimeManagement(int startH, int startM, int stopH, int stopM)
        {

            bool tradetime;
            bool tradehours;

            int currentHours = Server.Time.Hour;
            int currentMinutes = Server.Time.Minute;

            int startHour = startH - UTC;
            int stopHour = stopH - UTC;

            if (stopM == 0)
                tradehours = startHour < stopHour ? startHour <= currentHours && currentHours < stopHour : startHour <= currentHours || currentHours < stopHour;
            else
                tradehours = startHour < stopHour ? startHour <= currentHours && currentHours <= stopHour : startHour <= currentHours || currentHours <= stopHour;

            if (tradehours)
            {
                if (startHour == currentHours && startM != 0)
                    tradetime = startM <= currentMinutes;
                else if (stopHour == currentHours && stopM != 0)
                    tradetime = stopM >= currentMinutes;
                else
                    tradetime = true;
            }
            else
                tradetime = false;

            return tradetime;
        }
  
        protected override void OnStop()
        {
            foreach (var ord in PendingOrders)
            {
                if (ord.Label.Contains(_label))
                    CancelPendingOrder(ord);
            }
        }
        
    }

}

 

 


@moiz.forex
Replies

PanagiotisCharalampous
14 Sep 2022, 14:11

Hi there,

Here is a starting point to get the method right

        private bool TradingEnabled()
        {
            var @from = TimeSpan.ParseExact("11:00", "hh\\:mm", null);
            var to = TimeSpan.ParseExact("18:00", "hh\\:mm", null);
            return Server.Time.TimeOfDay >= @from && Server.Time.TimeOfDay < to;
        }

Best Regards,

Panagiotis 

Join us on Telegram and Facebook


@PanagiotisCharalampous

moiz.forex
14 Sep 2022, 14:23

RE: Thanks bro but i have no idea where to add this lol

Hi, Thanks for your quick response but i have no idea where i need to put this code and which Parameter i need to remove. I have no knowledge of this coding this

 

 

 

PanagiotisCharalampous said:

Hi there,

Here is a starting point to get the method right

        private bool TradingEnabled()
        {
            var @from = TimeSpan.ParseExact("11:00", "hh\\:mm", null);
            var to = TimeSpan.ParseExact("18:00", "hh\\:mm", null);
            return Server.Time.TimeOfDay >= @from && Server.Time.TimeOfDay < to;
        }

Best Regards,

Panagiotis 

Join us on Telegram and Facebook

 


@moiz.forex

PanagiotisCharalampous
14 Sep 2022, 14:26

Hi there,

If you have no knowledge of coding, then you can ask your programmer to do this for you or assign the job to somebody else.

Best Regards,

Panagiotis 

Join us on Telegram and Facebook


@PanagiotisCharalampous