-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy paththetadx.h
More file actions
972 lines (848 loc) · 38.8 KB
/
thetadx.h
File metadata and controls
972 lines (848 loc) · 38.8 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
/**
* thetadatadx C FFI header.
*
* This header declares the C interface to the thetadatadx Rust SDK.
* Used by both the C++ wrapper and any other C-compatible language.
*
* Memory model:
* - Opaque handles (TdxCredentials*, TdxClient*, TdxConfig*) are heap-allocated
* by the Rust side and MUST be freed with the corresponding tdx_*_free function.
* - Tick data is returned as #[repr(C)] struct arrays. Each array type has a
* corresponding tdx_*_array_free function that MUST be called.
* - String arrays (TdxStringArray) must be freed with tdx_string_array_free.
* - Functions that can fail return empty arrays (data=NULL, len=0) and set a
* thread-local error string retrievable via tdx_last_error().
*/
#ifndef THETADX_H
#define THETADX_H
#include <stdint.h>
#include <stddef.h>
#ifndef __cplusplus
#include <stdbool.h>
#endif
#if defined(_MSC_VER)
#define TDX_ALIGN64_BEGIN __declspec(align(64))
#define TDX_ALIGN64_END
#else
#define TDX_ALIGN64_BEGIN
#define TDX_ALIGN64_END __attribute__((aligned(64)))
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* ── Opaque handle types ── */
typedef struct TdxCredentials TdxCredentials;
typedef struct TdxClient TdxClient;
typedef struct TdxConfig TdxConfig;
typedef struct TdxFpssHandle TdxFpssHandle;
typedef struct TdxUnified TdxUnified;
/* Generated request-options bridge shared with Rust FFI. */
#include "endpoint_request_options.h.inc"
/* ═══════════════════════════════════════════════════════════════════════ */
/* #[repr(C)] tick types — layout-compatible with Rust tdbe structs */
/* ═══════════════════════════════════════════════════════════════════════ */
/* All tick structs are 64-byte aligned to match Rust's #[repr(C, align(64))].
* Explicit tail padding is part of that ABI contract so C/C++ array stepping
* stays byte-for-byte compatible with Rust. Price fields are f64 (double). */
TDX_ALIGN64_BEGIN typedef struct {
int32_t date;
int32_t is_open;
int32_t open_time;
int32_t close_time;
int32_t status;
uint8_t _tail_padding[44];
} TdxCalendarDay TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
int32_t ms_of_day2;
double open;
double high;
double low;
double close;
/* volume/count are int64 to match the core crate (issue #372) and
* prevent overflow on high-volume symbols (2.1B+ cumulative volume). */
int64_t volume;
int64_t count;
int32_t bid_size;
int32_t bid_exchange;
double bid;
int32_t bid_condition;
int32_t ask_size;
int32_t ask_exchange;
/* 4 bytes padding before f64 */
double ask;
int32_t ask_condition;
int32_t date;
int32_t expiration;
/* 4 bytes padding before f64 */
double strike;
int32_t right;
uint8_t _tail_padding[4];
} TdxEodTick TDX_ALIGN64_END;
/* Full-union Greeks tick (option_*_greeks_all, option_*_greeks_eod). */
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
/* 4 bytes padding before f64 */
double bid;
double ask;
double implied_volatility;
double delta;
double gamma;
double theta;
double vega;
double rho;
double iv_error;
double vanna;
double charm;
double vomma;
double veta;
double speed;
double zomma;
double color;
double ultima;
double d1;
double d2;
double dual_delta;
double dual_gamma;
double epsilon;
double lambda;
double vera;
int32_t underlying_ms_of_day;
/* 4 bytes padding before f64 */
double underlying_price;
int32_t date;
int32_t expiration;
double strike;
int32_t right;
uint8_t _tail_padding[20];
} TdxGreeksAllTick TDX_ALIGN64_END;
/* First-order Greeks subset tick (option_*_greeks_first_order). */
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
/* 4 bytes padding before f64 */
double bid;
double ask;
double delta;
double theta;
double vega;
double rho;
double epsilon;
double lambda;
double implied_volatility;
double iv_error;
int32_t underlying_ms_of_day;
/* 4 bytes padding before f64 */
double underlying_price;
int32_t date;
int32_t expiration;
double strike;
int32_t right;
uint8_t _tail_padding[4];
} TdxGreeksFirstOrderTick TDX_ALIGN64_END;
/* Second-order Greeks subset tick (option_*_greeks_second_order). */
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
/* 4 bytes padding before f64 */
double bid;
double ask;
double gamma;
double vanna;
double charm;
double vomma;
double veta;
double implied_volatility;
double iv_error;
int32_t underlying_ms_of_day;
/* 4 bytes padding before f64 */
double underlying_price;
int32_t date;
int32_t expiration;
double strike;
int32_t right;
uint8_t _tail_padding[12];
} TdxGreeksSecondOrderTick TDX_ALIGN64_END;
/* Third-order Greeks subset tick (option_*_greeks_third_order). The
* vendor's third-order schema does not publish `vera`. */
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
/* 4 bytes padding before f64 */
double bid;
double ask;
double speed;
double zomma;
double color;
double ultima;
double implied_volatility;
double iv_error;
int32_t underlying_ms_of_day;
/* 4 bytes padding before f64 */
double underlying_price;
int32_t date;
int32_t expiration;
double strike;
int32_t right;
uint8_t _tail_padding[20];
} TdxGreeksThirdOrderTick TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
/* 4 bytes padding before f64 */
double rate;
int32_t date;
uint8_t _tail_padding[40];
} TdxInterestRateTick TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
/* 4 bytes padding before f64 */
double implied_volatility;
double iv_error;
int32_t date;
int32_t expiration;
double strike;
int32_t right;
uint8_t _tail_padding[16];
} TdxIvTick TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
/* 4 bytes padding before f64 */
double market_bid;
double market_ask;
double market_price;
int32_t date;
int32_t expiration;
double strike;
int32_t right;
uint8_t _tail_padding[8];
} TdxMarketValueTick TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
/* 4 bytes padding before f64 */
double open;
double high;
double low;
double close;
/* volume/count are int64 to match the core crate (issue #372) and
* prevent overflow on high-volume symbols (2.1B+ cumulative volume). */
int64_t volume;
int64_t count;
int32_t date;
int32_t expiration;
double strike;
int32_t right;
uint8_t _tail_padding[52];
} TdxOhlcTick TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
int32_t open_interest;
int32_t date;
int32_t expiration;
double strike;
int32_t right;
uint8_t _tail_padding[32];
} TdxOpenInterestTick TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
/* 4 bytes padding before f64 */
double price;
int32_t date;
uint8_t _tail_padding[40];
} TdxPriceTick TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
int32_t bid_size;
int32_t bid_exchange;
/* 4 bytes padding before f64 */
double bid;
int32_t bid_condition;
int32_t ask_size;
int32_t ask_exchange;
/* 4 bytes padding before f64 */
double ask;
int32_t ask_condition;
int32_t date;
int32_t expiration;
/* 4 bytes padding before f64 */
double strike;
int32_t right;
/* 4 bytes padding before f64 */
double midpoint;
uint8_t _tail_padding[40];
} TdxQuoteTick TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
int32_t sequence;
int32_t ext_condition1;
int32_t ext_condition2;
int32_t ext_condition3;
int32_t ext_condition4;
int32_t condition;
int32_t size;
int32_t exchange;
/* 4 bytes padding before f64 */
double price;
int32_t condition_flags;
int32_t price_flags;
int32_t volume_type;
int32_t records_back;
int32_t quote_ms_of_day;
int32_t bid_size;
int32_t bid_exchange;
/* 4 bytes padding before f64 */
double bid;
int32_t bid_condition;
int32_t ask_size;
int32_t ask_exchange;
/* 4 bytes padding before f64 */
double ask;
int32_t ask_condition;
int32_t date;
int32_t expiration;
/* 4 bytes padding before f64 */
double strike;
int32_t right;
uint8_t _tail_padding[48];
} TdxTradeQuoteTick TDX_ALIGN64_END;
TDX_ALIGN64_BEGIN typedef struct {
int32_t ms_of_day;
int32_t sequence;
int32_t ext_condition1;
int32_t ext_condition2;
int32_t ext_condition3;
int32_t ext_condition4;
int32_t condition;
int32_t size;
int32_t exchange;
/* 4 bytes padding before f64 */
double price;
int32_t condition_flags;
int32_t price_flags;
int32_t volume_type;
int32_t records_back;
int32_t date;
int32_t expiration;
double strike;
int32_t right;
uint8_t _tail_padding[40];
} TdxTradeTick TDX_ALIGN64_END;
/* ═══════════════════════════════════════════════════════════════════════ */
/* Typed array return types */
/* ═══════════════════════════════════════════════════════════════════════ */
typedef struct { const TdxEodTick* data; size_t len; } TdxEodTickArray;
typedef struct { const TdxOhlcTick* data; size_t len; } TdxOhlcTickArray;
typedef struct { const TdxTradeTick* data; size_t len; } TdxTradeTickArray;
typedef struct { const TdxQuoteTick* data; size_t len; } TdxQuoteTickArray;
typedef struct { const TdxGreeksAllTick* data; size_t len; } TdxGreeksAllTickArray;
typedef struct { const TdxGreeksFirstOrderTick* data; size_t len; } TdxGreeksFirstOrderTickArray;
typedef struct { const TdxGreeksSecondOrderTick* data; size_t len; } TdxGreeksSecondOrderTickArray;
typedef struct { const TdxGreeksThirdOrderTick* data; size_t len; } TdxGreeksThirdOrderTickArray;
typedef struct { const TdxIvTick* data; size_t len; } TdxIvTickArray;
typedef struct { const TdxPriceTick* data; size_t len; } TdxPriceTickArray;
typedef struct { const TdxOpenInterestTick* data; size_t len; } TdxOpenInterestTickArray;
typedef struct { const TdxMarketValueTick* data; size_t len; } TdxMarketValueTickArray;
typedef struct { const TdxCalendarDay* data; size_t len; } TdxCalendarDayArray;
typedef struct { const TdxInterestRateTick* data; size_t len; } TdxInterestRateTickArray;
typedef struct { const TdxTradeQuoteTick* data; size_t len; } TdxTradeQuoteTickArray;
/* ── OptionContract (has heap-allocated symbol string) ── */
typedef struct {
const char* symbol; /* heap-allocated, freed with tdx_option_contract_array_free */
int32_t expiration;
/* 4 bytes padding before f64 */
double strike;
int32_t right;
} TdxOptionContract;
typedef struct { const TdxOptionContract* data; size_t len; } TdxOptionContractArray;
/* ── String array (for list endpoints) ── */
typedef struct {
const char* const* data; /* array of NUL-terminated C strings */
size_t len;
} TdxStringArray;
/* ── Greeks result (standalone tdx_all_greeks) ── */
typedef struct {
double value;
double delta;
double gamma;
double theta;
double vega;
double rho;
double epsilon;
double lambda;
double vanna;
double charm;
double vomma;
double veta;
double vera;
double speed;
double zomma;
double color;
double ultima;
double iv;
double iv_error;
double d1;
double d2;
double dual_delta;
double dual_gamma;
} TdxGreeksResult;
/* ── Subscription types (active_subscriptions) ── */
typedef struct {
const char* kind; /* "Quote", "Trade", or "OpenInterest" */
const char* contract; /* "SPY" or "SPY 20260417 550 C" */
} TdxSubscription;
typedef struct {
const TdxSubscription* data;
size_t len;
} TdxSubscriptionArray;
/* ═══════════════════════════════════════════════════════════════════════ */
/* Free functions for typed arrays */
/* ═══════════════════════════════════════════════════════════════════════ */
void tdx_eod_tick_array_free(TdxEodTickArray arr);
void tdx_ohlc_tick_array_free(TdxOhlcTickArray arr);
void tdx_trade_tick_array_free(TdxTradeTickArray arr);
void tdx_quote_tick_array_free(TdxQuoteTickArray arr);
void tdx_greeks_all_tick_array_free(TdxGreeksAllTickArray arr);
void tdx_greeks_first_order_tick_array_free(TdxGreeksFirstOrderTickArray arr);
void tdx_greeks_second_order_tick_array_free(TdxGreeksSecondOrderTickArray arr);
void tdx_greeks_third_order_tick_array_free(TdxGreeksThirdOrderTickArray arr);
void tdx_iv_tick_array_free(TdxIvTickArray arr);
void tdx_price_tick_array_free(TdxPriceTickArray arr);
void tdx_open_interest_tick_array_free(TdxOpenInterestTickArray arr);
void tdx_market_value_tick_array_free(TdxMarketValueTickArray arr);
void tdx_calendar_day_array_free(TdxCalendarDayArray arr);
void tdx_interest_rate_tick_array_free(TdxInterestRateTickArray arr);
void tdx_trade_quote_tick_array_free(TdxTradeQuoteTickArray arr);
void tdx_option_contract_array_free(TdxOptionContractArray arr);
void tdx_string_array_free(TdxStringArray arr);
void tdx_greeks_result_free(TdxGreeksResult* result);
void tdx_subscription_array_free(TdxSubscriptionArray* arr);
/* ── Error ── */
/** Retrieve the last error message (or NULL if no error).
* The returned pointer is valid until the next FFI call on the same thread.
* Do NOT free this pointer. */
const char* tdx_last_error(void);
/** Clear the thread-local error string.
* Higher-level wrappers should call this before issuing an FFI call so
* they can distinguish "the call set a new error" from "the previous
* call left a stale error in the slot" when an empty value (e.g. zero
* rows) is also a valid success outcome. */
void tdx_clear_error(void);
/* ── Credentials ── */
/** Create credentials from email and password. Returns NULL on error. */
TdxCredentials* tdx_credentials_new(const char* email, const char* password);
/** Load credentials from a file (line 1 = email, line 2 = password). Returns NULL on error. */
TdxCredentials* tdx_credentials_from_file(const char* path);
/** Free a credentials handle. */
void tdx_credentials_free(TdxCredentials* creds);
/* ── Config ── */
/** Create a production config (ThetaData NJ datacenter). */
TdxConfig* tdx_config_production(void);
/** Create a dev FPSS config (port 20200, infinite historical replay). */
TdxConfig* tdx_config_dev(void);
/** Create a stage FPSS config (port 20100, testing, unstable). */
TdxConfig* tdx_config_stage(void);
/** Free a config handle. */
void tdx_config_free(TdxConfig* config);
/**
* Set FPSS reconnect policy on a config handle.
* policy=0: Auto (default) -- auto-reconnect matching Java terminal behavior.
* policy=1: Manual -- no auto-reconnect.
*/
void tdx_config_set_reconnect_policy(TdxConfig* config, int policy);
/**
* Set FPSS flush mode on a config handle.
* mode=0: Batched (default) -- flush only on PING every 100ms.
* mode=1: Immediate -- flush after every frame write.
*/
void tdx_config_set_flush_mode(TdxConfig* config, int mode);
/**
* Set FPSS OHLCVC derivation on a config handle.
* enabled=1 (default): derive OHLCVC bars locally from trade events.
* enabled=0: only emit server-sent OHLCVC frames (lower overhead).
*/
void tdx_config_set_derive_ohlcvc(TdxConfig* config, int enabled);
/* ── Client ── */
/** Connect to ThetaData servers. Returns NULL on connection/auth failure. */
TdxClient* tdx_client_connect(const TdxCredentials* creds, const TdxConfig* config);
/** Free a client handle. */
void tdx_client_free(TdxClient* client);
/* ── String free ── */
/** Free a string returned by any tdx_* function. */
void tdx_string_free(char* s);
/* Generated option-aware endpoint declarations. */
#include "endpoint_with_options.h.inc"
/* ═══════════════════════════════════════════════════════════════════════ */
/* Greeks (standalone) */
/* ═══════════════════════════════════════════════════════════════════════ */
/** Compute all 23 Greeks + IV. `right` accepts "C"/"P" or "call"/"put" (case-insensitive).
* Returns heap-allocated TdxGreeksResult (or NULL on error). Caller must free with tdx_greeks_result_free. */
TdxGreeksResult* tdx_all_greeks(double spot, double strike, double rate, double div_yield,
double tte, double option_price, const char* right);
/** Compute implied volatility. `right` accepts "C"/"P" or "call"/"put" (case-insensitive).
* Returns 0 on success, -1 on failure. */
int tdx_implied_volatility(double spot, double strike, double rate, double div_yield,
double tte, double option_price, const char* right,
double* out_iv, double* out_error);
/* ═══════════════════════════════════════════════════════════════════════ */
/* Cross-language utility helpers — conditions / exchange / sequences */
/* ═══════════════════════════════════════════════════════════════════════ */
/* All `tdx_*_name` / `tdx_*_description` / `tdx_exchange_*` returns are
* NUL-terminated UTF-8 C strings owned by the library. They are
* `'static`-lifetime — DO NOT FREE. The pointer remains valid for the
* lifetime of the process. Unknown codes return either "UNKNOWN" (name
* lookup) or "" (description lookup), never NULL. */
/** Trade condition name lookup. Returns "UNKNOWN" for unrecognised codes. */
const char* tdx_condition_name(int32_t code);
/** Trade condition description lookup. Returns "" for unrecognised codes. */
const char* tdx_condition_description(int32_t code);
/** True if the trade condition code represents a cancellation. */
bool tdx_condition_is_cancel(int32_t code);
/** True if the trade condition code updates the volume bar. */
bool tdx_condition_updates_volume(int32_t code);
/** Quote condition name lookup. Returns "UNKNOWN" for unrecognised codes. */
const char* tdx_quote_condition_name(int32_t code);
/** Quote condition description lookup. Returns "" for unrecognised codes. */
const char* tdx_quote_condition_description(int32_t code);
/** True if the quote condition is firm (binding). */
bool tdx_quote_condition_is_firm(int32_t code);
/** True if the quote condition indicates a trading halt. */
bool tdx_quote_condition_is_halted(int32_t code);
/** Exchange name lookup (e.g. 3 -> "NewYorkStockExchange"). */
const char* tdx_exchange_name(int32_t code);
/** Exchange MIC-like symbol lookup (e.g. 3 -> "NYSE"). */
const char* tdx_exchange_symbol(int32_t code);
/** Convert a signed wire-encoded trade-sequence value to its unsigned
* monotonic form. */
uint64_t tdx_sequence_signed_to_unsigned(int64_t signed_value);
/** Convert an unsigned monotonic trade-sequence value back to its signed
* wire encoding. */
int64_t tdx_sequence_unsigned_to_signed(uint64_t unsigned_value);
/* ═══════════════════════════════════════════════════════════════════════ */
/* FPSS — #[repr(C)] streaming event types */
/* ═══════════════════════════════════════════════════════════════════════ */
/* FPSS event structs are schema-driven. The include below pulls in the
* same typedefs the Go SDK uses, generated from
* `crates/thetadatadx/fpss_event_schema.toml` — so the C++ header can
* never drift from the Rust `#[repr(C)]` layout again. See
* `thetadx.hpp` for `static_assert(offsetof)` guards that fail the
* build at compile time if the schema and the C++ consumer ever
* disagree.
*
* Flattened the flat `TdxFpssControl { kind, id, detail }`
* envelope into one typed `#[repr(C)]` struct per `FpssControl::*` Rust
* variant. Consumers dispatch via `event->kind` and read the matching
* `event-><variant>` payload — for example
*
* if (event->kind == TDX_FPSS_LOGIN_SUCCESS)
* printf("perms=%s\n", event->login_success.permissions);
* if (event->kind == TDX_FPSS_DISCONNECTED)
* printf("reason=%d\n", event->disconnected.reason);
*
* Borrowed pointers (`Contract.symbol`, `LoginSuccess.permissions`,
* `ServerError.message`, `Error.message`, `Ping.payload`,
* `UnknownFrame.payload`) are valid only for the duration of the
* user callback — copy out before returning. Do NOT free. */
#include "fpss_event_structs.h.inc"
/* ═══════════════════════════════════════════════════════════════════════ */
/* FPSS — Real-time streaming client */
/* ═══════════════════════════════════════════════════════════════════════ */
/** Connect to FPSS streaming servers. Returns NULL on failure. */
TdxFpssHandle* tdx_fpss_connect(const TdxCredentials* creds, const TdxConfig* config);
/** Polymorphic subscribe / unsubscribe — see TdxSubscriptionRequest below. */
/** Check if authenticated. Returns 1 if true, 0 if false. */
int tdx_fpss_is_authenticated(const TdxFpssHandle* h);
/** Get active subscriptions as typed array. Caller must free with tdx_subscription_array_free. */
TdxSubscriptionArray* tdx_fpss_active_subscriptions(const TdxFpssHandle* h);
/** User callback signature for tdx_*_set_callback.
* `event` is valid only for the duration of the call -- copy any fields the
* caller wants to outlive the callback. `ctx` is the opaque pointer the
* caller registered alongside the callback; it is passed back unchanged. */
typedef void (*TdxFpssCallback)(const TdxFpssEvent* event, void* ctx);
/** Register an FPSS callback and open the FPSS connection.
*
* Events flow `FPSS reader -> LMAX Disruptor ring -> consumer thread ->
* catch_unwind(callback)`. The reader thread NEVER blocks on user code:
* on ring overflow events are dropped and counted (tdx_fpss_dropped_events).
*
* ## ctx lifetime + thread affinity
*
* `ctx` MUST remain valid until ONE of: (a) tdx_fpss_free() returns
* (which performs shutdown if needed and applies the drain barrier
* internally with a 5 s timeout), or (b) tdx_fpss_shutdown() /
* tdx_fpss_reconnect() returns AND tdx_fpss_await_drain() has
* returned 1. The Disruptor consumer thread accesses ctx on every
* event and on every tdx_fpss_reconnect(), serially on a single
* thread. Freeing ctx without one of these barriers is undefined
* behavior.
*
* The Disruptor consumer thread invokes `callback(event, ctx)` serially on
* a single thread. The user does NOT need internal locks for callback-
* private state.
*
* ## Lifecycle contract (FPSS one-shot rule)
*
* Must be called exactly ONCE per handle. After tdx_fpss_shutdown() this
* handle is terminal: a second register, a register-after-shutdown, a
* reconnect-after-shutdown, or a double-shutdown all return -1 with a
* clear tdx_last_error() string ("FPSS callback already installed -- ..."
* or "FPSS handle has already been shut down -- this is terminal").
*
* This is intentionally stricter than tdx_unified_set_callback(), where
* set-after-stop is supported as a normal user flow.
*
* Returns 0 on success, -1 on error (check tdx_last_error()). */
int tdx_fpss_set_callback(const TdxFpssHandle* h, TdxFpssCallback callback, void* ctx);
/** Reconnect FPSS using the previously-registered callback. Returns 0 or -1.
* Returns -1 with "FPSS handle has already been shut down -- this is
* terminal" if the handle is past tdx_fpss_shutdown. */
int tdx_fpss_reconnect(const TdxFpssHandle* h);
/** Cumulative count of FPSS events the TLS reader could not publish into
* the LMAX Disruptor ring because the consumer fell behind and the ring
* was full (`Producer::try_publish` returned `RingBufferFull`). Returns 0
* if the handle is null or no callback has been installed yet. */
uint64_t tdx_fpss_dropped_events(const TdxFpssHandle* h);
/** Shut down the FPSS client. Terminal: every subsequent set_callback /
* reconnect / shutdown call on this handle returns -1 with a clear
* tdx_last_error() string. The handle remains valid for
* tdx_fpss_free() only. Returns asynchronously: the FPSS reader and
* Disruptor consumer continue draining in-flight events through the
* registered callback until they observe the shutdown signal and
* exit. Pair with tdx_fpss_await_drain() (or use tdx_fpss_free(), which
* applies the drain barrier internally) before freeing the callback
* ctx. */
void tdx_fpss_shutdown(const TdxFpssHandle* h);
/** Wait for the previously-superseded FPSS session to quiesce.
*
* Returns 1 once the previous tdx_fpss_reconnect / tdx_fpss_shutdown
* session's Disruptor consumer has finished firing the registered
* callback. Returns 0 on timeout or when no session has been
* superseded on this handle.
*
* Must be called from a thread other than the FPSS Disruptor consumer
* thread; calling it from inside the user callback would block the
* helper the consumer is waiting on and always time out. */
int tdx_fpss_await_drain(const TdxFpssHandle* h, uint64_t timeout_ms);
/** Free the FPSS handle.
*
* Accepts the handle in either lifecycle state: if shutdown has not
* yet been called, tdx_fpss_free performs the shutdown sequence
* itself. Returns only after the consumer thread has finished firing
* the registered callback (internal 5-second drain barrier). On
* drain-flag timeout, emits a tracing::error! and proceeds with
* destruction; in that diagnostic case the consumer may still be
* firing, so user code must keep ctx valid past return. Under normal
* operation drain completes in low single-digit milliseconds, so ctx
* is safe to free immediately on return. */
void tdx_fpss_free(TdxFpssHandle* h);
/* ======================================================================= */
/* Unified client -- historical + streaming through one handle */
/* ======================================================================= */
/** Connect to ThetaData (historical only -- FPSS streaming is NOT started).
* Returns NULL on connection/auth failure (check tdx_last_error()). */
TdxUnified* tdx_unified_connect(const TdxCredentials* creds, const TdxConfig* config);
/** Register an FPSS callback and start streaming on the unified client.
*
* Events flow `FPSS reader -> LMAX Disruptor ring -> consumer thread ->
* catch_unwind(callback)`. Reader never blocks on user code; ring-overflow
* events are dropped (tdx_unified_dropped_events).
*
* ## ctx lifetime + thread affinity
*
* `ctx` MUST remain valid until ONE of: (a) tdx_unified_free()
* returns (which calls stop_streaming and applies the drain barrier
* internally with a 5 s timeout), (b) tdx_unified_stop_streaming() /
* tdx_unified_reconnect() returns AND tdx_unified_await_drain() has
* returned 1, or (c) a successful replacement tdx_unified_set_callback
* has returned AND tdx_unified_await_drain() has returned 1 for the
* prior session. The Disruptor consumer thread accesses ctx on every
* event and reconnect, serially on a single thread. Freeing ctx
* without one of these barriers is undefined behavior.
*
* ## Lifecycle contract (REPLACEMENT after stop)
*
* Unlike tdx_fpss_set_callback (one-shot), the unified path supports
* stop+register as a normal user flow: after tdx_unified_stop_streaming
* another tdx_unified_set_callback REPLACES the saved (callback, ctx).
* tdx_unified_reconnect is built on top of this. Calling set_callback
* while streaming is already active returns -1 with "streaming already
* started".
*
* Returns 0 on success, -1 on error. */
int tdx_unified_set_callback(const TdxUnified* handle, TdxFpssCallback callback, void* ctx);
/** Subscription request scope discriminator (TdxSubscriptionRequest.scope). */
#define TDX_SUB_SCOPE_CONTRACT 0
#define TDX_SUB_SCOPE_FULL 1
/** Subscription kind discriminator (TdxSubscriptionRequest.kind). */
#define TDX_SUB_KIND_QUOTE 0
#define TDX_SUB_KIND_TRADE 1
#define TDX_SUB_KIND_OPEN_INTEREST 2
/** Polymorphic subscribe / unsubscribe request payload.
*
* Mirrors the Rust `Subscription` enum across the C ABI.
*
* - Per-contract stock: scope=CONTRACT, symbol="AAPL", option fields NULL.
* - Per-contract option: scope=CONTRACT, symbol="SPY", expiration / strike / right set.
* - Full-stream: scope=FULL, sec_type="OPTION" (or "STOCK", "INDEX"), per-contract fields NULL.
*/
typedef struct {
int32_t scope; /* TDX_SUB_SCOPE_CONTRACT or TDX_SUB_SCOPE_FULL */
int32_t kind; /* TDX_SUB_KIND_QUOTE / _TRADE / _OPEN_INTEREST */
const char* symbol; /* per-contract only */
const char* expiration; /* per-contract option only */
const char* strike; /* per-contract option only */
const char* right; /* per-contract option only */
const char* sec_type; /* full-stream only */
} TdxSubscriptionRequest;
/** Polymorphic subscribe on the unified client. Returns 0 or -1. */
int tdx_unified_subscribe(const TdxUnified* handle, const TdxSubscriptionRequest* request);
/** Polymorphic unsubscribe on the unified client. Returns 0 or -1. */
int tdx_unified_unsubscribe(const TdxUnified* handle, const TdxSubscriptionRequest* request);
/** Polymorphic subscribe on the standalone FPSS client. Returns 0 or -1. */
int tdx_fpss_subscribe(const TdxFpssHandle* h, const TdxSubscriptionRequest* request);
/** Polymorphic unsubscribe on the standalone FPSS client. Returns 0 or -1. */
int tdx_fpss_unsubscribe(const TdxFpssHandle* h, const TdxSubscriptionRequest* request);
/** Reconnect unified streaming, re-subscribing all previous subscriptions. Returns 0 or -1. */
int tdx_unified_reconnect(const TdxUnified* handle);
/** Check if streaming is active. Returns 1 if streaming, 0 otherwise. */
int tdx_unified_is_streaming(const TdxUnified* handle);
/** Get active subscriptions as typed array. Caller must free with tdx_subscription_array_free. */
TdxSubscriptionArray* tdx_unified_active_subscriptions(const TdxUnified* handle);
/** Borrow the historical client from a unified handle. Do NOT free the returned pointer. */
const TdxClient* tdx_unified_historical(const TdxUnified* handle);
/** Stop streaming on the unified client. Historical remains available.
* Returns asynchronously: the FPSS reader and Disruptor consumer
* continue draining in-flight events through the registered callback
* until they observe the shutdown signal. Pair with
* tdx_unified_await_drain() (or use tdx_unified_free(), which applies
* the drain barrier internally) before freeing the callback ctx. */
void tdx_unified_stop_streaming(const TdxUnified* handle);
/** Wait for the previously-superseded streaming session to quiesce.
*
* Returns 1 once the previous Disruptor consumer thread has finished
* firing the registered callback. Returns 0 on timeout or when no
* stream has ever been started or stopped on this handle.
*
* Must be called from a thread other than the FPSS consumer thread. */
int tdx_unified_await_drain(const TdxUnified* handle, uint64_t timeout_ms);
/** Cumulative count of FPSS events the TLS reader could not publish into
* the LMAX Disruptor ring because the consumer fell behind and the ring
* was full. Returns 0 if the handle is null or no callback has been
* installed yet. */
uint64_t tdx_unified_dropped_events(const TdxUnified* handle);
/** Free a unified client handle.
*
* Calls tdx_unified_stop_streaming internally, then waits up to 5
* seconds for the consumer thread to finish firing the registered
* callback before destroying the handle. On drain-flag timeout,
* emits a tracing::error! and proceeds with destruction; in that
* diagnostic case the consumer may still be firing, so user code
* must keep ctx valid past return. Under normal operation drain
* completes in low single-digit milliseconds, so ctx is safe to
* free immediately on return. */
void tdx_unified_free(TdxUnified* handle);
/* ── Pull-iter delivery ─────────────────────────────────────
*
* Sibling of the push-callback path. `tdx_unified_set_callback` sends
* each event through a user `extern "C" fn` invoked on the LMAX
* Disruptor consumer thread; the iterator instead drains a per-client
* bounded queue from the caller's own thread, so the consumer thread
* is decoupled from any per-event GIL / event-loop costs the binding
* pays. Mutually exclusive with the callback path on the same
* `TdxUnified*`; switch by stopping streaming and starting again.
*/
/** Opaque pull-iter handle returned by tdx_unified_start_streaming_iter. */
typedef struct TdxFpssEventIterator TdxFpssEventIterator;
/** Start FPSS streaming on the unified client in pull-iter mode.
*
* Returns a freshly allocated `TdxFpssEventIterator*` on success.
* Mutually exclusive with `tdx_unified_set_callback` — calling
* either while streaming is already running returns NULL with
* `tdx_last_error()` set to `"streaming already started"`. Free with
* `tdx_fpss_event_iter_free` when done iterating.
*
* Returns NULL on connection / auth / state failure. */
TdxFpssEventIterator* tdx_unified_start_streaming_iter(const TdxUnified* handle);
/** Pop the next FPSS event into `*out_event`. `timeout_ms = 0` is a
* non-blocking poll; positive `timeout_ms` blocks up to that
* deadline.
*
* Return values:
* - 0 — event filled into `*out_event`.
* - 1 — timeout expired with no event; `*out_event` untouched.
* - -1 — terminal end-of-stream (queue drained on a stopped session)
* OR call-site error (check `tdx_last_error()`).
*
* The borrowed pointer fields inside `*out_event` (`Contract.symbol`,
* `LoginSuccess.permissions`, payload byte slices, etc.) reference
* heap memory owned by the iterator handle's internal buffer. They
* are valid until the next `tdx_fpss_event_iter_next` call OR until
* `tdx_fpss_event_iter_free` is invoked, whichever happens first.
* Copy any fields the consumer wants to outlive the next call. */
int tdx_fpss_event_iter_next(TdxFpssEventIterator* it,
TdxFpssEvent* out_event,
int32_t timeout_ms);
/** Mark the iterator closed. Subsequent `_next` calls return -1
* (terminal) once the queue is drained, without shutting down the
* underlying streaming session. Idempotent. */
void tdx_fpss_event_iter_close(TdxFpssEventIterator* it);
/** Free a pull-iter handle. Does NOT stop the underlying streaming
* session — call `tdx_unified_stop_streaming` first if you need a
* full shutdown. */
void tdx_fpss_event_iter_free(TdxFpssEventIterator* it);
/* ── FLATFILES surface ────────────────────────────────────────────────
*
* Whole-universe daily snapshots over the legacy MDDS port. See
* `crates/thetadatadx/src/flatfiles/` for the wire format. The schema
* is determined at runtime by (sec_type, req_type), so the typed
* decoder returns an opaque row-list handle that you serialise to
* Arrow IPC bytes when you want columnar output.
*/
/** Opaque handle wrapping a decoded `Vec<FlatFileRow>`. Created by
* tdx_flatfile_request_decoded; freed by tdx_flatfile_rowlist_free. */
typedef struct TdxFlatFileRowList TdxFlatFileRowList;
/** Heap-owned byte buffer (Arrow IPC stream) returned by
* tdx_flatfile_rows_to_arrow_ipc. Caller MUST free with
* tdx_flatfile_bytes_free. */
typedef struct TdxFlatFileBytes {
const uint8_t* data;
size_t len;
} TdxFlatFileBytes;
/** Pull a decoded flat-file blob for (sec_type, req_type, date) and
* return an opaque row-list handle.
*
* sec_type -- "OPTION" / "STOCK" / "INDEX"
* req_type -- "EOD" / "QUOTE" / "OPEN_INTEREST" / "OHLC" / "TRADE" /
* "TRADE_QUOTE"
* date -- "YYYYMMDD"
*
* Returns NULL on error; check tdx_last_error(). The returned handle
* MUST be freed with tdx_flatfile_rowlist_free. */
TdxFlatFileRowList* tdx_flatfile_request_decoded(
const TdxUnified* handle,
const char* sec_type,
const char* req_type,
const char* date);
/** Number of rows in a row-list handle. Returns 0 if rowlist is NULL. */
size_t tdx_flatfile_rows_count(const TdxFlatFileRowList* rowlist);
/** Serialise the row list as Arrow IPC stream bytes. The schema is
* inferred from the first row by `flatfiles::arrow::rows_to_arrow`.
*
* Returns (data=NULL, len=0) on error; check tdx_last_error().
* Caller MUST free the returned bytes with tdx_flatfile_bytes_free. */
TdxFlatFileBytes tdx_flatfile_rows_to_arrow_ipc(
const TdxFlatFileRowList* rowlist);
/** Free a byte buffer returned by tdx_flatfile_rows_to_arrow_ipc. */
void tdx_flatfile_bytes_free(TdxFlatFileBytes bytes);
/** Free a row-list handle returned by tdx_flatfile_request_decoded. */
void tdx_flatfile_rowlist_free(TdxFlatFileRowList* rowlist);
/** Pull a flat-file blob and write the requested vendor format
* ("csv" / "jsonl") directly to `path`. Returns 0 on success, -1 on
* error; check tdx_last_error(). The format extension is appended to
* `path` automatically if missing. */
int tdx_flatfile_request_to_path(
const TdxUnified* handle,
const char* sec_type,
const char* req_type,
const char* date,
const char* path,
const char* format);
#ifdef __cplusplus
}
#endif
#endif /* THETADX_H */