// FTISignalCopier — cTrader cBot
//
// Copies the trades of the Freemium Trade Ideas master account onto
// THIS cTrader account: the same entry, stop and target, at a size you
// choose. When the master cancels or closes, this account follows.
// Same protocol and the same behaviour as the MT4/MT5 copiers.
//
// SETUP (once):
// 1. Run it in cTrader Desktop (or on a VPS). cTrader's cloud does not
// allow cBots internet access, so it can't reach the hub there.
// 2. Add it to ANY one chart.
// 3. Paste your licence key into the parameters and choose a lot size.
//
// A licence copies to one trading account at a time: the account number
// on your licence page. Change it there when you change account or
// broker.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Json;
using cAlgo.API;
using cAlgo.API.Internals;
namespace cAlgo.Robots
{
public enum FtiLotMode
{
Fixed, // the same lot for every trade
Per1000, // lots for each 1,000 of balance
Risk, // percent of balance at risk per trade
}
[Robot(AccessRights = AccessRights.None, AddIndicators = false, TimeZone = TimeZones.UTC)]
public class FTISignalCopier : Robot
{
private const string Version = "1.00";
private const string Platform = "CTRADER";
private const string Tag = "FTI#";
private const int MaxAttempts = 5;
private const string StatusObject = "fti_signal_copier_status";
[Parameter("Licence key (FTI-XXXXX-XXXXX-XXXXX-XXXXX)", Group = "Licence", DefaultValue = "")]
public string LicenseKey { get; set; }
[Parameter("Hub URL", Group = "Licence", DefaultValue = "https://freemiumtradeideas.com/copier")]
public string HubUrl { get; set; }
[Parameter("How the lot is worked out", Group = "Trade size", DefaultValue = FtiLotMode.Fixed)]
public FtiLotMode LotMode { get; set; }
[Parameter("Lot / lots per 1,000 / percent at risk", Group = "Trade size", DefaultValue = 0.01, MinValue = 0.0001)]
public double LotValue { get; set; }
[Parameter("Never trade more than this many lots", Group = "Trade size", DefaultValue = 1.0, MinValue = 0)]
public double MaxLot { get; set; }
[Parameter("Your broker's symbol prefix (blank = detect)", Group = "Symbols", DefaultValue = "")]
public string SymbolPrefix { get; set; }
[Parameter("Your broker's symbol suffix (blank = detect)", Group = "Symbols", DefaultValue = "")]
public string SymbolSuffix { get; set; }
[Parameter("Your own names, e.g. USA100=NAS100;XAUUSD=GOLD", Group = "Symbols", DefaultValue = "")]
public string SymbolMap { get; set; }
[Parameter("Copy only these, e.g. EURUSD,XAUUSD (blank = all)", Group = "Symbols", DefaultValue = "")]
public string OnlySymbols { get; set; }
[Parameter("Never copy these, e.g. BTCUSD,ETHUSD", Group = "Symbols", DefaultValue = "")]
public string SkipSymbols { get; set; }
[Parameter("Most copied trades open at once", Group = "Safety", DefaultValue = 40, MinValue = 1)]
public int MaxOpenTrades { get; set; }
[Parameter("Skip a symbol priced more than this % from the signal", Group = "Safety", DefaultValue = 10.0, MinValue = 0.1)]
public double MaxPriceGapPct { get; set; }
[Parameter("Join a trade the master already entered, up to this many seconds late", Group = "Safety", DefaultValue = 120, MinValue = 0)]
public int LateEntrySeconds { get; set; }
[Parameter("...and only within this % of the master's entry price", Group = "Safety", DefaultValue = 0.10, MinValue = 0)]
public double LateEntrySlipPct { get; set; }
[Parameter("Close a position when the master closes its own", Group = "Safety", DefaultValue = true)]
public bool FollowCloses { get; set; }
[Parameter("Seconds between checks (0 = the hub's; a higher number checks less often)", Group = "Advanced", DefaultValue = 0, MinValue = 0)]
public int PollSeconds { get; set; }
/// One master order, as the hub describes it.
private sealed class FtiOrder
{
public long Id;
public long Seq;
public string Symbol = "";
public string Side = "";
public string Type = "";
public string State = "";
public double Price;
public double Sl;
public double Tp;
public double Fill;
public long FilledAgo;
public List Alts = new List();
public bool Buy => Side == "buy";
public string Label => "#" + Id + " " + Side + " " + Symbol;
}
/// What this terminal remembers between restarts.
private sealed class Memory
{
public string Key { get; set; } = "";
public string Token { get; set; } = "";
public long Cursor { get; set; }
// Master orders already copied or given up on: never opened twice.
public List Done { get; set; } = new List();
}
// --- session
private int _login;
private string _server = "";
private Memory _memory = new Memory();
private readonly HashSet _done = new HashSet();
private bool _needActivate = true;
private bool _blocked;
private DateTime _nextActivateAt = DateTime.MinValue;
private DateTime _nextSyncAt = DateTime.MinValue;
private DateTime _nextFullAt = DateTime.MinValue;
private int _failStreak;
private int _pollSec = 5;
private DateTime _connectedSince = DateTime.MinValue;
// --- symbols
private string _prefix = "";
private string _suffix = "";
private readonly Dictionary _resolved = new Dictionary();
// --- failed attempts per order, in memory
private readonly Dictionary _attempts = new Dictionary();
// --- display
private string _status = "Starting...";
private string _licence = "";
private string _lastAction = "";
private string _lastNote = "";
private DateTime _lastOkAt = DateTime.MinValue;
private int _held;
private static DateTime Now => DateTime.UtcNow;
private static string Clock => DateTime.UtcNow.ToString("HH:mm:ss", CultureInfo.InvariantCulture);
private static string F(double v, int digits) => v.ToString("F" + digits, CultureInfo.InvariantCulture);
// ----------------------------------------------------------------
// Lifecycle
// ----------------------------------------------------------------
protected override void OnStart()
{
if (RunningMode != RunningMode.RealTime)
{
Print("FTI Signal Copier copies live trades; it does nothing in backtesting or optimization.");
Stop();
return;
}
var url = BaseUrl();
if (!url.StartsWith("https://") && !url.StartsWith("http://127.0.0.1") && !url.StartsWith("http://localhost"))
{
Fail("the Hub URL must start with https://");
return;
}
if (KeyTyped().Length < 20)
{
Fail("paste your licence key into the cBot parameters.");
return;
}
ResetForAccount();
Account.Switched += _ => ResetForAccount();
Timer.Start(TimeSpan.FromSeconds(1));
ShowStatus();
}
protected override void OnStop()
{
// Stopping the cBot stops copying. It never closes anything on
// the way out: open copies keep their stops and targets.
Chart.RemoveObject(StatusObject);
}
protected override void OnTimer()
{
if (_blocked) { ShowStatus(); return; }
if (!TerminalReady()) { ShowStatus(); return; }
if (Account.Number != _login) ResetForAccount();
if (_needActivate)
{
if (Now >= _nextActivateAt) Activate();
ShowStatus();
if (_needActivate || _blocked) return;
}
if (Now >= _nextSyncAt) Sync();
ShowStatus();
}
private void Fail(string message)
{
_status = "FTI Signal Copier: " + message;
Print(_status);
ShowStatus();
Stop();
}
private void ResetForAccount()
{
_login = Account.Number;
_server = Truncate($"{Account.BrokerName}-{(Account.IsLive ? "Live" : "Demo")}", 64);
LoadMemory();
_needActivate = _memory.Token == "";
_blocked = false;
_nextActivateAt = DateTime.MinValue;
_nextSyncAt = DateTime.MinValue;
_nextFullAt = DateTime.MinValue; // the first check after a start is always a full one
_resolved.Clear();
DetectAffixes();
}
private bool TerminalReady()
{
if (!Server.IsConnected)
{
_connectedSince = DateTime.MinValue;
_status = "Waiting for the trade server connection";
return false;
}
if (_connectedSince == DateTime.MinValue) _connectedSince = Now;
return (Now - _connectedSince).TotalSeconds >= 3 && Account.Number > 0;
}
// ----------------------------------------------------------------
// What this terminal remembers
//
// Without the "done" list, a copy that hit its stop here while the
// master's order was still live would be opened a second time.
// ----------------------------------------------------------------
private string MemoryKey => "fti_copier_" + _login;
private void LoadMemory()
{
_memory = new Memory();
_done.Clear();
try
{
var text = LocalStorage.GetString(MemoryKey, LocalStorageScope.Device);
if (!string.IsNullOrEmpty(text)) _memory = JsonSerializer.Deserialize(text) ?? new Memory();
}
catch (Exception)
{
_memory = new Memory();
}
// A different key in the parameters means a different licence: start afresh.
if (_memory.Key != KeyTyped())
{
_memory.Token = "";
_memory.Cursor = 0;
}
_memory.Key = KeyTyped();
foreach (var id in _memory.Done ?? new List()) _done.Add(id);
}
private void SaveMemory()
{
try
{
// The newest ids are the ones that can still be live at the master.
_memory.Done = _done.OrderByDescending(id => id).Take(3000).ToList();
LocalStorage.SetString(MemoryKey, JsonSerializer.Serialize(_memory), LocalStorageScope.Device);
LocalStorage.Flush(LocalStorageScope.Device);
}
catch (Exception ex)
{
Print("FTI Signal Copier: could not save its memory: " + ex.Message);
}
}
private void MarkDone(long id)
{
if (_done.Add(id)) SaveMemory();
}
// ----------------------------------------------------------------
// This account's copies. The label says whose copy it is, and a
// pending order keeps its label when it becomes a position.
// ----------------------------------------------------------------
private static long IdFromLabel(string label)
{
if (string.IsNullOrEmpty(label) || !label.StartsWith(Tag, StringComparison.Ordinal)) return 0;
var digits = new string(label.Substring(Tag.Length).TakeWhile(char.IsDigit).ToArray());
return long.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out var id) ? id : 0;
}
private Position FindPosition(long id) => Positions.FirstOrDefault(p => IdFromLabel(p.Label) == id);
private PendingOrder FindPending(long id) => PendingOrders.FirstOrDefault(o => IdFromLabel(o.Label) == id);
private int CountOwn() => Positions.Count(p => IdFromLabel(p.Label) > 0) + PendingOrders.Count(o => IdFromLabel(o.Label) > 0);
private List HeldIds()
{
var ids = new HashSet();
foreach (var p in Positions) { var id = IdFromLabel(p.Label); if (id > 0) ids.Add(id); }
foreach (var o in PendingOrders) { var id = IdFromLabel(o.Label); if (id > 0) ids.Add(id); }
_held = ids.Count;
return ids.OrderBy(id => id).ToList();
}
// ----------------------------------------------------------------
// Symbols: the master's name -> this broker's
// ----------------------------------------------------------------
private Symbol Usable(string name)
{
if (string.IsNullOrEmpty(name) || !Symbols.Exists(name)) return null;
return Symbols.GetSymbol(name);
}
// Works out what this broker adds around symbol names, from EURUSD.
private void DetectAffixes()
{
_prefix = (SymbolPrefix ?? "").Trim();
_suffix = (SymbolSuffix ?? "").Trim();
if (_prefix != "" || _suffix != "" || Symbols.Exists("EURUSD")) return;
foreach (var name in Symbols)
{
var p = name.IndexOf("EURUSD", StringComparison.OrdinalIgnoreCase);
if (p < 0) continue;
_prefix = name.Substring(0, p);
_suffix = name.Substring(p + 6);
return;
}
}
private static Dictionary ParseMap(string text)
{
var map = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var pair in (text ?? "").Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries))
{
var eq = pair.IndexOf('=');
if (eq <= 0) continue;
map[pair.Substring(0, eq).Trim()] = pair.Substring(eq + 1).Trim();
}
return map;
}
private static bool InList(string list, string name) =>
(list ?? "").Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries).Any(s => string.Equals(s.Trim(), name, StringComparison.OrdinalIgnoreCase));
private bool SymbolWanted(string master) =>
((OnlySymbols ?? "").Trim() == "" || InList(OnlySymbols, master)) && !InList(SkipSymbols, master);
private Symbol Resolve(FtiOrder o)
{
if (_resolved.TryGetValue(o.Symbol, out var known)) return Usable(known);
Symbol found = null;
if (ParseMap(SymbolMap).TryGetValue(o.Symbol, out var mapped) && mapped != "")
{
// The user's own choice is final: if it doesn't exist, say so rather than guess.
found = Usable(mapped);
}
else
{
foreach (var alt in o.Alts)
{
found = Usable(_prefix + alt + _suffix);
if (found != null) break;
}
if (found == null && (_prefix != "" || _suffix != ""))
{
foreach (var alt in o.Alts)
{
found = Usable(alt);
if (found != null) break;
}
}
}
if (found != null) _resolved[o.Symbol] = found.Name;
return found;
}
private static double NormPrice(Symbol symbol, double price)
{
if (price <= 0) return 0;
var tick = symbol.TickSize;
var p = tick > 0 ? Math.Round(price / tick) * tick : price;
return Math.Round(p, symbol.Digits);
}
/// A stop or target as cTrader wants it: a price, or nothing.
private static double? Level(double price) => price > 0 ? price : (double?)null;
private static bool Differs(double? have, double want, Symbol symbol) =>
Math.Abs((have ?? 0) - want) > symbol.TickSize / 2.0;
// ----------------------------------------------------------------
// Trade size (in units; cTrader trades units, not lots)
// ----------------------------------------------------------------
private double Volume(Symbol symbol, double entry, double sl, out string why)
{
why = "";
var min = symbol.VolumeInUnitsMin;
var max = symbol.VolumeInUnitsMax;
if (min <= 0) { why = "no volume information for " + symbol.Name; return 0; }
double units;
if (LotMode == FtiLotMode.Risk)
{
var pips = symbol.PipSize > 0 ? Math.Abs(entry - sl) / symbol.PipSize : 0;
if (sl <= 0 || pips <= 0 || symbol.PipValue <= 0) { why = "sizing by risk needs a stop loss"; return 0; }
units = Account.Balance * LotValue / 100.0 / (pips * symbol.PipValue);
}
else
{
var lots = LotMode == FtiLotMode.Per1000 ? LotValue * Account.Balance / 1000.0 : LotValue;
units = symbol.QuantityToVolumeInUnits(lots);
}
units = symbol.NormalizeVolumeInUnits(units, RoundingMode.Down);
if (units < min)
{
// Rounding a risk-sized trade UP would risk more than was asked for.
if (LotMode == FtiLotMode.Risk) { why = "the risk setting allows less than the smallest trade size"; return 0; }
units = min;
}
var cap = max;
if (MaxLot > 0) cap = Math.Min(cap, symbol.QuantityToVolumeInUnits(MaxLot));
if (units > cap) units = symbol.NormalizeVolumeInUnits(cap, RoundingMode.Down);
if (units < min) { why = "the maximum lot is below the broker's minimum"; return 0; }
return units;
}
// ----------------------------------------------------------------
// Failed attempts
// ----------------------------------------------------------------
// Counts a failure for this version of the order; true once it has failed too often.
private bool TooManyAttempts(FtiOrder o)
{
var count = _attempts.TryGetValue(o.Id, out var a) && a.Seq == o.Seq ? a.Count + 1 : 1;
_attempts[o.Id] = (o.Seq, count);
return count >= MaxAttempts;
}
private bool GaveUpChanging(FtiOrder o) => _attempts.TryGetValue(o.Id, out var a) && a.Seq == o.Seq && a.Count >= MaxAttempts;
// A refusal that says nothing about the order itself: try again, don't count it.
private static bool Passing(TradeResult result)
{
var error = result.Error;
return error == ErrorCode.MarketClosed || error == ErrorCode.Disconnected || error == ErrorCode.Timeout || error == ErrorCode.TechnicalError;
}
private static string Why(TradeResult result) => result.Error.HasValue ? result.Error.Value.ToString() : "refused";
// Results of handling one order: true = nothing more to do, false = come back to it.
private bool GiveUp(FtiOrder o, string why)
{
MarkDone(o.Id);
Note(o.Label + " not copied: " + why);
return true;
}
private bool Later(FtiOrder o, string why)
{
_lastNote = Clock + " " + o.Label + " waiting: " + why;
return false;
}
private void Note(string text)
{
_lastNote = Clock + " " + text;
Print("FTI Signal Copier: " + text);
}
private void Did(string text)
{
_lastAction = Clock + " " + text;
Print("FTI Signal Copier: " + text);
}
private bool EntryFailed(FtiOrder o, TradeResult result)
{
var why = Why(result);
if (Passing(result)) return Later(o, why);
return TooManyAttempts(o) ? GiveUp(o, why) : Later(o, why);
}
// ----------------------------------------------------------------
// Opening a copy
// ----------------------------------------------------------------
private bool PlaceEntry(FtiOrder o)
{
if (!SymbolWanted(o.Symbol)) return GiveUp(o, "not in your symbol lists");
var symbol = Resolve(o);
if (symbol == null) return GiveUp(o, "no symbol for " + o.Symbol + " at this broker (add it to the symbol map parameter)");
double bid = symbol.Bid, ask = symbol.Ask;
if (bid <= 0 || ask <= 0 || double.IsNaN(bid) || double.IsNaN(ask)) return Later(o, "no price for " + symbol.Name + " yet");
var late = o.State == "filled";
var level = late && o.Fill > 0 ? o.Fill : o.Price;
var mid = (bid + ask) / 2.0;
if (level <= 0) return GiveUp(o, "the signal has no entry price");
if (Math.Abs(level - mid) / mid * 100.0 > MaxPriceGapPct)
return GiveUp(o, symbol.Name + " is at " + F(mid, symbol.Digits) + " but the signal is for " + F(level, 5) + ": not the same instrument?");
if (CountOwn() >= MaxOpenTrades) return Later(o, "the maximum number of open trades is reached");
var units = Volume(symbol, o.Price, o.Sl, out var why);
if (units <= 0) return GiveUp(o, why);
var price = NormPrice(symbol, o.Price);
var sl = NormPrice(symbol, o.Sl);
var tp = NormPrice(symbol, o.Tp);
var side = o.Buy ? TradeType.Buy : TradeType.Sell;
var label = Tag + o.Id;
if (late && o.FilledAgo > LateEntrySeconds)
return GiveUp(o, "the master entered " + o.FilledAgo + "s ago, too late to join");
if (!late)
{
bool placeable;
if (o.Type == "limit") placeable = o.Buy ? price < ask : price > bid;
else placeable = o.Buy ? price > ask : price < bid;
if (placeable)
{
// The stop and target are the signal's own prices. No expiry:
// the master's own cancel removes the order.
var placed = o.Type == "limit"
? PlaceLimitOrder(side, symbol.Name, units, price, label, Level(sl), Level(tp), ProtectionType.Absolute, null, label)
: PlaceStopOrder(side, symbol.Name, units, price, label, Level(sl), Level(tp), ProtectionType.Absolute, null, label);
if (placed.IsSuccessful)
{
MarkDone(o.Id);
Did("placed " + o.Side + " " + o.Type + " " + symbol.Name + " " + F(symbol.VolumeInUnitsToQuantity(units), 2) + " at " + F(price, symbol.Digits) + " (#" + o.Id + ")");
return true;
}
return EntryFailed(o, placed);
}
// The market is already at or through the entry: the order
// would have triggered, so join at market if the price is
// still close.
}
var now = o.Buy ? ask : bid;
var slip = Math.Abs(now - level) / level * 100.0;
if (slip > LateEntrySlipPct)
{
var moved = "price is " + F(slip, 2) + "% from the entry";
return late ? GiveUp(o, moved) : Later(o, moved);
}
if (sl > 0 && (o.Buy ? now <= sl : now >= sl)) return late ? GiveUp(o, "price is already beyond the stop") : Later(o, "price is beyond the stop");
if (tp > 0 && (o.Buy ? now >= tp : now <= tp)) return late ? GiveUp(o, "price is already beyond the target") : Later(o, "price is beyond the target");
var opened = ExecuteMarketOrder(side, symbol.Name, units, label, (double?)null, (double?)null, label);
if (!opened.IsSuccessful) return EntryFailed(o, opened);
MarkDone(o.Id);
Did("opened " + o.Side + " " + symbol.Name + " " + F(symbol.VolumeInUnitsToQuantity(units), 2) + " at market (#" + o.Id + ")");
// The stop and target are prices, so they go on once the position exists.
if ((sl > 0 || tp > 0) && opened.Position != null)
{
var set = ModifyPosition(opened.Position, Level(sl), Level(tp), ProtectionType.Absolute);
if (!set.IsSuccessful) Note(o.Label + " opened WITHOUT its stop and target (" + Why(set) + "). The copier will keep trying to set them.");
}
return true;
}
// ----------------------------------------------------------------
// Keeping a copy in step: entry, stop and target
// ----------------------------------------------------------------
private bool EnsureLevels(FtiOrder o, PendingOrder pending, Position position)
{
if (GaveUpChanging(o)) return true;
TradeResult result;
if (pending != null)
{
var symbol = Symbols.GetSymbol(pending.SymbolName);
if (symbol == null) return true;
// Once the master is in, the entry no longer moves: leave ours where it is.
var wantPrice = o.State == "working" ? NormPrice(symbol, o.Price) : pending.TargetPrice;
var wantSl = NormPrice(symbol, o.Sl);
var wantTp = NormPrice(symbol, o.Tp);
if (!Differs(pending.TargetPrice, wantPrice, symbol) && !Differs(pending.StopLoss, wantSl, symbol) && !Differs(pending.TakeProfit, wantTp, symbol)) return true;
result = ModifyPendingOrder(pending, wantPrice, Level(wantSl), Level(wantTp), ProtectionType.Absolute, pending.ExpirationTime);
if (result.IsSuccessful) { Did("moved " + o.Label + " to the master's levels"); return true; }
}
else
{
var symbol = Symbols.GetSymbol(position.SymbolName);
if (symbol == null) return true;
var wantSl = NormPrice(symbol, o.Sl);
var wantTp = NormPrice(symbol, o.Tp);
if (!Differs(position.StopLoss, wantSl, symbol) && !Differs(position.TakeProfit, wantTp, symbol)) return true;
result = ModifyPosition(position, Level(wantSl), Level(wantTp), ProtectionType.Absolute);
if (result.IsSuccessful) { Did("moved the stop/target of " + o.Label); return true; }
}
var why = "could not move it: " + Why(result);
if (!Passing(result) && TooManyAttempts(o))
{
Note(o.Label + " " + why + ". Left as it is.");
return true;
}
return Later(o, why);
}
private bool RemovePending(FtiOrder o, PendingOrder pending, string reason)
{
var result = CancelPendingOrder(pending);
if (result.IsSuccessful)
{
MarkDone(o.Id);
Did("cancelled " + o.Label + ": " + reason);
return true;
}
// Gone already (it may have just triggered): look again next time.
return Later(o, "could not cancel: " + Why(result));
}
private bool CloseCopy(FtiOrder o, Position position)
{
var result = ClosePosition(position);
if (result.IsSuccessful)
{
MarkDone(o.Id);
Did("closed " + o.Label + " with the master");
return true;
}
return Later(o, "could not close: " + Why(result));
}
// ----------------------------------------------------------------
// One master order -> what this account should hold
// ----------------------------------------------------------------
private bool Apply(FtiOrder o)
{
var pending = FindPending(o.Id);
var position = pending == null ? FindPosition(o.Id) : null;
var have = pending != null || position != null;
if (o.State == "working" || o.State == "filled")
{
if (have) return EnsureLevels(o, pending, position);
// Copied before and no longer here: it ran its course on this account.
return _done.Contains(o.Id) || PlaceEntry(o);
}
if (o.State == "cancelled")
{
if (pending != null) return RemovePending(o, pending, "the master cancelled");
// Our copy triggered although the master's never did: it keeps its own stop and target.
if (position != null) Note(o.Label + " was cancelled by the master after it triggered here. It keeps its stop and target.");
MarkDone(o.Id);
return true;
}
if (o.State == "closed")
{
if (pending != null) return RemovePending(o, pending, "the master's trade is over");
if (position != null && FollowCloses) return CloseCopy(o, position);
MarkDone(o.Id);
return true;
}
return true;
}
private static FtiOrder ReadOrder(JsonElement e)
{
var o = new FtiOrder
{
Id = (long)Num(e, "id"), Seq = (long)Num(e, "seq"), Symbol = Str(e, "symbol"), Side = Str(e, "side"), Type = Str(e, "type"), State = Str(e, "state"),
Price = Num(e, "price"), Sl = Num(e, "sl"), Tp = Num(e, "tp"), Fill = Num(e, "fill"), FilledAgo = (long)Num(e, "filledAgo"),
};
if (e.TryGetProperty("alt", out var alt) && alt.ValueKind == JsonValueKind.Array)
foreach (var item in alt.EnumerateArray())
if (item.ValueKind == JsonValueKind.String) o.Alts.Add(item.GetString() ?? "");
if (o.Alts.Count == 0) o.Alts.Add(o.Symbol);
return o;
}
// ----------------------------------------------------------------
// Talking to the hub
// ----------------------------------------------------------------
private string BaseUrl() => (HubUrl ?? "").Trim().TrimEnd('/');
private string KeyTyped() => (LicenseKey ?? "").Trim().ToUpperInvariant();
// Returns the HTTP status, or -1 when the hub couldn't be reached.
private int Post(string path, string body, out string response)
{
try
{
var request = new HttpRequest(new Uri(BaseUrl() + path))
{
Method = HttpMethod.Post,
Body = body,
Timeout = TimeSpan.FromSeconds(10),
};
var result = Http.Send(request);
if (result.Exception != null || result.StatusCode <= 0)
{
response = "";
_status = "Cannot reach the hub (" + Truncate(result.Exception?.Message ?? "no response", 80) + ") - retrying";
return -1;
}
response = result.Body ?? "";
return result.StatusCode;
}
catch (Exception ex)
{
response = "";
_status = "Cannot reach the hub (" + Truncate(ex.Message, 80) + ") - retrying";
return -1;
}
}
private void Block(string message)
{
_blocked = true;
_status = message;
Print("FTI Signal Copier: " + message);
}
private void Activate()
{
var body = JsonSerializer.Serialize(new
{
p = 1, key = KeyTyped(), platform = Platform, account = _login.ToString(CultureInfo.InvariantCulture), server = _server,
company = Truncate(Account.BrokerName ?? "", 128), v = Version,
});
var code = Post("/v1/activate", body, out var resp);
var json = TryParse(resp);
var message = Str(json, "message");
var token = Str(json, "token");
if (code == 200 && token.Length == 64)
{
_memory.Token = token;
_memory.Cursor = 0; // a new session starts from the whole picture
_needActivate = false;
_nextSyncAt = DateTime.MinValue;
SaveMemory();
Print("FTI Signal Copier: licence accepted for account " + _login);
return;
}
if (code == 409)
{
// The licence is set to a different account on its owner's
// licence page. They may be about to change it to this one:
// keep asking.
_status = message != "" ? message : "This licence is set to a different trading account. Change it on your licence page.";
_nextActivateAt = Now.AddSeconds(60);
return;
}
if (code == 400 || code == 401 || code == 403)
{
// The key is wrong or withdrawn: trying again cannot help.
Block(message != "" ? message : "The hub refused the licence key (" + code + ").");
return;
}
if (code == 402 || code == 429)
{
_status = message != "" ? message : "The licence cannot be started right now.";
_nextActivateAt = Now.AddMinutes(10);
return;
}
if (code != -1) _status = "The hub is unavailable (HTTP " + code + ") - retrying";
_nextActivateAt = Now.AddSeconds(30);
}
private void Sync()
{
var full = _memory.Cursor <= 0 || Now >= _nextFullAt;
var body = JsonSerializer.Serialize(new
{
p = 1, token = _memory.Token, platform = Platform, account = _login.ToString(CultureInfo.InvariantCulture), server = _server, v = Version,
cursor = full ? 0 : _memory.Cursor, held = HeldIds(),
});
var code = Post("/v1/sync", body, out var resp);
var json = TryParse(resp);
var message = Str(json, "message");
if (code == 200 && json.HasValue)
{
_failStreak = 0;
_lastOkAt = Now;
var poll = (int)Num(json, "poll");
// The hub says how often to ask. The setting can only make it less often.
_pollSec = Math.Max(2, Math.Max(PollSeconds, poll > 0 ? poll : 5));
_nextSyncAt = Now.AddSeconds(_pollSec);
var expires = (long)Num(json, "expires");
var until = expires > 0 ? DateTimeOffset.FromUnixTimeMilliseconds(expires).UtcDateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) : "";
if (Str(json, "licence") == "active")
{
_status = "Copying";
_licence = "Licence active" + (until != "" ? " until " + until + " (" + (int)Num(json, "daysLeft") + " days left)" : "");
}
else
{
_status = "Licence expired: no new trades. Open trades are still closed with the master.";
_licence = "Expired " + until + ". Renew to carry on copying.";
}
var complete = true;
if (json.Value.TryGetProperty("orders", out var orders) && orders.ValueKind == JsonValueKind.Array)
{
foreach (var item in orders.EnumerateArray())
{
var o = ReadOrder(item);
if (o.Id <= 0) continue;
if (!Apply(o)) complete = false;
}
}
// Copies the hub has no record of: cancel what has not triggered, leave the rest.
if (json.Value.TryGetProperty("unknown", out var unknown) && unknown.ValueKind == JsonValueKind.Array)
{
foreach (var item in unknown.EnumerateArray())
{
if (item.ValueKind != JsonValueKind.Number || !item.TryGetInt64(out var id) || id <= 0) continue;
var pending = FindPending(id);
if (pending != null) CancelPendingOrder(pending);
MarkDone(id);
}
}
// Only move on once everything in this answer is dealt with:
// otherwise the same orders come again next time.
if (complete)
{
var cursor = (long)Num(json, "cursor");
if (cursor != _memory.Cursor)
{
_memory.Cursor = cursor;
SaveMemory();
}
}
if (full) _nextFullAt = Now.AddMinutes(5);
return;
}
if (code == 401 || code == 409)
{
// The session ended: the licence was started on another
// terminal, or moved to another account. Ask again; the
// answer says which.
_memory.Token = "";
_needActivate = true;
_nextActivateAt = DateTime.MinValue;
return;
}
if (code == 403)
{
Block(message != "" ? message : "The hub refused this licence (" + Str(json, "error") + ").");
return;
}
if (code == 402)
{
_status = message != "" ? message : "The licence has expired.";
_licence = "Expired";
_nextSyncAt = Now.AddMinutes(10); // renewing the same key brings it back
return;
}
_failStreak++;
var wait = (int)Math.Min(60, 5 * Math.Pow(2, Math.Min(_failStreak, 4)));
_nextSyncAt = Now.AddSeconds(wait);
if (code != -1) _status = "The hub is unavailable (HTTP " + code + ") - retrying in " + wait + "s";
}
// ----------------------------------------------------------------
// Display
// ----------------------------------------------------------------
private void ShowStatus()
{
var text = "FTI Signal Copier " + Version + " cTrader " + _login + "\n" + _status + "\n";
if (_licence != "") text += _licence + "\n";
if (_lastOkAt != DateTime.MinValue) text += "Holding " + _held + " copied trades. Last check " + _lastOkAt.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + " UTC\n";
if (_lastAction != "") text += "Last: " + _lastAction + "\n";
if (_lastNote != "") text += "Note: " + _lastNote + "\n";
Chart.DrawStaticText(StatusObject, text, VerticalAlignment.Top, HorizontalAlignment.Left, Chart.ColorSettings.ForegroundColor);
}
// ----------------------------------------------------------------
// Small helpers
// ----------------------------------------------------------------
private static string Truncate(string s, int max) => s.Length > max ? s.Substring(0, max) : s;
private static JsonElement? TryParse(string body)
{
if (string.IsNullOrEmpty(body)) return null;
try
{
using var doc = JsonDocument.Parse(body);
return doc.RootElement.Clone();
}
catch (JsonException)
{
return null;
}
}
private static string Str(JsonElement? e, string key) => e.HasValue ? Str(e.Value, key) : "";
private static string Str(JsonElement e, string key) =>
e.ValueKind == JsonValueKind.Object && e.TryGetProperty(key, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
private static double Num(JsonElement? e, string key) => e.HasValue ? Num(e.Value, key) : 0;
private static double Num(JsonElement e, string key) =>
e.ValueKind == JsonValueKind.Object && e.TryGetProperty(key, out var v) && v.ValueKind == JsonValueKind.Number ? v.GetDouble() : 0;
}
}