of_ffi_c 0.4.0

C ABI facade for the Orderflow runtime
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
#![allow(non_camel_case_types)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
#![doc = include_str!("../README.md")]

mod support;

use std::ffi::{c_char, c_void, CString};
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};

use of_adapters::{AdapterConfig, ProviderKind};
use of_core::{AnalyticsConfig, BookUpdate, DataQualityFlags, SignalState, SymbolId, TradePrint};
use of_execution::{
    simulated_engine_with_routes, AllowAllRiskGate, ConcurrentExecutionConfig,
    ConcurrentExecutionEngine, ConcurrentExecutionError, ExecutionCommand, ExecutionCommandKind,
    ExecutionCommandReport, ExecutionEngine, ExecutionError, ExecutionEventBuffer, InMemoryJournal,
    RouteConfig, SimExecutionAdapter,
};
use of_execution_core::{
    AmendRequest, CancelRequest, ExecutionEvent, ExecutionSymbol, FixedAscii, OrderPrice, OrderQty,
    OrderRequest, OrderSide, OrderState, OrderType, RiskLimits, StrategyId, TimeInForce,
    VenueOrderId,
};
use of_runtime::{
    build_default_engine, load_engine_config_from_path, DefaultEngine, EngineConfig,
    ExternalFeedPolicy, RuntimeError,
};
#[cfg(feature = "tickbar")]
use support::format_bar_series;
use support::{
    action_from_ffi, dispatch_callbacks, dispatch_health_callbacks, escape_json,
    format_acd_snapshot, format_agent_type_snapshot, format_almgren_chriss_snapshot,
    format_amihud_snapshot, format_analytics_snapshot, format_book_analytics_snapshot,
    format_book_event_analytics_snapshot, format_book_snapshot, format_cvd_enhancement_snapshot,
    format_dark_lit_correlation_snapshot, format_dark_pool_snapshot,
    format_derived_analytics_snapshot, format_futures_snapshot, format_hasbrouck_snapshot,
    format_institutional_flow_snapshot, format_interval_candle_snapshot,
    format_kinetic_energy_snapshot, format_kyle_lambda_snapshot, format_lob_feature_snapshot,
    format_noise_snapshot, format_oi_analysis_snapshot, format_options_flow_snapshot,
    format_pattern_snapshot, format_regime_snapshot, format_resiliency_snapshot,
    format_session_candle_snapshot, format_spread_decomp_snapshot, format_vol_signature_snapshot,
    format_volatility_snapshot, format_vpin_snapshot, non_empty_string, parse_csv, side_from_ffi,
    symbol_from_ffi, symbol_from_ffi_ref, write_json_to_c_buffer,
};

const API_VERSION: u32 = 0x0001_0000;
const EXECUTION_API_VERSION: u32 = 0x0001_0000;
const BUILD_INFO: &[u8] = concat!("of_ffi_c/", env!("CARGO_PKG_VERSION"), "\0").as_bytes();
const FFI_EVENT_BUFFER_CAP: usize = 32;

/// Analytics configuration passed to [`of_engine_set_analytics_config`].
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct of_analytics_config_t {
    /// Trade-size threshold for agent classification.
    pub agent_small_trade_threshold: f64,
    /// Large-trade threshold for institutional-flow classification.
    pub institutional_trade_threshold: i64,
    /// Window for cancel/arrival-rate computation.
    pub cancel_arrival_window_ns: u64,
    /// Volume per VPIN bucket.
    pub vpin_volume_bucket: u32,
    /// Max VPIN buckets.
    pub vpin_max_buckets: u32,
    /// Kyle's Lambda rolling window.
    pub kyle_lambda_max_len: u32,
    /// CVD enhancement rolling window.
    pub cvd_max_len: u32,
    /// Volatility estimator rolling window.
    pub vol_estimator_max_len: u32,
    /// Microstructure noise rolling window.
    pub noise_max_len: u32,
    /// Hasbrouck VAR rolling window.
    pub hasbrouck_max_len: u32,
    /// Almgren-Chriss rolling window.
    pub almgren_chriss_max_len: u32,
    /// ACD model rolling window.
    pub acd_max_len: u32,
    /// Volatility signature rolling window.
    pub vol_signature_max_len: u32,
    /// Agent detector rolling window.
    pub agent_max_len: u32,
    /// Minimum samples for agent classification.
    pub agent_min_samples: u32,
    /// Institutional-flow rolling window.
    pub institutional_max_len: u32,
    /// Resiliency tracker rolling window.
    pub resiliency_max_len: u32,
    /// Spread-decomposition rolling window.
    pub spread_decomp_max_len: u32,
    /// Regime detector rolling window.
    pub regime_max_len: u32,
    /// Book-event tracker capacity.
    pub event_tracker_max_len: u32,
    /// Spread tracker capacity.
    pub spread_tracker_max_len: u32,
    /// Default rolling window for trackers not otherwise specified.
    pub default_max_len: u32,
}

impl From<of_analytics_config_t> for AnalyticsConfig {
    fn from(value: of_analytics_config_t) -> Self {
        Self {
            vpin_volume_bucket: i64::from(value.vpin_volume_bucket),
            vpin_max_buckets: value.vpin_max_buckets,
            kyle_lambda_max_len: value.kyle_lambda_max_len,
            cvd_max_len: value.cvd_max_len,
            vol_estimator_max_len: value.vol_estimator_max_len,
            noise_max_len: value.noise_max_len,
            hasbrouck_max_len: value.hasbrouck_max_len,
            almgren_chriss_max_len: value.almgren_chriss_max_len,
            acd_max_len: value.acd_max_len,
            vol_signature_max_len: value.vol_signature_max_len,
            agent_max_len: value.agent_max_len,
            agent_min_samples: value.agent_min_samples,
            agent_small_trade_threshold: value.agent_small_trade_threshold,
            institutional_trade_threshold: value.institutional_trade_threshold,
            institutional_max_len: value.institutional_max_len,
            resiliency_max_len: value.resiliency_max_len,
            spread_decomp_max_len: value.spread_decomp_max_len,
            regime_max_len: value.regime_max_len,
            cancel_arrival_window_ns: value.cancel_arrival_window_ns,
            event_tracker_max_len: value.event_tracker_max_len,
            spread_tracker_max_len: value.spread_tracker_max_len,
            default_max_len: value.default_max_len,
        }
    }
}

/// Engine configuration passed to [`of_engine_create`].
#[repr(C)]
pub struct of_engine_config_t {
    /// Optional runtime instance identifier.
    pub instance_id: *const c_char,
    /// Optional config file path loaded by the runtime.
    pub config_path: *const c_char,
    /// Reserved log-level field for host integrations.
    pub log_level: u32,
    /// Non-zero enables persistence.
    pub enable_persistence: u8,
    /// Audit log rotation size threshold in bytes.
    pub audit_max_bytes: u64,
    /// Number of rotated audit log files to retain.
    pub audit_max_files: u32,
    /// Comma-separated redaction token list.
    pub audit_redact_tokens_csv: *const c_char,
    /// Maximum retained persistence bytes (0 disables).
    pub data_retention_max_bytes: u64,
    /// Maximum retained persistence age seconds (0 disables).
    pub data_retention_max_age_secs: u64,
}

/// Symbol descriptor used by subscription and snapshot functions.
#[repr(C)]
pub struct of_symbol_t {
    /// Venue or exchange identifier.
    pub venue: *const c_char,
    /// Venue-native symbol identifier.
    pub symbol: *const c_char,
    /// Requested level-2 depth for subscriptions.
    pub depth_levels: u16,
}

/// External trade payload accepted by [`of_ingest_trade`].
#[repr(C)]
pub struct of_trade_t {
    /// Trade symbol descriptor.
    pub symbol: of_symbol_t,
    /// Trade price in integer units.
    pub price: i64,
    /// Trade quantity.
    pub size: i64,
    /// Aggressor side (`0=Bid`, `1=Ask`).
    pub aggressor_side: u32,
    /// Venue sequence number.
    pub sequence: u64,
    /// Exchange timestamp in nanoseconds.
    pub ts_exchange_ns: u64,
    /// Local receive timestamp in nanoseconds.
    pub ts_recv_ns: u64,
}

