//+------------------------------------------------------------------+ //| FERGO Trader Connector MT5 | //| Somente leitura: este arquivo NÃO contém OrderSend, OrderClose | //| nem qualquer função de negociação. Ele não tem como abrir, | //| alterar ou fechar ordens. Só lê a conta e envia para a FERGO. | //| | //| SITUAÇÃO: código-fonte escrito e revisado; AINDA NÃO COMPILADO | //| no MetaEditor e AINDA NÃO TESTADO em terminal. Ver docs. | //+------------------------------------------------------------------+ #property copyright "FERGO LTDA" #property version "0.11" #property description "FERGO Trader Connector (MT5) - somente leitura. Instale em um grafico dedicado." #define VERSAO_CONECTOR "0.1.1" input string InpUrlBase = "https://trader.fergo.com.br"; // Endereco da plataforma (o mesmo liberado em WebRequest) input string InpCodigo = ""; // Codigo de pareamento (so na primeira vez) input int InpAtualizaSeg = 15; // Intervalo de atualizacao de saldo e posicoes (s) input int InpPulsoSeg = 30; // Intervalo do sinal de vida (s) input int InpReconciliaSeg = 21600; // Reenvio completo do historico para conferencia (s) input int InpLote = 200; // Negocios por envio (1 a 500) input int InpTimeoutMs = 8000; // Tempo maximo de cada chamada (ms) enum FASE { FASE_PAREAR, FASE_CURSOR, FASE_HISTORICO, FASE_EM_DIA, FASE_PARADO }; FASE g_fase = FASE_PAREAR; string g_token = ""; bool g_pendente = false; // ligado pelo OnTradeTransaction; lido no OnTimer bool g_inicial = false; // primeira importacao completa ainda em curso bool g_completa = false; // a varredura atual comecou do zero int g_indice = 0; long g_desdeMs = 0; long g_maiorMs = 0; int g_falhas = 0; datetime g_proximo = 0; datetime g_ultimaSync = 0; datetime g_ultimoPulso = 0; datetime g_ultimaCompleta = 0; string g_situacao = "iniciando"; //+------------------------------------------------------------------+ string ArquivoToken() { return "FergoTrader_" + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + ".tok"; } string LerToken() { int h = FileOpen(ArquivoToken(), FILE_READ | FILE_TXT | FILE_ANSI); if(h == INVALID_HANDLE) return ""; string t = FileReadString(h); FileClose(h); StringTrimLeft(t); StringTrimRight(t); return t; } bool GravarToken(const string t) { int h = FileOpen(ArquivoToken(), FILE_WRITE | FILE_TXT | FILE_ANSI); if(h == INVALID_HANDLE) return false; FileWriteString(h, t); FileClose(h); return true; } //+------------------------------------------------------------------+ //| JSON: montagem e leitura minimas, sem biblioteca externa | //+------------------------------------------------------------------+ string Esc(const string s) { string r = ""; int n = StringLen(s); for(int i = 0; i < n; i++) { ushort c = StringGetCharacter(s, i); if(c == '"') r += "\\\""; else if(c == '\\') r += "\\\\"; else if(c < 32) r += StringFormat("\\u%04x", c); else r += ShortToString(c); } return r; } string T(const string chave, const string valor) { return "\"" + chave + "\":\"" + Esc(valor) + "\""; } string N(const string chave, const long valor) { return "\"" + chave + "\":" + IntegerToString(valor); } string U(const string chave, const ulong valor) { return "\"" + chave + "\":\"" + StringFormat("%I64u", valor) + "\""; } string D(const string chave, const double valor, const int casas) { return "\"" + chave + "\":\"" + DoubleToString(valor, casas) + "\""; } string JsonTexto(const string json, const string chave) { int p = StringFind(json, "\"" + chave + "\":\""); if(p < 0) return ""; p += StringLen(chave) + 4; int f = StringFind(json, "\"", p); if(f < 0) return ""; return StringSubstr(json, p, f - p); } long JsonNumero(const string json, const string chave) { int p = StringFind(json, "\"" + chave + "\":"); if(p < 0) return 0; p += StringLen(chave) + 3; int f = p; int n = StringLen(json); while(f < n) { ushort c = StringGetCharacter(json, f); if((c < '0' || c > '9') && c != '-') break; f++; } return StringToInteger(StringSubstr(json, p, f - p)); } string Sha256Hex(const string s) { uchar src[], chave[], saida[]; int n = StringToCharArray(s, src, 0, WHOLE_ARRAY, CP_UTF8); if(n > 0) ArrayResize(src, n - 1); if(CryptEncode(CRYPT_HASH_SHA256, src, chave, saida) <= 0) return ""; string h = ""; for(int i = 0; i < ArraySize(saida); i++) h += StringFormat("%02x", saida[i]); return h; } //+------------------------------------------------------------------+ //| HTTP. WebRequest e sincrona: so e chamada a partir do OnTimer, | //| nunca de dentro do OnTradeTransaction. | //+------------------------------------------------------------------+ int Http(const string metodo, const string caminho, const string corpo, string &resposta) { char dados[], res[]; string cabRes = ""; string cab = "Content-Type: application/json\r\n"; if(g_token != "") cab += "Authorization: Bearer " + g_token + "\r\n"; if(corpo != "") { int n = StringToCharArray(corpo, dados, 0, WHOLE_ARRAY, CP_UTF8); if(n > 0) ArrayResize(dados, n - 1); } ResetLastError(); int http = WebRequest(metodo, InpUrlBase + caminho, cab, InpTimeoutMs, dados, res, cabRes); if(http == -1) { int e = GetLastError(); if(e == 4014) g_situacao = "URL nao liberada: Ferramentas > Opcoes > Expert Advisors > Permitir WebRequest para " + InpUrlBase; else g_situacao = "sem comunicacao com a plataforma (erro " + IntegerToString(e) + ")"; return -1; } resposta = CharArrayToString(res, 0, WHOLE_ARRAY, CP_UTF8); return http; } void Falhou() { g_falhas++; int espera = (int)MathMin(300.0, MathPow(2.0, (double)MathMin(g_falhas, 9))); g_proximo = TimeLocal() + espera; } void Deu() { g_falhas = 0; g_proximo = 0; } //+------------------------------------------------------------------+ string DadosConta() { string modo = "hedge"; long mm = AccountInfoInteger(ACCOUNT_MARGIN_MODE); if(mm == ACCOUNT_MARGIN_MODE_RETAIL_NETTING) modo = "netting"; else if(mm == ACCOUNT_MARGIN_MODE_EXCHANGE) modo = "exchange"; string amb = "real"; long tm = AccountInfoInteger(ACCOUNT_TRADE_MODE); if(tm == ACCOUNT_TRADE_MODE_DEMO) amb = "demo"; else if(tm == ACCOUNT_TRADE_MODE_CONTEST) amb = "concurso"; string pasta = TerminalInfoString(TERMINAL_DATA_PATH); if(StringLen(pasta) > 40) pasta = StringSubstr(pasta, StringLen(pasta) - 40); return T("plataforma", "mt5") + "," + U("login", (ulong)AccountInfoInteger(ACCOUNT_LOGIN)) + "," + T("servidor", AccountInfoString(ACCOUNT_SERVER)) + "," + T("corretora", AccountInfoString(ACCOUNT_COMPANY)) + "," + T("moeda", AccountInfoString(ACCOUNT_CURRENCY)) + "," + N("casas_moeda", AccountInfoInteger(ACCOUNT_CURRENCY_DIGITS)) + "," + N("alavancagem", AccountInfoInteger(ACCOUNT_LEVERAGE)) + "," + T("modo_margem", modo) + "," + T("ambiente", amb) + "," + T("terminal_id", pasta) + "," + T("versao_conector", VERSAO_CONECTOR) + "," + N("build_terminal", TerminalInfoInteger(TERMINAL_BUILD)); } string Cabecalho() { return U("login", (ulong)AccountInfoInteger(ACCOUNT_LOGIN)) + "," + T("servidor", AccountInfoString(ACCOUNT_SERVER)) + "," + N("desloc_seg", (long)(TimeTradeServer() - TimeGMT())); } void Parear() { if(InpCodigo == "") { g_situacao = "sem pareamento: informe o codigo gerado na plataforma no campo 'Codigo de pareamento'"; g_proximo = TimeLocal() + 10; return; } string r = ""; int http = Http("POST", "/v1/conector/vincular", "{" + T("codigo", InpCodigo) + "," + DadosConta() + "}", r); if(http == 201) { string tk = JsonTexto(r, "token"); if(tk != "" && GravarToken(tk)) { g_token = tk; g_fase = FASE_CURSOR; g_situacao = "pareado"; Deu(); return; } g_situacao = "pareou, mas nao conseguiu guardar o token no terminal"; } else if(http == 403) g_situacao = "codigo de pareamento invalido, vencido ou ja usado: gere outro na plataforma"; else if(http == 429) g_situacao = "muitas tentativas: aguarde 10 minutos"; else if(http != -1) g_situacao = "pareamento recusado (HTTP " + IntegerToString(http) + ")"; Falhou(); } void ObterCursor() { string r = ""; int http = Http("GET", "/v1/conector/cursor", "", r); if(!Tratar(http, r)) return; g_desdeMs = JsonNumero(r, "time_msc"); g_inicial = (StringFind(r, "\"historico_completo\":true") < 0); // Enquanto o historico inicial nao terminou, recomeca do zero: o servidor ignora o que ja tem. if(g_inicial) g_desdeMs = 0; IniciarVarredura(g_inicial); } void IniciarVarredura(const bool completa) { g_completa = completa; g_indice = 0; g_maiorMs = g_desdeMs; g_fase = FASE_HISTORICO; } // Trata respostas comuns. Devolve true so quando a chamada deu certo (200). bool Tratar(const int http, const string r) { if(http == 200) { Deu(); return true; } if(http == 401) { // Token revogado na plataforma: para de enviar e pede novo pareamento. FileDelete(ArquivoToken()); g_token = ""; g_fase = FASE_PAREAR; g_situacao = "acesso revogado na plataforma: gere novo codigo de pareamento"; } else if(http == 409) { g_fase = FASE_PARADO; g_situacao = "este conector foi pareado com outra conta: gere um codigo para esta conta"; } else if(http != -1) g_situacao = "plataforma respondeu HTTP " + IntegerToString(http) + " " + StringSubstr(r, 0, 120); Falhou(); return false; } string DealJson(const ulong t) { int dg = (int)AccountInfoInteger(ACCOUNT_CURRENCY_DIGITS); string j = "{" + U("ticket", t) + "," + U("ordem", (ulong)HistoryDealGetInteger(t, DEAL_ORDER)) + "," + U("posicao_id", (ulong)HistoryDealGetInteger(t, DEAL_POSITION_ID)) + "," + N("time_msc", HistoryDealGetInteger(t, DEAL_TIME_MSC)) + "," + T("tipo", EnumToString((ENUM_DEAL_TYPE)HistoryDealGetInteger(t, DEAL_TYPE))) + "," + T("entrada", EnumToString((ENUM_DEAL_ENTRY)HistoryDealGetInteger(t, DEAL_ENTRY))) + "," + T("motivo", EnumToString((ENUM_DEAL_REASON)HistoryDealGetInteger(t, DEAL_REASON))) + "," + T("simbolo", HistoryDealGetString(t, DEAL_SYMBOL)) + "," + D("volume", HistoryDealGetDouble(t, DEAL_VOLUME), 8) + "," + D("preco", HistoryDealGetDouble(t, DEAL_PRICE), 8) + "," + D("sl", HistoryDealGetDouble(t, DEAL_SL), 8) + "," + D("tp", HistoryDealGetDouble(t, DEAL_TP), 8) + "," + D("lucro", HistoryDealGetDouble(t, DEAL_PROFIT), dg) + "," + D("comissao", HistoryDealGetDouble(t, DEAL_COMMISSION), dg) + "," + D("swap", HistoryDealGetDouble(t, DEAL_SWAP), dg) + "," + D("taxa", HistoryDealGetDouble(t, DEAL_FEE), dg) + "," + U("magic", (ulong)HistoryDealGetInteger(t, DEAL_MAGIC)) + "," + T("comentario", HistoryDealGetString(t, DEAL_COMMENT)) + "," + T("id_externo", HistoryDealGetString(t, DEAL_EXTERNAL_ID)) + "}"; return j; } string SnapshotJson() { int dg = (int)AccountInfoInteger(ACCOUNT_CURRENCY_DIGITS); string hora = TimeToString(TimeTradeServer(), TIME_DATE | TIME_SECONDS); StringReplace(hora, ".", "-"); return "\"snapshot\":{" + T("hora_servidor", hora) + "," + D("saldo", AccountInfoDouble(ACCOUNT_BALANCE), dg) + "," + D("patrimonio", AccountInfoDouble(ACCOUNT_EQUITY), dg) + "," + D("credito", AccountInfoDouble(ACCOUNT_CREDIT), dg) + "," + D("margem", AccountInfoDouble(ACCOUNT_MARGIN), dg) + "," + D("margem_livre", AccountInfoDouble(ACCOUNT_MARGIN_FREE), dg) + "," + D("nivel_margem", AccountInfoDouble(ACCOUNT_MARGIN_LEVEL), 2) + "}"; } string PosicoesJson() { int dg = (int)AccountInfoInteger(ACCOUNT_CURRENCY_DIGITS); string itens = ""; int total = PositionsTotal(); for(int i = 0; i < total; i++) { ulong t = PositionGetTicket(i); if(t == 0) continue; if(itens != "") itens += ","; itens += "{" + U("ticket", t) + "," + U("posicao_id", (ulong)PositionGetInteger(POSITION_IDENTIFIER)) + "," + T("simbolo", PositionGetString(POSITION_SYMBOL)) + "," + T("direcao", PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? "buy" : "sell") + "," + D("volume", PositionGetDouble(POSITION_VOLUME), 8) + "," + D("preco_abertura", PositionGetDouble(POSITION_PRICE_OPEN), 8) + "," + D("preco_atual", PositionGetDouble(POSITION_PRICE_CURRENT), 8) + "," + D("sl", PositionGetDouble(POSITION_SL), 8) + "," + D("tp", PositionGetDouble(POSITION_TP), 8) + "," + D("lucro", PositionGetDouble(POSITION_PROFIT), dg) + "," + D("swap", PositionGetDouble(POSITION_SWAP), dg) + "," + U("magic", (ulong)PositionGetInteger(POSITION_MAGIC)) + "," + T("comentario", PositionGetString(POSITION_COMMENT)) + "," + N("aberta_msc", PositionGetInteger(POSITION_TIME_MSC)) + "}"; } return "\"posicoes_completo\":true,\"posicoes\":[" + itens + "]"; } // Um passo por tique do temporizador: no maximo InpLote negocios por chamada. void PassoHistorico() { long desdeSeg = g_desdeMs / 1000 - 86400; datetime de = (datetime)(desdeSeg > 0 ? desdeSeg : 0); if(!HistorySelect(de, TimeTradeServer() + 86400)) { g_situacao = "o terminal ainda nao carregou o historico"; Falhou(); return; } int lote = (int)MathMax(1, MathMin(500, InpLote)); int total = HistoryDealsTotal(); int ate = (int)MathMin(total, g_indice + lote); string itens = ""; long maior = g_maiorMs; for(int i = g_indice; i < ate; i++) { ulong t = HistoryDealGetTicket(i); if(t == 0) continue; if(itens != "") itens += ","; itens += DealJson(t); long ms = HistoryDealGetInteger(t, DEAL_TIME_MSC); if(ms > maior) maior = ms; } bool fim = (ate >= total); string miolo = Cabecalho() + ",\"deals\":[" + itens + "]"; if(fim) { miolo += "," + SnapshotJson() + "," + PosicoesJson(); if(g_inicial) miolo += ",\"fim_historico_inicial\":true"; } // O identificador do lote sai do proprio conteudo: reenviar o mesmo lote nao duplica. string corpo = "{" + T("lote_uid", "L" + StringSubstr(Sha256Hex(miolo), 0, 48)) + "," + miolo + "}"; string r = ""; int http = Http("POST", "/v1/conector/sincronizar", corpo, r); if(!Tratar(http, r)) return; g_indice = ate; g_maiorMs = maior; if(fim) { g_desdeMs = g_maiorMs; g_inicial = false; if(g_completa) g_ultimaCompleta = TimeLocal(); g_ultimaSync = TimeLocal(); g_ultimoPulso = TimeLocal(); g_fase = FASE_EM_DIA; g_situacao = "em dia (" + IntegerToString(total) + " negocios conferidos no ultimo envio)"; } else g_situacao = "enviando historico: " + IntegerToString(ate) + " de " + IntegerToString(total); } void Pulso() { string corpo = "{\"conectado\":" + (TerminalInfoInteger(TERMINAL_CONNECTED) ? "true" : "false") + ",\"negociacao_permitida\":" + (TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) ? "true" : "false") + "," + T("versao_conector", VERSAO_CONECTOR) + "}"; string r = ""; if(Tratar(Http("POST", "/v1/conector/pulso", corpo, r), r)) g_ultimoPulso = TimeLocal(); } //+------------------------------------------------------------------+ int OnInit() { g_token = LerToken(); g_fase = (g_token == "") ? FASE_PAREAR : FASE_CURSOR; g_falhas = 0; g_proximo = 0; g_ultimaCompleta = TimeLocal(); EventSetTimer(1); return INIT_SUCCEEDED; } void OnDeinit(const int motivo) { EventKillTimer(); Comment(""); } // Rapido de proposito: so levanta a bandeira. A fila de transacoes do // terminal tem 1024 posicoes e um manipulador lento perde eventos. void OnTradeTransaction(const MqlTradeTransaction &trans, const MqlTradeRequest &request, const MqlTradeResult &result) { g_pendente = true; } void OnTimer() { datetime agora = TimeLocal(); if(agora >= g_proximo) { if(!TerminalInfoInteger(TERMINAL_CONNECTED)) g_situacao = "terminal sem conexao com a corretora"; else if(g_fase == FASE_PAREAR) Parear(); else if(g_fase == FASE_CURSOR) ObterCursor(); else if(g_fase == FASE_HISTORICO) PassoHistorico(); else if(g_fase == FASE_EM_DIA) { if(agora - g_ultimaCompleta >= InpReconciliaSeg) { g_desdeMs = 0; IniciarVarredura(true); } else if(g_pendente || agora - g_ultimaSync >= InpAtualizaSeg) { g_pendente = false; IniciarVarredura(false); } else if(agora - g_ultimoPulso >= InpPulsoSeg) Pulso(); } } Comment("FERGO Trader Connector " + VERSAO_CONECTOR + " (somente leitura)\n" + g_situacao); } // Um Expert Advisor precisa do OnTick; este nao faz nada com ele. void OnTick() { } //+------------------------------------------------------------------+