using System; using System.Linq; using System.Collections.Generic; using System.Globalization; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Security.Cryptography; using cAlgo.API; using cAlgo.API.Internals; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class SignalBridgeCTrader : Robot { [Parameter("Bridge URL", DefaultValue = "https://signalbridgeadzean.duckdns.org/ctrader/YOUR_USER_ID")] public string BridgeUrl { get; set; } [Parameter("Bridge Token", DefaultValue = "")] public string BridgeToken { get; set; } [Parameter("Expected Account", DefaultValue = 0)] public int ExpectedAccount { get; set; } [Parameter("Expected Broker", DefaultValue = "")] public string ExpectedBroker { get; set; } [Parameter("Allow Live", DefaultValue = false)] public bool AllowLive { get; set; } [Parameter("Max Lots", DefaultValue = 0.10, MinValue = 0.001)] public double MaxLots { get; set; } [Parameter("Max Spread (pips)", DefaultValue = 5, MinValue = 0.1)] public double MaxSpreadPips { get; set; } private HttpClient client; private string pending = "", journalKey; private bool busy; private string DynamicLabel(long id) => "SD-"+journalKey.Substring(journalKey.Length-32,16)+"-"+Mode+"-"+id.ToString(Inv); public class StopConfig { public string Symbol {get;set;} public string Side {get;set;} public double Units {get;set;} public double Start {get;set;} public double Distance {get;set;} public double Trigger {get;set;} public double Offset {get;set;} public double Peak {get;set;} } private Dictionary quoteSeen = new Dictionary(); private HashSet watched = new HashSet(); private void Watch(Symbol symbol) { if(symbol!=null && watched.Add(symbol.Name)) symbol.Tick += e => quoteSeen[e.SymbolName]=DateTime.UtcNow; } private Dictionary stops = new Dictionary(); private bool SaveStops() { try { LocalStorage.SetString(journalKey+"-"+Mode+"-stops", JsonSerializer.Serialize(stops), LocalStorageScope.Instance); LocalStorage.Flush(LocalStorageScope.Instance); return true; } catch { Print("Dynamic settings could not be persisted. Check broker protection."); Stop(); return false; } } private void ManageStops() { foreach (var item in stops.ToArray()) { var cfg=item.Value; var owned=Positions.Where(p=>p.Label==DynamicLabel(item.Key) && p.SymbolName==cfg.Symbol).ToArray(); if(owned.Length!=1) continue; var pos=owned[0];var symbol=Symbols.GetSymbol(pos.SymbolName); if(symbol==null) continue;Watch(symbol); if(!quoteSeen.TryGetValue(symbol.Name,out var last) || (DateTime.UtcNow-last).TotalSeconds>30) continue; bool buy=pos.TradeType==TradeType.Buy; if((buy?"BUY":"SELL")!=cfg.Side || Math.Abs(pos.VolumeInUnits-cfg.Units)>1e-8 || symbol==null || !symbol.MarketHours.IsOpened()) continue; double quote=buy?symbol.Bid:symbol.Ask; if(quote<=0 || symbol.PipSize<=0) continue; cfg.Peak=cfg.Peak==0?quote:buy?Math.Max(cfg.Peak,quote):Math.Min(cfg.Peak,quote); double sign=buy?1:-1,gain=sign*(cfg.Peak-pos.EntryPrice)/symbol.PipSize; double? target=pos.StopLoss; Action improve=value=>{target=target==null?value:buy?Math.Max(target.Value,value):Math.Min(target.Value,value);}; if(cfg.Trigger>0 && gain>=cfg.Trigger) improve(pos.EntryPrice+sign*cfg.Offset*symbol.PipSize); if(cfg.Start>0 && gain>=cfg.Start) improve(cfg.Peak-sign*cfg.Distance*symbol.PipSize); if(!SaveStops()) return; if(target==null) continue; double tick=symbol.TickSize; if(tick<=0) continue; double rounded=(buy?Math.Floor(target.Value/tick):Math.Ceiling(target.Value/tick))*tick; if(rounded<=0 || (buy?rounded>=quote:rounded<=quote) || (pos.StopLoss!=null && (buy?rounded<=pos.StopLoss.Value:rounded>=pos.StopLoss.Value))) continue; var changed=ModifyPosition(pos,rounded,pos.TakeProfit,ProtectionType.Absolute); if(!changed.IsSuccessful) Print("Dynamic SL update rejected on position {0}: {1}. Existing broker SL retained.",pos.Id,changed.Error); } } private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; private string Mode => Account.IsLive ? "live" : "demo"; private string Identity => "\"login\":" + JsonSerializer.Serialize(Account.Number.ToString(Inv)) + ",\"server\":" + JsonSerializer.Serialize(Account.BrokerName) + ",\"account_mode\":" + JsonSerializer.Serialize(Mode); private bool Matches() => Account.Number == ExpectedAccount && Account.BrokerName == ExpectedBroker && (!Account.IsLive || AllowLive); protected override void OnStart() { if (RunningMode != RunningMode.RealTime) { Print("Connector supports real-time Demo/Live only; backtesting disabled."); Stop(); return; } if (!Uri.TryCreate(BridgeUrl, UriKind.Absolute, out var uri) || uri.Scheme != "https" || !uri.AbsolutePath.StartsWith("/ctrader/") || string.IsNullOrWhiteSpace(BridgeToken) || BridgeToken.Length < 32 || !Matches()) { Print("Check pairing URL, account, broker and Allow Live. Current account: {0}; broker: {1}", Account.Number, Account.BrokerName); Stop(); return; } BridgeUrl = BridgeUrl.TrimEnd('/'); // Device-independent instance journal: retry acknowledgments only after a restart. journalKey = "SignalBridge-pending-" + Account.Number.ToString(Inv) + "-" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(BridgeUrl + "|" + ExpectedBroker))).Substring(0,32); pending = LocalStorage.GetString(journalKey, LocalStorageScope.Instance) ?? ""; try { var saved=LocalStorage.GetString(journalKey+"-"+Mode+"-stops",LocalStorageScope.Instance); if(!string.IsNullOrEmpty(saved)) stops=JsonSerializer.Deserialize>(saved) ?? new Dictionary(); } catch { Print("Dynamic journal invalid. Check existing broker positions manually."); Stop(); return; } foreach(var cfg in stops.Values) Watch(Symbols.GetSymbol(cfg.Symbol)); client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(5) }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", BridgeToken); Print("SignalBridge cBot. Account {0}, broker {1}, mode {2}.", Account.Number, Account.BrokerName, Mode); Timer.Start(TimeSpan.FromSeconds(3)); } private bool Save(string value) { try { LocalStorage.SetString(journalKey, value, LocalStorageScope.Instance); LocalStorage.Flush(LocalStorageScope.Instance); pending = value; return true; } catch { Print("Journal storage failed. Stop and verify broker history. No replay."); Stop(); return false; } } private bool Post(string action, string body, out string response) { response = ""; try { using (var content = new StringContent(body, Encoding.UTF8, "application/json")) using (var result = client.PostAsync(BridgeUrl + "/" + action, content).GetAwaiter().GetResult()) { if ((int)result.StatusCode != 200) { Print("SignalBridge HTTP {0}; check pairing and account status.", (int)result.StatusCode); return false; } response = result.Content.ReadAsStringAsync().GetAwaiter().GetResult(); return true; } } catch { Print("SignalBridge network error. No order retry."); return false; } } private string Ack(long id, string status, string message, long order = 0, double filledLots = 0) { return "{" + Identity + ",\"id\":" + id.ToString(Inv) + ",\"status\":" + JsonSerializer.Serialize(status) + ",\"message\":" + JsonSerializer.Serialize(message) + ",\"order\":" + JsonSerializer.Serialize(order.ToString(Inv)) + ",\"filled_lots\":" + filledLots.ToString("G17", Inv) + "}"; } private void Reject(long id, string reason) => Save(Ack(id, "REJECTED", reason)); protected override void OnTimer() { if (busy || client == null) return; busy = true; try { if (!Matches()) { Print("Account/broker/mode changed. Stop connector."); Stop(); return; } ManageStops(); if (pending.Length > 0) { if (Post("ack", pending, out _)) Save(""); return; } var heartbeat = "{\"dynamic_protocol\":1," + Identity + ",\"balance\":" + Account.Balance.ToString("G17", Inv) + ",\"equity\":" + Account.Equity.ToString("G17", Inv) + ",\"currency\":" + JsonSerializer.Serialize(Account.Asset.Name) + "}"; if (!Post("poll", heartbeat, out var wire) || wire == "NONE") return; var f = wire.Split('\t'); if ((f.Length != 7 && f.Length != 11) || !long.TryParse(f[0], NumberStyles.None, Inv, out var id) || id <= 0) { Print("Invalid response. No order sent."); return; } if (!Save(Ack(id, "UNKNOWN", "Connector stopped before final result; verify cTrader history. No replay."))) return; if (f[6] != Mode || (f[2] != "BUY" && f[2] != "SELL") || !double.TryParse(f[3], NumberStyles.Float, Inv, out var lots) || !double.TryParse(f[4], NumberStyles.Float, Inv, out var sl) || !double.TryParse(f[5], NumberStyles.Float, Inv, out var tp) || !double.IsFinite(lots) || !double.IsFinite(sl) || !double.IsFinite(tp) || lots <= 0 || lots > MaxLots || sl < 0 || tp < 0) { Reject(id, "Invalid mode, lot size or protection values."); return; } double start=0,distance=0,trigger=0,offset=0; if(f.Length==11 && (!double.TryParse(f[7],NumberStyles.Float,Inv,out start) || !double.TryParse(f[8],NumberStyles.Float,Inv,out distance) || !double.TryParse(f[9],NumberStyles.Float,Inv,out trigger) || !double.TryParse(f[10],NumberStyles.Float,Inv,out offset) || !double.IsFinite(start+distance+trigger+offset) || start<0 || distance<0 || trigger<0 || offset<0 || (start>0 && (distance<=0 || distance>start)) || (trigger>0 && offset>=trigger) || sl<=0)) { Reject(id,"Invalid dynamic protection."); return; } var symbol = Symbols.GetSymbol(f[1]); if (symbol == null || symbol.Name != f[1] || symbol.PipSize <= 0 || symbol.Bid <= 0 || symbol.Ask <= 0 || !symbol.MarketHours.IsOpened()) { Reject(id, "Symbol/quote unavailable or market closed."); return; } Watch(symbol); var units = symbol.QuantityToVolumeInUnits(lots); var normalized = symbol.NormalizeVolumeInUnits(units, RoundingMode.ToNearest); if (units < symbol.VolumeInUnitsMin || units > symbol.VolumeInUnitsMax || Math.Abs(units - normalized) > Math.Max(0.000001, units * 1e-9)) { Reject(id, "Lot size does not match broker min/max/step; no rounding."); return; } if ((symbol.Ask - symbol.Bid) / symbol.PipSize > MaxSpreadPips) { Reject(id, "Spread exceeds local limit."); return; } if (Positions.Any(p => p.SymbolName == symbol.Name) || PendingOrders.Any(p => p.SymbolName == symbol.Name)) { Reject(id, "Existing position/order on symbol; manage it in cTrader first."); return; } var side = f[2] == "BUY" ? TradeType.Buy : TradeType.Sell; if(f.Length==11) { stops[id]=new StopConfig {Symbol=symbol.Name,Side=f[2],Units=units,Start=start,Distance=distance,Trigger=trigger,Offset=offset}; if(!SaveStops()) return; } // Only one broker request. Protection distances are in pips, supplied with entry. var result = ExecuteMarketOrder(side, symbol.Name, units, f.Length==11?DynamicLabel(id):"SB-" + id.ToString(Inv), sl > 0 ? (double?)sl : null, tp > 0 ? (double?)tp : null); if (result.IsSuccessful && result.Position != null) { var position = result.Position; bool unprotected = (sl > 0 && position.StopLoss == null) || (tp > 0 && position.TakeProfit == null); double filled = symbol.VolumeInUnitsToQuantity(position.VolumeInUnits); var status = unprotected ? "UNKNOWN" : Math.Abs(filled - lots) > 1e-8 ? "PARTIAL" : "FILLED"; Save(Ack(id, status, unprotected ? "Position opened without requested protection. Check broker immediately." : "cTrader position created.", position.Id, filled)); } else { var error = result.Error.HasValue ? result.Error.Value.ToString() : "Unknown"; var definite = new[] { "BadVolume", "NoMoney", "MarketClosed", "InvalidStopLossTakeProfit", "NoTradingPermission", "InvalidRequest" }; Save(Ack(id, definite.Contains(error) ? "REJECTED" : "UNKNOWN", "Broker result: " + error)); } } catch { Print("Execution result uncertain. Pending journal retained; no replay."); } finally { busy = false; } } protected override void OnStop() { Timer.Stop(); client?.Dispose(); } } }