HOW TO START CBOT when the Market open & STOP it at market colsed or before 5 min.

Created at 17 Dec 2021, 18:34
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

mohsabry.ms

Joined 15.09.2021

HOW TO START CBOT when the Market open & STOP it at market colsed or before 5 min.
17 Dec 2021, 18:34


HOW TO START CBOT

when the Market open &

STOP it at market colsed or before 5 min.

and how make a daily process

Thanx in advance


@mohsabry.ms
Replies

m4trader4
19 Dec 2021, 15:29

Hi mohsabry.ms,

You cannot start/stop CBot through program.

The way out is use scheduler (Quartz) -> Message Queue (Nats) -> CBot

a. Configure CBot to be Nats Client

b. Have a counter in the CBot -> StartStop

c. Before placing order Check Counter StartStop

d. Through Quartz Scheduler (Nats Client) send message to Start or Stop

e. CBot (Nats client) receives the message set the counter StartStop accordingly

 

I found Nats to be easy to configure and fast, which has C# client not much of effort configure client. You can use other open source kafka etc

 

 

Ahmed

 

 

 


@m4trader4

mohsabry.ms
21 Dec 2021, 00:33

RE:

Thanx , But I need a time function to run condition at certain time everyday and stop at another certain time also everyday

 


@mohsabry.ms

amusleh
21 Dec 2021, 09:44

Hi,

You can use Server.Time, set a time interval when you want to run your cBot and check if the current time is inside your specified time interval or not, if its not then skip the OnBar/OnTick methods otherwise continue running them.

You don't have to start/stop your cBot, you can do it with code.


@amusleh

mohsabry.ms
21 Dec 2021, 22:50

RE:

Hi,

Did you mean that  "  if (Server.TimeInUtc.TimeOfDay.TotalMinutes == 1)"

or What?

 

 


@mohsabry.ms

amusleh
22 Dec 2021, 09:12

RE: RE:

mohsabry.ms said:

Hi,

Did you mean that  "  if (Server.TimeInUtc.TimeOfDay.TotalMinutes == 1)"

or What?

 

 

Hi,

No, I mean if you know the time you want to pause your cBot then you can do it with code, ex:

using cAlgo.API;
using System;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class NewcBot : Robot
    {
        private List<DayOfWeek> _pauseDays;

        private TimeSpan _startTime, _endTime;

        private bool _isPaused;

        [Parameter("Days", DefaultValue = "Friday,Saturday", Group = "Pause")]
        public string Days { get; set; }

        [Parameter("Start Time", DefaultValue = "07:00:00", Group = "Pause")]
        public string StartTime { get; set; }

        [Parameter("End Time", DefaultValue = "16:00:00", Group = "Pause")]
        public string EndTime { get; set; }

        protected override void OnStart()
        {
            _pauseDays = Days.Split(',').Select(day => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day)).ToList();

            if (TimeSpan.TryParse(StartTime, CultureInfo.InvariantCulture, out _startTime) == false)
            {
                Print("Invalid StartTime");
                Stop();
            }

            if (TimeSpan.TryParse(EndTime, CultureInfo.InvariantCulture, out _endTime) == false)
            {
                Print("Invalid EndTime");
                Stop();
            }

            Timer.Start(1);
        }

        protected override void OnTimer()
        {
            if (_pauseDays.Contains(Server.Time.DayOfWeek) && Server.Time.TimeOfDay >= _startTime && Server.Time.TimeOfDay <= _endTime)
            {
                _isPaused = true;
            }

            _isPaused = false;
        }

        protected override void OnBar()
        {
            if (_isPaused) return;

            // Otherwise continue running cBot logic
        }

        protected override void OnTick()
        {
            if (_isPaused) return;

            // Otherwise continue running cBot logic
        }
    }
}

The above cBot will be paused based on your provided start/end time and days of week.


@amusleh

mohsabry.ms
23 Dec 2021, 12:26

RE: RE: RE:

amusleh said:

mohsabry.ms said:

