-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmartMoneyCommon.mqh
More file actions
330 lines (311 loc) · 12.3 KB
/
Copy pathSmartMoneyCommon.mqh
File metadata and controls
330 lines (311 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//+------------------------------------------------------------------+
//| SmartMoneyCommon.mqh |
//| Helpers compartilhados dos EAs/Indicadores do OIL_Dashboard_v4 |
//| |
//| FONTE CANÔNICA ÚNICA — qualquer mudança aqui se propaga para |
//| DataBridge.mq5, MLPredictor.mq5, ZonesPlotter.mq5, BayesianSMC.mq5|
//| |
//| Este arquivo é o espelho, em MQL5, do ml/_utils.py. Toda lógica |
//| de pip e de limpeza de símbolo DEVE ficar aqui — nunca escreva |
//| "replace('m','')" ou "_Point" num EA. |
//+------------------------------------------------------------------+
#ifndef __SMARTMONEY_COMMON_MQH__
#define __SMARTMONEY_COMMON_MQH__
//==================================================================
// 1) CLEAN SYMBOL
// Remove sufixos de broker ('m', '.', '#', '_pro', '.raw', '-ecn'…)
// e normaliza para MAIÚSCULAS. Deve bater com symbol_base() em
// ml/_utils.py.
//
// Exemplos:
// "EURUSDm" → "EURUSD"
// "XAUUSD#" → "XAUUSD"
// "USOIL.raw" → "USOIL"
// "BTCUSD_pro" → "BTCUSD"
//==================================================================
string SMC_CleanSymbol(const string sym)
{
string s = sym;
// 1) trim final após ponto '.'
int dot = StringFind(s, ".");
if(dot > 0) s = StringSubstr(s, 0, dot);
// 2) corta sufixos comuns
string suffixes[] = {"_pro", "_raw", "-ecn", "-pro", "#", "m"};
for(int i = 0; i < ArraySize(suffixes); i++)
{
int L = StringLen(suffixes[i]);
if(StringLen(s) > L &&
StringSubstr(s, StringLen(s) - L, L) == suffixes[i])
{
s = StringSubstr(s, 0, StringLen(s) - L);
break; // um sufixo por vez basta
}
}
StringToUpper(s);
return s;
}
//==================================================================
// 2) PIP SIZE
// Retorna o tamanho CORRETO de 1 pip em unidade do símbolo.
// Esta é a correção mais importante do projeto: usar _Point em
// XAUUSD devolve 0.01, mas 1 pip em ouro é 0.1 ⇒ margem de
// invalidação 10× menor que o pretendido. Em BTCUSD _Point é
// 0.01, mas 1 pip prático é 1.0 ⇒ erro de 100×.
//
// Tabela de overrides bate com _PIP_OVERRIDES em ml/_utils.py.
// Fallback: 10 * _Point para pares 5-digit, _Point para 3-digit.
//==================================================================
double SMC_PipSize(const string sym)
{
string b = SMC_CleanSymbol(sym);
// ── Overrides explícitos (DEVEM espelhar _PIP_OVERRIDES em ml/_utils.py) ──
// Metais
if(b == "XAUUSD") return 0.1;
if(b == "XAGUSD") return 0.01;
// Crypto
if(b == "BTCUSD") return 1.0;
if(b == "ETHUSD") return 0.1; // Python canônico = 0.1 (não 1.0)
if(b == "XRPUSD") return 0.0001;
// Commodities/óleo — inclui "WTIUSD" explicitamente (Python tem essa chave)
if(b == "USOIL" || b == "UKOIL" ||
b == "WTI" || b == "WTIUSD" ||
b == "BRENT") return 0.01;
// Forex (redundante com o fallback, mas explícito ⇒ documenta o esperado)
if(b == "EURUSD" || b == "GBPUSD" || b == "AUDUSD" || b == "NZDUSD" ||
b == "USDCAD" || b == "USDCHF" || b == "EURGBP") return 0.0001;
if(b == "USDJPY" || b == "EURJPY" || b == "GBPJPY") return 0.01;
// ── Heurística por prefixo (espelha o startswith() do Python) ──────────
// Cobre variações tipo BTCUSDT, ETHBTC, XAUUSDT, USOIL.cash, etc. onde
// SMC_CleanSymbol não conseguiu reduzir ao símbolo canônico.
if(StringSubstr(b, 0, 3) == "XAU") return 0.1;
if(StringSubstr(b, 0, 3) == "XAG") return 0.01;
if(StringSubstr(b, 0, 3) == "BTC") return 1.0;
if(StringSubstr(b, 0, 3) == "ETH") return 0.1;
if(StringSubstr(b, 0, 5) == "USOIL" ||
StringSubstr(b, 0, 5) == "UKOIL" ||
StringSubstr(b, 0, 3) == "WTI" ||
StringSubstr(b, 0, 5) == "BRENT") return 0.01;
// Pares JPY genéricos (3-digit) — 1 pip = 0.01
if(StringFind(b, "JPY") >= 0) return 0.01;
// ── Fallback via Digits/Point do próprio símbolo ──────────────────────
// forex 5-digit → 10 × Point ; 3-digit → Point (já é pip) ; 2-digit
// normalmente é metal/commodity e já foi capturado acima.
int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
double point = SymbolInfoDouble(sym, SYMBOL_POINT);
if(point <= 0) point = _Point; // defesa contra símbolo offline
if(digits == 3) return point;
if(digits == 2) return point;
return 10.0 * point;
}
//==================================================================
// 3) PRICE → STRING formatado no número de casas decimais do
// símbolo. Evita DoubleToString(px, _Digits) quando o símbolo
// não é o do gráfico (ex: DataBridge exportando USOILm a partir
// de um gráfico EURUSDm).
//==================================================================
string SMC_FormatPrice(const string sym, double px)
{
int d = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
if(d <= 0) d = _Digits;
return DoubleToString(px, d);
}
//==================================================================
// 4) JSON — parsers leves, KEY-BOUNDARY-SAFE
//
// Problema observado: os indicadores usavam StringFind("\"prob\":")
// que casa com "\"prob_buy\":" ⇒ lê o valor errado. Aqui exigimos
// aspa fechando a chave antes de ':'.
//
// Estes parsers NÃO são JSON completos — resolvem 95% dos casos
// do projeto (pares chave:valor planos, sem nesting). Para
// aninhamento real use uma lib JSON dedicada.
//==================================================================
// Localiza o padrão "key": no texto, com aspa fechando ANTES do ':'.
// Retorna índice do primeiro caractere APÓS os ':' + espaços, ou -1.
int SMC_JsonFindKey(const string raw, const string key)
{
string needle = "\"" + key + "\"";
int from = 0;
while(from < StringLen(raw))
{
int k = StringFind(raw, needle, from);
if(k < 0) return -1;
int after = k + StringLen(needle);
// pula espaços brancos até ':'
while(after < StringLen(raw))
{
ushort ch = StringGetCharacter(raw, after);
if(ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')
{ after++; continue; }
break;
}
if(after < StringLen(raw) && StringGetCharacter(raw, after) == ':')
{
after++;
// pula espaços após ':'
while(after < StringLen(raw))
{
ushort ch = StringGetCharacter(raw, after);
if(ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')
{ after++; continue; }
break;
}
return after;
}
// não era a chave — continua procurando
from = k + 1;
}
return -1;
}
// Lê string "key":"value" — retorna "" se ausente.
string SMC_JsonGetStr(const string raw, const string key)
{
int pos = SMC_JsonFindKey(raw, key);
if(pos < 0) return "";
if(StringGetCharacter(raw, pos) != '"') return "";
pos++;
int end = StringFind(raw, "\"", pos);
if(end < 0) return "";
return StringSubstr(raw, pos, end - pos);
}
// Lê número "key": 1.23 — retorna dflt se ausente/invalido.
double SMC_JsonGetDbl(const string raw, const string key, double dflt = 0.0)
{
int pos = SMC_JsonFindKey(raw, key);
if(pos < 0) return dflt;
// extrai até próximo ',' '}' ou fim
int end = pos;
while(end < StringLen(raw))
{
ushort ch = StringGetCharacter(raw, end);
if(ch == ',' || ch == '}' || ch == ']' ||
ch == '\n' || ch == '\r') break;
end++;
}
string tok = StringSubstr(raw, pos, end - pos);
StringTrimLeft(tok);
StringTrimRight(tok);
if(StringLen(tok) == 0) return dflt;
// aceita "1.23" entre aspas
if(StringGetCharacter(tok, 0) == '"')
{
tok = StringSubstr(tok, 1, StringLen(tok) - 2);
}
return StringToDouble(tok);
}
// Lê int "key": 42
long SMC_JsonGetInt(const string raw, const string key, long dflt = 0)
{
return (long)SMC_JsonGetDbl(raw, key, (double)dflt);
}
//==================================================================
// 5) FILE IO — escrita atômica
// Escreve content em {filename}.tmp e renomeia para {filename}.
// Evita que o Python leia arquivo parcialmente escrito pelo EA
// (race condition que causava JSONDecodeError esporádico).
//
// Uso: SMC_AtomicWrite("dashboard_EURUSDm.json", json_string);
//==================================================================
bool SMC_AtomicWrite(const string filename, const string content,
int common_flag = FILE_COMMON)
{
string tmp = filename + ".tmp";
int h = FileOpen(tmp,
FILE_WRITE | FILE_TXT | FILE_ANSI | common_flag);
if(h == INVALID_HANDLE)
{
PrintFormat("[SMC] FileOpen falhou: %s (err=%d)", tmp, GetLastError());
return false;
}
FileWriteString(h, content);
FileClose(h);
// FileMove com FILE_REWRITE para sobrescrever destino existente
if(!FileMove(tmp, common_flag, filename,
common_flag | FILE_REWRITE))
{
PrintFormat("[SMC] FileMove falhou: %s → %s (err=%d)",
tmp, filename, GetLastError());
FileDelete(tmp, common_flag);
return false;
}
return true;
}
//==================================================================
// 6) STRING BUILDER — concat O(N) (MQL5 "string += x" é O(N²))
// Para loops grandes (>500 iterações) ex: serialização de 1000
// barras em DataBridge, use este helper em vez de concatenar
// direto.
//==================================================================
class SMC_StringBuilder
{
private:
string m_chunks[];
int m_count;
public:
// Construtor — sem tipo de retorno em MQL5
SMC_StringBuilder() { m_count = 0; ArrayResize(m_chunks, 64); }
void Append(const string s)
{
if(m_count >= ArraySize(m_chunks))
ArrayResize(m_chunks, ArraySize(m_chunks) * 2);
m_chunks[m_count++] = s;
}
string ToString()
{
string r = "";
for(int i = 0; i < m_count; i++) r += m_chunks[i];
return r;
}
void Reset() { m_count = 0; }
};
//==================================================================
// 7) TIME — epoch UTC do servidor (não do broker)
// TimeCurrent() devolve horário do servidor do broker, que pode
// não ser UTC. Para timestamps em JSON sincronizados com o
// Python, use TimeGMT().
//==================================================================
long SMC_UtcEpoch() { return (long)TimeGMT(); }
//==================================================================
// 8) SIGNAL FRESHNESS
// Descarta sinais mais velhos que max_age_sec. Protege contra
// ficheiros obsoletos deixados por sessões anteriores do Python.
//==================================================================
bool SMC_SignalFresh(long signal_ts, int max_age_sec = 900)
{
long now = SMC_UtcEpoch();
return (now - signal_ts) <= max_age_sec && signal_ts > 0;
}
//==================================================================
// 9) TIMEFRAME → string curta ("M15", "H1", "H4", "D1"…)
// Padroniza a exibição em indicadores que mostram o período no
// painel. Cobre os timeframes suportados pelo MT5 atual.
//==================================================================
string SMC_TimeframeToStr(const ENUM_TIMEFRAMES tf)
{
switch(tf)
{
case PERIOD_M1: return "M1";
case PERIOD_M2: return "M2";
case PERIOD_M3: return "M3";
case PERIOD_M4: return "M4";
case PERIOD_M5: return "M5";
case PERIOD_M6: return "M6";
case PERIOD_M10: return "M10";
case PERIOD_M12: return "M12";
case PERIOD_M15: return "M15";
case PERIOD_M20: return "M20";
case PERIOD_M30: return "M30";
case PERIOD_H1: return "H1";
case PERIOD_H2: return "H2";
case PERIOD_H3: return "H3";
case PERIOD_H4: return "H4";
case PERIOD_H6: return "H6";
case PERIOD_H8: return "H8";
case PERIOD_H12: return "H12";
case PERIOD_D1: return "D1";
case PERIOD_W1: return "W1";
case PERIOD_MN1: return "MN1";
}
return EnumToString(tf);
}
#endif // __SMARTMONEY_COMMON_MQH__