//+------------------------------------------------------------------+ //| FTISignalCopier.mq5 | //| | //| Copies the trades of the Freemium Trade Ideas master account | //| onto THIS MetaTrader 5 account: the same entry, stop and target, | //| at a size you choose. When the master cancels or closes, this | //| account follows. | //| | //| SETUP (once): | //| 1. Tools > Options > Expert Advisors > tick "Allow WebRequest | //| for listed URL" and add https://freemiumtradeideas.com | //| 2. Attach this EA to ANY one chart and allow Algo Trading. | //| 3. Paste your licence key into the inputs 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. Needs a hedging account. | //+------------------------------------------------------------------+ #property copyright "Freemium Trade Ideas" #property version "1.00" #property description "Copies the FTI master account's trades onto this account." #define EA_VERSION "1.00" #define PLATFORM "MT5" #define TAG "FTI#" #define GV_PREFIX "FTIC_" #define MAX_ATTEMPTS 5 enum ENUM_FTI_LOT_MODE { FTI_LOT_FIXED = 0, // The same lot for every trade FTI_LOT_PER_1000 = 1, // Lots for each 1,000 of balance FTI_LOT_RISK = 2 // Percent of balance at risk per trade }; input group "Licence" input string InpLicenseKey = ""; // Licence key (FTI-XXXXX-XXXXX-XXXXX-XXXXX) input string InpHubUrl = "https://freemiumtradeideas.com/copier"; // Hub URL (allow https://freemiumtradeideas.com under Tools > Options > Expert Advisors) input group "Trade size" input ENUM_FTI_LOT_MODE InpLotMode = FTI_LOT_FIXED; // How the lot is worked out input double InpLotValue = 0.01; // Lot / lots per 1,000 / percent at risk input double InpMaxLot = 1.0; // Never trade more than this many lots input group "Symbols" input string InpSymbolPrefix = ""; // Your broker's symbol prefix (blank = detect) input string InpSymbolSuffix = ""; // Your broker's symbol suffix, e.g. .m (blank = detect) input string InpSymbolMap = ""; // Your own names, e.g. USA100=NAS100;XAUUSD=GOLD input string InpOnlySymbols = ""; // Copy only these, e.g. EURUSD,XAUUSD (blank = all) input string InpSkipSymbols = ""; // Never copy these, e.g. BTCUSD,ETHUSD input group "Safety" input int InpMaxOpenTrades = 40; // Most copied trades open at once (orders + positions) input double InpMaxPriceGapPct = 10.0; // Skip a symbol priced more than this % from the signal input int InpLateEntrySeconds = 120; // Join a trade the master already entered, up to this many seconds late input double InpLateEntrySlipPct = 0.10; // ...and only within this % of the master's entry price input bool InpFollowCloses = true; // Close a position when the master closes its own input group "Advanced" input long InpMagic = 20260810; // Magic number of the copier's trades input int InpPollSeconds = 0; // Seconds between checks (0 = the hub's; a higher number checks less often) //--- one master order, as the hub describes it struct FtiOrder { long id; long seq; string symbol; string side; string type; string state; double price; double sl; double tp; double fill; long filledAgo; string alts[]; }; //--- the last trade request's result uint g_rc = 0; string g_rcText = ""; ulong g_rcOrder = 0; //--- session long g_login = 0; string g_token = ""; long g_cursor = 0; bool g_needActivate = true; bool g_blocked = false; // the hub refused the key: wait for the user to fix the inputs datetime g_nextActivateAt = 0; datetime g_nextSyncAt = 0; datetime g_nextFullAt = 0; int g_failStreak = 0; int g_pollSec = 5; datetime g_connectedSince = 0; //--- symbols string g_prefix = ""; string g_suffix = ""; string g_symFrom[]; string g_symTo[]; //--- failed attempts per order, in memory long g_tryId[]; long g_trySeq[]; int g_tryCount[]; //--- display string g_status = "Starting..."; string g_licence = ""; string g_lastAction = ""; string g_lastNote = ""; datetime g_lastOkAt = 0; int g_held = 0; //+------------------------------------------------------------------+ //| Small helpers | //+------------------------------------------------------------------+ string Trim(const string s) { int a = 0; int b = StringLen(s) - 1; while(a <= b && StringGetCharacter(s, a) <= 32) a++; while(b >= a && StringGetCharacter(s, b) <= 32) b--; return b < a ? "" : StringSubstr(s, a, b - a + 1); } string Upper(const string s) { string out = s; StringToUpper(out); return out; } string JsonEscape(const string s) { string out = ""; int n = StringLen(s); for(int i = 0; i < n; i++) { ushort c = StringGetCharacter(s, i); if(c == '"') out += "\\\""; else if(c == '\\') out += "\\\\"; else if(c < 32) out += " "; else out += ShortToString(c); } return out; } string Q(const string s) { return "\"" + JsonEscape(s) + "\""; } string Truncate(const string s, const int maxLen) { return StringLen(s) > maxLen ? StringSubstr(s, 0, maxLen) : s; } string BaseUrl() { string u = Trim(InpHubUrl); while(StringLen(u) > 0 && StringSubstr(u, StringLen(u) - 1) == "/") u = StringSubstr(u, 0, StringLen(u) - 1); return u; } // The site the hub is on, which is what MetaTrader's allow-list wants. string HubOrigin() { string u = BaseUrl(); int start = StringFind(u, "://"); if(start < 0) return u; int slash = StringFind(u, "/", start + 3); return slash < 0 ? u : StringSubstr(u, 0, slash); } string KeyTyped() { return Upper(Trim(InpLicenseKey)); } string Clock() { return TimeToString(TimeLocal(), TIME_SECONDS); } void Note(const string text) { g_lastNote = Clock() + " " + text; Print("FTI Signal Copier: ", text); } void Did(const string text) { g_lastAction = Clock() + " " + text; Print("FTI Signal Copier: ", text); } //+------------------------------------------------------------------+ //| Minimal JSON readers for the hub's own (compact) responses | //+------------------------------------------------------------------+ int JsonValueStart(const string json, const string key) { int p = StringFind(json, "\"" + key + "\":"); return p < 0 ? -1 : p + StringLen(key) + 3; } string JsonGetString(const string json, const string key) { int p = JsonValueStart(json, key); if(p < 0 || StringGetCharacter(json, p) != '"') return ""; string out = ""; int n = StringLen(json); for(int i = p + 1; i < n; i++) { ushort c = StringGetCharacter(json, i); if(c == '\\' && i + 1 < n) { out += ShortToString(StringGetCharacter(json, i + 1)); i++; continue; } if(c == '"') break; out += ShortToString(c); } return out; } double JsonGetNumber(const string json, const string key) { int p = JsonValueStart(json, key); if(p < 0) return 0; int e = p; int n = StringLen(json); while(e < n) { ushort c = StringGetCharacter(json, e); if(c == ',' || c == '}' || c == ']') break; e++; } return StringToDouble(StringSubstr(json, p, e - p)); } // Contents of the array at `key` (without the brackets); "" if absent. string JsonGetArray(const string json, const string key) { int p = JsonValueStart(json, key); if(p < 0 || StringGetCharacter(json, p) != '[') return ""; int depth = 0; bool inString = false; int n = StringLen(json); for(int i = p; i < n; i++) { ushort c = StringGetCharacter(json, i); if(inString) { if(c == '\\') { i++; continue; } if(c == '"') inString = false; continue; } if(c == '"') inString = true; else if(c == '[') depth++; else if(c == ']') { depth--; if(depth == 0) return StringSubstr(json, p + 1, i - p - 1); } } return ""; } // Splits the contents of an array of objects into its objects. int JsonObjects(const string arr, string &out[]) { ArrayResize(out, 0); int depth = 0; int start = -1; bool inString = false; int n = StringLen(arr); for(int i = 0; i < n; i++) { ushort c = StringGetCharacter(arr, i); if(inString) { if(c == '\\') { i++; continue; } if(c == '"') inString = false; continue; } if(c == '"') inString = true; else if(c == '{') { if(depth == 0) start = i; depth++; } else if(c == '}') { depth--; if(depth == 0 && start >= 0) { int k = ArraySize(out); ArrayResize(out, k + 1); out[k] = StringSubstr(arr, start, i - start + 1); start = -1; } } } return ArraySize(out); } // Splits the contents of an array of strings into its strings. int JsonStrings(const string arr, string &out[]) { ArrayResize(out, 0); bool inString = false; string cur = ""; int n = StringLen(arr); for(int i = 0; i < n; i++) { ushort c = StringGetCharacter(arr, i); if(!inString) { if(c == '"') { inString = true; cur = ""; } continue; } if(c == '\\' && i + 1 < n) { cur += ShortToString(StringGetCharacter(arr, i + 1)); i++; continue; } if(c == '"') { int k = ArraySize(out); ArrayResize(out, k + 1); out[k] = cur; inString = false; continue; } cur += ShortToString(c); } return ArraySize(out); } //+------------------------------------------------------------------+ //| HTTP | //+------------------------------------------------------------------+ int HttpPost(const string path, const string body, string &response) { string headers = "Content-Type: application/json\r\n"; char data[]; int len = StringToCharArray(body, data, 0, WHOLE_ARRAY, CP_UTF8); if(len > 0) ArrayResize(data, len - 1); // drop the terminating NUL char result[]; string resultHeaders; ResetLastError(); int code = WebRequest("POST", BaseUrl() + path, headers, 10000, data, result, resultHeaders); if(code == -1) { int err = GetLastError(); response = ""; if(err == 4014 || err == 4060) g_status = "Allow WebRequest for " + HubOrigin() + " in Tools > Options > Expert Advisors"; else g_status = "Cannot reach the hub (error " + IntegerToString(err) + ") - retrying"; return -1; } response = CharArrayToString(result, 0, WHOLE_ARRAY, CP_UTF8); return code; } string Identity() { return "\"platform\":\"" + PLATFORM + "\",\"account\":\"" + IntegerToString(g_login) + "\"" + ",\"server\":" + Q(Truncate(AccountInfoString(ACCOUNT_SERVER), 64)) + ",\"v\":\"" + EA_VERSION + "\""; } //+------------------------------------------------------------------+ //| What this terminal remembers between restarts | //| | //| Per master order, one terminal global variable: | //| ..._k the ticket of the copy this account holds | //| ..._d finished or skipped: never touch it again | //| Without this, a copy that hit its stop here while the master's | //| order was still live would be opened a second time. | //| The terminal deletes a global variable four weeks after it was | //| last read. Finished ones are only read when the hub mentions the | //| order again, so they clear themselves out once it is history. | //+------------------------------------------------------------------+ string GvBase() { return GV_PREFIX + IntegerToString(g_login) + "_"; } string GvOrder(const long id) { return GvBase() + "k" + IntegerToString(id); } string GvDone(const long id) { return GvBase() + "d" + IntegerToString(id); } // > 0: the ticket of our copy. -1: finished or skipped. 0: never seen. double MemGet(const long id) { string name = GvOrder(id); if(GlobalVariableCheck(name)) return GlobalVariableGet(name); return GlobalVariableCheck(GvDone(id)) ? -1 : 0; } void MemSet(const long id, const double value) { if(value > 0) { GlobalVariableDel(GvDone(id)); GlobalVariableSet(GvOrder(id), value); return; } GlobalVariableDel(GvOrder(id)); GlobalVariableSet(GvDone(id), 1); } string TokenFile() { return "FTISignalCopier_" + IntegerToString(g_login) + ".dat"; } void SaveSession() { int h = FileOpen(TokenFile(), FILE_WRITE | FILE_TXT | FILE_ANSI); if(h == INVALID_HANDLE) return; FileWrite(h, KeyTyped()); FileWrite(h, g_token); FileClose(h); } void LoadSession() { g_token = ""; int h = FileOpen(TokenFile(), FILE_READ | FILE_TXT | FILE_ANSI); if(h == INVALID_HANDLE) return; string key = Trim(FileReadString(h)); string token = Trim(FileReadString(h)); FileClose(h); // A different key in the inputs means a different licence: start afresh. if(key == KeyTyped() && StringLen(token) == 64) g_token = token; } long IdFromComment(const string comment) { if(StringFind(comment, TAG) != 0) return 0; long id = 0; int n = StringLen(comment); for(int i = StringLen(TAG); i < n; i++) { ushort c = StringGetCharacter(comment, i); if(c < '0' || c > '9') break; id = id * 10 + (c - '0'); } return id; } //+------------------------------------------------------------------+ //| This account's copies | //+------------------------------------------------------------------+ // Finds the copy of master order `id`: a pending order or a position. bool FindLocal(const long id, ulong &ticket, bool &pending) { double mem = MemGet(id); if(mem > 0) { ulong t = (ulong)mem; if(PositionSelectByTicket(t)) { ticket = t; pending = false; return true; } if(OrderSelect(t)) { ticket = t; pending = true; return true; } } // The memory may be gone (a new terminal): the comment still says whose copy it is. for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong t = PositionGetTicket(i); if(t == 0 || PositionGetInteger(POSITION_MAGIC) != InpMagic) continue; if(IdFromComment(PositionGetString(POSITION_COMMENT)) != id) continue; ticket = t; pending = false; MemSet(id, (double)t); return true; } for(int i = OrdersTotal() - 1; i >= 0; i--) { ulong t = OrderGetTicket(i); if(t == 0 || OrderGetInteger(ORDER_MAGIC) != InpMagic) continue; if(IdFromComment(OrderGetString(ORDER_COMMENT)) != id) continue; ticket = t; pending = true; MemSet(id, (double)t); return true; } return false; } int CountOwn() { int count = 0; for(int i = PositionsTotal() - 1; i >= 0; i--) if(PositionGetTicket(i) != 0 && PositionGetInteger(POSITION_MAGIC) == InpMagic) count++; for(int i = OrdersTotal() - 1; i >= 0; i--) if(OrderGetTicket(i) != 0 && OrderGetInteger(ORDER_MAGIC) == InpMagic) count++; return count; } void AddId(long &ids[], const long id) { if(id <= 0) return; for(int i = ArraySize(ids) - 1; i >= 0; i--) if(ids[i] == id) return; int n = ArraySize(ids); ArrayResize(ids, n + 1); ids[n] = id; } // The master orders this account currently holds a copy of. void HeldIds(long &ids[]) { ArrayResize(ids, 0); string base = GvBase() + "k"; int baseLen = StringLen(base); // Names first: marking one as finished changes the list being walked. string names[]; for(int i = GlobalVariablesTotal() - 1; i >= 0; i--) { string name = GlobalVariableName(i); if(StringFind(name, base) != 0) continue; int n = ArraySize(names); ArrayResize(names, n + 1); names[n] = name; } for(int i = 0; i < ArraySize(names); i++) { double mem = GlobalVariableGet(names[i]); long id = StringToInteger(StringSubstr(names[i], baseLen)); if(mem <= 0 || id <= 0) continue; ulong t = (ulong)mem; if(PositionSelectByTicket(t) || OrderSelect(t)) AddId(ids, id); else MemSet(id, -1); // it closed here: done with it } for(int i = PositionsTotal() - 1; i >= 0; i--) if(PositionGetTicket(i) != 0 && PositionGetInteger(POSITION_MAGIC) == InpMagic) AddId(ids, IdFromComment(PositionGetString(POSITION_COMMENT))); for(int i = OrdersTotal() - 1; i >= 0; i--) if(OrderGetTicket(i) != 0 && OrderGetInteger(ORDER_MAGIC) == InpMagic) AddId(ids, IdFromComment(OrderGetString(ORDER_COMMENT))); g_held = ArraySize(ids); } //+------------------------------------------------------------------+ //| Symbols: the master's name -> this broker's | //+------------------------------------------------------------------+ bool SymbolUsable(const string name) { if(name == "") return false; if(!SymbolSelect(name, true)) return false; // also puts it in Market Watch, so it gets prices return SymbolInfoInteger(name, SYMBOL_TRADE_MODE) != SYMBOL_TRADE_MODE_DISABLED; } // Works out what this broker adds around symbol names, from EURUSD. void DetectAffixes() { g_prefix = Trim(InpSymbolPrefix); g_suffix = Trim(InpSymbolSuffix); if(g_prefix != "" || g_suffix != "") return; if(SymbolSelect("EURUSD", true)) return; string firstPrefix = ""; string firstSuffix = ""; bool found = false; int total = SymbolsTotal(false); for(int i = 0; i < total; i++) { string name = SymbolName(i, false); int p = StringFind(name, "EURUSD"); if(p < 0) continue; string prefix = StringSubstr(name, 0, p); string suffix = StringSubstr(name, p + 6); if(!found) { firstPrefix = prefix; firstSuffix = suffix; found = true; } // Prefer the variant the chart this EA sits on belongs to. int tail = StringLen(_Symbol) - StringLen(suffix); if(StringFind(_Symbol, prefix) == 0 && tail >= 0 && StringSubstr(_Symbol, tail) == suffix) { g_prefix = prefix; g_suffix = suffix; return; } } if(found) { g_prefix = firstPrefix; g_suffix = firstSuffix; } } // "A=B;C=D" (or commas): the value for `key`, or "". string MapLookup(const string map, const string key) { string text = map; StringReplace(text, ",", ";"); string pairs[]; int n = StringSplit(text, ';', pairs); for(int i = 0; i < n; i++) { int eq = StringFind(pairs[i], "="); if(eq <= 0) continue; if(Upper(Trim(StringSubstr(pairs[i], 0, eq))) == Upper(key)) return Trim(StringSubstr(pairs[i], eq + 1)); } return ""; } bool InList(const string list, const string name) { string text = list; StringReplace(text, ";", ","); string items[]; int n = StringSplit(text, ',', items); for(int i = 0; i < n; i++) if(Upper(Trim(items[i])) == Upper(name)) return true; return false; } bool SymbolWanted(const string master) { if(Trim(InpOnlySymbols) != "" && !InList(InpOnlySymbols, master)) return false; return !InList(InpSkipSymbols, master); } string Resolve(FtiOrder &o) { for(int i = ArraySize(g_symFrom) - 1; i >= 0; i--) if(g_symFrom[i] == o.symbol) return g_symTo[i]; string found = ""; string mapped = MapLookup(InpSymbolMap, o.symbol); if(mapped != "") { // The user's own choice is final: if it doesn't exist, say so rather than guess. if(SymbolUsable(mapped)) found = mapped; } else { int n = ArraySize(o.alts); for(int i = 0; i < n && found == ""; i++) if(SymbolUsable(g_prefix + o.alts[i] + g_suffix)) found = g_prefix + o.alts[i] + g_suffix; if(g_prefix != "" || g_suffix != "") for(int i = 0; i < n && found == ""; i++) if(SymbolUsable(o.alts[i])) found = o.alts[i]; } if(found == "") return ""; int k = ArraySize(g_symFrom); ArrayResize(g_symFrom, k + 1); ArrayResize(g_symTo, k + 1); g_symFrom[k] = o.symbol; g_symTo[k] = found; return found; } double NormPrice(const string sym, const double price) { if(price <= 0) return 0; double tick = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); double p = tick > 0 ? MathRound(price / tick) * tick : price; return NormalizeDouble(p, (int)SymbolInfoInteger(sym, SYMBOL_DIGITS)); } bool Differs(const double a, const double b, const double point) { return MathAbs(a - b) > point / 2.0; } //+------------------------------------------------------------------+ //| Trade size | //+------------------------------------------------------------------+ double Lots(const string sym, const double entry, const double sl, string &why) { double minLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN); double maxLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX); double step = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP); if(minLot <= 0) { why = "no lot information for " + sym; return 0; } if(step <= 0) step = minLot; double lots = InpLotValue; if(InpLotMode == FTI_LOT_PER_1000) lots = InpLotValue * AccountInfoDouble(ACCOUNT_BALANCE) / 1000.0; else if(InpLotMode == FTI_LOT_RISK) { double tickValue = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE_LOSS); if(tickValue <= 0) tickValue = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_VALUE); double tickSize = SymbolInfoDouble(sym, SYMBOL_TRADE_TICK_SIZE); double distance = MathAbs(entry - sl); if(sl <= 0 || distance <= 0 || tickValue <= 0 || tickSize <= 0) { why = "sizing by risk needs a stop loss"; return 0; } double lossPerLot = distance / tickSize * tickValue; lots = AccountInfoDouble(ACCOUNT_BALANCE) * InpLotValue / 100.0 / lossPerLot; } lots = MathFloor(lots / step + 0.0000001) * step; if(lots < minLot) { // Rounding a risk-sized trade UP would risk more than was asked for. if(InpLotMode == FTI_LOT_RISK) { why = "the risk setting allows less than the smallest lot (" + DoubleToString(minLot, 2) + ")"; return 0; } lots = minLot; } double cap = maxLot; if(InpMaxLot > 0 && InpMaxLot < cap) cap = InpMaxLot; if(lots > cap) lots = MathFloor(cap / step + 0.0000001) * step; if(lots < minLot) { why = "the maximum lot is below the broker's minimum"; return 0; } return NormalizeDouble(lots, 8); } //+------------------------------------------------------------------+ //| Failed attempts | //+------------------------------------------------------------------+ // Counts a failure for this version of the order; true once it has failed too often. bool TooManyAttempts(const long id, const long seq) { int n = ArraySize(g_tryId); for(int i = 0; i < n; i++) { if(g_tryId[i] != id) continue; if(g_trySeq[i] != seq) { g_trySeq[i] = seq; g_tryCount[i] = 0; } g_tryCount[i]++; return g_tryCount[i] >= MAX_ATTEMPTS; } ArrayResize(g_tryId, n + 1); ArrayResize(g_trySeq, n + 1); ArrayResize(g_tryCount, n + 1); g_tryId[n] = id; g_trySeq[n] = seq; g_tryCount[n] = 1; return false; } bool GaveUpChanging(const long id, const long seq) { for(int i = ArraySize(g_tryId) - 1; i >= 0; i--) if(g_tryId[i] == id && g_trySeq[i] == seq && g_tryCount[i] >= MAX_ATTEMPTS) return true; return false; } // A refusal that says nothing about the order itself: try again, don't count it. bool Passing(const uint rc) { return rc == TRADE_RETCODE_REQUOTE || rc == TRADE_RETCODE_PRICE_CHANGED || rc == TRADE_RETCODE_PRICE_OFF || rc == TRADE_RETCODE_TIMEOUT || rc == TRADE_RETCODE_CONNECTION || rc == TRADE_RETCODE_TOO_MANY_REQUESTS || rc == TRADE_RETCODE_LOCKED || rc == TRADE_RETCODE_FROZEN || rc == TRADE_RETCODE_MARKET_CLOSED || rc == TRADE_RETCODE_TRADE_DISABLED || rc == TRADE_RETCODE_SERVER_DISABLES_AT || rc == TRADE_RETCODE_CLIENT_DISABLES_AT; } bool Done(const uint rc) { return rc == TRADE_RETCODE_DONE || rc == TRADE_RETCODE_PLACED || rc == TRADE_RETCODE_DONE_PARTIAL; } string RcText() { return (g_rcText != "" ? g_rcText : "refused") + " (" + IntegerToString(g_rc) + ")"; } // Sends one trade request. Brokers differ in the fill policy they accept // for a symbol, so the likely ones are tried in turn. bool Send(MqlTradeRequest &req, const bool atMarket) { ENUM_ORDER_TYPE_FILLING fills[3]; if(atMarket) { fills[0] = ORDER_FILLING_FOK; fills[1] = ORDER_FILLING_IOC; fills[2] = ORDER_FILLING_RETURN; } else { fills[0] = ORDER_FILLING_RETURN; fills[1] = ORDER_FILLING_FOK; fills[2] = ORDER_FILLING_IOC; } req.magic = (ulong)InpMagic; for(int i = 0; i < 3; i++) { MqlTradeResult res; ZeroMemory(res); req.type_filling = fills[i]; ResetLastError(); bool sent = OrderSend(req, res); g_rc = res.retcode; g_rcText = res.comment; g_rcOrder = res.order; if(g_rc == 0 && !sent) g_rcText = "request rejected by the terminal, error " + IntegerToString(GetLastError()); if(g_rc != TRADE_RETCODE_INVALID_FILL) return sent && Done(g_rc); } return false; } string Label(FtiOrder &o) { return "#" + IntegerToString(o.id) + " " + o.side + " " + o.symbol; } // Results of handling one order: 1 = nothing more to do, 0 = come back to it. int GiveUp(FtiOrder &o, const string why) { MemSet(o.id, -1); Note(Label(o) + " not copied: " + why); return 1; } int Later(FtiOrder &o, const string why) { g_lastNote = Clock() + " " + Label(o) + " waiting: " + why; return 0; } //+------------------------------------------------------------------+ //| Opening a copy | //+------------------------------------------------------------------+ int EntryFailed(FtiOrder &o) { string why = RcText(); if(Passing(g_rc)) return Later(o, why); if(TooManyAttempts(o.id, o.seq)) return GiveUp(o, why); return Later(o, why); } int PlaceEntry(FtiOrder &o) { if(!SymbolWanted(o.symbol)) return GiveUp(o, "not in your symbol lists"); string sym = Resolve(o); if(sym == "") return GiveUp(o, "no symbol for " + o.symbol + " at this broker (add it to the symbol map input)"); double bid = SymbolInfoDouble(sym, SYMBOL_BID); double ask = SymbolInfoDouble(sym, SYMBOL_ASK); if(bid <= 0 || ask <= 0) return Later(o, "no price for " + sym + " yet"); bool late = o.state == "filled"; double level = (late && o.fill > 0) ? o.fill : o.price; double mid = (bid + ask) / 2.0; if(level <= 0) return GiveUp(o, "the signal has no entry price"); if(MathAbs(level - mid) / mid * 100.0 > InpMaxPriceGapPct) return GiveUp(o, sym + " is at " + DoubleToString(mid, (int)SymbolInfoInteger(sym, SYMBOL_DIGITS)) + " but the signal is for " + DoubleToString(level, 5) + ": not the same instrument?"); if(CountOwn() >= InpMaxOpenTrades) return Later(o, "the maximum number of open trades is reached"); string why = ""; double lots = Lots(sym, o.price, o.sl, why); if(lots <= 0) return GiveUp(o, why); bool buy = o.side == "buy"; double price = NormPrice(sym, o.price); double sl = NormPrice(sym, o.sl); double tp = NormPrice(sym, o.tp); double gap = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL) * SymbolInfoDouble(sym, SYMBOL_POINT); string comment = TAG + IntegerToString(o.id); bool atMarket = late; if(late && o.filledAgo > InpLateEntrySeconds) return GiveUp(o, "the master entered " + IntegerToString(o.filledAgo) + "s ago, too late to join"); if(!late) { bool placeable; if(o.type == "limit") placeable = buy ? (price < ask - gap) : (price > bid + gap); else placeable = buy ? (price > ask + gap) : (price < bid - gap); if(placeable) { ENUM_ORDER_TYPE kind; if(o.type == "limit") kind = buy ? ORDER_TYPE_BUY_LIMIT : ORDER_TYPE_SELL_LIMIT; else kind = buy ? ORDER_TYPE_BUY_STOP : ORDER_TYPE_SELL_STOP; // Good-till-cancelled where the symbol allows it: the master's own cancel removes it. ENUM_ORDER_TYPE_TIME life = ORDER_TIME_GTC; if((SymbolInfoInteger(sym, SYMBOL_EXPIRATION_MODE) & SYMBOL_EXPIRATION_GTC) == 0) life = ORDER_TIME_DAY; MqlTradeRequest req; ZeroMemory(req); req.action = TRADE_ACTION_PENDING; req.symbol = sym; req.type = kind; req.volume = lots; req.price = price; req.sl = sl; req.tp = tp; req.type_time = life; req.comment = comment; if(Send(req, false)) { MemSet(o.id, g_rcOrder > 0 ? (double)g_rcOrder : 1.0); Did("placed " + o.side + " " + o.type + " " + sym + " " + DoubleToString(lots, 2) + " at " + DoubleToString(price, (int)SymbolInfoInteger(sym, SYMBOL_DIGITS)) + " (#" + IntegerToString(o.id) + ")"); return 1; } return EntryFailed(o); } // The market is already at or through the entry: the order would // have triggered, so join at market if the price is still close. atMarket = true; } if(atMarket) { double now = buy ? ask : bid; double slip = MathAbs(now - level) / level * 100.0; if(slip > InpLateEntrySlipPct) { string moved = "price is " + DoubleToString(slip, 2) + "% from the entry"; if(late) return GiveUp(o, moved); return Later(o, moved); } if(sl > 0 && (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 && (buy ? (now >= tp) : (now <= tp))) return late ? GiveUp(o, "price is already beyond the target") : Later(o, "price is beyond the target"); MqlTradeRequest req; ZeroMemory(req); req.action = TRADE_ACTION_DEAL; req.symbol = sym; req.type = buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL; req.volume = lots; req.price = now; req.sl = sl; req.tp = tp; req.deviation = 50; req.comment = comment; if(Send(req, true)) { MemSet(o.id, g_rcOrder > 0 ? (double)g_rcOrder : 1.0); // 1 = "placed": FindLocal picks the ticket up from the comment Did("opened " + o.side + " " + sym + " " + DoubleToString(lots, 2) + " at market (#" + IntegerToString(o.id) + ")"); return 1; } return EntryFailed(o); } return 1; } //+------------------------------------------------------------------+ //| Keeping a copy in step: entry, stop and target | //+------------------------------------------------------------------+ int EnsureLevels(FtiOrder &o, const ulong ticket, const bool pending) { if(GaveUpChanging(o.id, o.seq)) return 1; if(pending) { if(!OrderSelect(ticket)) return 1; string sym = OrderGetString(ORDER_SYMBOL); double point = SymbolInfoDouble(sym, SYMBOL_POINT); double have = OrderGetDouble(ORDER_PRICE_OPEN); // Once the master is in, the entry no longer moves: leave ours where it is. double wantPrice = o.state == "working" ? NormPrice(sym, o.price) : have; double wantSl = NormPrice(sym, o.sl); double wantTp = NormPrice(sym, o.tp); if(!Differs(have, wantPrice, point) && !Differs(OrderGetDouble(ORDER_SL), wantSl, point) && !Differs(OrderGetDouble(ORDER_TP), wantTp, point)) return 1; MqlTradeRequest req; ZeroMemory(req); req.action = TRADE_ACTION_MODIFY; req.order = ticket; req.symbol = sym; req.price = wantPrice; req.sl = wantSl; req.tp = wantTp; req.type_time = (ENUM_ORDER_TYPE_TIME)OrderGetInteger(ORDER_TYPE_TIME); req.expiration = (datetime)OrderGetInteger(ORDER_TIME_EXPIRATION); if(Send(req, false)) { Did("moved " + Label(o) + " to the master's levels"); return 1; } } else { if(!PositionSelectByTicket(ticket)) return 1; string sym = PositionGetString(POSITION_SYMBOL); double point = SymbolInfoDouble(sym, SYMBOL_POINT); double wantSl = NormPrice(sym, o.sl); double wantTp = NormPrice(sym, o.tp); if(!Differs(PositionGetDouble(POSITION_SL), wantSl, point) && !Differs(PositionGetDouble(POSITION_TP), wantTp, point)) return 1; MqlTradeRequest req; ZeroMemory(req); req.action = TRADE_ACTION_SLTP; req.position = ticket; req.symbol = sym; req.sl = wantSl; req.tp = wantTp; if(Send(req, false)) { Did("moved the stop/target of " + Label(o)); return 1; } } if(g_rc == TRADE_RETCODE_NO_CHANGES) return 1; string why = "could not move it: " + RcText(); if(!Passing(g_rc) && TooManyAttempts(o.id, o.seq)) { Note(Label(o) + " " + why + ". Left as it is."); return 1; } return Later(o, why); } bool DeletePending(const ulong ticket) { MqlTradeRequest req; ZeroMemory(req); req.action = TRADE_ACTION_REMOVE; req.order = ticket; return Send(req, false); } int RemovePending(FtiOrder &o, const ulong ticket, const string reason) { if(DeletePending(ticket)) { MemSet(o.id, -1); Did("cancelled " + Label(o) + ": " + reason); return 1; } // Gone already (it may have just triggered): look again next time. return Later(o, "could not cancel: " + RcText()); } int ClosePosition(FtiOrder &o, const ulong ticket) { if(!PositionSelectByTicket(ticket)) { MemSet(o.id, -1); return 1; } string sym = PositionGetString(POSITION_SYMBOL); bool isBuy = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY; MqlTradeRequest req; ZeroMemory(req); req.action = TRADE_ACTION_DEAL; req.position = ticket; // closes this position rather than opening an opposite one req.symbol = sym; req.type = isBuy ? ORDER_TYPE_SELL : ORDER_TYPE_BUY; req.volume = PositionGetDouble(POSITION_VOLUME); req.price = isBuy ? SymbolInfoDouble(sym, SYMBOL_BID) : SymbolInfoDouble(sym, SYMBOL_ASK); req.deviation = 50; if(Send(req, true)) { MemSet(o.id, -1); Did("closed " + Label(o) + " with the master"); return 1; } return Later(o, "could not close: " + RcText()); } //+------------------------------------------------------------------+ //| One master order -> what this account should hold | //+------------------------------------------------------------------+ int Apply(FtiOrder &o) { ulong ticket = 0; bool pending = false; bool have = FindLocal(o.id, ticket, pending); double mem = MemGet(o.id); if(o.state == "working" || o.state == "filled") { if(have) return EnsureLevels(o, ticket, pending); if(mem == 0) return PlaceEntry(o); // It was copied and is no longer here: it ran its course on this account. if(mem > 0) MemSet(o.id, -1); return 1; } if(o.state == "cancelled") { if(have && pending) return RemovePending(o, ticket, "the master cancelled"); // Our copy triggered although the master's never did: it keeps its own stop and target. if(have) Note(Label(o) + " was cancelled by the master after it triggered here. It keeps its stop and target."); MemSet(o.id, -1); return 1; } if(o.state == "closed") { if(have && pending) return RemovePending(o, ticket, "the master's trade is over"); if(have && InpFollowCloses) return ClosePosition(o, ticket); MemSet(o.id, -1); return 1; } return 1; } void ReadOrder(const string json, FtiOrder &o) { o.id = (long)JsonGetNumber(json, "id"); o.seq = (long)JsonGetNumber(json, "seq"); o.symbol = JsonGetString(json, "symbol"); o.side = JsonGetString(json, "side"); o.type = JsonGetString(json, "type"); o.state = JsonGetString(json, "state"); o.price = JsonGetNumber(json, "price"); o.sl = JsonGetNumber(json, "sl"); o.tp = JsonGetNumber(json, "tp"); o.fill = JsonGetNumber(json, "fill"); o.filledAgo = (long)JsonGetNumber(json, "filledAgo"); JsonStrings(JsonGetArray(json, "alt"), o.alts); if(ArraySize(o.alts) == 0) { ArrayResize(o.alts, 1); o.alts[0] = o.symbol; } } //+------------------------------------------------------------------+ //| Talking to the hub | //+------------------------------------------------------------------+ void Block(const string message) { g_blocked = true; g_status = message; Alert("FTI Signal Copier: ", message); } void Activate() { string body = "{\"p\":1,\"key\":" + Q(KeyTyped()) + "," + Identity() + ",\"company\":" + Q(Truncate(AccountInfoString(ACCOUNT_COMPANY), 128)) + "}"; string resp; int code = HttpPost("/v1/activate", body, resp); string message = JsonGetString(resp, "message"); if(code == 200 && StringLen(JsonGetString(resp, "token")) == 64) { g_token = JsonGetString(resp, "token"); g_needActivate = false; g_cursor = 0; // a new session starts from the whole picture g_nextSyncAt = 0; SaveSession(); Print("FTI Signal Copier: licence accepted for account ", g_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. g_status = message != "" ? message : "This licence is set to a different trading account. Change it on your licence page."; g_nextActivateAt = TimeLocal() + 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 (" + IntegerToString(code) + ")."); return; } if(code == 402 || code == 429) { g_status = message != "" ? message : "The licence cannot be started right now."; g_nextActivateAt = TimeLocal() + 600; return; } if(code != -1) g_status = "The hub is unavailable (HTTP " + IntegerToString(code) + ") - retrying"; g_nextActivateAt = TimeLocal() + 30; } void Sync() { datetime now = TimeLocal(); bool full = g_cursor <= 0 || now >= g_nextFullAt; long held[]; HeldIds(held); string heldJson = "["; for(int i = 0; i < ArraySize(held); i++) heldJson += (i > 0 ? "," : "") + IntegerToString(held[i]); heldJson += "]"; string body = "{\"p\":1,\"token\":\"" + g_token + "\"," + Identity() + ",\"cursor\":" + IntegerToString(full ? 0 : g_cursor) + ",\"held\":" + heldJson + "}"; string resp; int code = HttpPost("/v1/sync", body, resp); string error = JsonGetString(resp, "error"); string message = JsonGetString(resp, "message"); if(code == 200) { g_failStreak = 0; g_lastOkAt = now; int poll = (int)JsonGetNumber(resp, "poll"); // The hub says how often to ask. The input can only make it less often. g_pollSec = poll > 0 ? poll : 5; if(InpPollSeconds > g_pollSec) g_pollSec = InpPollSeconds; if(g_pollSec < 2) g_pollSec = 2; g_nextSyncAt = now + g_pollSec; string licence = JsonGetString(resp, "licence"); long expires = (long)(JsonGetNumber(resp, "expires") / 1000.0); int daysLeft = (int)JsonGetNumber(resp, "daysLeft"); string until = expires > 0 ? TimeToString((datetime)expires, TIME_DATE) : ""; if(licence == "active") { g_status = "Copying"; g_licence = "Licence active" + (until != "" ? " until " + until + " (" + IntegerToString(daysLeft) + " days left)" : ""); } else { g_status = "Licence expired: no new trades. Open trades are still closed with the master."; g_licence = "Expired " + until + ". Renew to carry on copying."; } bool complete = true; string objects[]; int n = JsonObjects(JsonGetArray(resp, "orders"), objects); for(int i = 0; i < n; i++) { FtiOrder o; ReadOrder(objects[i], o); if(o.id <= 0) continue; if(Apply(o) == 0) complete = false; } // Copies the hub has no record of: cancel what has not triggered, leave the rest. string unknown[]; StringSplit(JsonGetArray(resp, "unknown"), ',', unknown); for(int i = 0; i < ArraySize(unknown); i++) { long id = StringToInteger(Trim(unknown[i])); if(id <= 0) continue; ulong ticket = 0; bool pending = false; if(FindLocal(id, ticket, pending) && pending) DeletePending(ticket); MemSet(id, -1); } // Only move on once everything in this answer is dealt with: // otherwise the same orders come again next time. if(complete) { g_cursor = (long)JsonGetNumber(resp, "cursor"); GlobalVariableSet(GvBase() + "cursor", (double)g_cursor); } if(full) g_nextFullAt = now + 300; 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. g_token = ""; g_needActivate = true; g_nextActivateAt = 0; return; } if(code == 403) { Block(message != "" ? message : "The hub refused this licence (" + error + ")."); return; } if(code == 402) { g_status = message != "" ? message : "The licence has expired."; g_licence = "Expired"; g_nextSyncAt = now + 600; // renewing the same key brings it back return; } g_failStreak++; int wait = (int)MathMin(60, 5 * MathPow(2, MathMin(g_failStreak, 4))); g_nextSyncAt = now + wait; if(code != -1) g_status = "The hub is unavailable (HTTP " + IntegerToString(code) + ") - retrying in " + IntegerToString(wait) + "s"; } //+------------------------------------------------------------------+ //| Terminal readiness | //+------------------------------------------------------------------+ bool TerminalReady() { if(!TerminalInfoInteger(TERMINAL_CONNECTED)) { g_connectedSince = 0; g_status = "Waiting for the trade server connection"; return false; } if(g_connectedSince == 0) g_connectedSince = TimeLocal(); if(TimeLocal() - g_connectedSince < 3) return false; if(AccountInfoInteger(ACCOUNT_LOGIN) <= 0) return false; if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) || !MQLInfoInteger(MQL_TRADE_ALLOWED)) { g_status = "Algo Trading is off: switch it on (toolbar button, and in this EA's settings)"; return false; } if(!AccountInfoInteger(ACCOUNT_TRADE_EXPERT) || !AccountInfoInteger(ACCOUNT_TRADE_ALLOWED)) { g_status = "This account does not allow trading by Expert Advisors"; return false; } return true; } void ResetForAccount() { g_login = AccountInfoInteger(ACCOUNT_LOGIN); LoadSession(); g_needActivate = g_token == ""; g_blocked = false; string cursorName = GvBase() + "cursor"; g_cursor = GlobalVariableCheck(cursorName) ? (long)GlobalVariableGet(cursorName) : 0; g_nextActivateAt = 0; g_nextSyncAt = 0; g_nextFullAt = 0; // the first check after a start is always a full one ArrayResize(g_symFrom, 0); ArrayResize(g_symTo, 0); DetectAffixes(); } void ShowStatus() { string s = "FTI Signal Copier " + EA_VERSION + " " + PLATFORM + " " + IntegerToString(g_login) + "\n" + g_status + "\n"; if(g_licence != "") s += g_licence + "\n"; if(g_lastOkAt > 0) s += "Holding " + IntegerToString(g_held) + " copied trades. Last check " + TimeToString(g_lastOkAt, TIME_SECONDS) + "\n"; if(g_lastAction != "") s += "Last: " + g_lastAction + "\n"; if(g_lastNote != "") s += "Note: " + g_lastNote + "\n"; Comment(s); } //+------------------------------------------------------------------+ //| Event handlers | //+------------------------------------------------------------------+ int OnInit() { if(MQLInfoInteger(MQL_TESTER)) { Print("FTI Signal Copier copies live trades; it does nothing in the Strategy Tester."); return INIT_FAILED; } string url = BaseUrl(); if(StringFind(url, "https://") != 0 && StringFind(url, "http://127.0.0.1") != 0 && StringFind(url, "http://localhost") != 0) { Alert("FTI Signal Copier: the Hub URL must start with https://"); return INIT_PARAMETERS_INCORRECT; } if(StringLen(KeyTyped()) < 20) { Alert("FTI Signal Copier: paste your licence key into the EA inputs."); return INIT_PARAMETERS_INCORRECT; } if(InpLotValue <= 0) { Alert("FTI Signal Copier: the lot value must be greater than zero."); return INIT_PARAMETERS_INCORRECT; } if(AccountInfoInteger(ACCOUNT_MARGIN_MODE) != ACCOUNT_MARGIN_MODE_RETAIL_HEDGING) { // On a netting account the two parts of one signal would merge into // one position with one target. Refuse rather than copy it wrongly. Alert("FTI Signal Copier needs a hedging account. This account nets positions, so it cannot hold the two parts of a signal separately."); return INIT_FAILED; } ResetForAccount(); EventSetTimer(1); ShowStatus(); return INIT_SUCCEEDED; } void OnDeinit(const int reason) { EventKillTimer(); // Removing the EA stops copying. It never closes anything on the way // out: open copies keep their stops and targets. Comment(""); } void OnTimer() { if(g_blocked) { ShowStatus(); return; } if(!TerminalReady()) { ShowStatus(); return; } if(AccountInfoInteger(ACCOUNT_LOGIN) != g_login) ResetForAccount(); datetime now = TimeLocal(); if(g_needActivate) { if(now >= g_nextActivateAt) Activate(); ShowStatus(); if(g_needActivate || g_blocked) return; } if(now >= g_nextSyncAt) Sync(); ShowStatus(); } //+------------------------------------------------------------------+