Hi,

Did you mean that  "  if (Server.TimeInUtc.TimeOfDay.TotalMinutes == 1)"

or What?

 

 

Hi,

No, I mean if you know the time you want to pause your cBot then you can do it with code, ex:

using cAlgo.API;
using System;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class NewcBot : Robot
    {
        private List<DayOfWeek> _pauseDays;

        private TimeSpan _startTime, _endTime;

        private bool _isPaused;

        [Parameter("Days", DefaultValue = "Friday,Saturday", Group = "Pause")]
        public string Days { get; set; }

        [Parameter("Start Time", DefaultValue = "07:00:00", Group = "Pause")]
        public string StartTime { get; set; }

        [Parameter("End Time", DefaultValue = "16:00:00", Group = "Pause")]
        public string EndTime { get; set; }

        protected override void OnStart()
        {
            _pauseDays = Days.Split(',').Select(day => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day)).ToList();

            if (TimeSpan.TryParse(StartTime, CultureInfo.InvariantCulture, out _startTime) == false)
            {
                Print("Invalid StartTime");
                Stop();
            }

            if (TimeSpan.TryParse(EndTime, CultureInfo.InvariantCulture, out _endTime) == false)
            {
                Print("Invalid EndTime");
                Stop();
            }

            Timer.Start(1);
        }

        protected override void OnTimer()
        {
            if (_pauseDays.Contains(Server.Time.DayOfWeek) && Server.Time.TimeOfDay >= _startTime && Server.Time.TimeOfDay <= _endTime)
            {
                _isPaused = true;
            }

            _isPaused = false;
        }

        protected override void OnBar()
        {
            if (_isPaused) return;

            // Otherwise continue running cBot logic
        }

        protected override void OnTick()
        {
            if (_isPaused) return;

            // Otherwise continue running cBot logic
        }
    }
}

The above cBot will be paused based on your provided start/end time and days of week.

Appreciate your help

Thanx Alot


@mohsabry.ms

forexmozking
12 Feb 2022, 03:59

RE: RE: RE:

amusleh said:

mohsabry.ms said:

Hi,

Did you mean that  "  if (Server.TimeInUtc.TimeOfDay.TotalMinutes == 1)"

or What?

 

 

Hi,

No, I mean if you know the time you want to pause your cBot then you can do it with code, ex:

using cAlgo.API;
using System;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class NewcBot : Robot
    {
        private List<DayOfWeek> _pauseDays;

        private TimeSpan _startTime, _endTime;

        private bool _isPaused;

        [Parameter("Days", DefaultValue = "Friday,Saturday", Group = "Pause")]
        public string Days { get; set; }

        [Parameter("Start Time", DefaultValue = "07:00:00", Group = "Pause")]
        public string StartTime { get; set; }

        [Parameter("End Time", DefaultValue = "16:00:00", Group = "Pause")]
        public string EndTime { get; set; }

        protected override void OnStart()
        {
            _pauseDays = Days.Split(',').Select(day => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day)).ToList();

            if (TimeSpan.TryParse(StartTime, CultureInfo.InvariantCulture, out _startTime) == false)
            {
                Print("Invalid StartTime");
                Stop();
            }

            if (TimeSpan.TryParse(EndTime, CultureInfo.InvariantCulture, out _endTime) == false)
            {
                Print("Invalid EndTime");
                Stop();
            }

            Timer.Start(1);
        }

        protected override void OnTimer()
        {
            if (_pauseDays.Contains(Server.Time.DayOfWeek) && Server.Time.TimeOfDay >= _startTime && Server.Time.TimeOfDay <= _endTime)
            {
                _isPaused = true;
            }

            _isPaused = false;
        }

        protected override void OnBar()
        {
            if (_isPaused) return;

            // Otherwise continue running cBot logic
        }

        protected override void OnTick()
        {
            if (_isPaused) return;

            // Otherwise continue running cBot logic
        }
    }
}

The above cBot will be paused based on your provided start/end time and days of week.

