-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathPlugin.cpp
More file actions
3676 lines (3136 loc) · 114 KB
/
Plugin.cpp
File metadata and controls
3676 lines (3136 loc) · 114 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
// Plugin.cpp - Complete implementation with Quotes and Historical data
#include "stdafx.h"
#include "resource.h" // Include resource definitions
#include "OpenAlgoGlobals.h"
#include "Plugin.h"
#include "Plugin_Legacy.h"
#include "OpenAlgoConfigDlg.h"
#include <math.h>
#include <time.h>
#include <stdlib.h> // For qsort
// Plugin identification
#define PLUGIN_NAME "OpenAlgo Data Plugin"
#define VENDOR_NAME "OpenAlgo Community"
#define PLUGIN_VERSION 10003
#define PLUGIN_ID PIDCODE('T', 'E', 'S', 'T') // Unique 4-char code
#define THIS_PLUGIN_TYPE PLUGIN_TYPE_DATA
#define AGENT_NAME PLUGIN_NAME
// Timer IDs
#define TIMER_INIT 198
#define TIMER_REFRESH 199
#define TIMER_WEBSOCKET 200 // High-frequency timer for WebSocket data processing
#define RETRY_COUNT 8
////////////////////////////////////////
// Plugin Info Structure
////////////////////////////////////////
static struct PluginInfo oPluginInfo =
{
sizeof(struct PluginInfo),
THIS_PLUGIN_TYPE,
PLUGIN_VERSION,
PLUGIN_ID,
PLUGIN_NAME,
VENDOR_NAME,
0,
530000
};
///////////////////////////////
// Global Variables
///////////////////////////////
HWND g_hAmiBrokerWnd = NULL;
int g_nPortNumber = 5000;
int g_nRefreshInterval = 5;
int g_nTimeShift = 0;
CString g_oServer = _T("127.0.0.1");
CString g_oApiKey = _T(""); // API Key for authentication
CString g_oWebSocketUrl = _T("ws://127.0.0.1:8765"); // WebSocket URL
int g_nStatus = STATUS_WAIT;
// Backfill request tracking
int g_nBackfillDays = 0; // Number of days to backfill (0 = use default logic)
int g_nBackfillPeriodicity = 0; // 60 for 1-minute, 86400 for daily
BOOL g_bBackfillRequested = FALSE;
// Local static variables
static int g_nRetryCount = RETRY_COUNT;
static struct RecentInfo* g_aInfos = NULL;
static int RecentInfoSize = 0;
static BOOL g_bPluginInitialized = FALSE;
// WebSocket connection management
static SOCKET g_websocket = INVALID_SOCKET;
static BOOL g_bWebSocketConnected = FALSE;
static BOOL g_bWebSocketAuthenticated = FALSE;
static BOOL g_bWebSocketConnecting = FALSE;
static DWORD g_dwLastConnectionAttempt = 0;
static CMap<CString, LPCTSTR, BOOL, BOOL> g_SubscribedSymbols;
static CRITICAL_SECTION g_WebSocketCriticalSection;
static BOOL g_bCriticalSectionInitialized = FALSE;
// Cache for recent quotes
struct QuoteCache {
CString symbol;
CString exchange;
float ltp;
float open;
float high;
float low;
float close;
float volume;
float oi;
DWORD lastUpdate;
// Constructor to initialize all values
QuoteCache() : ltp(0.0f), open(0.0f), high(0.0f), low(0.0f),
close(0.0f), volume(0.0f), oi(0.0f), lastUpdate(0) {
}
};
static CMap<CString, LPCTSTR, QuoteCache, QuoteCache&> g_QuoteCache;
typedef CArray< struct Quotation, struct Quotation > CQuoteArray;
//////////////////////////////////////////////////////////
// REAL-TIME CANDLE BUILDING STRUCTURES
//////////////////////////////////////////////////////////
// Real-time configuration (non-static so they can be accessed from OpenAlgoConfigDlg)
BOOL g_bRealTimeCandlesEnabled = TRUE; // Default: enabled
int g_nBackfillIntervalMs = 5000; // HTTP backfill every 5 seconds
// HTTP response caching (performance optimization)
// Cache HTTP responses to avoid calling HTTP API on every GetQuotesEx() call
CMapStringToPtr g_HttpResponseCache; // Maps "SYMBOL-PERIODICITY" → last HTTP call time (DWORD*)
CRITICAL_SECTION g_HttpCacheCriticalSection;
const DWORD HTTP_CACHE_LIFETIME_MS = 60000; // Cache HTTP responses for 60 seconds
static BOOL g_bHttpCacheCriticalSectionInitialized = FALSE;
// BarBuilder: Per-symbol tick-to-bar aggregation state
struct BarBuilder {
CString symbol;
CString exchange;
int periodicity; // 60 for 1-minute (only 1-minute supported initially)
// Current bar being built from ticks
struct Quotation currentBar;
BOOL bBarStarted;
time_t barStartTime;
// Tick accumulation
float volumeAccumulator; // Sum of last_trade_quantity
int tickCount;
// Historical bars storage
CArray<struct Quotation, struct Quotation> bars; // Up to 10,000 bars
int maxBars;
// Timestamps for backfill management
DWORD lastTickTime; // Last tick received
DWORD lastBackfillTime; // Last HTTP backfill
// State flags
BOOL bBackfillMerged;
BOOL bFirstTickReceived;
// Constructor
BarBuilder() : periodicity(60), bBarStarted(FALSE), barStartTime(0),
volumeAccumulator(0.0f), tickCount(0), maxBars(10000),
lastTickTime(0), lastBackfillTime(0),
bBackfillMerged(FALSE), bFirstTickReceived(FALSE) {
memset(¤tBar, 0, sizeof(struct Quotation));
}
};
// Global cache of bar builders (one per symbol)
static CMap<CString, LPCTSTR, BarBuilder*, BarBuilder*> g_BarBuilders;
static CRITICAL_SECTION g_BarBuilderCriticalSection;
static BOOL g_bBarBuilderCriticalSectionInitialized = FALSE;
// Forward declarations
VOID CALLBACK OnTimerProc(HWND, UINT, UINT_PTR, DWORD);
void SetupRetry(void);
BOOL TestOpenAlgoConnection(void);
BOOL GetOpenAlgoQuote(LPCTSTR pszTicker, QuoteCache& quote);
int GetOpenAlgoHistory(LPCTSTR pszTicker, int nPeriodicity, int nLastValid, int nSize, struct Quotation* pQuotes);
CString GetExchangeFromTicker(LPCTSTR pszTicker);
CString GetIntervalString(int nPeriodicity);
void ConvertUnixToPackedDate(time_t unixTime, union AmiDate* pAmiDate);
// WebSocket functions
BOOL InitializeWebSocket(void);
void CleanupWebSocket(void);
BOOL ConnectWebSocket(void);
BOOL AuthenticateWebSocket(void);
BOOL SendWebSocketFrame(const CString& message);
CString DecodeWebSocketFrame(const char* buffer, int length);
BOOL SubscribeToSymbol(LPCTSTR pszTicker);
BOOL UnsubscribeFromSymbol(LPCTSTR pszTicker);
BOOL ProcessWebSocketData(void);
void GenerateWebSocketMaskKey(unsigned char* maskKey);
void SubscribePendingSymbols(void);
// Real-time candle building functions
BOOL ProcessTick(const CString& symbol, const CString& exchange, float ltp, float lastTradeQty, time_t timestamp);
time_t ParseISO8601Timestamp(const CString& isoTimestamp);
BarBuilder* GetOrCreateBarBuilder(const CString& ticker);
void CleanupBarBuilders(void);
// Helper function for mixed EOD/Intraday data
int FindLastBarOfMatchingType(int nPeriodicity, int nLastValid, struct Quotation* pQuotes);
// Helper function to compare two quotations for sorting by timestamp
int CompareQuotations(const void* a, const void* b);
///////////////////////////////
// Helper Functions
///////////////////////////////
// Compare two quotations for sorting by timestamp (oldest to newest)
// Used by qsort() to ensure quotes array is in chronological order
// This is CRITICAL for AmiBroker to display charts correctly
int CompareQuotations(const void* a, const void* b)
{
const struct Quotation* qa = (const struct Quotation*)a;
const struct Quotation* qb = (const struct Quotation*)b;
// Compare 64-bit DateTime.Date field directly
// This handles both EOD and Intraday data correctly
if (qa->DateTime.Date < qb->DateTime.Date)
return -1;
else if (qa->DateTime.Date > qb->DateTime.Date)
return 1;
else
return 0;
}
// Find last bar in array that matches the requested periodicity type
// This is CRITICAL for Mixed EOD/Intraday support (AllowMixedEODIntra = TRUE)
//
// When mixed data is enabled, pQuotes array contains BOTH:
// - Daily bars (Hour=31, Minute=63)
// - Intraday bars (Hour=0-23)
//
// We must find the last bar of the CORRECT type to calculate gaps properly
int FindLastBarOfMatchingType(int nPeriodicity, int nLastValid, struct Quotation* pQuotes)
{
if (nLastValid < 0 || pQuotes == NULL)
return -1; // No data at all
if (nPeriodicity == 86400) // Looking for Daily data
{
// Scan backwards to find last Daily bar (Hour=31, Minute=63)
for (int i = nLastValid; i >= 0; i--)
{
if (pQuotes[i].DateTime.PackDate.Hour == DATE_EOD_HOURS &&
pQuotes[i].DateTime.PackDate.Minute == DATE_EOD_MINUTES)
{
return i; // Found last Daily bar
}
}
return -1; // No Daily bars found in array
}
else if (nPeriodicity == 60) // Looking for 1-minute (or other intraday) data
{
// Scan backwards to find last Intraday bar (Hour < 31)
for (int i = nLastValid; i >= 0; i--)
{
if (pQuotes[i].DateTime.PackDate.Hour < DATE_EOD_HOURS)
{
return i; // Found last Intraday bar
}
}
return -1; // No Intraday bars found in array
}
else
{
// Unknown periodicity - use last bar overall
return nLastValid;
}
}
CString BuildOpenAlgoURL(const CString& server, int port, const CString& endpoint)
{
CString result;
result.Format(_T("http://%s:%d%s"), (LPCTSTR)server, port, (LPCTSTR)endpoint);
return result;
}
// Extract exchange from ticker format (e.g., "RELIANCE-NSE" -> "NSE")
CString GetExchangeFromTicker(LPCTSTR pszTicker)
{
CString ticker(pszTicker);
int dashPos = ticker.ReverseFind(_T('-'));
if (dashPos != -1)
{
return ticker.Mid(dashPos + 1);
}
// Default to NSE if no exchange suffix found
return _T("NSE");
}
// Get clean symbol without exchange suffix
CString GetCleanSymbol(LPCTSTR pszTicker)
{
CString ticker(pszTicker);
int dashPos = ticker.ReverseFind(_T('-'));
if (dashPos != -1)
{
return ticker.Left(dashPos);
}
return ticker;
}
// Convert periodicity to OpenAlgo interval string
// Currently supporting only 1m and D (daily) intervals
CString GetIntervalString(int nPeriodicity)
{
// Only support 1-minute and Daily for now
if (nPeriodicity == 60) // 1 minute in seconds
return _T("1m");
else if (nPeriodicity == 86400) // Daily in seconds (24*60*60)
return _T("D"); // Daily
else
return _T("D"); // Default to daily for all other timeframes
}
// Convert Unix timestamp to AmiBroker date format
// Works for all market types including 24x7 markets
void ConvertUnixToPackedDate(time_t unixTime, union AmiDate* pAmiDate)
{
struct tm* timeinfo = localtime(&unixTime);
pAmiDate->PackDate.Year = timeinfo->tm_year + 1900;
pAmiDate->PackDate.Month = timeinfo->tm_mon + 1;
pAmiDate->PackDate.Day = timeinfo->tm_mday;
pAmiDate->PackDate.Hour = timeinfo->tm_hour;
pAmiDate->PackDate.Minute = timeinfo->tm_min;
pAmiDate->PackDate.Second = timeinfo->tm_sec;
pAmiDate->PackDate.MilliSec = 0;
pAmiDate->PackDate.MicroSec = 0;
pAmiDate->PackDate.Reserved = 0;
pAmiDate->PackDate.IsFuturePad = 0;
}
// Fetch real-time quote from OpenAlgo
// WARNING: This is ONLY for Level 1 quotes in Real-time Quote Window
// NEVER use this data for creating OHLC bars or historical charts
BOOL GetOpenAlgoQuote(LPCTSTR pszTicker, QuoteCache& quote)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if (g_oApiKey.IsEmpty())
return FALSE;
BOOL bSuccess = FALSE;
try
{
CString oURL = BuildOpenAlgoURL(g_oServer, g_nPortNumber, _T("/api/v1/quotes"));
// Prepare POST data
CString symbol = GetCleanSymbol(pszTicker);
CString exchange = GetExchangeFromTicker(pszTicker);
CString oPostData;
oPostData.Format(_T("{\"apikey\":\"%s\",\"symbol\":\"%s\",\"exchange\":\"%s\"}"),
(LPCTSTR)g_oApiKey, (LPCTSTR)symbol, (LPCTSTR)exchange);
CInternetSession oSession(AGENT_NAME, 1, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL,
INTERNET_FLAG_DONT_CACHE);
oSession.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 3000);
oSession.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, 3000);
CHttpConnection* pConnection = NULL;
CHttpFile* pFile = NULL;
// Parse server
INTERNET_PORT nPort = (INTERNET_PORT)g_nPortNumber;
CString oServer = g_oServer;
oServer.Replace(_T("http://"), _T(""));
oServer.Replace(_T("https://"), _T(""));
pConnection = oSession.GetHttpConnection(oServer, nPort);
if (pConnection)
{
pFile = pConnection->OpenRequest(
CHttpConnection::HTTP_VERB_POST,
_T("/api/v1/quotes"),
NULL, 1, NULL, NULL,
INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE);
if (pFile)
{
CString oHeaders = _T("Content-Type: application/json\r\n");
CStringA oPostDataA(oPostData);
if (pFile->SendRequest(oHeaders, (LPVOID)(LPCSTR)oPostDataA, oPostDataA.GetLength()))
{
DWORD dwStatusCode = 0;
pFile->QueryInfoStatusCode(dwStatusCode);
if (dwStatusCode == 200)
{
CString oResponse;
CString oLine;
while (pFile->ReadString(oLine))
{
oResponse += oLine;
}
// Parse JSON response (simple parsing)
if (oResponse.Find(_T("\"status\":\"success\"")) >= 0)
{
// Extract values using simple string parsing
int pos;
// Parse LTP
pos = oResponse.Find(_T("\"ltp\":"));
if (pos >= 0)
{
pos += 6;
int endPos = oResponse.Find(_T(","), pos);
if (endPos < 0) endPos = oResponse.Find(_T("}"), pos);
CString val = oResponse.Mid(pos, endPos - pos);
quote.ltp = (float)_tstof(val);
}
// Parse Open
pos = oResponse.Find(_T("\"open\":"));
if (pos >= 0)
{
pos += 7;
int endPos = oResponse.Find(_T(","), pos);
if (endPos < 0) endPos = oResponse.Find(_T("}"), pos);
CString val = oResponse.Mid(pos, endPos - pos);
quote.open = (float)_tstof(val);
}
// Parse High
pos = oResponse.Find(_T("\"high\":"));
if (pos >= 0)
{
pos += 7;
int endPos = oResponse.Find(_T(","), pos);
if (endPos < 0) endPos = oResponse.Find(_T("}"), pos);
CString val = oResponse.Mid(pos, endPos - pos);
quote.high = (float)_tstof(val);
}
// Parse Low
pos = oResponse.Find(_T("\"low\":"));
if (pos >= 0)
{
pos += 6;
int endPos = oResponse.Find(_T(","), pos);
if (endPos < 0) endPos = oResponse.Find(_T("}"), pos);
CString val = oResponse.Mid(pos, endPos - pos);
quote.low = (float)_tstof(val);
}
// Parse Volume
pos = oResponse.Find(_T("\"volume\":"));
if (pos >= 0)
{
pos += 9;
int endPos = oResponse.Find(_T(","), pos);
if (endPos < 0) endPos = oResponse.Find(_T("}"), pos);
CString val = oResponse.Mid(pos, endPos - pos);
quote.volume = (float)_tstof(val);
}
// Parse OI
pos = oResponse.Find(_T("\"oi\":"));
if (pos >= 0)
{
pos += 5;
int endPos = oResponse.Find(_T(","), pos);
if (endPos < 0) endPos = oResponse.Find(_T("}"), pos);
CString val = oResponse.Mid(pos, endPos - pos);
quote.oi = (float)_tstof(val);
}
// Parse Previous Close
pos = oResponse.Find(_T("\"prev_close\":"));
if (pos >= 0)
{
pos += 13;
int endPos = oResponse.Find(_T(","), pos);
if (endPos < 0) endPos = oResponse.Find(_T("}"), pos);
CString val = oResponse.Mid(pos, endPos - pos);
quote.close = (float)_tstof(val);
}
quote.symbol = symbol;
quote.exchange = exchange;
quote.lastUpdate = (DWORD)GetTickCount64();
bSuccess = TRUE;
}
}
}
pFile->Close();
delete pFile;
}
pConnection->Close();
delete pConnection;
}
oSession.Close();
}
catch (CInternetException* e)
{
e->Delete();
}
return bSuccess;
}
// Fetch historical data from OpenAlgo with intelligent backfill strategy
// COMPLETELY EXCHANGE-AGNOSTIC - Works with ANY exchange and ANY trading hours
//
// OPTIMAL GAP-FREE BACKFILL STRATEGY (DATE-BASED):
// - First load: 30 days (1m) or 10 years (daily) of historical data
// - Subsequent refreshes: Smart gap detection from last bar's date
// - Automatically fills data gaps (user absences, network outages, etc.)
// - Safety limits: Max 30 days for 1m, max 730 days (2 years) for daily
// - Zero data holes within safety limits
//
// HOW IT WORKS:
// 1. Extract last bar's DATE (not time) from existing data
// 2. Calculate gap in days between last bar and today
// 3. Apply safety limits to prevent server overload
// 4. Request date range from OpenAlgo API (DATE-only, no time)
// 5. API returns ALL bars for each date in range
// 6. Duplicate detection handles overlapping bars
//
// EXCHANGE SUPPORT:
// - NSE: Regular + evening sessions + special Sunday sessions
// - MCX: Overnight sessions + extended hours
// - Crypto: 24x7 including weekends
// - Any future sessions that exchanges may introduce
//
// Currently supports 1m and D (daily) intervals
int GetOpenAlgoHistory(LPCTSTR pszTicker, int nPeriodicity, int nLastValid, int nSize, struct Quotation* pQuotes)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if (g_oApiKey.IsEmpty())
return nLastValid + 1;
try
{
CString oURL = BuildOpenAlgoURL(g_oServer, g_nPortNumber, _T("/api/v1/history"));
// Prepare POST data
CString symbol = GetCleanSymbol(pszTicker);
CString exchange = GetExchangeFromTicker(pszTicker);
CString interval = GetIntervalString(nPeriodicity);
// Get current time and today's date (at midnight)
CTime currentTime = CTime::GetCurrentTime();
CTime todayDate = CTime(currentTime.GetYear(), currentTime.GetMonth(), currentTime.GetDay(), 0, 0, 0);
CTime startTime;
CTime endTime = todayDate; // Request up to today for both Daily and Intraday
// Check if manual backfill was requested - override normal logic
if (g_bBackfillRequested && g_nBackfillPeriodicity == nPeriodicity && g_nBackfillDays > 0)
{
// Manual backfill - fetch full requested period regardless of existing data
startTime = todayDate - CTimeSpan((LONG)g_nBackfillDays, 0, 0, 0);
g_bBackfillRequested = FALSE; // Clear the request
goto skip_gap_detection;
}
// SMART GAP-FREE BACKFILL LOGIC WITH MIXED EOD/INTRADAY SUPPORT
if (nLastValid >= 0 && pQuotes != NULL)
{
// ============================================================
// EXISTING DATA FOUND - Smart Gap Detection
// ============================================================
// CRITICAL: Find last bar of MATCHING TYPE for mixed data support
// When AllowMixedEODIntra = TRUE, array contains both Daily and Intraday bars
// We must find the last bar that matches our requested periodicity!
int lastMatchingBarIndex = FindLastBarOfMatchingType(nPeriodicity, nLastValid, pQuotes);
if (lastMatchingBarIndex < 0)
{
// No bars of matching type found → Treat as initial load
// Example: Requesting Daily data but only 1-minute bars exist
if (nPeriodicity == 60)
startTime = todayDate - CTimeSpan(30, 0, 0, 0);
else
startTime = todayDate - CTimeSpan(3650, 0, 0, 0);
goto skip_gap_detection;
}
// Extract last matching bar's DATE (ignore time component)
int lastBarYear = pQuotes[lastMatchingBarIndex].DateTime.PackDate.Year;
int lastBarMonth = pQuotes[lastMatchingBarIndex].DateTime.PackDate.Month;
int lastBarDay = pQuotes[lastMatchingBarIndex].DateTime.PackDate.Day;
// Create CTime for last bar's date (at midnight)
CTime lastBarDate;
try
{
lastBarDate = CTime(lastBarYear, lastBarMonth, lastBarDay, 0, 0, 0);
}
catch (...)
{
// Invalid date in last bar (corrupted data)
// Fall back to initial load
if (nPeriodicity == 60)
startTime = todayDate - CTimeSpan(30, 0, 0, 0);
else
startTime = todayDate - CTimeSpan(3650, 0, 0, 0);
goto skip_gap_detection;
}
// VALIDATE: Check if last bar is in the future (corrupted data)
if (lastBarDate > todayDate)
{
// Last bar is in future - corrupted data detected
// Fall back to initial load
if (nPeriodicity == 60)
startTime = todayDate - CTimeSpan(30, 0, 0, 0);
else
startTime = todayDate - CTimeSpan(3650, 0, 0, 0);
goto skip_gap_detection;
}
// Calculate gap in days
CTimeSpan gap = todayDate - lastBarDate;
int gapDays = (int)gap.GetDays();
// DEBUG: Log backfill info for diagnosis
//CString debugMsg;
//debugMsg.Format(_T("BACKFILL - Symbol: %s, GapDays: %d, LastBar: %s, Today: %s, Periodicity: %d"),
// pszTicker, gapDays,
// lastBarDate.Format(_T("%Y-%m-%d")).GetString(),
// todayDate.Format(_T("%Y-%m-%d")).GetString(),
// nPeriodicity);
//OutputDebugString(debugMsg);
// Apply different logic for Daily vs Intraday data
if (nPeriodicity == 60) // 1-minute data
{
const int MAX_BACKFILL_DAYS_1M = 30; // Safety limit for 1-minute data
// Check if data is too old → Force initial load
if (gapDays > MAX_BACKFILL_DAYS_1M)
{
// Data too stale - do fresh 30-day load
startTime = todayDate - CTimeSpan(MAX_BACKFILL_DAYS_1M, 0, 0, 0);
}
else
{
// Recent data - backfill from last bar's date
startTime = lastBarDate;
}
}
else // Daily data (nPeriodicity == 86400)
{
const int MAX_BACKFILL_DAYS_DAILY = 730; // Safety limit: 2 years
const int MIN_DAILY_BARS = 250; // ~1 year of trading days
const int STALENESS_THRESHOLD_DAYS = 365; // 1 year staleness check
// CHECK 1: Do we have enough bars for proper analysis?
if (lastMatchingBarIndex < MIN_DAILY_BARS)
{
// Too few Daily bars - do initial 10-year load
startTime = todayDate - CTimeSpan(3650, 0, 0, 0);
}
// CHECK 2: Is data too stale?
else if (gapDays > STALENESS_THRESHOLD_DAYS)
{
// Gap > 1 year - do initial 10-year load
startTime = todayDate - CTimeSpan(3650, 0, 0, 0);
}
// CHECK 3: Gap within safety limit?
else if (gapDays > MAX_BACKFILL_DAYS_DAILY)
{
// Gap exceeds 2-year safety limit - cap at maximum
startTime = todayDate - CTimeSpan(MAX_BACKFILL_DAYS_DAILY, 0, 0, 0);
}
else
{
// Good recent data - backfill from last bar's date
startTime = lastBarDate;
}
}
}
else
{
// ============================================================
// NO EXISTING DATA - Initial Backfill
// ============================================================
// Check if manual backfill was requested
if (g_bBackfillRequested && g_nBackfillPeriodicity == nPeriodicity && g_nBackfillDays > 0)
{
// Use requested backfill period
startTime = todayDate - CTimeSpan((LONG)g_nBackfillDays, 0, 0, 0);
g_bBackfillRequested = FALSE; // Clear the request
}
else if (nPeriodicity == 60) // 1-minute data
{
// Initial load: 30 days of 1-minute data
startTime = todayDate - CTimeSpan(30, 0, 0, 0);
}
else // Daily data
{
// Initial load: 10 years of daily data (increased from 1 year)
// This provides sufficient historical context for technical analysis
startTime = todayDate - CTimeSpan(3650, 0, 0, 0);
}
}
skip_gap_detection:
CString startDate = startTime.Format(_T("%Y-%m-%d"));
CString endDate = endTime.Format(_T("%Y-%m-%d"));
// DEBUG: Log API request details
//CString apiDebugMsg;
//apiDebugMsg.Format(_T("API REQUEST - Symbol: %s, Exchange: %s, Interval: %s, Start: %s, End: %s"),
// (LPCTSTR)symbol, (LPCTSTR)exchange, (LPCTSTR)interval, (LPCTSTR)startDate, (LPCTSTR)endDate);
//OutputDebugString(apiDebugMsg);
CString oPostData;
oPostData.Format(_T("{\"apikey\":\"%s\",\"symbol\":\"%s\",\"exchange\":\"%s\",\"interval\":\"%s\",\"start_date\":\"%s\",\"end_date\":\"%s\"}"),
(LPCTSTR)g_oApiKey, (LPCTSTR)symbol, (LPCTSTR)exchange, (LPCTSTR)interval, (LPCTSTR)startDate, (LPCTSTR)endDate);
CInternetSession oSession(AGENT_NAME, 1, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL,
INTERNET_FLAG_DONT_CACHE);
oSession.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 10000);
oSession.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, 10000);
CHttpConnection* pConnection = NULL;
CHttpFile* pFile = NULL;
// Parse server
INTERNET_PORT nPort = (INTERNET_PORT)g_nPortNumber;
CString oServer = g_oServer;
oServer.Replace(_T("http://"), _T(""));
oServer.Replace(_T("https://"), _T(""));
pConnection = oSession.GetHttpConnection(oServer, nPort);
if (pConnection)
{
pFile = pConnection->OpenRequest(
CHttpConnection::HTTP_VERB_POST,
_T("/api/v1/history"),
NULL, 1, NULL, NULL,
INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE);
if (pFile)
{
CString oHeaders = _T("Content-Type: application/json\r\n");
CStringA oPostDataA(oPostData);
if (pFile->SendRequest(oHeaders, (LPVOID)(LPCSTR)oPostDataA, oPostDataA.GetLength()))
{
DWORD dwStatusCode = 0;
pFile->QueryInfoStatusCode(dwStatusCode);
if (dwStatusCode == 200)
{
CString oResponse;
CString oLine;
while (pFile->ReadString(oLine))
{
oResponse += oLine;
}
// Parse JSON response
if (oResponse.Find(_T("\"status\":\"success\"")) >= 0)
{
// Find data array
int dataStart = oResponse.Find(_T("\"data\":["));
if (dataStart >= 0)
{
dataStart += 8;
int dataEnd = oResponse.Find(_T("]"), dataStart);
if (dataEnd < 0) dataEnd = oResponse.GetLength();
CString dataArray = oResponse.Mid(dataStart, dataEnd - dataStart);
// DEBUG: Log data received
//CString dataDebugMsg;
//dataDebugMsg.Format(_T("API RESPONSE - DataLength: %d bytes"), dataArray.GetLength());
//OutputDebugString(dataDebugMsg);
// Debug: Check if we have meaningful data
if (dataArray.GetLength() < 10)
{
// Very little data, might be an issue
//OutputDebugString(_T("WARNING: Very little data received from API"));
return nLastValid + 1;
}
// Parse each candle and merge with existing data
int quoteIndex = 0;
int pos = 0;
int originalLastValid = nLastValid; // Save for accurate counting
// If we have existing data, we'll need to merge properly
BOOL bHasExistingData = (nLastValid >= 0);
if (bHasExistingData)
{
// CRITICAL: Check if array is near full before adding new data
// If array is 95% full, remove oldest 10% to make room for new bars
const int ARRAY_THRESHOLD = (int)(nSize * 0.95); // 95% full
const int BARS_TO_REMOVE = (int)(nSize * 0.10); // Remove 10%
if (nLastValid >= ARRAY_THRESHOLD)
{
// Array is nearly full - shift data to remove oldest bars
memmove(pQuotes, pQuotes + BARS_TO_REMOVE, (nLastValid - BARS_TO_REMOVE + 1) * sizeof(struct Quotation));
nLastValid -= BARS_TO_REMOVE;
// DEBUG: Log array cleanup
//CString cleanupMsg;
//cleanupMsg.Format(_T("ARRAY CLEANUP - Removed %d oldest bars, New nLastValid: %d"), BARS_TO_REMOVE, nLastValid);
//OutputDebugString(cleanupMsg);
}
// Start appending after existing data
quoteIndex = nLastValid + 1;
}
// Count duplicates for debugging
int duplicateCount = 0;
int uniqueCount = 0;
while (pos < dataArray.GetLength() && quoteIndex < nSize)
{
int candleStart = dataArray.Find(_T("{"), pos);
if (candleStart < 0) break;
int candleEnd = dataArray.Find(_T("}"), candleStart);
if (candleEnd < 0) break;
CString candle = dataArray.Mid(candleStart, candleEnd - candleStart + 1);
// Parse timestamp
int tsPos = candle.Find(_T("\"timestamp\":"));
if (tsPos >= 0)
{
tsPos += 12;
int tsEnd = candle.Find(_T(","), tsPos);
if (tsEnd < 0) tsEnd = candle.Find(_T("}"), tsPos);
CString tsStr = candle.Mid(tsPos, tsEnd - tsPos);
time_t timestamp = (time_t)_tstoi64(tsStr);
// Convert to AmiBroker date
if (nPeriodicity == 86400) // Daily data
{
// For daily data, set the DAILY_MASK and EOD markers
ConvertUnixToPackedDate(timestamp, &pQuotes[quoteIndex].DateTime);
pQuotes[quoteIndex].DateTime.Date |= DAILY_MASK;
// Set EOD markers and normalize ALL time fields
// CRITICAL: All Daily bars must have identical time fields
// to avoid display issues with the last candle
pQuotes[quoteIndex].DateTime.PackDate.Hour = 31; // EOD marker
pQuotes[quoteIndex].DateTime.PackDate.Minute = 63; // EOD marker
pQuotes[quoteIndex].DateTime.PackDate.Second = 0; // Normalize
pQuotes[quoteIndex].DateTime.PackDate.MilliSec = 0; // Normalize
pQuotes[quoteIndex].DateTime.PackDate.MicroSec = 0; // Normalize
}
else
{
// For intraday data
ConvertUnixToPackedDate(timestamp, &pQuotes[quoteIndex].DateTime);
// CRITICAL FIX: Normalize sub-minute time fields for 1-minute bars
// This prevents freak candles during live updates when seconds change
// Same principle as Daily bars - all bars for the same minute must have
// identical time fields to avoid duplicate bar creation
if (nPeriodicity == 60) // 1-minute data
{
pQuotes[quoteIndex].DateTime.PackDate.Second = 0; // Normalize
pQuotes[quoteIndex].DateTime.PackDate.MilliSec = 0; // Normalize
pQuotes[quoteIndex].DateTime.PackDate.MicroSec = 0; // Normalize
}
}
// Parse OHLCV
int oPos = candle.Find(_T("\"open\":"));
if (oPos >= 0)
{
oPos += 7;
int oEnd = candle.Find(_T(","), oPos);
CString val = candle.Mid(oPos, oEnd - oPos);
pQuotes[quoteIndex].Open = (float)_tstof(val);
}
int hPos = candle.Find(_T("\"high\":"));
if (hPos >= 0)
{
hPos += 7;
int hEnd = candle.Find(_T(","), hPos);
CString val = candle.Mid(hPos, hEnd - hPos);
pQuotes[quoteIndex].High = (float)_tstof(val);
}
int lPos = candle.Find(_T("\"low\":"));
if (lPos >= 0)
{
lPos += 6;
int lEnd = candle.Find(_T(","), lPos);
CString val = candle.Mid(lPos, lEnd - lPos);
pQuotes[quoteIndex].Low = (float)_tstof(val);
}
int cPos = candle.Find(_T("\"close\":"));
if (cPos >= 0)
{
cPos += 8;
int cEnd = candle.Find(_T(","), cPos);
if (cEnd < 0) cEnd = candle.Find(_T("}"), cPos);
CString val = candle.Mid(cPos, cEnd - cPos);
pQuotes[quoteIndex].Price = (float)_tstof(val);
}
int vPos = candle.Find(_T("\"volume\":"));
if (vPos >= 0)
{
vPos += 9;
int vEnd = candle.Find(_T(","), vPos);
if (vEnd < 0) vEnd = candle.Find(_T("}"), vPos);
CString val = candle.Mid(vPos, vEnd - vPos);
pQuotes[quoteIndex].Volume = (float)_tstof(val);
}
int oiPos = candle.Find(_T("\"oi\":"));
if (oiPos >= 0)
{
oiPos += 5;
int oiEnd = candle.Find(_T(","), oiPos);
if (oiEnd < 0) oiEnd = candle.Find(_T("}"), oiPos);
CString val = candle.Mid(oiPos, oiEnd - oiPos);
pQuotes[quoteIndex].OpenInterest = (float)_tstof(val);
}
// Set auxiliary data
pQuotes[quoteIndex].AuxData1 = 0;
pQuotes[quoteIndex].AuxData2 = 0;
// Check for duplicate timestamps against existing data
// FIXED: Properly handle mixed EOD/Intraday data without mktime() corruption
BOOL bIsDuplicate = FALSE;
if (bHasExistingData)
{
// Get new bar's properties
BOOL bNewBarIsEOD = (pQuotes[quoteIndex].DateTime.PackDate.Hour == DATE_EOD_HOURS &&
pQuotes[quoteIndex].DateTime.PackDate.Minute == DATE_EOD_MINUTES);
// Check against ALL existing bars for same-day duplicates
// CRITICAL: After sorting, today's bars are scattered throughout array
// Must check entire array, not just "last N bars by index"
// Optimization: array is sorted, so stop when date changes
unsigned int newBarYear = pQuotes[quoteIndex].DateTime.PackDate.Year;
unsigned int newBarMonth = pQuotes[quoteIndex].DateTime.PackDate.Month;
unsigned int newBarDay = pQuotes[quoteIndex].DateTime.PackDate.Day;
for (int i = nLastValid; i >= 0; i--)
{
// SOLUTION 2: Filter by periodicity - Never compare across interval types
BOOL bExistingBarIsEOD = (pQuotes[i].DateTime.PackDate.Hour == DATE_EOD_HOURS &&
pQuotes[i].DateTime.PackDate.Minute == DATE_EOD_MINUTES);
// Skip if different interval types (EOD vs Intraday)
if (bNewBarIsEOD != bExistingBarIsEOD)
continue;
// Optimization: Since sorted by time, if existing bar is older than new bar's date, stop searching
if (pQuotes[i].DateTime.PackDate.Year < newBarYear ||
(pQuotes[i].DateTime.PackDate.Year == newBarYear && pQuotes[i].DateTime.PackDate.Month < newBarMonth) ||
(pQuotes[i].DateTime.PackDate.Year == newBarYear && pQuotes[i].DateTime.PackDate.Month == newBarMonth && pQuotes[i].DateTime.PackDate.Day < newBarDay))
{
break; // No more bars from same day
}
// SOLUTION 3: Direct PackDate comparison instead of mktime()
BOOL bSameBar = FALSE;
if (bNewBarIsEOD)
{
// For EOD bars: Compare DATE ONLY (Year, Month, Day)
// Ignore time components since Hour=31, Minute=63 are markers, not actual time
bSameBar = (pQuotes[quoteIndex].DateTime.PackDate.Year == pQuotes[i].DateTime.PackDate.Year &&
pQuotes[quoteIndex].DateTime.PackDate.Month == pQuotes[i].DateTime.PackDate.Month &&
pQuotes[quoteIndex].DateTime.PackDate.Day == pQuotes[i].DateTime.PackDate.Day);
}
else
{
// For Intraday bars: Compare full timestamp (Year, Month, Day, Hour, Minute)
// Allow same minute to be considered duplicate
bSameBar = (pQuotes[quoteIndex].DateTime.PackDate.Year == pQuotes[i].DateTime.PackDate.Year &&
pQuotes[quoteIndex].DateTime.PackDate.Month == pQuotes[i].DateTime.PackDate.Month &&
pQuotes[quoteIndex].DateTime.PackDate.Day == pQuotes[i].DateTime.PackDate.Day &&
pQuotes[quoteIndex].DateTime.PackDate.Hour == pQuotes[i].DateTime.PackDate.Hour &&
pQuotes[quoteIndex].DateTime.PackDate.Minute == pQuotes[i].DateTime.PackDate.Minute);
}
if (bSameBar)
{
bIsDuplicate = TRUE;
// Update existing bar with latest data instead of adding new
pQuotes[i].Price = pQuotes[quoteIndex].Price; // Close
pQuotes[i].High = max(pQuotes[i].High, pQuotes[quoteIndex].High);
pQuotes[i].Low = (pQuotes[i].Low == 0) ? pQuotes[quoteIndex].Low : min(pQuotes[i].Low, pQuotes[quoteIndex].Low);
pQuotes[i].Volume = pQuotes[quoteIndex].Volume;
pQuotes[i].OpenInterest = pQuotes[quoteIndex].OpenInterest;
break;
}
}