Close on Time

by cysecsbin.01 in category Other at 29/06/2019
Description

Follow my cTrader Telegram group at https://t.me/cTraderCommunity; it's a new community but it will grow fast, plus everyone can talk about cTrader indicators and algorithm without restrictions, though it is not allowed to spam commercial indicators to sell them. There's also a Discord Server now @ https://discord.gg/5GAPMtp

This is a bot that closes position for current Symbol at the specified times minus X minutes. Simple as that.

Useful to close everything before some news and avoid high volatility.

To remove a Closing Time you must select it and click on Remove Time

REMEMBER TO SET YOUR TIMEZONE

You can even backtest this in visual mode to ensure it work properly with the setting you chose, start a visual backtesting, then use ctrl or alt + click to open a position and shift + ctrl + click or shift + alt + click to open an order.

For any bug report or suggestion, contact me by joining the telegram group linked above or by commenting below.

Download
117 downloads
How to install
Warning! Executing the following cBot may result in loss of funds. Use it at your own risk.
Notification Publishing copyrighted material is strictly prohibited. If you believe there is copyrighted material in this section you may use the Copyright Infringement Notification form to submit a claim.
Formula / Source Code
Language: C#
Trading Platform: cAlgo
using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class CloseonTime : Robot
    {
        [Parameter("Close X Minutes Prior to Time", DefaultValue = 5)]
        public int minutesPrior { get; set; }
        [Parameter("Close Only New Positions/Orders", DefaultValue = false)]
        public bool onlyNewPos { get; set; }
        [Parameter("Cancel Pending Orders?", DefaultValue = false)]
        public bool delOrd { get; set; }
        [Parameter("TimeZone UTC +/-", DefaultValue = 3)]
        public int timezone { get; set; }

        private ClosingTimes form;
        private List<Position> posList = new List<Position>();
        private List<PendingOrder> ordList = new List<PendingOrder>();

        protected override void OnStart()
        {
            Thread t = new Thread(() =>
            {
                Application.EnableVisualStyles();
                form = new ClosingTimes();
                form.TitleBox.Text += ("\n" + Symbol.Name);
                form.Text += Symbol.Name;
                Application.Run(form);
            });
            t.Priority = ThreadPriority.BelowNormal;
            t.IsBackground = true;
            t.Start();

            if (RunningMode == RunningMode.VisualBacktesting)
            {
                Chart.MouseDown += OnChartMouseDown;
            }

            if (!onlyNewPos)
                return;
            Positions.Opened += OnPositionsOpened;
            Positions.Closed += OnPositionsClosed;
            PendingOrders.Created += OnPendingOrdersCreated;
            PendingOrders.Cancelled += OnPendingOrdersCancelled;
            PendingOrders.Filled += OnPendingOrdersFilled;
        }

        void OnChartMouseDown(ChartMouseEventArgs obj)
        {
            if (obj.AltKey && !obj.CtrlKey && !obj.ShiftKey)
                ExecuteMarketOrder(TradeType.Buy, Symbol, Symbol.NormalizeVolumeInUnits(1), "");
            if (obj.CtrlKey && !obj.AltKey && !obj.ShiftKey)
                ExecuteMarketOrder(TradeType.Sell, Symbol, Symbol.NormalizeVolumeInUnits(1), "");

            if (obj.ShiftKey && !obj.CtrlKey && obj.AltKey)
            {
                if (obj.YValue > Symbol.Bid)
                    PlaceStopOrder(TradeType.Buy, Symbol, Symbol.NormalizeVolumeInUnits(1), obj.YValue, "");
                else
                    PlaceLimitOrder(TradeType.Buy, Symbol, Symbol.NormalizeVolumeInUnits(1), obj.YValue, "");
            }
            if (obj.ShiftKey && obj.CtrlKey && !obj.AltKey)
            {
                if (obj.YValue > Symbol.Bid)
                    PlaceLimitOrder(TradeType.Sell, Symbol, Symbol.NormalizeVolumeInUnits(1), obj.YValue, "");
                else
                    PlaceStopOrder(TradeType.Sell, Symbol, Symbol.NormalizeVolumeInUnits(1), obj.YValue, "");
            }
        }

        void OnPendingOrdersFilled(PendingOrderFilledEventArgs obj)
        {
            ordList.Remove(ordList.Find(x => x == obj.PendingOrder));
        }

        void OnPendingOrdersCancelled(PendingOrderCancelledEventArgs obj)
        {
            ordList.Remove(ordList.Find(x => x == obj.PendingOrder));
        }

        void OnPendingOrdersCreated(PendingOrderCreatedEventArgs obj)
        {
            ordList.Add(obj.PendingOrder);
        }

        void OnPositionsClosed(PositionClosedEventArgs obj)
        {
            posList.Remove(posList.Find(x => x == obj.Position));
        }

        void OnPositionsOpened(PositionOpenedEventArgs obj)
        {
            posList.Add(obj.Position);
        }

        protected override void OnTick()
        {
            try
            {
                foreach (var time in form.TimeBox.Items)
                {
                    string hour = time.ToString().Substring(1, 1) == ":" ? time.ToString().Substring(0, 1) : time.ToString().Substring(0, 2);

                    string minute = time.ToString().Substring(hour.ToString().Length + 1, 2);

                    string dt = Time.Day.ToString() + "/" + Time.Month.ToString() + "/" + Time.Year.ToString() + " " + hour + ":" + minute + ":00";

                    //Print("Time is: " + Time.ToString() + " datetime is: " + DateTime.Now.ToString() + " hour: " + hour + " minute: " + minute + " parsed: " + dt + " substring(1,1): " + time.ToString().Substring(1, 1));

// 28/05/2019 00:23:00

                    if (DateTime.Parse(Time.AddMinutes(minutesPrior).AddHours(timezone).ToString()) > DateTime.Parse(dt) && DateTime.Parse(Time.AddHours(timezone).ToString()) < DateTime.Parse(dt))
                    {
                        if (onlyNewPos)
                        {
                            cancelNewOrders();
                            closeNewPositions();
                        }
                        else
                        {
                            closeAllPositions();
                            cancelAllPOrders();
                        }
                    }
                }
            } catch (Exception e)
            {
                Print(e);
            }
        }

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

        private void closeAllPositions()
        {
            foreach (Position pos in Positions)
            {
                if (pos.SymbolName == Symbol.Name)
                    ClosePosition(pos);
            }
        }

        private void cancelAllPOrders()
        {
            foreach (PendingOrder ord in PendingOrders)
            {
                if (ord.SymbolCode == Symbol.Name)
                    CancelPendingOrder(ord);
            }
        }

        private void closeNewPositions()
        {
            foreach (Position pos in Positions)
            {
                if (pos.SymbolName == Symbol.Name && posList.Contains(pos))
                    ClosePosition(pos);
            }
        }

        private void cancelNewOrders()
        {
            foreach (PendingOrder ord in PendingOrders)
            {
                if (ord.SymbolCode == Symbol.Name && ordList.Contains(ord))
                    CancelPendingOrder(ord);
            }
        }
    }

    public class ClosingTimes : Form
    {
        public ClosingTimes()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void addTime_Click(object sender, EventArgs e)
        {
            this.TimeBox.Items.Add(this.numericHour.Text + ":" + (this.numericMinute.Text.Length < 2 ? "0" + this.numericMinute.Text : this.numericMinute.Text));
        }

        private void remTime_Click(object sender, EventArgs e)
        {
            try
            {
                for (int n = this.TimeBox.SelectedItems.Count - 1; n >= 0; --n)
                {
                    this.TimeBox.Items.Remove(this.TimeBox.SelectedItems[n]);
                }

            } catch (Exception i)
            {
            }
        }

        private void InitializeComponent()
        {
            try
            {
                this.AddTimeButton = new System.Windows.Forms.Button();
                this.TimeBox = new System.Windows.Forms.ListBox();
                this.RemtimeButton = new System.Windows.Forms.Button();
                this.TitleBox = new System.Windows.Forms.TextBox();
                this.numericHour = new System.Windows.Forms.NumericUpDown();
                this.numericMinute = new System.Windows.Forms.NumericUpDown();
                this.label1 = new System.Windows.Forms.Label();
                this.label2 = new System.Windows.Forms.Label();
                ((System.ComponentModel.ISupportInitialize)(this.numericHour)).BeginInit();
                ((System.ComponentModel.ISupportInitialize)(this.numericMinute)).BeginInit();
                this.SuspendLayout();
                // 
                // AddTimeButton
                // 
                this.AddTimeButton.Location = new System.Drawing.Point(12, 159);
                this.AddTimeButton.Name = "AddTimeButton";
                this.AddTimeButton.Size = new System.Drawing.Size(146, 27);
                this.AddTimeButton.TabIndex = 0;
                this.AddTimeButton.Text = "Add Time";
                this.AddTimeButton.UseVisualStyleBackColor = true;
                this.AddTimeButton.Click += new System.EventHandler(this.addTime_Click);
                // 
                // TimeBox
                // 
                this.TimeBox.FormattingEnabled = true;
                this.TimeBox.Location = new System.Drawing.Point(190, 12);
                this.TimeBox.Name = "TimeBox";
                this.TimeBox.Size = new System.Drawing.Size(457, 212);
                this.TimeBox.TabIndex = 1;
                // 
                // RemtimeButton
                // 
                this.RemtimeButton.Location = new System.Drawing.Point(12, 201);
                this.RemtimeButton.Name = "RemtimeButton";
                this.RemtimeButton.Size = new System.Drawing.Size(146, 23);
                this.RemtimeButton.TabIndex = 2;
                this.RemtimeButton.Text = "Remove Time";
                this.RemtimeButton.UseVisualStyleBackColor = true;
                this.RemtimeButton.Click += new System.EventHandler(this.remTime_Click);
                // 
                // TitleBox
                // 
                this.TitleBox.Location = new System.Drawing.Point(12, 12);
                this.TitleBox.Multiline = true;
                this.TitleBox.Name = "TitleBox";
                this.TitleBox.ReadOnly = true;
                this.TitleBox.Size = new System.Drawing.Size(145, 36);
                this.TitleBox.TabIndex = 3;
                this.TitleBox.Text = "Closing Times for ";
                this.TitleBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
                // 
                // numericHour
                // 
                this.numericHour.Location = new System.Drawing.Point(12, 122);
                this.numericHour.Maximum = new decimal(new int[] 
                {
                    23,
                    0,
                    0,
                    0
                });
                this.numericHour.Name = "numericHour";
                this.numericHour.Size = new System.Drawing.Size(41, 20);
                this.numericHour.TabIndex = 4;
                this.numericHour.Value = new decimal(new int[] 
                {
                    9,
                    0,
                    0,
                    0
                });
                // 
                // numericMinute
                // 
                this.numericMinute.Location = new System.Drawing.Point(76, 122);
                this.numericMinute.Maximum = new decimal(new int[] 
                {
                    59,
                    0,
                    0,
                    0
                });
                this.numericMinute.Name = "numericMinute";
                this.numericMinute.Size = new System.Drawing.Size(36, 20);
                this.numericMinute.TabIndex = 5;
                // 
                // label1
                // 
                this.label1.AutoSize = true;
                this.label1.Location = new System.Drawing.Point(12, 94);
                this.label1.Name = "label1";
                this.label1.Size = new System.Drawing.Size(30, 13);
                this.label1.TabIndex = 6;
                this.label1.Text = "Hour";
                // 
                // label2
                // 
                this.label2.AutoSize = true;
                this.label2.Location = new System.Drawing.Point(73, 94);
                this.label2.Name = "label2";
                this.label2.Size = new System.Drawing.Size(39, 13);
                this.label2.TabIndex = 7;
                this.label2.Text = "Minute";
                // 
                // ClosingTimes
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(667, 239);
                this.Controls.Add(this.label2);
                this.Controls.Add(this.label1);
                this.Controls.Add(this.numericMinute);
                this.Controls.Add(this.numericHour);
                this.Controls.Add(this.TitleBox);
                this.Controls.Add(this.RemtimeButton);
                this.Controls.Add(this.TimeBox);
                this.Controls.Add(this.AddTimeButton);
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                this.Name = "ClosingTimes";
                this.Text = "Closing Times for ";
                this.Load += new System.EventHandler(this.Form1_Load);
                ((System.ComponentModel.ISupportInitialize)(this.numericHour)).EndInit();
                ((System.ComponentModel.ISupportInitialize)(this.numericMinute)).EndInit();
                this.ResumeLayout(false);
                this.PerformLayout();
            } catch (Exception e)
            {
            }
        }

        private System.Windows.Forms.Button AddTimeButton;
        private System.Windows.Forms.Button RemtimeButton;
        public System.Windows.Forms.ListBox TimeBox;
        public System.Windows.Forms.TextBox TitleBox;
        private System.Windows.Forms.NumericUpDown numericHour;
        private System.Windows.Forms.NumericUpDown numericMinute;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;


    }
}
Comments
0