Copy Trades from JSON free

by fstraps in category Other at 01/11/2021
Description

I've written a cBot for myself for copying trades from 2 MT4 accounts to a cTrader one

JSON is exported from MT4 using the following EA, but you can write your own exporter

It exports all positions and orders to a JSON almost in realtime and this cBot do the opposite, open the same positions on cTrader

It only opens and closes new and closed trades, doesnt' copy stop losses ot take profits, but it can be improved

It lets you specify the source Symbol to copy from and opens the trades on the attached chart

It doesn't require external libraries, you only need to include the following .NET referencies:
 - System.Runtime.Serialization
 - System.Runtime.Serialization.JSON
 - System.Collections

Hope you like it and find it useful, if you want to talk you can find me on Telegram at https://t.me/fstraps

Thanks

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 System.IO;
using System.Text;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Collections.Generic;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class StrxCopyTradesJSON : Robot
    {
        [Parameter(DefaultValue = "C:\\YOUR MT4 PATH\\MQL4\\Files\\trades.json")]
        public string FileTradesJSON { get; set; }

        [Parameter(DefaultValue = "")]
        public string SymbolToCopyFrom { get; set; }

        private JSONTrades trades;
        protected SortedSet<int> managedTickets;
        protected DateTime lastFileWriteDT;

        protected override void OnStart()
        {
            CheckParameters();

            managedTickets = new SortedSet<int>();
            lastFileWriteDT = new DateTime(2000, 1, 1);

            UpdateJSONTrades();
            UpdateManagedTickets();
        }

        protected void CheckParameters()
        {
            if (SymbolToCopyFrom.Length == 0)
            {
                Print("Error SymbolToCopyFrom Mandatory");
                Stop();
            }
            else
            {
                FileInfo f = new FileInfo(FileTradesJSON);
                if (!f.Exists)
                {
                    Print("JSON File does not exists!");
                    Stop();
                }
            }
        }

        protected override void OnTick() {
            if (UpdateJSONTrades()) {
                CheckNewTrades();
                UpdateManagedTickets();
                CheckClosedTrades();
            }
        }

        protected override void OnStop() {
        }

        protected bool UpdateJSONTrades() {
            FileInfo f = new FileInfo(FileTradesJSON);
            if (f.LastWriteTime <= lastFileWriteDT)
                return false;

            lastFileWriteDT = f.LastWriteTime;

            Print("LastWriteTime " + lastFileWriteDT + " checking trades");

            string content = File.ReadAllText(FileTradesJSON);
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(content));
            DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(JSONTrades));
            trades = (JSONTrades)deserializer.ReadObject(ms);

            return true;
        }

        protected void UpdateManagedTickets() {
            foreach (JSONTrade o in trades.trades) {
                if (!o.pending && !managedTickets.Contains(o.ticket))
                    managedTickets.Add(o.ticket);
            }
        }

        protected void CheckNewTrades() {
            IList<JSONTrade> unmanaged = unmanagedTrades();
            foreach (JSONTrade o in unmanaged) {
                if (o.symbol == SymbolToCopyFrom && !o.pending) {
                    ExecuteMarketOrderAsync(o.buy ? TradeType.Buy : TradeType.Sell, SymbolName, o.lots, "o:" + o.ticket);
                }
            }
        }

        protected void CheckClosedTrades() {
            foreach (Position p in Positions) {
                if (p.SymbolName == SymbolName && p.Label.IndexOf("o:") == 0) {
                    int ticket = int.Parse(p.Label.Substring(2));
                    bool exists = false;
                    foreach (JSONTrade o in trades.trades)
                    {
                        if (o.ticket == ticket)
                        {
                            exists = true;
                            break;
                        }
                    }
                    if (!exists)
                        ClosePositionAsync(p);
                }
            }
        }

        private IList<JSONTrade> unmanagedTrades()
        {
            IList<JSONTrade> rv = new List<JSONTrade>();
            for (int i = 0; i < trades.trades.Length; i++)
            {
                if (!managedTickets.Contains(trades.trades[i].ticket))
                {
                    rv.Add(trades.trades[i]);
                }
            }
            return rv;
        }
    }

    [DataContract()]
    class JSONTrade
    {
        [DataMember()]
        public string symbol { get; set; }

        [DataMember()]
        public int ticket { get; set; }

        [DataMember()]
        public bool buy { get; set; }

        [DataMember()]
        public bool pending { get; set; }

        [DataMember()]
        public bool limit { get; set; }

        [DataMember()]
        public bool stop { get; set; }

        [DataMember()]
        public double openPrice { get; set; }

        [DataMember()]
        public int openTime { get; set; }

        [DataMember()]
        public double lots { get; set; }

        [DataMember()]
        public double sl { get; set; }

        [DataMember()]
        public double tp { get; set; }

        [DataMember()]
        public string comment { get; set; }

        [DataMember()]
        public double swap { get; set; }

        [DataMember()]
        public double commission { get; set; }
    }

    [DataContract()]
    class JSONTrades
    {
        [DataMember()]
        public JSONTrade[] trades { get; set; }
    }
}
Comments
5