Hello, i found it very usefull, can you please help me to apply this on the following code, thanks in advance.

 

using cAlgo.API;
using cAlgo.API.Indicators;
using System;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class Siple_MA : Robot
    {
        public enum ENUM_TP_TYPE
        {
            Fixed = 0,
            RiskRatio = 1
        }
        public enum ENUM_RISK_SOURCE
        {
            Equity = 0,
            Balance = 1
        }

        public enum ENUM_LOT_TYPE
        {
            Fixed_Lot = 0,
            Percent = 1
        }
        public enum ENUM_CROSS_TYPE
        {
            Ask_Bid = 1,
            // Ask/Bid
            Close_Price = 0
            // Close Price
        }

        public enum ENUM_SIGNAL_TYPE
        {
            MA_Cross = 0,
            // MAs cross
            Price_Touch = 1
            // Price hits First MA
        }


        #region Input Fast MA Parameters
        [Parameter("Fast MA Type", Group = "Fast MA Parameters")]
        public MovingAverageType FastType { get; set; }

        [Parameter("Fast MA Source", Group = "Fast MA Parameters")]
        public DataSeries FastSeries { get; set; }

        [Parameter("Fast MA Period", Group = "Fast MA Parameters", DefaultValue = 10)]
        public int FastPeriods { get; set; }
        #endregion

        #region Input Slow MA Parameters
        [Parameter("Slow MA Type", Group = "Slow MA Parameters")]
        public MovingAverageType SlowType { get; set; }

        [Parameter("Slow MA Source", Group = "Slow MA Parameters")]
        public DataSeries SlowSeries { get; set; }

        [Parameter("Slow MA Period", Group = "Slow MA Parameters", DefaultValue = 60)]
        public int SlowPeriods { get; set; }
        #endregion

        #region Input Trade Parameters
        [Parameter("Label", Group = "Trade Parameters", DefaultValue = "Gad Elias")]
        public string Label { get; set; }

        [Parameter("Applied price", Group = "Trade Parameters", DefaultValue = ENUM_CROSS_TYPE.Close_Price)]
        public ENUM_CROSS_TYPE priceType { get; set; }

        [Parameter("Signal Type", Group = "Trade Parameters", DefaultValue = ENUM_SIGNAL_TYPE.MA_Cross)]
        public ENUM_SIGNAL_TYPE signalType { get; set; }

        [Parameter("Take Profit type", Group = "Trade Parameters", DefaultValue = ENUM_TP_TYPE.Fixed)]
        public ENUM_TP_TYPE tpType { get; set; }

        [Parameter("Stop Loss in pips", Group = "Trade Parameters", DefaultValue = 0)]
        public double SL { get; set; }

        [Parameter("Take Profit value", Group = "Trade Parameters", DefaultValue = 0)]
        public double TP { get; set; }

        [Parameter("Close on the opposite signal", Group = "Trade Parameters", DefaultValue = true)]
        public bool oppositeClose { get; set; }

        [Parameter("Max Orders", Group = "Trade Parameters", DefaultValue = 1)]
        public int maxOrders { get; set; }

        [Parameter("Use Reverse Trade", Group = "Trade Parameters", DefaultValue = true)]
        public bool reverseTrade { get; set; }

        #endregion

        #region Input Lot Size Parameters
        [Parameter("Lot Type", Group = "Lot Size", DefaultValue = ENUM_LOT_TYPE.Fixed_Lot)]
        public ENUM_LOT_TYPE lotType { get; set; }

        [Parameter("Risk Source", Group = "Lot Size", DefaultValue = ENUM_RISK_SOURCE.Balance)]
        public ENUM_RISK_SOURCE riskSource { get; set; }

        [Parameter("Risk/Lot Value", Group = "Lot Size", DefaultValue = 0.1)]
        public double risk { get; set; }
        #endregion

        #region Input Break Even Parameters
        [Parameter("Use BreakEven", Group = "BreakEven", DefaultValue = false)]
        public bool UseBE { get; set; }
        [Parameter("BreakEven Start(pips)", Group = "BreakEven", DefaultValue = 10)]
        public double BEStart { get; set; }

        [Parameter("BreakEven Profit(pips)", Group = "BreakEven", DefaultValue = 0)]
        public double BEProfit { get; set; }
        #endregion

        private MovingAverage fastMA;
        private MovingAverage slowMA;

        protected override void OnStart()
        {
            fastMA = Indicators.MovingAverage(FastSeries, FastPeriods, FastType);
            slowMA = Indicators.MovingAverage(SlowSeries, SlowPeriods, SlowType);

            if (priceType == ENUM_CROSS_TYPE.Ask_Bid)
            {
                lastAsk = Ask;
                lastBid = Bid;
            }
            else
            {
                lastClose = Bars.ClosePrices.Last(0);
            }
            lastMA = fastMA.Result.Last(0);
            // Put your initialization logic here
        }


        double lastAsk;
        double lastBid;
        double lastClose;
        double lastMA;

        DateTime lastBar;

        protected override void OnTick()
        {
            if (UseBE)
                BreakEven();
            double ma = 0;
            // Put your core logic here
            if (lastBar != Bars.OpenTimes.Last(0))
            {
                if (signalType == ENUM_SIGNAL_TYPE.MA_Cross)
                {
                    lastBar = Bars.OpenTimes.Last(0);
                    double ma1 = fastMA.Result.Last(1);
                    double ma1prev = fastMA.Result.Last(2);
                    double ma2 = slowMA.Result.Last(1);
                    double ma2prev = slowMA.Result.Last(2);
                    int currCross = CheckCross(ma1, ma1prev, ma2, ma2prev);
                    if (currCross == 0)
                    {
                        if (oppositeClose)
                        {
                            CloseOrders(TradeType.Sell);
                        }
                        if ((CalculateOrders() < maxOrders))
                        {
                            OpenOrder(TradeType.Buy);
                        }
                    }
                    if (currCross == 1)
                    {
                        if (oppositeClose)
                        {
                            CloseOrders(TradeType.Buy);
                        }
                        if ((CalculateOrders() < maxOrders))
                        {
                            OpenOrder(TradeType.Sell);
                        }
                    }
                }
                else
                {
                    ma = fastMA.Result.Last(0);

                    double prevPrice = priceType == ENUM_CROSS_TYPE.Ask_Bid ? lastAsk : lastClose;
                    double currPrice = priceType == ENUM_CROSS_TYPE.Ask_Bid ? Ask : Bars.ClosePrices.Last(0);
                    if (currPrice >= ma && prevPrice < lastMA)
                    {
                        if (CheckOrders())
                        {
                            OpenOrder(TradeType.Buy);
                        }
                        //Open Buy
                    }
                    prevPrice = priceType == ENUM_CROSS_TYPE.Ask_Bid ? lastBid : lastClose;
                    currPrice = priceType == ENUM_CROSS_TYPE.Ask_Bid ? Bid : Bars.ClosePrices.Last(0);
                    if (currPrice <= ma && prevPrice > lastMA)
                    {
                        if (CheckOrders())
                        {
                            OpenOrder(TradeType.Sell);
                        }
                        //Open Sell
                    }
                }
            }
            lastMA = ma;
            lastAsk = Ask;
            lastBid = Bid;
            lastClose = Bars.ClosePrices.Last(0);
        }

        bool CheckOrders()
        {
            if (Positions.Find(Label, Symbol) != null)
                return false;
            return true;
        }

        int CalculateOrders()
        {
            return Positions.FindAll(Label, Symbol).Length;
        }

        void CloseOrders(TradeType type)
        {
            if (reverseTrade)
                type = type == TradeType.Buy ? TradeType.Sell : TradeType.Buy;

            foreach (var pos in Positions.FindAll(Label, Symbol, type))
            {
                ClosePosition(pos);
            }
        }

        void OpenOrder(TradeType type)
        {
            if (reverseTrade)
                type = type == TradeType.Buy ? TradeType.Sell : TradeType.Buy;

            double op;
            double tp = tpType == ENUM_TP_TYPE.Fixed ? TP : SL * TP;
            double sl;

            double source = riskSource == ENUM_RISK_SOURCE.Balance ? Account.Balance : Account.Equity;

            double volumeInUnits = 0;
            if (lotType == ENUM_LOT_TYPE.Fixed_Lot)
                volumeInUnits = Symbol.QuantityToVolumeInUnits(risk);
            else
                volumeInUnits = CalculateVolume(SL, risk, source);

            if (volumeInUnits == -1)
                return;
            ExecuteMarketOrder(type, SymbolName, volumeInUnits, Label, SL, TP);
        }

        private double CalculateVolume(double stopLossPips, double riskSize, double source)
        {
            // source = Account.Balance or Account.Equity
            double riskPerTrade = source * riskSize / 100;
            double totalPips = stopLossPips;

            double _volume;
            double exactVolume = riskPerTrade / (Symbol.PipValue * totalPips);
            if (exactVolume >= Symbol.VolumeInUnitsMin)
            {
                _volume = Symbol.NormalizeVolumeInUnits(exactVolume);
            }
            else
            {
                _volume = -1;
                Print("Not enough Equity to place minimum trade, exactVolume " + exactVolume + " is not >= Symbol.VolumeInUnitsMin " + Symbol.VolumeInUnitsMin);
            }
            return _volume;
        }

        int CheckCross(double v1, double v1prev, double v2, double v2prev)
        {
            if (v1prev < v2prev && v1 > v2)
                return 0;
            if (v1prev > v2prev && v1 < v2)
                return 1;
            return -1;
        }
        private void BreakEven()
        {
            if (!UseBE)
                return;

            foreach (var pos in Positions.FindAll(Label, SymbolName))
            {
                if (pos.TradeType == TradeType.Buy)
                {
                    if (Symbol.Ask >= pos.EntryPrice + BEStart * Symbol.PipSize && (pos.StopLoss < pos.EntryPrice + BEProfit * Symbol.PipSize || pos.StopLoss == null))
                    {
                        ModifyPosition(pos, pos.EntryPrice + BEProfit * Symbol.PipSize, pos.TakeProfit);
                    }
                }
                if (pos.TradeType == TradeType.Sell)
                {
                    if (Symbol.Bid <= pos.EntryPrice - BEStart * Symbol.PipSize && (pos.StopLoss > pos.EntryPrice - BEProfit * Symbol.PipSize || pos.StopLoss == null))
                    {
                        ModifyPosition(pos, pos.EntryPrice + BEProfit * Symbol.PipSize, pos.TakeProfit);
                    }
                }
            }
        }
        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
    }
}


