Trading Time Interval

Created at 01 Mar 2013, 11:47
admin's avatar

Spotware Support

Joined 30.09.2011

Trading Time Interval
01 Mar 2013, 11:47


The code executes only within a specific time interval of the day. The input parameters for the start and stop time are in hours. For instance, if the Start Hour is 10 and the Stop Hour is 12, the robot will only execute when the server time is between 10am and 12am.

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

namespace cAlgo.Robots
{
    [Robot]
    public class SampleTradingTime2 : Robot
    {
        private DateTime _startTime;
        private DateTime _stopTime;
        private BollingerBands _bollingerBands;

        [Parameter("Start Hour", DefaultValue = 10.0)]
        public double StartTime { get; set; }

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


        protected override void OnStart()
        {
            // Start Time is the same day at 22:00:00 Server Time
            _startTime = Server.Time.Date.AddHours(StartTime);

            // Stop Time is the next day at 06:00:00
            _stopTime = Server.Time.Date.AddHours(StopTime);

            Print("Start Time {0},", _startTime);
            Print("Stop Time {0},", _stopTime);

            _bollingerBands = Indicators.BollingerBands(MarketSeries.Close, 20, 2, MovingAverageType.Simple);
        }

        protected override void OnTick()
        {
            if (Trade.IsExecuting) return;

            var currentHours = Server.Time.TimeOfDay.TotalHours;
            bool tradeTime = StartTime < StopTime
                ? currentHours > StartTime && currentHours < StopTime
                : currentHours < StopTime || currentHours > StartTime;

            if (!tradeTime)
                return;

            if (Positions.Count != 0) return;

            var top = _bollingerBands.Top.LastValue;
            var bottom = _bollingerBands.Bottom.LastValue;

            if (Symbol.Ask > top)                
                ExecuteMarketOrder(TradeType.Buy, Symbol, 10000);
            else if (Symbol.Bid < bottom)
                ExecuteMarketOrder(TradeType.Sell, Symbol, 10000);
        }
    }
}

 


@admin
Replies

ironmine
09 Oct 2015, 13:35

RE:

admin said:

The code executes only within a specific time interval of the day. The input parameters for the start and stop time are in hours. For instance, if the Start Hour is 10 and the Stop Hour is 12, the robot will only execute when the server time is between 10am and 12am.

Hello!
How can I explain to a cBot that during optimization or backtesting it should refer not to the current server time hours, but to the server time which the historical tick data from the server are dated with?


@ironmine

cTrader Team
13 Oct 2015, 00:49

Dear Trader,

You can use the Server.Time method instead of the DateTime.Now method. It will return the time of the historical tick when it is used in backtesting.


@Spotware

Robot forex
10 Dec 2015, 18:20

RE:

Spotware,

 

is there a way to integrate the code inside another cBot?

 

Spotware said:

Dear Trader,

You can use the Server.Time method instead of the DateTime.Now method. It will return the time of the historical tick when it is used in backtesting.

 


@Robot forex

cTrader Team
11 Dec 2015, 07:26

RE: RE:

Dear stetrimo,

You can integrate any code inside other code.

However, currently we don't provide Users with any methods that will start/stop cBots programmatically. We will provide it in the future.

You can take advantage of the C# language used in cAlgo and create a workaround.

stetrimo said:

Spotware,

 

is there a way to integrate the code inside another cBot?

 

Spotware said:

Dear Trader,

You can use the Server.Time method instead of the DateTime.Now method. It will return the time of the historical tick when it is used in backtesting.

 

 


@Spotware

davidp13
19 Jan 2016, 16:43

Close the open position at a certain time

Hi,

What code should one add to close the open positions at lets say 3pm?

Thank you


@davidp13

cTrader Team
20 Jan 2016, 07:57

Dear Trader,

We would like to inform you that we do not provide coding assistance services. We more than glad to assist you with specific questions about cAlgo.API. You can contact one of our Partners or post a job in Development Jobs section for further coding assistance.


@Spotware

firemyst
09 Oct 2019, 18:09

RE: Close the open position at a certain time

davidp13 said:

Hi,

What code should one add to close the open positions at lets say 3pm?

Thank you

//Rough sample to give you an idea to close at 3pm server time.
if (ServerTime.Hour == 15)
{
    foreach (Position p in Positions)
        ClosePosition(p);
}

//Rough sample to give you an idea to close 3pm according to your computer's time that's running the bot
if (DateTime.Now.Hour == 15)
{
    foreach (Position p in Positions)
        ClosePosition(p);
}

 