/// External order-book payload accepted by [`of_ingest_book`].
#[repr(C)]
pub struct of_book_t {
    /// Book update symbol descriptor.
    pub symbol: of_symbol_t,
    /// Book side (`0=Bid`, `1=Ask`).
    pub side: u32,
    /// Price level index from top of book.
    pub level: u16,
    /// Level price in integer units.
    pub price: i64,
    /// Level quantity.
    pub size: i64,
    /// Mutation action (`0=Upsert`, `1=Delete`).
    pub action: u32,
    /// Venue sequence number.
    pub sequence: u64,
    /// Exchange timestamp in nanoseconds.
    pub ts_exchange_ns: u64,
    /// Local receive timestamp in nanoseconds.
    pub ts_recv_ns: u64,
}

/// External-feed quality policy configured via [`of_configure_external_feed`].
#[repr(C)]
pub struct of_external_feed_policy_t {
    /// Stale threshold in milliseconds.
    pub stale_after_ms: u64,
    /// Non-zero enables sequence checks.
    pub enforce_sequence: u8,
}

/// Error codes returned by C ABI functions.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum of_error_t {
    /// Success.
    OF_OK = 0,
    /// Invalid argument.
    OF_ERR_INVALID_ARG = 1,
    /// Invalid runtime state.
    OF_ERR_STATE = 2,
    /// I/O failure.
    OF_ERR_IO = 3,
    /// Authentication failure.
    OF_ERR_AUTH = 4,
    /// Backpressure condition.
    OF_ERR_BACKPRESSURE = 5,
    /// Data-quality policy rejection.
    OF_ERR_DATA_QUALITY = 6,
    /// Pre-trade risk rejection.
    OF_ERR_RISK = 7,
    /// Internal/unknown failure.
    OF_ERR_INTERNAL = 255,
}

/// Execution route and risk configuration.
#[repr(C)]
pub struct of_execution_route_config_t {
    /// Route identifier.
    pub route_id: *const c_char,
    /// Account identifier.
    pub account_id: *const c_char,
    /// Venue identifier.
    pub venue: *const c_char,
    /// Instrument identifier.
    pub instrument: *const c_char,
    /// Non-zero enables the route.
    pub enabled: u8,
    /// Non-zero enables the kill switch.
    pub kill_switch: u8,
    /// Maximum order quantity; zero disables.
    pub max_order_qty: i64,
    /// Maximum order notional; zero disables.
    pub max_order_notional: i64,
    /// Maximum open orders; zero disables.
    pub max_open_orders: u32,
    /// Maximum open notional; zero disables.
    pub max_open_notional: i64,
    /// Maximum price distance from reference, in ticks; zero disables.
    pub price_band_ticks: i64,
}

/// Execution order request.
#[repr(C)]
pub struct of_execution_order_request_t {
    /// Client order id.
    pub client_order_id: *const c_char,
    /// Account id.
    pub account_id: *const c_char,
    /// Route id.
    pub route_id: *const c_char,
    /// Strategy id.
    pub strategy_id: *const c_char,
    /// Venue id.
    pub venue: *const c_char,
    /// Instrument id.
    pub instrument: *const c_char,
    /// Side (`1=Buy`, `2=Sell`).
    pub side: u32,
    /// Order type (`1=Market`, `2=Limit`, `3=Stop`, `4=StopLimit`).
    pub order_type: u32,
    /// Time-in-force (`1=Day`, `2=Gtc`, `3=Ioc`, `4=Fok`, `5=Gtd`).
    pub time_in_force: u32,
    /// Quantity in integer-normalized units.
    pub quantity: i64,
    /// Limit price in integer-normalized units, or zero.
    pub limit_price: i64,
    /// Stop price in integer-normalized units, or zero.
    pub stop_price: i64,
    /// Exchange timestamp in nanoseconds.
    pub ts_exchange_ns: u64,
    /// Local receive/create timestamp in nanoseconds.
    pub ts_recv_ns: u64,
}

/// Execution cancel request.
#[repr(C)]
pub struct of_execution_cancel_request_t {
    /// Client id for the cancel request.
    pub client_order_id: *const c_char,
    /// Last accepted client order id.
    pub orig_client_order_id: *const c_char,
    /// Venue order id, if known.
    pub venue_order_id: *const c_char,
    /// Account id.
    pub account_id: *const c_char,
    /// Route id.
    pub route_id: *const c_char,
    /// Venue id.
    pub venue: *const c_char,
    /// Instrument id.
    pub instrument: *const c_char,
    /// Local receive/create timestamp in nanoseconds.
    pub ts_recv_ns: u64,
}

/// Execution amend request.
#[repr(C)]
pub struct of_execution_amend_request_t {
    /// Client id for the replacement request.
    pub client_order_id: *const c_char,
    /// Last accepted client order id.
    pub orig_client_order_id: *const c_char,
    /// Venue order id, if known.
    pub venue_order_id: *const c_char,
    /// Account id.
    pub account_id: *const c_char,
    /// Route id.
    pub route_id: *const c_char,
    /// Venue id.
    pub venue: *const c_char,
    /// Instrument id.
    pub instrument: *const c_char,
    /// Replacement quantity.
    pub quantity: i64,
    /// Replacement limit price.
    pub limit_price: i64,
    /// Local receive/create timestamp in nanoseconds.
    pub ts_recv_ns: u64,
}

/// Execution event returned by execution C APIs.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct of_execution_event_t {
    /// Execution type.
    pub exec_type: u32,
    /// Current order status.
    pub order_status: u32,
    /// Client order id.
    pub client_order_id: [c_char; 41],
    /// Original client order id.
    pub orig_client_order_id: [c_char; 41],
    /// Venue order id.
    pub venue_order_id: [c_char; 49],
    /// Execution id.
    pub execution_id: [c_char; 49],
    /// Account id.
    pub account_id: [c_char; 33],
    /// Route id.
    pub route_id: [c_char; 33],
    /// Venue id.
    pub venue: [c_char; 17],
    /// Instrument id.
    pub instrument: [c_char; 33],
    /// Last fill quantity.
    pub last_qty: i64,
    /// Last fill price.
    pub last_price: i64,
    /// Cumulative quantity.
    pub cumulative_qty: i64,
    /// Leaves quantity.
    pub leaves_qty: i64,
    /// Average price.
    pub average_price: i64,
    /// Exchange timestamp in nanoseconds.
    pub ts_exchange_ns: u64,
    /// Local receive timestamp in nanoseconds.
    pub ts_recv_ns: u64,
    /// Structured reason code.
    pub reason: u32,
    /// Bounded diagnostic text.
    pub text: [c_char; 129],
}

/// Execution order state returned by state query.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct of_execution_order_state_t {
    /// Client order id.
    pub client_order_id: [c_char; 41],
    /// Venue order id.
    pub venue_order_id: [c_char; 49],
    /// Account id.
    pub account_id: [c_char; 33],
    /// Route id.
    pub route_id: [c_char; 33],
    /// Venue id.
    pub venue: [c_char; 17],
    /// Instrument id.
    pub instrument: [c_char; 33],
    /// Order status.
    pub status: u32,
    /// Original order quantity.
    pub order_qty: i64,
    /// Cumulative quantity.
    pub cumulative_qty: i64,
    /// Leaves quantity.
    pub leaves_qty: i64,
    /// Average price.
    pub average_price: i64,
    /// Last update timestamp in nanoseconds.
    pub updated_ns: u64,
}

/// Execution health snapshot.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct of_execution_health_t {
    /// Non-zero when connected.
    pub connected: u8,
    /// Non-zero when degraded.
    pub degraded: u8,
    /// Monotonic health sequence.
    pub health_seq: u64,
}

/// Execution metrics snapshot.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct of_execution_metrics_t {
    /// Submitted orders accepted locally.
    pub submitted: u64,
    /// Cancel commands accepted locally.
    pub cancelled: u64,
    /// Amend commands accepted locally.
    pub amended: u64,
    /// Events applied.
    pub events_applied: u64,
    /// Risk rejections.
    pub risk_rejected: u64,
    /// Adapter errors.
    pub adapter_errors: u64,
    /// Recovery events applied.
    pub recovered: u64,
}

/// Concurrent execution worker configuration.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct of_execution_concurrent_config_t {
    /// Bounded command queue capacity.
    pub command_capacity: u32,
    /// Bounded report queue capacity.
    pub report_capacity: u32,
    /// Per-command event buffer capacity.
    pub event_buffer_capacity: u32,
}

/// Concurrent execution command report.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct of_execution_command_report_t {
    /// Monotonic command sequence.
    pub sequence: u64,
    /// Command kind.
    pub kind: u32,
    /// Result code for the command.
    pub result_code: i32,
    /// Number of events copied to the caller event array.
    pub event_count: u32,
}