@forexmozking

amusleh
14 Feb 2022, 08:48

Hi,

Try this:

using cAlgo.API;
using cAlgo.API.Indicators;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class Siple_MA : Robot
    {
        public enum ENUM_TP_TYPE
        {
            Fixed = 0,
            RiskRatio = 1
        }

        public enum ENUM_RISK_SOURCE
        {
            Equity = 0,
            Balance = 1
        }

        public enum ENUM_LOT_TYPE
        {
            Fixed_Lot = 0,
            Percent = 1
        }

        public enum ENUM_CROSS_TYPE
        {
            Ask_Bid = 1,

            // Ask/Bid
            Close_Price = 0

            // Close Price
        }

        public enum ENUM_SIGNAL_TYPE
        {
            MA_Cross = 0,

            // MAs cross
            Price_Touch = 1

            // Price hits First MA
        }

        #region Input Fast MA Parameters

        [Parameter("Fast MA Type", Group = "Fast MA Parameters")]
        public MovingAverageType FastType { get; set; }

        [Parameter("Fast MA Source", Group = "Fast MA Parameters")]
        public DataSeries FastSeries { get; set; }

        [Parameter("Fast MA Period", Group = "Fast MA Parameters", DefaultValue = 10)]
        public int FastPeriods { get; set; }

        #endregion Input Fast MA Parameters

        #region Input Slow MA Parameters

        [Parameter("Slow MA Type", Group = "Slow MA Parameters")]
        public MovingAverageType SlowType { get; set; }

        [Parameter("Slow MA Source", Group = "Slow MA Parameters")]
        public DataSeries SlowSeries { get; set; }

        [Parameter("Slow MA Period", Group = "Slow MA Parameters", DefaultValue = 60)]
        public int SlowPeriods { get; set; }

        #endregion Input Slow MA Parameters

        #region Input Trade Parameters

        [Parameter("Label", Group = "Trade Parameters", DefaultValue = "Gad Elias")]
        public string Label { get; set; }

        [Parameter("Applied price", Group = "Trade Parameters", DefaultValue = ENUM_CROSS_TYPE.Close_Price)]
        public ENUM_CROSS_TYPE priceType { get; set; }

        [Parameter("Signal Type", Group = "Trade Parameters", DefaultValue = ENUM_SIGNAL_TYPE.MA_Cross)]
        public ENUM_SIGNAL_TYPE signalType { get; set; }

        [Parameter("Take Profit type", Group = "Trade Parameters", DefaultValue = ENUM_TP_TYPE.Fixed)]
        public ENUM_TP_TYPE tpType { get; set; }

        [Parameter("Stop Loss in pips", Group = "Trade Parameters", DefaultValue = 0)]
        public double SL { get; set; }

        [Parameter("Take Profit value", Group = "Trade Parameters", DefaultValue = 0)]
        public double TP { get; set; }

        [Parameter("Close on the opposite signal", Group = "Trade Parameters", DefaultValue = true)]
        public bool oppositeClose { get; set; }

        [Parameter("Max Orders", Group = "Trade Parameters", DefaultValue = 1)]
        public int maxOrders { get; set; }

        [Parameter("Use Reverse Trade", Group = "Trade Parameters", DefaultValue = true)]
        public bool reverseTrade { get; set; }

        #endregion Input Trade Parameters

        #region Input Lot Size Parameters

        [Parameter("Lot Type", Group = "Lot Size", DefaultValue = ENUM_LOT_TYPE.Fixed_Lot)]
        public ENUM_LOT_TYPE lotType { get; set; }

        [Parameter("Risk Source", Group = "Lot Size", DefaultValue = ENUM_RISK_SOURCE.Balance)]
        public ENUM_RISK_SOURCE riskSource { get; set; }

        [Parameter("Risk/Lot Value", Group = "Lot Size", DefaultValue = 0.1)]
        public double risk { get; set; }

        #endregion Input Lot Size Parameters

        #region Input Break Even Parameters

        [Parameter("Use BreakEven", Group = "BreakEven", DefaultValue = false)]
        public bool UseBE { get; set; }

        [Parameter("BreakEven Start(pips)", Group = "BreakEven", DefaultValue = 10)]
        public double BEStart { get; set; }

        [Parameter("BreakEven Profit(pips)", Group = "BreakEven", DefaultValue = 0)]
        public double BEProfit { get; set; }

        #endregion Input Break Even Parameters

        private List<DayOfWeek> _pauseDays;

        private TimeSpan _startTime, _endTime;

        private bool _isPaused;

        [Parameter("Days", DefaultValue = "Friday,Saturday", Group = "Pause")]
        public string Days { get; set; }

        [Parameter("Start Time", DefaultValue = "07:00:00", Group = "Pause")]
        public string StartTime { get; set; }

        [Parameter("End Time", DefaultValue = "16:00:00", Group = "Pause")]
        public string EndTime { get; set; }

        private MovingAverage fastMA;
        private MovingAverage slowMA;

        protected override void OnStart()
        {
            fastMA = Indicators.MovingAverage(FastSeries, FastPeriods, FastType);
            slowMA = Indicators.MovingAverage(SlowSeries, SlowPeriods, SlowType);

            if (priceType == ENUM_CROSS_TYPE.Ask_Bid)
            {
                lastAsk = Ask;
                lastBid = Bid;
            }
            else
            {
                lastClose = Bars.ClosePrices.Last(0);
            }
            lastMA = fastMA.Result.Last(0);
            // Put your initialization logic here

            _pauseDays = Days.Split(',').Select(day => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day)).ToList();

            if (TimeSpan.TryParse(StartTime, CultureInfo.InvariantCulture, out _startTime) == false)
            {
                Print("Invalid StartTime");
                Stop();
            }

            if (TimeSpan.TryParse(EndTime, CultureInfo.InvariantCulture, out _endTime) == false)
            {
                Print("Invalid EndTime");
                Stop();
            }

            Timer.Start(1);
        }

        protected override void OnTimer()
        {
            if (_pauseDays.Contains(Server.Time.DayOfWeek) && Server.Time.TimeOfDay >= _startTime && Server.Time.TimeOfDay <= _endTime)
            {
                _isPaused = true;
            }

            _isPaused = false;
        }

        private double lastAsk;
        private double lastBid;
        private double lastClose;
        private double lastMA;

        private DateTime lastBar;

        protected override void OnTick()
        {
            if (_isPaused) return;

            if (UseBE)
                BreakEven();
            double ma = 0;
            // Put your core logic here
            if (lastBar != Bars.OpenTimes.Last(0))
            {
                if (signalType == ENUM_SIGNAL_TYPE.MA_Cross)
                {
                    lastBar = Bars.OpenTimes.Last(0);
                    double ma1 = fastMA.Result.Last(1);
                    double ma1prev = fastMA.Result.Last(2);
                    double ma2 = slowMA.Result.Last(1);
                    double ma2prev = slowMA.Result.Last(2);
                    int currCross = CheckCross(ma1, ma1prev, ma2, ma2prev);
                    if (currCross == 0)
                    {
                        if (oppositeClose)
                        {
                            CloseOrders(TradeType.Sell);
                        }
                        if ((CalculateOrders() < maxOrders))
                        {
                            OpenOrder(TradeType.Buy);
                        }
                    }
                    if (currCross == 1)
                    {
                        if (oppositeClose)
                        {
                            CloseOrders(TradeType.Buy);
                        }
                        if ((CalculateOrders() < maxOrders))
                        {
                            OpenOrder(TradeType.Sell);
                        }
                    }
                }
                else
                {
                    ma = fastMA.Result.Last(0);

                    double prevPrice = priceType == ENUM_CROSS_TYPE.Ask_Bid ? lastAsk : lastClose;
                    double currPrice = priceType == ENUM_CROSS_TYPE.Ask_Bid ? Ask : Bars.ClosePrices.Last(0);
                    if (currPrice >= ma && prevPrice < lastMA)
                    {
                        if (CheckOrders())
                        {
                            OpenOrder(TradeType.Buy);
                        }
                        //Open Buy
                    }
                    prevPrice = priceType == ENUM_CROSS_TYPE.Ask_Bid ? lastBid : lastClose;
                    currPrice = priceType == ENUM_CROSS_TYPE.Ask_Bid ? Bid : Bars.ClosePrices.Last(0);
                    if (currPrice <= ma && prevPrice > lastMA)
                    {
                        if (CheckOrders())
                        {
                            OpenOrder(TradeType.Sell);
                        }
                        //Open Sell
                    }
                }
            }
            lastMA = ma;
            lastAsk = Ask;
            lastBid = Bid;
            lastClose = Bars.ClosePrices.Last(0);
        }

        private bool CheckOrders()
        {
            if (Positions.Find(Label, Symbol) != null)
                return false;
            return true;
        }

        private int CalculateOrders()
        {
            return Positions.FindAll(Label, Symbol).Length;
        }

        private void CloseOrders(TradeType type)
        {
            if (reverseTrade)
                type = type == TradeType.Buy ? TradeType.Sell : TradeType.Buy;

            foreach (var pos in Positions.FindAll(Label, Symbol, type))
            {
                ClosePosition(pos);
            }
        }

        private void OpenOrder(TradeType type)
        {
            if (reverseTrade)
                type = type == TradeType.Buy ? TradeType.Sell : TradeType.Buy;

            double op;
            double tp = tpType == ENUM_TP_TYPE.Fixed ? TP : SL * TP;
            double sl;

            double source = riskSource == ENUM_RISK_SOURCE.Balance ? Account.Balance : Account.Equity;

            double volumeInUnits = 0;
            if (lotType == ENUM_LOT_TYPE.Fixed_Lot)
                volumeInUnits = Symbol.QuantityToVolumeInUnits(risk);
            else
                volumeInUnits = CalculateVolume(SL, risk, source);

            if (volumeInUnits == -1)
                return;
            ExecuteMarketOrder(type, SymbolName, volumeInUnits, Label, SL, TP);
        }

        private double CalculateVolume(double stopLossPips, double riskSize, double source)
        {
            // source = Account.Balance or Account.Equity
            double riskPerTrade = source * riskSize / 100;
            double totalPips = stopLossPips;

            double _volume;
            double exactVolume = riskPerTrade / (Symbol.PipValue * totalPips);
            if (exactVolume >= Symbol.VolumeInUnitsMin)
            {
                _volume = Symbol.NormalizeVolumeInUnits(exactVolume);
            }
            else
            {
                _volume = -1;
                Print("Not enough Equity to place minimum trade, exactVolume " + exactVolume + " is not >= Symbol.VolumeInUnitsMin " + Symbol.VolumeInUnitsMin);
            }
            return _volume;
        }

        private int CheckCross(double v1, double v1prev, double v2, double v2prev)
        {
            if (v1prev < v2prev && v1 > v2)
                return 0;
            if (v1prev > v2prev && v1 < v2)
                return 1;
            return -1;
        }

        private void BreakEven()
        {
            if (!UseBE)
                return;

            foreach (var pos in Positions.FindAll(Label, SymbolName))
            {
                if (pos.TradeType == TradeType.Buy)
                {
                    if (Symbol.Ask >= pos.EntryPrice + BEStart * Symbol.PipSize && (pos.StopLoss < pos.EntryPrice + BEProfit * Symbol.PipSize || pos.StopLoss == null))
                    {
                        ModifyPosition(pos, pos.EntryPrice + BEProfit * Symbol.PipSize, pos.TakeProfit);
                    }
                }
                if (pos.TradeType == TradeType.Sell)
                {
                    if (Symbol.Bid <= pos.EntryPrice - BEStart * Symbol.PipSize && (pos.StopLoss > pos.EntryPrice - BEProfit * Symbol.PipSize || pos.StopLoss == null))
                    {
                        ModifyPosition(pos, pos.EntryPrice + BEProfit * Symbol.PipSize, pos.TakeProfit);
                    }
                }
            }
        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
    }
}

 


@amusleh

driftingprogrammer
14 Oct 2023, 18:03

Start Stop a third party cBot

Hi,

The cBot which I want to shutdown 1 hour before the market close and start 1 hour after the market reopen is a third party cBot that I have purchased.

This cBot is called Trendpilot and it does not have a setting to not trade when the spread is very high, because of which it places ridiculous amounts of trades at market start time when the price is going bonkers.

On this computer I have 3 different profiles of cTrader running. I only want to stop and start (2 hours later) this particular profile of cTrader and leave the other 2 profiles of cTrader untouched.

What would be a recommended way to do it.

If someone can provide me a batch file to start and stop a particular profile of ctrader then I can use that batch file and just create an entry in the Windows scheduler to run these batch files one hour before the market closes and one hour after the market opens.

Is it possible to write such a batch file or is AutoHotKey the only way to accomplish this.

Please let me know,

Thanks.


@driftingprogrammer