-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsole.mq5
More file actions
10279 lines (9192 loc) · 379 KB
/
Console.mq5
File metadata and controls
10279 lines (9192 loc) · 379 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//+------------------------------------------------------------------+
//| Console.mq5 |
//| Copyright © 2026, EarnForex.com |
//| https://www.earnforex.com/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2026, EarnForex.com"
#property link "https://www.earnforex.com/software/MT5-Console/"
#property service
#property version "1.00"
string Version = "1.00";
#property description "MT5 Console adds a command line interface to MetaTrader 5 terminal."
#property description "Press ` (backtick) to toggle the console window."
#property description ""
#property description "WARNING: Use at your own risk. No functionality is guaranteed."
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| Windows DLL Imports |
//+------------------------------------------------------------------+
#import "user32.dll"
long CreateWindowExW(uint dwExStyle,
string lpClassName,
string lpWindowName,
uint dwStyle,
int x, int y,
int nWidth, int nHeight,
long hWndParent,
long hMenu,
long hInstance,
long lpParam);
// Alternative with ushort array for class name.
long CreateWindowExW(uint dwExStyle,
const ushort &lpClassName[],
const ushort &lpWindowName[],
uint dwStyle,
int x, int y,
int nWidth, int nHeight,
long hWndParent,
long hMenu,
long hInstance,
long lpParam);
bool DestroyWindow(long hWnd);
bool ShowWindow(long hWnd, int nCmdShow);
bool GetClientRect(long hWnd, int &lpRect[]);
bool IsWindow(long hWnd);
long FindWindowW(string lpClassName, string lpWindowName);
long FindWindowExW(long hWndParent, long hWndChildAfter, string lpszClass, string lpszWindow);
long GetParent(long hWnd);
bool SetWindowPos(long hWnd, long hWndInsertAfter, int X, int Y,
int cx, int cy, uint uFlags);
bool MoveWindow(long hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
short GetAsyncKeyState(int vKey);
long GetDC(long hWnd);
bool ReleaseDC(long hWnd, long hDC);
bool FillRect(long hdc, const int &lprc[], long hbr);
bool GetWindowRect(long hWnd, int &lpRect[]);
int MessageBoxW(long hWnd, string lpText, string lpCaption, uint uType);
long GetWindowLongW(long hWnd, int nIndex);
bool EnableWindow(long hWnd, bool bEnable);
bool SetForegroundWindow(long hWnd);
long GetForegroundWindow();
long GetWindow(long hWnd, uint uCmd);
long SendMessageW(long hWnd, uint Msg, long wParam, long lParam);
void keybd_event(uchar bVk, uchar bScan, uint dwFlags, uint dwExtraInfo);
bool IsWindowVisible(long hWnd);
bool SetWindowTextW(long hWnd, string lpString);
// Message pump.
bool PeekMessageW(uchar &lpMsg[], long hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
bool TranslateMessage(const uchar &lpMsg[]);
long DispatchMessageW(const uchar &lpMsg[]);
bool PostMessageW(long hWnd, uint Msg, long wParam, long lParam);
int RegisterWindowMessageW(string lpString);
long GetDlgItem(long hDlg, int nIDDlgItem);
// Overloads with long params.
long SendMessageW(long hWnd, uint Msg, long wParam, uchar &lParam[]);
long SendMessageW(long hWnd, uint Msg, long wParam, int &lParam[]);
// Mouse and window.
int SetCursorPos(int x, int y);
void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, ulong dwExtraInfo);
int GetClassNameW(long hWnd, ushort &lpClassName[], int nMaxCount);
int GetWindowTextW(long hWnd, ushort &lpString[], int nMaxCount);
int GetWindowTextLengthW(long hWnd);
long SetFocus(long hWnd);
// Clipboard.
bool OpenClipboard(long hWndNewOwner);
bool CloseClipboard();
bool EmptyClipboard();
long GetClipboardData(uint uFormat);
// Menu functions.
long GetMenu(long hWnd);
long GetSubMenu(long hMenu, int nPos);
int GetMenuItemCount(long hMenu);
uint GetMenuItemID(long hMenu, int nPos);
int GetMenuStringW(long hMenu, uint uIDItem, ushort &lpString[], int cchMax, uint flags);
#import
// WIN32_FIND_DATAW structure for file enumeration.
struct FILETIME
{
uint dwLowDateTime;
uint dwHighDateTime;
};
struct WIN32_FIND_DATAW
{
uint dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
uint nFileSizeHigh;
uint nFileSizeLow;
uint dwReserved0;
uint dwReserved1;
ushort cFileName[260]; // MAX_PATH
ushort cAlternateFileName[14];
};
#define FILE_ATTRIBUTE_DIRECTORY 0x10
#import "kernel32.dll"
// File functions.
int CreateFileW(string lpFileName, uint dwDesiredAccess, uint dwShareMode,
int lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, int hTemplateFile);
bool ReadFile(int hFile, uchar &lpBuffer[], uint nNumberOfBytesToRead,
uint &lpNumberOfBytesRead, int lpOverlapped);
bool WriteFile(int hFile, const uchar &lpBuffer[], uint nNumberOfBytesToWrite,
uint &lpNumberOfBytesWritten, int lpOverlapped);
bool CloseHandle(int hObject);
uint GetFileSize(int hFile, uint &lpFileSizeHigh);
// File search functions.
long FindFirstFileW(string lpFileName, WIN32_FIND_DATAW &lpFindFileData);
bool FindNextFileW(long hFindFile, WIN32_FIND_DATAW &lpFindFileData);
bool FindClose(long hFindFile);
// Process and module functions.
uint GetCurrentProcessId();
uint GetCurrentThreadId();
void SetLastError(uint dwErrCode);
int GetFileAttributesW(string lpFileName);
bool CreateDirectoryW(string lpPathName, int lpSecurityAttributes);
bool CopyFileW(string lpExistingFileName, string lpNewFileName, bool bFailIfExists);
bool DeleteFileW(string lpFileName);
bool RemoveDirectoryW(string lpPathName);
bool MoveFileW(string lpExistingFileName, string lpNewFileName);
// Clipboard support.
long GlobalLock(long hMem);
bool GlobalUnlock(long hMem);
string lstrcatW(long string1, const string string2);
bool CloseHandle(long hObject); // Overload for long handle.
#import
#import "gdi32.dll"
long CreateFontW(int nHeight,
int nWidth,
int nEscapement,
int nOrientation,
int fnWeight,
uint fdwItalic,
uint fdwUnderline,
uint fdwStrikeOut,
uint fdwCharSet,
uint fdwOutputPrecision,
uint fdwClipPrecision,
uint fdwQuality,
uint fdwPitchAndFamily,
const ushort &lpszFace[]);
long CreateSolidBrush(uint colorValue);
bool DeleteObject(long hObject);
long SelectObject(long hdc, long h);
long GetStockObject(int i);
bool TextOutW(long hdc, int x, int y, const ushort &lpString[], int c);
bool SetTextColor(long hdc, uint colorValue);
bool SetBkColor(long hdc, uint colorValue);
bool SetBkMode(long hdc, int mode);
// Double-buffering functions.
long CreateCompatibleDC(long hdc);
long CreateCompatibleBitmap(long hdc, int cx, int cy);
bool BitBlt(long hdc, int x, int y, int cx, int cy, long hdcSrc, int x1, int y1, uint rop);
bool DeleteDC(long hdc);
#import
#import "urlmon.dll"
int URLDownloadToFileW(long pCaller, string szURL, string szFileName, uint dwReserved, long lpfnCB);
#import
#import "shell32.dll"
long ShellExecuteW(long hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);
#import
//+------------------------------------------------------------------+
//| Constants |
//+------------------------------------------------------------------+
#define WS_POPUP 0x80000000
#define WS_VISIBLE 0x10000000
#define WS_BORDER 0x00800000
#define WS_CAPTION 0x00C00000
#define WS_SYSMENU 0x00080000
#define WS_MINIMIZEBOX 0x00020000
#define WS_MAXIMIZEBOX 0x00010000
#define WS_EX_TOPMOST 0x00000008
#define WS_EX_APPWINDOW 0x00040000
#define SW_HIDE 0
#define SW_SHOWNORMAL 1
#define SW_SHOW 5
#define VK_RETURN 0x0D
#define VK_ESCAPE 0x1B
#define VK_BACK 0x08
#define VK_UP 0x26
#define VK_DOWN 0x28
#define VK_LEFT 0x25
#define VK_RIGHT 0x27
#define VK_HOME 0x24
#define VK_END 0x23
#define VK_DELETE 0x2E
#define VK_F4 0x73
#define VK_F10 0x79
#define VK_PRIOR 0x21 // Page Up.
#define VK_NEXT 0x22 // Page Down.
#define VK_OEM_3 0xC0 // Backtick.
#define VK_SHIFT 0x10
#define VK_INSERT 0x2D
#define VK_V 0x56
#define VK_SPACE 0x20
#define VK_TAB 0x09
#define VK_LWIN 0x5B // Left Windows key.
#define VK_RWIN 0x5C // Right Windows key.
#define VK_NUMPAD0 0x60
#define VK_NUMPAD1 0x61
#define VK_NUMPAD2 0x62
#define VK_NUMPAD3 0x63
#define VK_NUMPAD4 0x64
#define VK_NUMPAD5 0x65
#define VK_NUMPAD6 0x66
#define VK_NUMPAD7 0x67
#define VK_NUMPAD8 0x68
#define VK_NUMPAD9 0x69
#define VK_DECIMAL 0x6E
#define VK_OEM_1 0xBA // ; :
#define VK_OEM_PLUS 0xBB // = +
#define VK_OEM_COMMA 0xBC // , <
#define VK_OEM_MINUS 0xBD // - _
#define VK_OEM_PERIOD 0xBE // . >
#define VK_OEM_2 0xBF // / ?
#define VK_OEM_4 0xDB // [ {
#define VK_OEM_5 0xDC // \ |
#define VK_OEM_6 0xDD // ] }
#define VK_OEM_7 0xDE // ' "
#define BLACK_BRUSH 4
#define SM_CXSCREEN 0
#define SM_CYSCREEN 1
#define SWP_NOSIZE 0x0001
#define SWP_NOMOVE 0x0002
#define SWP_NOZORDER 0x0004
#define SWP_SHOWWINDOW 0x0040
#define SWP_NOACTIVATE 0x0010
#define RGB(r,g,b) ((uint)((b)<<16|(g)<<8|(r)))
#define COLOR_BLACK RGB(0,0,0)
#define COLOR_GREEN RGB(0,255,0)
#define MB_OK 0x00000000
#define MB_ICONINFORMATION 0x00000040
#define PM_REMOVE 0x0001
#define PM_NOREMOVE 0x0000
#define WM_QUIT 0x0012
#define WM_CLOSE 0x0010
#define WM_COMMAND 0x0111
#define WM_KEYDOWN 0x0100
#define WM_KEYUP 0x0101
// File access constants.
#define GENERIC_READ 0x80000000
#define GENERIC_WRITE 0x40000000
#define WIN_FILE_SHARE_READ 0x00000001
#define OPEN_EXISTING 3
#define CREATE_ALWAYS 2
#define FILE_ATTRIBUTE_NORMAL 0x80
#define INVALID_HANDLE_VALUE -1
#define MF_BYPOSITION 0x0400
#define SS_BLACKRECT 0x00000004
#define WS_CLIPCHILDREN 0x02000000
#define SRCCOPY 0x00CC0020 // BitBlt raster operation.
#define GW_CHILD 5 // GetWindow command to get first child.
#define GW_HWNDNEXT 2 // GetWindow command to get next sibling.
// Tab control messages.
#define TCM_FIRST 0x1300
#define TCM_GETITEMCOUNT (TCM_FIRST + 4)
#define TCM_GETITEMRECT (TCM_FIRST + 10)
#define TCM_GETCURSEL (TCM_FIRST + 11)
// ListView messages.
#define LVM_FIRST 0x1000
#define LVM_GETITEMCOUNT (LVM_FIRST + 4)
#define LVM_GETITEMTEXTW (LVM_FIRST + 115)
#define LVM_GETHEADER (LVM_FIRST + 31)
// Cross-process memory constants.
#define CF_UNICODETEXT 13 // Clipboard format for Unicode text.
#define WM_MDIGETACTIVE 0x0229 // MDI message to get active child.
#define KEYEVENTF_KEYUP 0x0002 // Key up flag for keybd_event.
#define VK_CONTROL 0x11 // Ctrl key.
#define VK_MENU 0x12 // Alt key.
#define VK_E 0x45 // E key.
// MT internal message load types.
#define MT_LOAD_STANDARD_INDICATOR 13
#define MT_LOAD_EXPERT 14
#define MT_LOAD_CUSTOM_INDICATOR 15
#define MT_LOAD_SCRIPT 16
// Button message.
#define BM_CLICK 0x00F5
// TreeView messages and constants.
#define TV_FIRST 0x1100
#define TVM_EXPAND (TV_FIRST + 2)
#define TVM_GETITEMRECT (TV_FIRST + 4)
#define TVM_GETNEXTITEM (TV_FIRST + 10)
#define TVM_SELECTITEM (TV_FIRST + 11)
#define TVM_GETITEMW (TV_FIRST + 62)
#define TVGN_ROOT 0x0000
#define TVGN_NEXT 0x0001
#define TVGN_CHILD 0x0004
#define TVGN_CARET 0x0009
#define TVE_EXPAND 0x0002
#define TVIF_TEXT 0x0001
#define TVIF_HANDLE 0x0010
// Mouse event constants.
#define MOUSEEVENTF_LEFTDOWN 0x0002
#define MOUSEEVENTF_LEFTUP 0x0004
#define MOUSEEVENTF_RIGHTDOWN 0x0008
#define MOUSEEVENTF_RIGHTUP 0x0010
#define MOUSEEVENTF_ABSOLUTE 0x8000
// WM constants for mouse.
#define WM_LBUTTONDOWN 0x0201
#define WM_LBUTTONUP 0x0202
#define MK_LBUTTON 0x0001
//+------------------------------------------------------------------+
//| Format money value with thousands separator and currency |
//+------------------------------------------------------------------+
string FormatMoney(double amount, bool showSign = false)
{
string currency = AccountInfoString(ACCOUNT_CURRENCY);
bool negative = (amount < 0);
if (negative) amount = -amount;
// Format to 2 decimal places.
string str = DoubleToString(amount, 2);
// Find decimal point.
int decPos = StringFind(str, ".");
if (decPos < 0) decPos = StringLen(str);
// Add commas to integer part.
string intPart = StringSubstr(str, 0, decPos);
string decPart = StringSubstr(str, decPos);
string formatted = "";
int len = StringLen(intPart);
for (int i = 0; i < len; i++)
{
if (i > 0 && (len - i) % 3 == 0)
formatted += ",";
formatted += StringSubstr(intPart, i, 1);
}
// Build result.
string result = "";
if (showSign)
{
if (negative)
result = "-";
else
result = "+";
}
else if (negative)
{
result = "-";
}
result += formatted + decPart + " " + currency;
return result;
}
//+------------------------------------------------------------------+
//| Windows Console Class |
//+------------------------------------------------------------------+
class CWindowsConsole
{
private:
long m_hwnd;
long m_hwndMT5;
long m_hFont;
long m_hBrush;
bool m_visible;
string m_lines[];
string m_inputText;
int m_cursorPos;
string m_commandHistory[];
int m_historyIndex;
int m_scrollOffset;
int m_maxVisibleLines;
int m_maxBufferLines;
bool m_needsRedraw;
bool m_quitRequested;
uint m_lastMessageTime;
long m_currentChartId; // Track which chart we're attached to.
// Undo tracking.
string m_lastUndoCommand; // Command type that can be undone.
string m_lastUndoData; // Data needed for undo (object name, indicator, etc.).
long m_lastUndoChartId; // Chart ID where action was performed.
// Breathing mode.
bool m_breathingMode;
uint m_breathingStart;
int m_breathingDuration; // seconds
int m_breathingPhase; // 0=inhale, 1=exhale
uint m_breathingPhaseStart;
// Shutdown timer.
bool m_shutdownPending;
uint m_shutdownStart;
int m_shutdownDuration; // seconds
bool m_shutdownWarned; // 1-minute warning shown
int m_lastCountdown; // last countdown value shown
public:
CWindowsConsole();
~CWindowsConsole();
bool Create();
void Destroy();
void Toggle();
void Show();
void Hide();
bool IsVisible() { return m_visible; }
bool IsQuitRequested() { return m_quitRequested; }
bool IsMT5Active(); // Check if MT5 or console is the active window.
void UpdatePosition(); // Reposition to active chart.
void ProcessChar(string c);
void ProcessKey(int keyCode);
void Redraw();
void ForceRedraw();
void AddLine(string text);
void ExecuteCommand(string cmd);
bool ProcessMessages(); // Returns false if window was closed.
bool IsBreathing() { return m_breathingMode; }
void UpdateBreathing(); // Update breathing animation.
bool IsShutdownPending() { return m_shutdownPending; }
void UpdateShutdown(); // Update shutdown countdown.
private:
void DrawConsole();
void ScrollUp();
void ScrollDown();
void ScrollToBottom();
long FindMT5Window();
long GetActiveChartId();
void InstallFromURL(string url);
bool DownloadFile(string url, string localPath);
bool ExtractZip(string zipPath, string destPath);
string GetMQL5Folder(string fileType);
string FindDownloadLink(string html, string baseUrl);
string ReadZipComment(string zipPath);
int InstallExtractedFiles(string srcPath, string destPath);
void LoadHistory();
void SaveHistory();
// Helper: finds Toolbox window and tab control (pure enumeration, no Sleep).
bool FindToolbox(long &hToolbox, long &hTabControl);
// Helper: opens Toolbox via View menu if not already open.
bool OpenToolbox(long &hToolbox, long &hTabControl);
// Helper: finds first visible SysListView32 child (pure enumeration, no Sleep).
long FindVisibleListView(long hParent);
// Helper: simulates key press (down + up, no Sleep).
void PressKey(int vk);
// Helper: simulates mouse click at screen coordinates (no Sleep).
void ClickAt(int x, int y);
// Helper: switch to adjacent chart (direction: -1 = left, +1 = right).
void SwitchChart(int direction);
// Helper: execute buy/sell trade (isBuy: true=buy, false=sell; isAsync: true=async mode).
void ExecuteTrade(bool isBuy, bool isAsync, string args);
// Helper: set color scheme (modeIndex: 0=system, 1=light, 2=dark).
void SetColorScheme(int modeIndex, string modeName);
};
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CWindowsConsole::CWindowsConsole()
{
m_hwnd = 0;
m_hwndMT5 = 0;
m_hFont = 0;
m_hBrush = 0;
m_visible = false;
m_inputText = "";
m_cursorPos = 0;
m_historyIndex = -1;
m_scrollOffset = 0;
m_maxVisibleLines = 20;
m_maxBufferLines = 1000;
m_needsRedraw = false;
m_quitRequested = false;
m_lastMessageTime = 0;
m_currentChartId = 0;
// Undo tracking.
m_lastUndoCommand = "";
m_lastUndoData = "";
m_lastUndoChartId = 0;
// Breathing mode.
m_breathingMode = false;
m_breathingStart = 0;
m_breathingDuration = 30;
m_breathingPhase = 0;
m_breathingPhaseStart = 0;
// Shutdown timer.
m_shutdownPending = false;
m_shutdownStart = 0;
m_shutdownDuration = 0;
m_shutdownWarned = false;
m_lastCountdown = -1;
ArrayResize(m_lines, 0);
ArrayResize(m_commandHistory, 0);
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CWindowsConsole::~CWindowsConsole()
{
Destroy();
}
//+------------------------------------------------------------------+
//| Load command history from file. |
//+------------------------------------------------------------------+
void CWindowsConsole::LoadHistory()
{
int hFile = FileOpen("console_history.txt", FILE_READ|FILE_TXT|FILE_ANSI);
if (hFile == INVALID_HANDLE)
return; // No history file yet.
while (!FileIsEnding(hFile))
{
string line = FileReadString(hFile);
StringTrimRight(line);
StringTrimLeft(line);
if (StringLen(line) > 0)
{
int size = ArraySize(m_commandHistory);
if (size < 100) // Max 100 commands.
{
ArrayResize(m_commandHistory, size + 1);
m_commandHistory[size] = line;
}
}
}
FileClose(hFile);
}
//+------------------------------------------------------------------+
//| Save command history to file. |
//+------------------------------------------------------------------+
void CWindowsConsole::SaveHistory()
{
int hFile = FileOpen("console_history.txt", FILE_WRITE|FILE_TXT|FILE_ANSI);
if (hFile == INVALID_HANDLE)
return;
// Keep last 100 commands.
int total = ArraySize(m_commandHistory);
int start = MathMax(0, total - 100);
for (int i = start; i < total; i++)
{
FileWriteString(hFile, m_commandHistory[i] + "\n");
}
FileClose(hFile);
}
//+------------------------------------------------------------------+
//| Find Toolbox window and its tab control. |
//| Returns true if both found, false otherwise. |
//| Pure window enumeration - no Sleep calls. |
//+------------------------------------------------------------------+
bool CWindowsConsole::FindToolbox(long &hToolbox, long &hTabControl)
{
hToolbox = 0;
hTabControl = 0;
long hChild = GetWindow(m_hwndMT5, GW_CHILD);
while (hChild != 0)
{
ushort className[64];
ArrayInitialize(className, 0);
GetClassNameW(hChild, className, 64);
string classStr = ShortArrayToString(className);
ushort windowText[128];
ArrayInitialize(windowText, 0);
GetWindowTextW(hChild, windowText, 128);
string textStr = ShortArrayToString(windowText);
// Check class, text, AND visibility.
if (StringFind(classStr, "Afx:ControlBar") >= 0 &&
StringFind(textStr, "Toolbox") >= 0 &&
IsWindowVisible(hChild))
{
hToolbox = hChild;
// Find tab control inside Toolbox.
long hToolChild = GetWindow(hToolbox, GW_CHILD);
while (hToolChild != 0)
{
ushort childClass[64];
ArrayInitialize(childClass, 0);
GetClassNameW(hToolChild, childClass, 64);
string childClassStr = ShortArrayToString(childClass);
if (StringFind(childClassStr, "SysTabControl32") >= 0)
{
hTabControl = hToolChild;
break;
}
hToolChild = GetWindow(hToolChild, GW_HWNDNEXT);
}
break;
}
hChild = GetWindow(hChild, GW_HWNDNEXT);
}
return (hToolbox != 0 && hTabControl != 0);
}
//+------------------------------------------------------------------+
//| Open Toolbox via View menu if not already visible. |
//| Returns true if Toolbox is found/opened, fills handles. |
//+------------------------------------------------------------------+
bool CWindowsConsole::OpenToolbox(long &hToolbox, long &hTabControl)
{
// First check if already open.
if (FindToolbox(hToolbox, hTabControl))
return true;
// Open via View menu.
long hMenu = GetMenu(m_hwndMT5);
if (hMenu == 0)
return false;
// Find View menu.
int menuCount = GetMenuItemCount(hMenu);
long hViewMenu = 0;
for (int i = 0; i < menuCount; i++)
{
ushort menuText[64];
ArrayInitialize(menuText, 0);
GetMenuStringW(hMenu, i, menuText, 64, MF_BYPOSITION);
string menuName = ShortArrayToString(menuText);
if (StringFind(menuName, "View") >= 0 || StringFind(menuName, "iew") >= 0)
{
hViewMenu = GetSubMenu(hMenu, i);
break;
}
}
if (hViewMenu == 0)
return false;
// Find Toolbox item in View menu.
int viewCount = GetMenuItemCount(hViewMenu);
uint toolboxCmdId = 0;
for (int i = 0; i < viewCount; i++)
{
ushort menuText[64];
ArrayInitialize(menuText, 0);
GetMenuStringW(hViewMenu, i, menuText, 64, MF_BYPOSITION);
string menuName = ShortArrayToString(menuText);
if (StringFind(menuName, "Toolbox") >= 0)
{
toolboxCmdId = GetMenuItemID(hViewMenu, i);
break;
}
}
if (toolboxCmdId == 0 || toolboxCmdId == 0xFFFFFFFF)
return false;
// Send command to toggle Toolbox.
PostMessageW(m_hwndMT5, WM_COMMAND, (int)toolboxCmdId, 0);
Sleep(100);
// Try to find Toolbox again.
return FindToolbox(hToolbox, hTabControl);
}
//+------------------------------------------------------------------+
//| Find first visible SysListView32 child window. |
//| Returns handle or 0 if not found. |
//| Pure window enumeration - no Sleep calls. |
//+------------------------------------------------------------------+
long CWindowsConsole::FindVisibleListView(long hParent)
{
if (hParent == 0)
return 0;
long hChild = GetWindow(hParent, GW_CHILD);
while (hChild != 0)
{
ushort childClass[64];
ArrayInitialize(childClass, 0);
GetClassNameW(hChild, childClass, 64);
string childClassStr = ShortArrayToString(childClass);
if (StringFind(childClassStr, "SysListView32") >= 0 && IsWindowVisible(hChild))
return hChild;
hChild = GetWindow(hChild, GW_HWNDNEXT);
}
return 0;
}
//+------------------------------------------------------------------+
//| Simulate a key press (down + up). |
//| No Sleep calls - timing handled by caller. |
//+------------------------------------------------------------------+
void CWindowsConsole::PressKey(int vk)
{
keybd_event((uchar)vk, 0, 0, 0);
keybd_event((uchar)vk, 0, KEYEVENTF_KEYUP, 0);
}
//+------------------------------------------------------------------+
//| Simulate mouse click at screen coordinates. |
//| No Sleep calls - timing handled by caller. |
//+------------------------------------------------------------------+
void CWindowsConsole::ClickAt(int x, int y)
{
SetCursorPos(x, y);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
//+------------------------------------------------------------------+
//| Switch to adjacent chart (direction: -1 = left, +1 = right). |
//+------------------------------------------------------------------+
void CWindowsConsole::SwitchChart(int direction)
{
// Build list of all chart IDs.
long charts[];
int count = 0;
long chartId = ChartFirst();
while (chartId >= 0)
{
ArrayResize(charts, count + 1);
charts[count] = chartId;
count++;
chartId = ChartNext(chartId);
}
if (count <= 1)
{
AddLine("No other charts open.");
return;
}
// Find current chart index.
int currentIdx = -1;
for (int i = 0; i < count; i++)
{
if (charts[i] == m_currentChartId)
{
currentIdx = i;
break;
}
}
if (currentIdx < 0)
currentIdx = 0;
// Calculate new index with wrap-around.
int newIdx = (currentIdx + direction + count) % count;
m_currentChartId = charts[newIdx];
// Bring chart to front.
ChartSetInteger(m_currentChartId, CHART_BRING_TO_TOP, true);
string sym = ChartSymbol(m_currentChartId);
ENUM_TIMEFRAMES tf = (ENUM_TIMEFRAMES)ChartPeriod(m_currentChartId);
AddLine("Switched focus to " + sym + " " + EnumToString(tf) + ".");
}
//+------------------------------------------------------------------+
//| Execute buy or sell trade (sync or async). |
//+------------------------------------------------------------------+
void CWindowsConsole::ExecuteTrade(bool isBuy, bool isAsync, string args)
{
string cmdName = (isBuy ? "buy" : "sell");
if (isAsync) cmdName = "a" + cmdName;
StringTrimLeft(args);
StringTrimRight(args);
if (StringLen(args) == 0)
{
AddLine("Usage: " + cmdName + " [symbol] <lots> [sl=<price>] [tp=<price>]");
AddLine("Example: " + cmdName + " 0.1" + (isBuy ? " sl=1.0850 tp=1.0950" : " sl=1.0950 tp=1.0850"));
AddLine(" " + cmdName + " eurusd 0.1");
return;
}
// Parse arguments.
string parts[];
StringSplit(args, ' ', parts);
string symbol = "";
double lots = 0;
double sl = 0;
double tp = 0;
for (int i = 0; i < ArraySize(parts); i++)
{
string part = parts[i];
StringTrimLeft(part);
StringTrimRight(part);
if (StringLen(part) == 0) continue;
if (StringFind(part, "sl=") == 0)
sl = StringToDouble(StringSubstr(part, 3));
else if (StringFind(part, "tp=") == 0)
tp = StringToDouble(StringSubstr(part, 3));
else
{
double val = StringToDouble(part);
if (val > 0 && lots == 0)
lots = val;
else if (symbol == "" && lots == 0)
{
symbol = part;
StringToUpper(symbol);
}
}
}
// Default to chart symbol if not specified.
if (symbol == "")
{
if (m_currentChartId <= 0)
{
AddLine("No active chart - specify symbol.");
AddLine("Example: " + cmdName + " eurusd 0.1");
return;
}
symbol = ChartSymbol(m_currentChartId);
}
// Validate symbol exists.
if (!SymbolInfoInteger(symbol, SYMBOL_EXIST))
{
AddLine("Symbol not found: " + symbol);
return;
}
// Add to Market Watch if not already there.
if (!SymbolInfoInteger(symbol, SYMBOL_SELECT))
{
if (SymbolSelect(symbol, true))
AddLine("Added " + symbol + " to Market Watch.");
else
{
AddLine("Failed to add " + symbol + " to Market Watch.");
return;
}
}
if (lots <= 0)
{
AddLine("Invalid lot size.");
return;
}
if (!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
{
AddLine("Autotrading is disabled!");
if (!isAsync) AddLine("Use 'auto' command to enable it.");
return;
}
if (!isAsync && SymbolInfoInteger(symbol, SYMBOL_TRADE_MODE) == SYMBOL_TRADE_MODE_DISABLED)
{
AddLine("Trading not allowed for: " + symbol);
return;
}
// Normalize lot size.
double minLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MAX);
double lotStep = SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
lots = MathMax(minLot, MathMin(maxLot, lots));
lots = NormalizeDouble(MathFloor(lots / lotStep) * lotStep, 2);
double price = SymbolInfoDouble(symbol, isBuy ? SYMBOL_ASK : SYMBOL_BID);
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
// Normalize SL/TP.
if (sl != 0) sl = NormalizeDouble(sl, digits);
if (tp != 0) tp = NormalizeDouble(tp, digits);
string orderType = (isBuy ? "BUY" : "SELL");
if (isAsync) orderType = "Async " + orderType;
else orderType = "Sending " + orderType;
string orderInfo = orderType + " " + DoubleToString(lots, 2) + " " + symbol +
" @ " + DoubleToString(price, digits);
if (sl != 0 && !isAsync) orderInfo += " SL=" + DoubleToString(sl, digits);
if (tp != 0 && !isAsync) orderInfo += " TP=" + DoubleToString(tp, digits);
AddLine(orderInfo);
// Execute trade.
CTrade trade;
trade.SetExpertMagicNumber(123456);
trade.SetDeviationInPoints(10);
if (isAsync) trade.SetAsyncMode(true);
string comment = "Console " + (isAsync ? "async " : "") + (isBuy ? "buy" : "sell");
bool success = isBuy ? trade.Buy(lots, symbol, price, sl, tp, comment)
: trade.Sell(lots, symbol, price, sl, tp, comment);
if (success)
{
if (isAsync)
{
MqlTradeResult result;
trade.Result(result);
AddLine("Request sent! ReqID: " + IntegerToString(result.request_id));
}
else
{
AddLine("SUCCESS! Order #" + IntegerToString(trade.ResultOrder()));
AddLine("Deal #" + IntegerToString(trade.ResultDeal()) +
" @ " + DoubleToString(trade.ResultPrice(), digits));
}
}
else
{
if (isAsync)
AddLine("FAILED to send request");
else
{
AddLine("FAILED! Retcode: " + IntegerToString(trade.ResultRetcode()));
AddLine("Comment: " + trade.ResultComment());
}
}