/// Opaque engine handle.
pub struct of_engine {
    inner: DefaultEngine,
    subs: Vec<SubscriptionRecord>,
}

/// Opaque execution engine handle.
pub struct of_execution_engine {
    inner: ExecutionEngine<SimExecutionAdapter, AllowAllRiskGate, InMemoryJournal>,
}

/// Opaque concurrent execution engine handle.
pub struct of_execution_concurrent_engine {
    inner: ConcurrentExecutionEngine,
}

/// Opaque subscription token.
pub struct of_subscription {
    token: *mut SubscriptionToken,
}

/// Event envelope dispatched to subscription callbacks.
#[repr(C)]
pub struct of_event_t {
    /// Exchange timestamp in nanoseconds.
    pub ts_exchange_ns: u64,
    /// Local receive timestamp in nanoseconds.
    pub ts_recv_ns: u64,
    /// Stream/event kind value.
    pub kind: u32,
    /// Pointer to UTF-8 payload bytes.
    pub payload: *const c_void,
    /// Payload byte length.
    pub payload_len: u32,
    /// Payload schema identifier.
    pub schema_id: u32,
    /// Quality flags bitset associated with this event.
    pub quality_flags: u32,
}

/// C callback signature for subscription delivery.
pub type of_event_cb = extern "C" fn(*const of_event_t, *mut c_void);

struct SubscriptionRecord {
    symbol: SymbolId,
    kind: u32,
    cb: of_event_cb,
    user_data: *mut c_void,
    active: Arc<AtomicBool>,
    last_health_seq: u64,
}

struct SubscriptionToken {
    active: Arc<AtomicBool>,
}

/// Returns ABI version (`major << 16 | minor` style encoding).
#[no_mangle]
pub extern "C" fn of_api_version() -> u32 {
    API_VERSION
}

/// Returns build/version info as a static NUL-terminated C string.
#[no_mangle]
pub extern "C" fn of_build_info() -> *const c_char {
    BUILD_INFO.as_ptr() as *const c_char
}

/// Returns execution ABI version (`major << 16 | minor` style encoding).
#[no_mangle]
pub extern "C" fn of_execution_api_version() -> u32 {
    EXECUTION_API_VERSION
}

