//+------------------------------------------------------------------+ //| FTISignalCopier.mq4 | //| | //| Copies the trades of the Freemium Trade Ideas master account | //| onto THIS MetaTrader 4 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 live 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. | //+------------------------------------------------------------------+ #property copyright "Freemium Trade Ideas" #property version "1.00" #property description "Copies the FTI master account's trades onto this account." #property strict #define EA_VERSION "1.00" #define PLATFORM "MT4" #define TAG "FTI#" #define GV_PREFIX "FTIC_" #define MAX_ATTEMPTS 5 #define SLIPPAGE 50 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 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 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 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 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 int 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[]; }; //--- 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, int &ticket, bool &pending) { double mem = MemGet(id); if(mem > 0) { int t = (int)mem; if(OrderSelect(t, SELECT_BY_TICKET) && OrderCloseTime() == 0) { ticket = t; pending = OrderType() > OP_SELL; return true; } } // The memory may be gone (a new terminal): the comment still says whose copy it is. for(int i = OrdersTotal() - 1; i >= 0; i--) { if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue; if(OrderMagicNumber() != InpMagic) continue; if(IdFromComment(OrderComment()) != id) continue; ticket = OrderTicket(); pending = OrderType() > OP_SELL; MemSet(id, (double)ticket); return true; } return false; } int CountOwn() { int count = 0; for(int i = OrdersTotal() - 1; i >= 0; i--) if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderMagicNumber() == 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; if(OrderSelect((int)mem, SELECT_BY_TICKET) && OrderCloseTime() == 0) AddId(ids, id); else MemSet(id, -1); // it closed here: done with it } for(int i = OrdersTotal() - 1; i >= 0; i--) if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderMagicNumber() == InpMagic) AddId(ids, IdFromComment(OrderComment())); 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 MarketInfo(name, MODE_POINT) > 0; } // 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 = MarketInfo(sym, MODE_TICKSIZE); double p = tick > 0 ? MathRound(price / tick) * tick : price; return NormalizeDouble(p, (int)MarketInfo(sym, MODE_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 = MarketInfo(sym, MODE_MINLOT); double maxLot = MarketInfo(sym, MODE_MAXLOT); double step = MarketInfo(sym, MODE_LOTSTEP); 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 = MarketInfo(sym, MODE_TICKVALUE); double tickSize = MarketInfo(sym, MODE_TICKSIZE); 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 int err) { return err == 4 || err == 6 || err == 8 || err == 128 || err == 129 || err == 132 || err == 133 || err == 135 || err == 136 || err == 137 || err == 138 || err == 139 || err == 141 || err == 146 || err == 4109 || err == 4110 || err == 4111; } string ErrorText(const int err) { switch(err) { case 4: return "trade server busy"; case 6: return "no connection"; case 8: return "too many requests"; case 128: return "trade timeout"; case 129: return "invalid price"; case 130: return "invalid stops"; case 131: return "invalid lot size"; case 132: return "market closed"; case 133: return "trading disabled for this symbol"; case 134: return "not enough money"; case 135: return "price changed"; case 136: return "no quotes"; case 138: return "requote"; case 139: return "order locked"; case 145: return "too close to the market to change"; case 146: return "trade context busy"; case 148: return "too many orders at the broker"; case 149: return "hedging not allowed"; case 4109: return "live trading is not allowed for this EA"; case 4110: return "buying is not allowed for this EA"; case 4111: return "selling is not allowed for this EA"; } return "error"; } 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, const int err) { string why = ErrorText(err) + " (" + IntegerToString(err) + ")"; if(Passing(err)) 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)"); RefreshRates(); double bid = MarketInfo(sym, MODE_BID); double ask = MarketInfo(sym, MODE_ASK); if(bid <= 0 || ask <= 0) return Later(o, "no price for " + sym + " yet"); int digits = (int)MarketInfo(sym, MODE_DIGITS); 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, 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 = MarketInfo(sym, MODE_STOPLEVEL) * MarketInfo(sym, MODE_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) { int kind; if(o.type == "limit") kind = buy ? OP_BUYLIMIT : OP_SELLLIMIT; else kind = buy ? OP_BUYSTOP : OP_SELLSTOP; ResetLastError(); // No expiry: the master's own cancel removes it. int ticket = OrderSend(sym, kind, lots, price, 0, sl, tp, comment, InpMagic, 0, clrNONE); if(ticket > 0) { MemSet(o.id, (double)ticket); Did("placed " + o.side + " " + o.type + " " + sym + " " + DoubleToString(lots, 2) + " at " + DoubleToString(price, digits) + " (#" + IntegerToString(o.id) + ")"); return 1; } return EntryFailed(o, GetLastError()); } // 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"); int kind = buy ? OP_BUY : OP_SELL; ResetLastError(); int ticket = OrderSend(sym, kind, lots, NormalizeDouble(now, digits), SLIPPAGE, sl, tp, comment, InpMagic, 0, clrNONE); int err = ticket > 0 ? 0 : GetLastError(); if(ticket <= 0 && err == 130) { // Some accounts take a market order only without stops: open it, then add them. ResetLastError(); ticket = OrderSend(sym, kind, lots, NormalizeDouble(now, digits), SLIPPAGE, 0, 0, comment, InpMagic, 0, clrNONE); err = ticket > 0 ? 0 : GetLastError(); if(ticket > 0 && OrderSelect(ticket, SELECT_BY_TICKET)) if(!OrderModify(ticket, OrderOpenPrice(), sl, tp, 0, clrNONE)) Note(Label(o) + " opened WITHOUT its stop and target (" + ErrorText(GetLastError()) + "). The copier will keep trying to set them."); } if(ticket > 0) { MemSet(o.id, (double)ticket); Did("opened " + o.side + " " + sym + " " + DoubleToString(lots, 2) + " at market (#" + IntegerToString(o.id) + ")"); return 1; } return EntryFailed(o, err); } return 1; } //+------------------------------------------------------------------+ //| Keeping a copy in step: entry, stop and target | //+------------------------------------------------------------------+ int EnsureLevels(FtiOrder &o, const int ticket, const bool pending) { if(GaveUpChanging(o.id, o.seq)) return 1; if(!OrderSelect(ticket, SELECT_BY_TICKET) || OrderCloseTime() != 0) return 1; string sym = OrderSymbol(); double point = MarketInfo(sym, MODE_POINT); double have = OrderOpenPrice(); // Only a pending order's entry can move, and only while the master's is still pending too. double wantPrice = (pending && 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(OrderStopLoss(), wantSl, point) && !Differs(OrderTakeProfit(), wantTp, point)) return 1; ResetLastError(); if(OrderModify(ticket, wantPrice, wantSl, wantTp, OrderExpiration(), clrNONE)) { Did(pending ? "moved " + Label(o) + " to the master's levels" : "moved the stop/target of " + Label(o)); return 1; } int err = GetLastError(); if(err == 1) return 1; // nothing to change string why = "could not move it: " + ErrorText(err) + " (" + IntegerToString(err) + ")"; if(!Passing(err) && TooManyAttempts(o.id, o.seq)) { Note(Label(o) + " " + why + ". Left as it is."); return 1; } return Later(o, why); } int RemovePending(FtiOrder &o, const int ticket, const string reason) { ResetLastError(); if(OrderDelete(ticket, clrNONE)) { 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: " + ErrorText(GetLastError())); } int ClosePosition(FtiOrder &o, const int ticket) { if(!OrderSelect(ticket, SELECT_BY_TICKET) || OrderCloseTime() != 0) { MemSet(o.id, -1); return 1; } RefreshRates(); string sym = OrderSymbol(); double price = OrderType() == OP_BUY ? MarketInfo(sym, MODE_BID) : MarketInfo(sym, MODE_ASK); ResetLastError(); if(OrderClose(ticket, OrderLots(), NormalizeDouble(price, (int)MarketInfo(sym, MODE_DIGITS)), SLIPPAGE, clrNONE)) { MemSet(o.id, -1); Did("closed " + Label(o) + " with the master"); return 1; } return Later(o, "could not close: " + ErrorText(GetLastError())); } //+------------------------------------------------------------------+ //| One master order -> what this account should hold | //+------------------------------------------------------------------+ int Apply(FtiOrder &o) { int 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; int ticket = 0; bool pending = false; if(FindLocal(id, ticket, pending) && pending) if(!OrderDelete(ticket, clrNONE)) Print("FTI Signal Copier: could not cancel order ", 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(!IsConnected()) { 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 = "AutoTrading is off: switch it on (toolbar button, and \"Allow live trading\" 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; } if(IsTradeContextBusy()) return false; // another EA is trading: next second 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(IsTesting()) { 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; } 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(); } //+------------------------------------------------------------------+