@firemyst

Alfie
05 Jul 2022, 13:50

Trade.isExecuting is obsolete.

Instead of Robot.Trade and Trade.isExecuting what shouuld I use. Here, its showing both are obsolete.


@Alfie

useretinv
19 Nov 2022, 12:40

RE:

admin said:

The code executes only within a specific time interval of the day. The input parameters for the start and stop time are in hours. For instance, if the Start Hour is 10 and the Stop Hour is 12, the robot will only execute when the server time is between 10am and 12am.

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

namespace cAlgo.Robots
{
    [Robot]
    public class SampleTradingTime2 : Robot
    {
        private DateTime _startTime;
        private DateTime _stopTime;
        private BollingerBands _bollingerBands;

        [Parameter("Start Hour", DefaultValue = 10.0)]
        public double StartTime { get; set; }

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


        protected override void OnStart()
        {
            // Start Time is the same day at 22:00:00 Server Time
            _startTime = Server.Time.Date.AddHours(StartTime);

            // Stop Time is the next day at 06:00:00
            _stopTime = Server.Time.Date.AddHours(StopTime);

            Print("Start Time {0},", _startTime);
            Print("Stop Time {0},", _stopTime);

            _bollingerBands = Indicators.BollingerBands(MarketSeries.Close, 20, 2, MovingAverageType.Simple);
        }

        protected override void OnTick()
        {
            if (Trade.IsExecuting) return;

            var currentHours = Server.Time.TimeOfDay.TotalHours;
            bool tradeTime = StartTime < StopTime
                ? currentHours > StartTime && currentHours < StopTime
                : currentHours < StopTime || currentHours > StartTime;

            if (!tradeTime)
                return;

            if (Positions.Count != 0) return;

            var top = _bollingerBands.Top.LastValue;
            var bottom = _bollingerBands.Bottom.LastValue;

            if (Symbol.Ask > top)                
                ExecuteMarketOrder(TradeType.Buy, Symbol, 10000);
            else if (Symbol.Bid < bottom)
                ExecuteMarketOrder(TradeType.Sell, Symbol, 10000);
        }
    }
}

 

 

i just need to integrate that code to Sample Martingale cBot for purpose to trading it at spasific times 

 

 

// -------------------------------------------------------------------------------------------------
//
//    This code is a cTrader Automate API example.
//
//    This cBot is intended to be used as a sample and does not guarantee any particular outcome or
//    profit of any kind. Use it at your own risk.
//    
//    All changes to this file might be lost on the next application update.
//    If you are going to modify this file please make a copy using the "Duplicate" command.
//
//    The "Sample Martingale cBot" creates a random Sell or Buy order. If the Stop loss is hit, a new 
//    order of the same type (Buy / Sell) is created with double the Initial Volume amount. The cBot will 
//    continue to double the volume amount for  all orders created until one of them hits the take Profit. 
//    After a Take Profit is hit, a new random Buy or Sell order is created with the Initial Volume amount.
//
// -------------------------------------------------------------------------------------------------

using System;
using cAlgo.API;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class SampleMartingalecBot : Robot
    {
        [Parameter("Initial Quantity (Lots)", Group = "Volume", DefaultValue = 1, MinValue = 0.01, Step = 0.01)]
        public double InitialQuantity { get; set; }

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

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


        private Random random = new Random();

        protected override void OnStart()
        {
            Positions.Closed += OnPositionsClosed;

            ExecuteOrder(InitialQuantity, GetRandomTradeType());
        }

        private void ExecuteOrder(double quantity, TradeType tradeType)
        {
            var volumeInUnits = Symbol.QuantityToVolumeInUnits(quantity);
            var result = ExecuteMarketOrder(tradeType, SymbolName, volumeInUnits, "Martingale", StopLoss, TakeProfit);

            if (result.Error == ErrorCode.NoMoney)
                Stop();
        }

        private void OnPositionsClosed(PositionClosedEventArgs args)
        {
            Print("Closed");
            var position = args.Position;

            if (position.Label != "Martingale" || position.SymbolName != SymbolName)
                return;

            if (position.GrossProfit > 0)
            {
                ExecuteOrder(InitialQuantity, GetRandomTradeType());
            }
            else
            {
                ExecuteOrder(position.Quantity * 2, position.TradeType);
            }
        }

        private TradeType GetRandomTradeType()
        {
            return random.Next(2) == 0 ? TradeType.Sell : TradeType.Buy;
        }
    }
}

 


@useretinv

... Deleted by UFO ...