/// Creates a simulated execution engine and stores it in `out_engine`.
#[no_mangle]
pub extern "C" fn of_execution_engine_create(
    cfg: *const of_execution_route_config_t,
    out_engine: *mut *mut of_execution_engine,
) -> i32 {
    if cfg.is_null() || out_engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let cfg = unsafe { &*cfg };
    let route = match route_config_from_ffi(cfg) {
        Ok(route) => route,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    create_execution_engine_from_routes(vec![route], out_engine)
}

/// Creates a simulated execution engine from multiple route configs.
#[no_mangle]
pub extern "C" fn of_execution_engine_create_multi(
    routes: *const of_execution_route_config_t,
    route_count: u32,
    out_engine: *mut *mut of_execution_engine,
) -> i32 {
    if routes.is_null() || route_count == 0 || out_engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let route_configs = match route_configs_from_ffi(routes, route_count) {
        Ok(routes) => routes,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    create_execution_engine_from_routes(route_configs, out_engine)
}

fn create_execution_engine_from_routes(
    routes: Vec<RouteConfig>,
    out_engine: *mut *mut of_execution_engine,
) -> i32 {
    let engine = Box::new(of_execution_engine {
        inner: simulated_engine_with_routes(routes),
    });
    unsafe {
        *out_engine = Box::into_raw(engine);
    }
    of_error_t::OF_OK as i32
}

/// Creates and starts a concurrent simulated execution engine.
#[no_mangle]
pub extern "C" fn of_execution_concurrent_engine_create_multi(
    routes: *const of_execution_route_config_t,
    route_count: u32,
    config: *const of_execution_concurrent_config_t,
    out_engine: *mut *mut of_execution_concurrent_engine,
) -> i32 {
    if routes.is_null() || route_count == 0 || out_engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let route_configs = match route_configs_from_ffi(routes, route_count) {
        Ok(routes) => routes,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    let cfg = concurrent_config_from_ffi(config);
    let engine = simulated_engine_with_routes(route_configs);
    let inner = match ConcurrentExecutionEngine::spawn(engine, cfg) {
        Ok(engine) => engine,
        Err(err) => return map_concurrent_execution_error(&err),
    };
    let wrapped = Box::new(of_execution_concurrent_engine { inner });
    unsafe {
        *out_engine = Box::into_raw(wrapped);
    }
    of_error_t::OF_OK as i32
}

/// Destroys a concurrent execution engine.
#[no_mangle]
pub extern "C" fn of_execution_concurrent_engine_destroy(
    engine: *mut of_execution_concurrent_engine,
) {
    if engine.is_null() {
        return;
    }
    unsafe {
        let _ = Box::from_raw(engine);
    }
}

/// Requests graceful concurrent execution worker stop.
#[no_mangle]
pub extern "C" fn of_execution_concurrent_stop(
    engine: *mut of_execution_concurrent_engine,
    out_sequence: *mut u64,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    match engine.inner.request_stop() {
        Ok(sequence) => {
            write_optional_u64(out_sequence, sequence);
            of_error_t::OF_OK as i32
        }
        Err(err) => map_concurrent_execution_error(&err),
    }
}

/// Sends a non-blocking submit command to a concurrent execution worker.
#[no_mangle]
pub extern "C" fn of_execution_concurrent_submit_order(
    engine: *mut of_execution_concurrent_engine,
    req: *const of_execution_order_request_t,
    out_sequence: *mut u64,
) -> i32 {
    if engine.is_null() || req.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let req = match order_request_from_ffi(unsafe { &*req }) {
        Ok(req) => req,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    let engine = unsafe { &mut *engine };
    send_concurrent_command(engine, ExecutionCommand::Submit(req), out_sequence)
}

/// Sends a non-blocking cancel command to a concurrent execution worker.
#[no_mangle]
pub extern "C" fn of_execution_concurrent_cancel_order(
    engine: *mut of_execution_concurrent_engine,
    req: *const of_execution_cancel_request_t,
    out_sequence: *mut u64,
) -> i32 {
    if engine.is_null() || req.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let req = match cancel_request_from_ffi(unsafe { &*req }) {
        Ok(req) => req,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    let engine = unsafe { &mut *engine };
    send_concurrent_command(engine, ExecutionCommand::Cancel(req), out_sequence)
}

/// Sends a non-blocking amend command to a concurrent execution worker.
#[no_mangle]
pub extern "C" fn of_execution_concurrent_amend_order(
    engine: *mut of_execution_concurrent_engine,
    req: *const of_execution_amend_request_t,
    out_sequence: *mut u64,
) -> i32 {
    if engine.is_null() || req.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let req = match amend_request_from_ffi(unsafe { &*req }) {
        Ok(req) => req,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    let engine = unsafe { &mut *engine };
    send_concurrent_command(engine, ExecutionCommand::Amend(req), out_sequence)
}

/// Sends a non-blocking poll command to a concurrent execution worker.
#[no_mangle]
pub extern "C" fn of_execution_concurrent_poll(
    engine: *mut of_execution_concurrent_engine,
    out_sequence: *mut u64,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    send_concurrent_command(engine, ExecutionCommand::Poll, out_sequence)
}

/// Attempts to receive one concurrent command report without blocking.
#[no_mangle]
pub extern "C" fn of_execution_concurrent_try_recv_report(
    engine: *mut of_execution_concurrent_engine,
    out_report: *mut of_execution_command_report_t,
    out_events: *mut of_execution_event_t,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() || out_report.is_null() || inout_len.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    let report = match engine.inner.try_recv_report() {
        Ok(report) => report,
        Err(err) => return map_concurrent_execution_error(&err),
    };
    write_concurrent_report(&report, out_report, out_events, inout_len)
}

/// Starts an execution engine.
#[no_mangle]
pub extern "C" fn of_execution_engine_start(engine: *mut of_execution_engine) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    map_execution_result(engine.inner.start())
}

/// Stops an execution engine.
#[no_mangle]
pub extern "C" fn of_execution_engine_stop(engine: *mut of_execution_engine) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    of_error_t::OF_OK as i32
}

/// Destroys an execution engine.
#[no_mangle]
pub extern "C" fn of_execution_engine_destroy(engine: *mut of_execution_engine) {
    if engine.is_null() {
        return;
    }
    unsafe {
        let _ = Box::from_raw(engine);
    }
}

/// Submits an execution order.
#[no_mangle]
pub extern "C" fn of_execution_submit_order(
    engine: *mut of_execution_engine,
    req: *const of_execution_order_request_t,
    out_events: *mut of_execution_event_t,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() || req.is_null() || inout_len.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let req = match order_request_from_ffi(unsafe { &*req }) {
        Ok(req) => req,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    let engine = unsafe { &mut *engine };
    let mut events = ExecutionEventBuffer::with_capacity(FFI_EVENT_BUFFER_CAP);
    let rc = match engine.inner.submit(req, &mut events) {
        Ok(()) => of_error_t::OF_OK as i32,
        Err(err) => map_execution_error(&err),
    };
    let copy_rc = copy_execution_events(&events, out_events, inout_len);
    if copy_rc != of_error_t::OF_OK as i32 {
        copy_rc
    } else {
        rc
    }
}

/// Cancels an execution order.
#[no_mangle]
pub extern "C" fn of_execution_cancel_order(
    engine: *mut of_execution_engine,
    req: *const of_execution_cancel_request_t,
    out_events: *mut of_execution_event_t,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() || req.is_null() || inout_len.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let req = match cancel_request_from_ffi(unsafe { &*req }) {
        Ok(req) => req,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    let engine = unsafe { &mut *engine };
    let mut events = ExecutionEventBuffer::with_capacity(FFI_EVENT_BUFFER_CAP);
    let rc = match engine.inner.cancel(req, &mut events) {
        Ok(()) => of_error_t::OF_OK as i32,
        Err(err) => map_execution_error(&err),
    };
    let copy_rc = copy_execution_events(&events, out_events, inout_len);
    if copy_rc != of_error_t::OF_OK as i32 {
        copy_rc
    } else {
        rc
    }
}

/// Amends an execution order.
#[no_mangle]
pub extern "C" fn of_execution_amend_order(
    engine: *mut of_execution_engine,
    req: *const of_execution_amend_request_t,
    out_events: *mut of_execution_event_t,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() || req.is_null() || inout_len.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let req = match amend_request_from_ffi(unsafe { &*req }) {
        Ok(req) => req,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    let engine = unsafe { &mut *engine };
    let mut events = ExecutionEventBuffer::with_capacity(FFI_EVENT_BUFFER_CAP);
    let rc = match engine.inner.amend(req, &mut events) {
        Ok(()) => of_error_t::OF_OK as i32,
        Err(err) => map_execution_error(&err),
    };
    let copy_rc = copy_execution_events(&events, out_events, inout_len);
    if copy_rc != of_error_t::OF_OK as i32 {
        copy_rc
    } else {
        rc
    }
}

/// Polls execution events.
#[no_mangle]
pub extern "C" fn of_execution_poll(
    engine: *mut of_execution_engine,
    out_events: *mut of_execution_event_t,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() || inout_len.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    let mut events = ExecutionEventBuffer::with_capacity(FFI_EVENT_BUFFER_CAP);
    let rc = match engine.inner.poll(&mut events) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(err) => map_execution_error(&err),
    };
    let copy_rc = copy_execution_events(&events, out_events, inout_len);
    if copy_rc != of_error_t::OF_OK as i32 {
        copy_rc
    } else {
        rc
    }
}

/// Gets current order state for a client order id.
#[no_mangle]
pub extern "C" fn of_execution_get_order_state(
    engine: *const of_execution_engine,
    client_order_id: *const c_char,
    out_state: *mut of_execution_order_state_t,
) -> i32 {
    if engine.is_null() || client_order_id.is_null() || out_state.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let id = match fixed_from_ptr::<40>(client_order_id) {
        Ok(id) => id,
        Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
    };
    let engine = unsafe { &*engine };
    let Some(state) = engine.inner.order_state(&id) else {
        return of_error_t::OF_ERR_STATE as i32;
    };
    unsafe {
        *out_state = order_state_to_ffi(&state);
    }
    of_error_t::OF_OK as i32
}

/// Gets execution health.
#[no_mangle]
pub extern "C" fn of_execution_health(
    engine: *const of_execution_engine,
    out_health: *mut of_execution_health_t,
) -> i32 {
    if engine.is_null() || out_health.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let health = unsafe { &*engine }.inner.health();
    unsafe {
        *out_health = of_execution_health_t {
            connected: u8::from(health.connected),
            degraded: u8::from(health.degraded),
            health_seq: health.health_seq,
        };
    }
    of_error_t::OF_OK as i32
}

/// Gets execution metrics.
#[no_mangle]
pub extern "C" fn of_execution_metrics(
    engine: *const of_execution_engine,
    out_metrics: *mut of_execution_metrics_t,
) -> i32 {
    if engine.is_null() || out_metrics.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let metrics = unsafe { &*engine }.inner.metrics();
    unsafe {
        *out_metrics = of_execution_metrics_t {
            submitted: metrics.submitted,
            cancelled: metrics.cancelled,
            amended: metrics.amended,
            events_applied: metrics.events_applied,
            risk_rejected: metrics.risk_rejected,
            adapter_errors: metrics.adapter_errors,
            recovered: metrics.recovered,
        };
    }
    of_error_t::OF_OK as i32
}

/// Creates a runtime engine and stores it in `out_engine`.
#[no_mangle]
pub extern "C" fn of_engine_create(
    cfg: *const of_engine_config_t,
    out_engine: *mut *mut of_engine,
) -> i32 {
    if cfg.is_null() || out_engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let cfg_ref = unsafe { &*cfg };
    let mut runtime_cfg = if let Some(path) = non_empty_string(cfg_ref.config_path) {
        match load_engine_config_from_path(&path) {
            Ok(v) => v,
            Err(_) => return of_error_t::OF_ERR_INVALID_ARG as i32,
        }
    } else {
        EngineConfig {
            instance_id: "default".to_string(),
            enable_persistence: false,
            data_root: "data".to_string(),
            audit_log_path: "audit/orderflow_audit.log".to_string(),
            audit_max_bytes: 10 * 1024 * 1024,
            audit_max_files: 5,
            audit_redact_tokens: vec![
                "secret".to_string(),
                "password".to_string(),
                "token".to_string(),
                "api_key".to_string(),
            ],
            data_retention_max_bytes: 10 * 1024 * 1024,
            data_retention_max_age_secs: 7 * 24 * 60 * 60,
            adapter: AdapterConfig {
                provider: ProviderKind::Mock,
                ..AdapterConfig::default()
            },
            signal_threshold: 100,
        }
    };

    if let Some(instance_id) = non_empty_string(cfg_ref.instance_id) {
        runtime_cfg.instance_id = instance_id;
    }
    runtime_cfg.enable_persistence = cfg_ref.enable_persistence != 0;
    if cfg_ref.audit_max_bytes > 0 {
        runtime_cfg.audit_max_bytes = cfg_ref.audit_max_bytes;
    }
    if cfg_ref.audit_max_files > 0 {
        runtime_cfg.audit_max_files = cfg_ref.audit_max_files;
    }
    if let Some(tokens) = parse_csv(cfg_ref.audit_redact_tokens_csv) {
        runtime_cfg.audit_redact_tokens = tokens;
    }
    if cfg_ref.data_retention_max_bytes > 0 {
        runtime_cfg.data_retention_max_bytes = cfg_ref.data_retention_max_bytes;
    }
    if cfg_ref.data_retention_max_age_secs > 0 {
        runtime_cfg.data_retention_max_age_secs = cfg_ref.data_retention_max_age_secs;
    }

    let engine = match build_default_engine(runtime_cfg) {
        Ok(v) => v,
        Err(_) => return of_error_t::OF_ERR_STATE as i32,
    };

    let wrapped = Box::new(of_engine {
        inner: engine,
        subs: Vec::new(),
    });
    unsafe {
        *out_engine = Box::into_raw(wrapped);
    }
    of_error_t::OF_OK as i32
}

/// Starts adapter polling/session for a created engine.
#[no_mangle]
pub extern "C" fn of_engine_start(engine: *mut of_engine) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let engine = unsafe { &mut *engine };
    match engine.inner.start() {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(_) => of_error_t::OF_ERR_STATE as i32,
    }
}

/// Stops adapter polling/session for an engine.
#[no_mangle]
pub extern "C" fn of_engine_stop(engine: *mut of_engine) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    engine.inner.stop();
    of_error_t::OF_OK as i32
}

/// Destroys an engine created by [`of_engine_create`].
#[no_mangle]
pub extern "C" fn of_engine_destroy(engine: *mut of_engine) {
    if !engine.is_null() {
        unsafe {
            drop(Box::from_raw(engine));
        }
    }
}

/// Subscribes to a symbol stream and returns a subscription token.
#[no_mangle]
pub extern "C" fn of_subscribe(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    _kind: u32,
    cb: Option<of_event_cb>,
    user_data: *mut c_void,
    out_sub: *mut *mut of_subscription,
) -> i32 {
    if engine.is_null() || symbol.is_null() || out_sub.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, depth_levels) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    if engine
        .inner
        .subscribe(symbol.clone(), depth_levels)
        .is_err()
    {
        return of_error_t::OF_ERR_STATE as i32;
    }

    let active = Arc::new(AtomicBool::new(true));
    if let Some(cb_fn) = cb {
        engine.subs.push(SubscriptionRecord {
            symbol: symbol.clone(),
            kind: _kind,
            cb: cb_fn,
            user_data,
            active: active.clone(),
            last_health_seq: 0,
        });
    }

    let token = Box::new(SubscriptionToken { active });
    let sub = Box::new(of_subscription {
        token: Box::into_raw(token),
    });
    unsafe {
        *out_sub = Box::into_raw(sub);
    }
    of_error_t::OF_OK as i32
}

/// Unsubscribes and destroys a subscription token.
#[no_mangle]
pub extern "C" fn of_unsubscribe(sub: *mut of_subscription) -> i32 {
    if sub.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    unsafe {
        let sub = Box::from_raw(sub);
        if !sub.token.is_null() {
            let token = Box::from_raw(sub.token);
            token.active.store(false, Ordering::Release);
        }
    }
    of_error_t::OF_OK as i32
}

/// Unsubscribes all active streams for a symbol on this engine.
#[no_mangle]
pub extern "C" fn of_unsubscribe_symbol(engine: *mut of_engine, symbol: *const of_symbol_t) -> i32 {
    if engine.is_null() || symbol.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    if engine.inner.unsubscribe(symbol.clone()).is_err() {
        return of_error_t::OF_ERR_STATE as i32;
    }

    for sub in &mut engine.subs {
        if sub.symbol == symbol {
            sub.active.store(false, Ordering::Release);
        }
    }
    engine.subs.retain(|s| s.active.load(Ordering::Acquire));
    of_error_t::OF_OK as i32
}

/// Resets per-symbol analytics session state.
#[no_mangle]
pub extern "C" fn of_reset_symbol_session(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
) -> i32 {
    if engine.is_null() || symbol.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    if engine.inner.reset_symbol_session(symbol).is_err() {
        return of_error_t::OF_ERR_STATE as i32;
    }
    of_error_t::OF_OK as i32
}

/// Injects one external trade event into runtime processing.
#[no_mangle]
pub extern "C" fn of_ingest_trade(
    engine: *mut of_engine,
    trade: *const of_trade_t,
    quality_flags: u32,
) -> i32 {
    if engine.is_null() || trade.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let trade = unsafe { &*trade };
    let (symbol, _) = match symbol_from_ffi_ref(&trade.symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let aggressor_side = match side_from_ffi(trade.aggressor_side) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let q = DataQualityFlags::from_bits_truncate(quality_flags);
    let event = TradePrint {
        symbol,
        price: trade.price,
        size: trade.size,
        aggressor_side,
        sequence: trade.sequence,
        ts_exchange_ns: trade.ts_exchange_ns,
        ts_recv_ns: trade.ts_recv_ns,
    };

    let engine = unsafe { &mut *engine };
    match engine.inner.ingest_trade(event, q) {
        Ok(_) => {
            dispatch_callbacks(engine, engine.inner.current_quality_flags_bits());
            of_error_t::OF_OK as i32
        }
        Err(_) => of_error_t::OF_ERR_STATE as i32,
    }
}

/// Injects one external book event into runtime processing.
#[no_mangle]
pub extern "C" fn of_ingest_book(
    engine: *mut of_engine,
    book: *const of_book_t,
    quality_flags: u32,
) -> i32 {
    if engine.is_null() || book.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let book = unsafe { &*book };
    let (symbol, _) = match symbol_from_ffi_ref(&book.symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let side = match side_from_ffi(book.side) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let action = match action_from_ffi(book.action) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let q = DataQualityFlags::from_bits_truncate(quality_flags);
    let event = BookUpdate {
        symbol,
        side,
        level: book.level,
        price: book.price,
        size: book.size,
        action,
        sequence: book.sequence,
        ts_exchange_ns: book.ts_exchange_ns,
        ts_recv_ns: book.ts_recv_ns,
    };

    let engine = unsafe { &mut *engine };
    match engine.inner.ingest_book(event, q) {
        Ok(_) => {
            dispatch_callbacks(engine, engine.inner.current_quality_flags_bits());
            of_error_t::OF_OK as i32
        }
        Err(_) => of_error_t::OF_ERR_STATE as i32,
    }
}

/// Configures stale/sequence policy for external ingest mode.
#[no_mangle]
pub extern "C" fn of_configure_external_feed(
    engine: *mut of_engine,
    policy: *const of_external_feed_policy_t,
) -> i32 {
    if engine.is_null() || policy.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    let policy = unsafe { &*policy };
    match engine.inner.configure_external_feed(ExternalFeedPolicy {
        stale_after_ms: policy.stale_after_ms,
        enforce_sequence: policy.enforce_sequence != 0,
    }) {
        Ok(_) => {
            dispatch_health_callbacks(engine, engine.inner.current_quality_flags_bits());
            of_error_t::OF_OK as i32
        }
        Err(_) => of_error_t::OF_ERR_STATE as i32,
    }
}

/// Marks external feed reconnecting state.
#[no_mangle]
pub extern "C" fn of_external_set_reconnecting(engine: *mut of_engine, reconnecting: u8) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    match engine.inner.set_external_reconnecting(reconnecting != 0) {
        Ok(_) => {
            dispatch_health_callbacks(engine, engine.inner.current_quality_flags_bits());
            of_error_t::OF_OK as i32
        }
        Err(_) => of_error_t::OF_ERR_STATE as i32,
    }
}

/// Re-evaluates external feed health without ingesting new events.
#[no_mangle]
pub extern "C" fn of_external_health_tick(engine: *mut of_engine) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    match engine.inner.external_health_tick() {
        Ok(_) => {
            dispatch_health_callbacks(engine, engine.inner.current_quality_flags_bits());
            of_error_t::OF_OK as i32
        }
        Err(_) => of_error_t::OF_ERR_STATE as i32,
    }
}

/// Writes current book snapshot JSON into caller buffer.
#[no_mangle]
pub extern "C" fn of_get_book_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.book_snapshot(&symbol) {
        Some(snapshot) => format_book_snapshot(&snapshot),
        None => "{}".to_string(),
    };
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes current book analytics snapshot JSON into caller buffer.
///
/// Payload shape:
/// ```json
/// {"best_bid":...,"best_ask":...,"quoted_spread":...,"relative_spread_bps":...,
///  "microprice":...,"bid_depth":...,"ask_depth":...,"depth_imbalance_bps":...}
/// ```
#[no_mangle]
pub extern "C" fn of_get_book_analytics_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.book_analytics_snapshot(&symbol) {
        Some(snap) => format_book_analytics_snapshot(&snap),
        None => "{}".to_string(),
    };

    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Computes weighted average price for an order of `qty` and writes JSON result.
///
/// Payload: `{"price": N}` on success, `{}` if insufficient liquidity.
/// Positive qty = buy (walks asks), negative qty = sell (walks bids).
#[no_mangle]
pub extern "C" fn of_compute_weighted_average_price(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    qty: i64,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.weighted_average_price(&symbol, qty) {
        Some(price) => format!("{{\"price\":{}}}", price),
        None => "{}".to_string(),
    };

    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Computes depth slope for the first `levels` price levels and writes JSON result.
///
/// Payload: `{"slope": N.N}`. Returns `{"slope":0.0}` if book has fewer than 2 levels.
#[no_mangle]
pub extern "C" fn of_compute_depth_slope(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    levels: u32,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let slope = engine.inner.depth_slope(&symbol, levels as usize);
    let payload = format!("{{\"slope\":{:.4}}}", slope);

    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes mid price as JSON: `{"mid": N}`, or `{}` if no book data.
#[no_mangle]
pub extern "C" fn of_get_mid_price(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.mid_price(&symbol) {
        Some(mid) => format!("{{\"mid\":{}}}", mid),
        None => "{}".to_string(),
    };
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes last effective spread in bps as JSON: `{"bps": N}`, or `{}`.
#[no_mangle]
pub extern "C" fn of_get_effective_spread_bps(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let bps = engine.inner.effective_spread_bps(&symbol);
    let payload = format!("{{\"bps\":{}}}", bps);
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes average half-spread cost over `window` trades: `{"bps": N}`.
#[no_mangle]
pub extern "C" fn of_get_half_spread_cost_bps(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    window: u32,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let bps = engine.inner.half_spread_cost_bps(&symbol, window as usize);
    let payload = format!("{{\"bps\":{}}}", bps);
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes realised spread over `hold_ticks` ticks ago: `{"bps": N}`.
#[no_mangle]
pub extern "C" fn of_get_realised_spread_bps(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    hold_ticks: u32,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let bps = engine
        .inner
        .realised_spread_bps(&symbol, hold_ticks as usize);
    let payload = format!("{{\"bps\":{}}}", bps);
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes book-event analytics snapshot JSON over `window_ns`.
#[no_mangle]
pub extern "C" fn of_get_book_event_analytics(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    window_ns: u64,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let snap = engine.inner.book_event_analytics(&symbol, window_ns);
    let payload = format_book_event_analytics_snapshot(&snap);
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes resiliency snapshot JSON.
#[no_mangle]
pub extern "C" fn of_get_resiliency_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let snap = engine.inner.resiliency_snapshot(&symbol);
    let payload = format_resiliency_snapshot(&snap);
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes VPIN snapshot JSON.
#[no_mangle]
pub extern "C" fn of_get_vpin_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let payload = format_vpin_snapshot(&engine.inner.vpin_snapshot(&symbol));
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes Kyle's Lambda snapshot JSON.
#[no_mangle]
pub extern "C" fn of_get_kyle_lambda_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let payload = format_kyle_lambda_snapshot(&engine.inner.kyle_lambda_snapshot(&symbol));
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes Amihud illiquidity snapshot JSON.
#[no_mangle]
pub extern "C" fn of_get_amihud_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let payload = format_amihud_snapshot(&engine.inner.amihud_snapshot(&symbol));
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes CVD enhancement snapshot JSON.
#[no_mangle]
pub extern "C" fn of_get_cvd_enhancement_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let payload = format_cvd_enhancement_snapshot(&engine.inner.cvd_enhancement_snapshot(&symbol));
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes pattern detection snapshot JSON into caller buffer.
#[no_mangle]
pub extern "C" fn of_get_pattern_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &mut *engine };
    let payload = format_pattern_snapshot(&engine.inner.pattern_snapshot(&symbol));
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

macro_rules! snapshot_c_abi {
    ($name:ident, $format:ident, $method:ident) => {
        /// Writes an analytics snapshot JSON payload into the caller-provided buffer.
        #[no_mangle]
        pub extern "C" fn $name(
            engine: *mut of_engine,
            symbol: *const of_symbol_t,
            out_buf: *mut c_void,
            inout_len: *mut u32,
        ) -> i32 {
            if engine.is_null() {
                return of_error_t::OF_ERR_INVALID_ARG as i32;
            }
            let (symbol, _) = match symbol_from_ffi(symbol) {
                Ok(v) => v,
                Err(e) => return e as i32,
            };
            let engine = unsafe { &mut *engine };
            let payload = $format(&engine.inner.$method(&symbol));
            match write_json_to_c_buffer(&payload, out_buf, inout_len) {
                Ok(_) => of_error_t::OF_OK as i32,
                Err(e) => e as i32,
            }
        }
    };
}

snapshot_c_abi!(
    of_get_volatility_snapshot,
    format_volatility_snapshot,
    volatility_snapshot
);
snapshot_c_abi!(of_get_noise_snapshot, format_noise_snapshot, noise_snapshot);
snapshot_c_abi!(
    of_get_hasbrouck_snapshot,
    format_hasbrouck_snapshot,
    hasbrouck_snapshot
);
snapshot_c_abi!(
    of_get_almgren_chriss_snapshot,
    format_almgren_chriss_snapshot,
    almgren_chriss_snapshot
);
snapshot_c_abi!(
    of_get_spread_decomp_snapshot,
    format_spread_decomp_snapshot,
    spread_decomp_snapshot
);
snapshot_c_abi!(of_get_acd_snapshot, format_acd_snapshot, acd_snapshot);
snapshot_c_abi!(
    of_get_regime_snapshot,
    format_regime_snapshot,
    regime_snapshot
);
snapshot_c_abi!(
    of_get_kinetic_energy_snapshot,
    format_kinetic_energy_snapshot,
    kinetic_energy_snapshot
);
snapshot_c_abi!(
    of_get_dark_pool_snapshot,
    format_dark_pool_snapshot,
    dark_pool_snapshot
);
snapshot_c_abi!(
    of_get_options_flow_snapshot,
    format_options_flow_snapshot,
    options_flow_snapshot
);
snapshot_c_abi!(
    of_get_futures_snapshot,
    format_futures_snapshot,
    futures_snapshot
);
snapshot_c_abi!(
    of_get_vol_signature_snapshot,
    format_vol_signature_snapshot,
    vol_signature_snapshot
);
snapshot_c_abi!(
    of_get_agent_type_snapshot,
    format_agent_type_snapshot,
    agent_type_snapshot
);
snapshot_c_abi!(
    of_get_dark_lit_correlation_snapshot,
    format_dark_lit_correlation_snapshot,
    dark_lit_correlation_snapshot
);
snapshot_c_abi!(
    of_get_institutional_flow_snapshot,
    format_institutional_flow_snapshot,
    institutional_flow_snapshot
);
snapshot_c_abi!(
    of_get_oi_analysis_snapshot,
    format_oi_analysis_snapshot,
    oi_analysis_snapshot
);

/// Computes LOB feature snapshot from engine book state and caller-provided flow metrics.
#[no_mangle]
pub extern "C" fn of_compute_lob_features(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    trade_imbalance: f64,
    cancel_rate: f64,
    arrival_rate: f64,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };
    let engine = unsafe { &*engine };
    let payload = format_lob_feature_snapshot(&engine.inner.lob_features(
        &symbol,
        trade_imbalance,
        cancel_rate,
        arrival_rate,
    ));
    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes current analytics snapshot JSON into caller buffer.
#[no_mangle]
pub extern "C" fn of_get_analytics_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.analytics_snapshot(&symbol) {
        Some(snap) => format_analytics_snapshot(&snap),
        None => "{}".to_string(),
    };

    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes current derived analytics snapshot JSON into caller buffer.
#[no_mangle]
pub extern "C" fn of_get_derived_analytics_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.derived_analytics_snapshot(&symbol) {
        Some(snap) => format_derived_analytics_snapshot(&snap),
        None => "{}".to_string(),
    };

    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes current session candle snapshot JSON into caller buffer.
#[no_mangle]
pub extern "C" fn of_get_session_candle_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.session_candle_snapshot(&symbol) {
        Some(snap) => format_session_candle_snapshot(&snap),
        None => "{}".to_string(),
    };

    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Writes rolling interval candle snapshot JSON into caller buffer.
#[no_mangle]
pub extern "C" fn of_get_interval_candle_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    window_ns: u64,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.interval_candle_snapshot(&symbol, window_ns) {
        Some(snap) => format_interval_candle_snapshot(&snap),
        None => "{}".to_string(),
    };

    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Sets the tickbar aggregation interval for new per-symbol accumulators.
///
/// A positive `interval_ns` enables tickbar aggregation at the given interval for
/// symbols whose accumulators are created after this call. Zero or negative values
/// disable tickbar aggregation for future accumulators. Existing accumulators
/// are not affected.
///
/// Requires the `tickbar` feature to be enabled at build time.
#[cfg(feature = "tickbar")]
#[no_mangle]
pub extern "C" fn of_engine_set_tickbar_interval(engine: *mut of_engine, interval_ns: i64) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    if interval_ns > 0 {
        engine.inner.set_tickbar_interval(Some(interval_ns));
    } else {
        engine.inner.set_tickbar_interval(None);
    }
    of_error_t::OF_OK as i32
}

/// Reports unsupported tickbar configuration when the native library is built without `tickbar`.
#[cfg(not(feature = "tickbar"))]
#[no_mangle]
pub extern "C" fn of_engine_set_tickbar_interval(engine: *mut of_engine, _interval_ns: i64) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    of_error_t::OF_ERR_STATE as i32
}

/// Writes completed bar series JSON array into caller buffer.
///
/// Requires the `tickbar` feature to be enabled at build time.
/// Returns `OF_ERR_STATE` when tickbar aggregation is not configured for the symbol.
#[cfg(feature = "tickbar")]
#[no_mangle]
pub extern "C" fn of_get_bar_series(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.bar_series(&symbol) {
        Some(bars) => format_bar_series(&bars),
        None => "[]".to_string(),
    };

    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Reports unsupported tickbar bar retrieval when the native library is built without `tickbar`.
#[cfg(not(feature = "tickbar"))]
#[no_mangle]
pub extern "C" fn of_get_bar_series(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() || symbol.is_null() || out_buf.is_null() || inout_len.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    of_error_t::OF_ERR_STATE as i32
}

/// Writes current signal snapshot JSON into caller buffer.
#[no_mangle]
pub extern "C" fn of_get_signal_snapshot(
    engine: *mut of_engine,
    symbol: *const of_symbol_t,
    out_buf: *mut c_void,
    inout_len: *mut u32,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let (symbol, _) = match symbol_from_ffi(symbol) {
        Ok(v) => v,
        Err(e) => return e as i32,
    };

    let engine = unsafe { &mut *engine };
    let payload = match engine.inner.signal_snapshot(&symbol) {
        Some(snap) => {
            let state = match snap.state {
                SignalState::Neutral => "neutral",
                SignalState::LongBias => "long_bias",
                SignalState::ShortBias => "short_bias",
                SignalState::Blocked => "blocked",
            };
            format!(
                "{{\"module\":\"{}\",\"state\":\"{}\",\"confidence_bps\":{},\"quality_flags\":{},\"reason\":\"{}\"}}",
                escape_json(snap.module_id),
                state,
                snap.confidence_bps,
                snap.quality_flags,
                escape_json(&snap.reason)
            )
        }
        None => "{}".to_string(),
    };

    match write_json_to_c_buffer(&payload, out_buf, inout_len) {
        Ok(_) => of_error_t::OF_OK as i32,
        Err(e) => e as i32,
    }
}

/// Allocates and returns metrics JSON (`*out`) plus byte length (`*out_len`).
#[no_mangle]
pub extern "C" fn of_get_metrics_json(
    engine: *mut of_engine,
    out_json: *mut *const c_char,
    out_len: *mut u32,
) -> i32 {
    if engine.is_null() || out_json.is_null() || out_len.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }

    let engine = unsafe { &mut *engine };
    let metrics = engine.inner.metrics_json();
    let c = match CString::new(metrics) {
        Ok(c) => c,
        Err(_) => return of_error_t::OF_ERR_INTERNAL as i32,
    };

    let len = c.as_bytes().len() as u32;
    let ptr = c.into_raw();
    unsafe {
        *out_json = ptr;
        *out_len = len;
    }
    of_error_t::OF_OK as i32
}

/// Frees a C string returned by this library.
#[no_mangle]
pub extern "C" fn of_string_free(p: *const c_char) {
    if p.is_null() {
        return;
    }
    unsafe {
        let _ = CString::from_raw(p as *mut c_char);
    }
}

/// Polls adapter once and dispatches subscription callbacks.
#[no_mangle]
pub extern "C" fn of_engine_poll_once(engine: *mut of_engine, quality_flags: u32) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    let q = DataQualityFlags::from_bits_truncate(quality_flags);
    match engine.inner.poll_once(q) {
        Ok(_) => {
            dispatch_callbacks(engine, engine.inner.current_quality_flags_bits());
            of_error_t::OF_OK as i32
        }
        Err(err) => {
            let status = map_runtime_error(&err);
            if err.is_backpressure() {
                dispatch_callbacks(engine, engine.inner.current_quality_flags_bits());
            }
            status
        }
    }
}

/// Override analytics thresholds and buffer sizes at runtime.
/// Pass a pointer to a populated analytics config. Passing NULL resets to defaults.
#[no_mangle]
pub extern "C" fn of_engine_set_analytics_config(
    engine: *mut of_engine,
    config: *const of_analytics_config_t,
) -> i32 {
    if engine.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let engine = unsafe { &mut *engine };
    if config.is_null() {
        engine
            .inner
            .set_analytics_config(AnalyticsConfig::default());
    } else {
        let cfg = unsafe { *config };
        engine.inner.set_analytics_config(cfg.into());
    }
    of_error_t::OF_OK as i32
}

fn map_runtime_error(err: &RuntimeError) -> i32 {
    if err.is_backpressure() {
        of_error_t::OF_ERR_BACKPRESSURE as i32
    } else {
        of_error_t::OF_ERR_STATE as i32
    }
}

fn map_execution_result(result: Result<(), ExecutionError>) -> i32 {
    match result {
        Ok(()) => of_error_t::OF_OK as i32,
        Err(err) => map_execution_error(&err),
    }
}

fn map_execution_error(err: &ExecutionError) -> i32 {
    match err {
        ExecutionError::RiskRejected(_) => of_error_t::OF_ERR_RISK as i32,
        ExecutionError::BufferFull => of_error_t::OF_ERR_BACKPRESSURE as i32,
        ExecutionError::Disconnected | ExecutionError::RouteNotFound => {
            of_error_t::OF_ERR_STATE as i32
        }
        ExecutionError::Core(_) => of_error_t::OF_ERR_INVALID_ARG as i32,
        ExecutionError::Adapter(_) | ExecutionError::Journal(_) => {
            of_error_t::OF_ERR_INTERNAL as i32
        }
    }
}

fn map_concurrent_execution_error(err: &ConcurrentExecutionError) -> i32 {
    match err {
        ConcurrentExecutionError::Backpressure => of_error_t::OF_ERR_BACKPRESSURE as i32,
        ConcurrentExecutionError::Stopped | ConcurrentExecutionError::WorkerPanic => {
            of_error_t::OF_ERR_STATE as i32
        }
        ConcurrentExecutionError::Execution(err) => map_execution_error(err),
    }
}

fn route_configs_from_ffi(
    routes: *const of_execution_route_config_t,
    route_count: u32,
) -> Result<Vec<RouteConfig>, ()> {
    let routes = unsafe { std::slice::from_raw_parts(routes, route_count as usize) };
    let mut route_configs = Vec::with_capacity(routes.len());
    for route in routes {
        route_configs.push(route_config_from_ffi(route)?);
    }
    Ok(route_configs)
}

fn concurrent_config_from_ffi(
    config: *const of_execution_concurrent_config_t,
) -> ConcurrentExecutionConfig {
    if config.is_null() {
        return ConcurrentExecutionConfig::default();
    }
    let config = unsafe { *config };
    ConcurrentExecutionConfig {
        command_capacity: nonzero_usize(config.command_capacity, 1024),
        report_capacity: nonzero_usize(config.report_capacity, 1024),
        event_buffer_capacity: nonzero_usize(config.event_buffer_capacity, FFI_EVENT_BUFFER_CAP),
    }
}

fn nonzero_usize(value: u32, default_value: usize) -> usize {
    if value == 0 {
        default_value
    } else {
        value as usize
    }
}

fn send_concurrent_command(
    engine: &mut of_execution_concurrent_engine,
    command: ExecutionCommand,
    out_sequence: *mut u64,
) -> i32 {
    match engine.inner.try_send(command) {
        Ok(sequence) => {
            write_optional_u64(out_sequence, sequence);
            of_error_t::OF_OK as i32
        }
        Err(err) => map_concurrent_execution_error(&err),
    }
}

fn write_concurrent_report(
    report: &ExecutionCommandReport,
    out_report: *mut of_execution_command_report_t,
    out_events: *mut of_execution_event_t,
    inout_len: *mut u32,
) -> i32 {
    let copy_rc = copy_execution_events(&report.events, out_events, inout_len);
    let event_count = unsafe { *inout_len };
    unsafe {
        *out_report = of_execution_command_report_t {
            sequence: report.sequence,
            kind: execution_command_kind_to_u32(report.kind),
            result_code: match &report.result {
                Ok(_) => of_error_t::OF_OK as i32,
                Err(err) => map_execution_error(err),
            },
            event_count,
        };
    }
    copy_rc
}

fn execution_command_kind_to_u32(kind: ExecutionCommandKind) -> u32 {
    match kind {
        ExecutionCommandKind::Submit => 1,
        ExecutionCommandKind::Cancel => 2,
        ExecutionCommandKind::Amend => 3,
        ExecutionCommandKind::Poll => 4,
        ExecutionCommandKind::RecoverOpenOrders => 5,
        ExecutionCommandKind::Stop => 6,
    }
}

fn write_optional_u64(ptr: *mut u64, value: u64) {
    if !ptr.is_null() {
        unsafe {
            *ptr = value;
        }
    }
}

fn fixed_from_ptr<const N: usize>(ptr: *const c_char) -> Result<FixedAscii<N>, ()> {
    let value = non_empty_string(ptr).ok_or(())?;
    FixedAscii::new(&value).map_err(|_| ())
}

fn route_config_from_ffi(cfg: &of_execution_route_config_t) -> Result<RouteConfig, ()> {
    Ok(RouteConfig {
        route_id: fixed_from_ptr::<32>(cfg.route_id)?,
        account_id: fixed_from_ptr::<32>(cfg.account_id)?,
        symbol: ExecutionSymbol {
            venue: fixed_from_ptr::<16>(cfg.venue)?,
            instrument: fixed_from_ptr::<32>(cfg.instrument)?,
        },
        enabled: cfg.enabled != 0,
        risk_limits: RiskLimits {
            kill_switch: cfg.kill_switch != 0,
            max_order_qty: cfg.max_order_qty,
            max_order_notional: i128::from(cfg.max_order_notional),
            max_open_orders: cfg.max_open_orders,
            max_open_notional: i128::from(cfg.max_open_notional),
            price_band_ticks: cfg.price_band_ticks,
        },
    })
}

fn order_request_from_ffi(req: &of_execution_order_request_t) -> Result<OrderRequest, ()> {
    Ok(OrderRequest {
        client_order_id: fixed_from_ptr::<40>(req.client_order_id)?,
        account_id: fixed_from_ptr::<32>(req.account_id)?,
        route_id: fixed_from_ptr::<32>(req.route_id)?,
        strategy_id: fixed_from_ptr::<32>(req.strategy_id).unwrap_or_else(|_| StrategyId::empty()),
        symbol: ExecutionSymbol {
            venue: fixed_from_ptr::<16>(req.venue)?,
            instrument: fixed_from_ptr::<32>(req.instrument)?,
        },
        side: side_from_execution_ffi(req.side)?,
        order_type: order_type_from_ffi(req.order_type)?,
        time_in_force: tif_from_ffi(req.time_in_force)?,
        quantity: OrderQty(req.quantity),
        limit_price: OrderPrice(req.limit_price),
        stop_price: OrderPrice(req.stop_price),
        ts_exchange_ns: req.ts_exchange_ns,
        ts_recv_ns: req.ts_recv_ns,
    })
}

fn cancel_request_from_ffi(req: &of_execution_cancel_request_t) -> Result<CancelRequest, ()> {
    Ok(CancelRequest {
        client_order_id: fixed_from_ptr::<40>(req.client_order_id)?,
        orig_client_order_id: fixed_from_ptr::<40>(req.orig_client_order_id)?,
        venue_order_id: fixed_from_ptr::<48>(req.venue_order_id)
            .unwrap_or_else(|_| VenueOrderId::empty()),
        account_id: fixed_from_ptr::<32>(req.account_id)?,
        route_id: fixed_from_ptr::<32>(req.route_id)?,
        symbol: ExecutionSymbol {
            venue: fixed_from_ptr::<16>(req.venue)?,
            instrument: fixed_from_ptr::<32>(req.instrument)?,
        },
        ts_recv_ns: req.ts_recv_ns,
    })
}

fn amend_request_from_ffi(req: &of_execution_amend_request_t) -> Result<AmendRequest, ()> {
    Ok(AmendRequest {
        client_order_id: fixed_from_ptr::<40>(req.client_order_id)?,
        orig_client_order_id: fixed_from_ptr::<40>(req.orig_client_order_id)?,
        venue_order_id: fixed_from_ptr::<48>(req.venue_order_id)
            .unwrap_or_else(|_| VenueOrderId::empty()),
        account_id: fixed_from_ptr::<32>(req.account_id)?,
        route_id: fixed_from_ptr::<32>(req.route_id)?,
        symbol: ExecutionSymbol {
            venue: fixed_from_ptr::<16>(req.venue)?,
            instrument: fixed_from_ptr::<32>(req.instrument)?,
        },
        quantity: OrderQty(req.quantity),
        limit_price: OrderPrice(req.limit_price),
        ts_recv_ns: req.ts_recv_ns,
    })
}

fn side_from_execution_ffi(value: u32) -> Result<OrderSide, ()> {
    match value {
        1 => Ok(OrderSide::Buy),
        2 => Ok(OrderSide::Sell),
        _ => Err(()),
    }
}

fn order_type_from_ffi(value: u32) -> Result<OrderType, ()> {
    match value {
        1 => Ok(OrderType::Market),
        2 => Ok(OrderType::Limit),
        3 => Ok(OrderType::Stop),
        4 => Ok(OrderType::StopLimit),
        _ => Err(()),
    }
}

fn tif_from_ffi(value: u32) -> Result<TimeInForce, ()> {
    match value {
        1 => Ok(TimeInForce::Day),
        2 => Ok(TimeInForce::Gtc),
        3 => Ok(TimeInForce::Ioc),
        4 => Ok(TimeInForce::Fok),
        5 => Ok(TimeInForce::Gtd),
        _ => Err(()),
    }
}

fn copy_execution_events(
    events: &ExecutionEventBuffer,
    out_events: *mut of_execution_event_t,
    inout_len: *mut u32,
) -> i32 {
    if inout_len.is_null() {
        return of_error_t::OF_ERR_INVALID_ARG as i32;
    }
    let capacity = unsafe { *inout_len as usize };
    let needed = events.len();
    unsafe {
        *inout_len = needed as u32;
    }
    if needed == 0 {
        return of_error_t::OF_OK as i32;
    }
    if out_events.is_null() {
        return of_error_t::OF_ERR_BACKPRESSURE as i32;
    }
    if capacity < needed {
        return of_error_t::OF_ERR_BACKPRESSURE as i32;
    }
    for (idx, event) in events.as_slice().iter().enumerate() {
        unsafe {
            *out_events.add(idx) = event_to_ffi(event);
        }
    }
    of_error_t::OF_OK as i32
}

fn event_to_ffi(event: &ExecutionEvent) -> of_execution_event_t {
    of_execution_event_t {
        exec_type: event.exec_type as u32,
        order_status: event.order_status as u32,
        client_order_id: cstr_array(event.client_order_id.as_str()),
        orig_client_order_id: cstr_array(event.orig_client_order_id.as_str()),
        venue_order_id: cstr_array(event.venue_order_id.as_str()),
        execution_id: cstr_array(event.execution_id.as_str()),
        account_id: cstr_array(event.account_id.as_str()),
        route_id: cstr_array(event.route_id.as_str()),
        venue: cstr_array(event.symbol.venue.as_str()),
        instrument: cstr_array(event.symbol.instrument.as_str()),
        last_qty: event.last_qty.0,
        last_price: event.last_price.0,
        cumulative_qty: event.cumulative_qty.0,
        leaves_qty: event.leaves_qty.0,
        average_price: event.average_price.0,
        ts_exchange_ns: event.ts_exchange_ns,
        ts_recv_ns: event.ts_recv_ns,
        reason: event.reason as u32,
        text: cstr_array(event.text.as_str()),
    }
}

fn order_state_to_ffi(state: &OrderState) -> of_execution_order_state_t {
    of_execution_order_state_t {
        client_order_id: cstr_array(state.client_order_id.as_str()),
        venue_order_id: cstr_array(state.venue_order_id.as_str()),
        account_id: cstr_array(state.account_id.as_str()),
        route_id: cstr_array(state.route_id.as_str()),
        venue: cstr_array(state.symbol.venue.as_str()),
        instrument: cstr_array(state.symbol.instrument.as_str()),
        status: state.status as u32,
        order_qty: state.order_qty.0,
        cumulative_qty: state.cumulative_qty.0,
        leaves_qty: state.leaves_qty.0,
        average_price: state.average_price.0,
        updated_ns: state.updated_ns,
    }
}

fn cstr_array<const N: usize>(value: &str) -> [c_char; N] {
    let mut out = [0 as c_char; N];
    if N == 0 {
        return out;
    }
    let bytes = value.as_bytes();
    let max = bytes.len().min(N - 1);
    for idx in 0..max {
        out[idx] = bytes[idx] as c_char;
    }
    out
}

#[cfg(test)]
include!("tests.rs");