-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMT5RemoteBridgeAPI.mq5
More file actions
247 lines (234 loc) · 18.5 KB
/
MT5RemoteBridgeAPI.mq5
File metadata and controls
247 lines (234 loc) · 18.5 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
//+------------------------------------------------------------------+
//| MT5RemoteBridgeAPI.mq5 |
//+------------------------------------------------------------------+
#property strict
#property copyright "ding9736"
#property version "3.0"
#property description "High-performance, fully automated encrypted, client-driven MT5RemoteBridgeAPI service framework (production-grade)"
#property link "https://github.com/ding9736/MT5BridgeAPI "
#property service
//+------------------------------------------------------------------+
//| Core dependency imports |
//+------------------------------------------------------------------+
#include "Lib/ZeroMQ/ZeroMQ.mqh"
#include "Core/Config.mqh"
#include "Core/ServiceState.mqh"
#include "Core/CommandProcessor.mqh"
#include "Core/HandshakeHandler.mqh"
#include "Core/Logger.mqh"
//+------------------------------------------------------------------+
//| Global service instances |
//+------------------------------------------------------------------+
CServiceConfig g_Config;
CServiceState g_State;
//+------------------------------------------------------------------+
//| Service start entry point |
//+------------------------------------------------------------------+
void OnStart()
{
g_Config.LoadDefaults();
CLogger::Initialize(g_Config.ConfigPath, g_Config.LogFilename, g_Config.LogLevel, g_Config.LogToJournal);
CLogger::LogInfo("======================================");
CLogger::LogInfo("MT5RemoteBridgeAPI service is starting...");
CLogger::LogInfo("======================================");
if(!InitializeService())
{
CLogger::LogError("Service initialization failed, stopping now.");
CLogger::Shutdown();
return;
}
RunServiceLoop();
CleanupService();
CLogger::LogInfo("ZMQ service has been completely stopped.");
CLogger::Shutdown();
}
//+------------------------------------------------------------------+
//| Initialize service |
//+------------------------------------------------------------------+
bool InitializeService()
{
// Load configuration from JSON file (will override items with the same name loaded by LoadDefaults)
g_Config.Load();
if(!g_Config.Validate())
{
CLogger::LogError("Configuration validation failed: " + g_Config.LastError + " Please check the configuration file.");
return false;
}
if(!g_State.Initialize(g_Config))
{
CLogger::LogError("Service state initialization failed.");
return false;
}
g_State.SetConfigReloadCallback(ReloadConfiguration);
CLogger::LogInfo(StringFormat("Service core components initialized successfully. Default trading parameters - MagicNumber:%d, Slippage:%d",
g_Config.MagicNumber,
g_Config.Slippage));
return true;
}
//+------------------------------------------------------------------+
//| Service main loop |
//+------------------------------------------------------------------+
void RunServiceLoop()
{
CLogger::LogInfo("Entering service main loop...");
if(!ValidateSockets())
{
CLogger::LogError("Socket validation failed, cannot enter main loop.");
return;
}
ZmqPoller poller;
if(!SetupPoller(poller))
{
CLogger::LogError("Poller setup failed.");
return;
}
int poll_timeout_ms = g_Config.TimerMs > 0 ? g_Config.TimerMs : 10;
while(!IsStopped())
{
if(poller.poll(poll_timeout_ms))
{
int processed_count = 0;
if(ProcessHandshakeMessages() > 0)
{
processed_count++;
}
if(ProcessCommandMessages() > 0)
{
processed_count++;
}
if(processed_count > 0)
{
g_State.SignalActivity();
}
}
g_State.ProcessAuthTasks();
PerformPeriodicTasks();
if(g_State.ShouldLogPerformanceStats())
{
ulong current_total_messages = g_State.GetTotalMessagesProcessed();
ulong last_message_count = g_State.GetLastStatMessageCount();
ulong messages_in_period = (current_total_messages > last_message_count) ? (current_total_messages - last_message_count) : 0;
LogPerformanceStatistics(messages_in_period);
g_State.ResetPerformanceStats(current_total_messages);
}
}
CLogger::LogInfo("Service main loop has exited.");
}
//+------------------------------------------------------------------+
//| Validate sockets |
//+------------------------------------------------------------------+
bool ValidateSockets()
{
if(CheckPointer(g_State.pHandshakeSocket) != POINTER_DYNAMIC || !g_State.pHandshakeSocket.isValid())
{
CLogger::LogError("Handshake socket is invalid.");
return false;
}
if(CheckPointer(g_State.pCmdSocket) != POINTER_DYNAMIC || !g_State.pCmdSocket.isValid())
{
CLogger::LogError("Command socket is invalid.");
return false;
}
if(CheckPointer(g_State.pPubSocket) != POINTER_DYNAMIC || !g_State.pPubSocket.isValid())
{
CLogger::LogError("Publish socket is invalid.");
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Setup poller |
//+------------------------------------------------------------------+
bool SetupPoller(ZmqPoller &poller)
{
if(!poller.add(*g_State.pHandshakeSocket, ZMQ_POLLIN))
{
CLogger::LogError("Failed to add handshake socket to poller.");
return false;
}
if(!poller.add(*g_State.pCmdSocket, ZMQ_POLLIN))
{
CLogger::LogError("Failed to add command socket to poller.");
return false;
}
CLogger::LogInfo("Poller setup successful.");
return true;
}
//+------------------------------------------------------------------+
//| Process handshake messages |
//+------------------------------------------------------------------+
int ProcessHandshakeMessages()
{
ZmqMsg request;
if(g_State.pHandshakeSocket.recv(request, ZMQ_FLAG_DONTWAIT))
{
g_State.IncrementTotalMessagesProcessed();
string request_data = request.getData();
if(StringLen(request_data) > 0)
{
CHandshakeHandler::Process(request_data, g_State);
return 1;
}
}
return 0;
}
//+------------------------------------------------------------------+
//| Process command messages |
//+------------------------------------------------------------------+
int ProcessCommandMessages()
{
ZmqMsg request;
if(g_State.ReceiveCommand(request))
{
string request_data = request.getData();
if(StringLen(request_data) > 0)
{
CCommandProcessor::Process(request_data, g_State);
return 1;
}
}
return 0;
}
//+------------------------------------------------------------------+
//| Perform periodic tasks |
//+------------------------------------------------------------------+
void PerformPeriodicTasks()
{
static ulong last_update_time_ms = 0;
ulong current_time_ms = GetTickCount64();
if (current_time_ms - last_update_time_ms < 1000) return;
if(g_State.IsHealthy())
{
g_State.PublishUpdates();
last_update_time_ms = current_time_ms;
}
}
//+------------------------------------------------------------------+
//| Output performance statistics |
//+------------------------------------------------------------------+
void LogPerformanceStatistics(ulong message_count)
{
double elapsed_sec = (double)STATS_LOG_INTERVAL;
double msg_per_sec = (message_count > 0) ? (double)message_count / elapsed_sec : 0;
CLogger::LogInfo(StringFormat("Performance statistics: Messages processed=%d, Period=%.1f sec, Throughput=%.0f msg/s",
message_count, elapsed_sec, msg_per_sec));
}
//+------------------------------------------------------------------+
//| Configuration reload callback |
//+------------------------------------------------------------------+
void ReloadConfiguration()
{
CLogger::LogInfo("Reloading configuration...");
g_Config.Load();
CLogger::LogWarning("Note: Only some configurations (like default MagicNumber/Slippage) can be hot-reloaded. Core settings like ports/keys require a service restart to take effect.");
CLogger::LogInfo("Configuration reload complete.");
}
//+------------------------------------------------------------------+
//| Cleanup service |
//+------------------------------------------------------------------+
void CleanupService()
{
CLogger::LogInfo("Cleaning up service resources...");
g_State.Shutdown();
CLogger::LogInfo("Service resource cleanup complete.");
}