nautilus-live 0.63.0

Core live trading components and machinery for the Nautilus trading engine
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
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Python bindings for live node.

use std::{
    cell::{Cell, Ref, RefCell, RefMut},
    collections::HashMap,
    fmt::Debug,
    future::Future,
    pin::Pin,
    rc::Rc,
    str::FromStr,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
        mpsc,
    },
    task::{Context, Poll, Waker},
    thread,
    time::{Duration, Instant},
};

use nautilus_common::{
    actor::data_actor::ImportableActorConfig,
    cache::CacheConfig,
    enums::Environment,
    live::get_runtime,
    logging::logger::LoggerConfig,
    msgbus::MessageBusConfig,
    python::{
        actor::{PyDataActor, prepare_python_actor},
        cache::{PyCache, get_global_cache_database_factory_registry},
        msgbus::get_global_msgbus_factory_registry,
    },
};
#[cfg(feature = "examples")]
use nautilus_core::python::to_pytype_err;
use nautilus_core::{
    UUID4,
    python::{to_pyruntime_err, to_pyvalue_err},
};
use nautilus_model::{
    enums::OmsType,
    identifiers::{ActorId, ExecAlgorithmId, InstrumentId, TraderId},
};
use nautilus_portfolio::{config::PortfolioConfig, python::PyPortfolio};
use nautilus_system::get_global_pyo3_registry;
#[cfg(feature = "examples")]
use nautilus_testkit::{DataTester, DataTesterConfig, ExecTester, ExecTesterConfig};
#[cfg(feature = "examples")]
use nautilus_trading::examples::{
    actors::{BookImbalanceActor, BookImbalanceActorConfig},
    strategies::{
        CompositeMarketMaker, CompositeMarketMakerConfig, DeltaNeutralVol, DeltaNeutralVolConfig,
        EmaCross, EmaCrossConfig, GridMarketMaker, GridMarketMakerConfig, HurstVpinDirectional,
        HurstVpinDirectionalConfig,
    },
};
use nautilus_trading::{
    ImportableControllerConfig, ImportableExecutionAlgorithmConfig, ImportableStrategyConfig,
    python::{algorithm::PyExecutionAlgorithm, strategy::PyStrategy},
};
use parking_lot::{Condvar, Mutex};
use pyo3::{
    ffi::c_str,
    intern,
    prelude::*,
    sync::PyOnceLock,
    types::{PyCFunction, PyDict, PyTuple},
};
use serde_json;

// Re-exported so the `live` module registers every Python class through this module.
pub use crate::node::NodeState;
use crate::{
    builder::LiveNodeBuilder,
    config::{
        LiveDataEngineConfig, LiveExecutionEngineConfig, LiveNodeConfig, LiveRiskEngineConfig,
        PluginConfig,
    },
    node::{LiveNode, LiveNodeHandle, NodeRunMode, config::RoutingConfig},
    python::config::coerce_json_config,
};

/// Python-facing wrapper owning a [`LiveNode`].
///
/// `run_async` moves the node into the returned awaitable, so the wrapper is empty for the
/// remainder of a hosted run. Every method then fails with a clear error rather than aliasing the
/// node the run future is driving. Capture `cache`, `portfolio`, and `handle` before starting a
/// hosted run; each is an independent handle that stays usable while the node runs.
#[pyo3::pyclass(module = "nautilus_trader.live", name = "LiveNode", unsendable)]
#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")]
#[derive(Debug)]
pub struct PyLiveNode {
    inner: Rc<RefCell<Option<LiveNode>>>,
    handle: LiveNodeHandle,
}

impl PyLiveNode {
    /// Wraps an owned node for Python.
    #[must_use]
    pub fn new(node: LiveNode) -> Self {
        Self {
            handle: node.handle(),
            inner: Rc::new(RefCell::new(Some(node))),
        }
    }

    fn node(&self) -> PyResult<Ref<'_, LiveNode>> {
        let borrow = self.inner.try_borrow().map_err(|_| node_busy_err())?;
        if borrow.is_none() {
            return Err(node_consumed_err());
        }

        Ok(Ref::map(borrow, |node| {
            node.as_ref().expect("node presence checked above")
        }))
    }

    fn node_mut(&self) -> PyResult<RefMut<'_, LiveNode>> {
        let borrow = self.inner.try_borrow_mut().map_err(|_| node_busy_err())?;
        if borrow.is_none() {
            return Err(node_consumed_err());
        }

        Ok(RefMut::map(borrow, |node| {
            node.as_mut().expect("node presence checked above")
        }))
    }

    fn is_consumed(&self) -> bool {
        self.inner.try_borrow().is_ok_and(|node| node.is_none())
    }
}

/// Thread-safe control handle for a [`LiveNode`].
///
/// Stays valid for the node's whole lifetime, including while a hosted run owns the node, and is
/// safe to call from any thread or from a signal handler.
#[pyo3::pyclass(
    module = "nautilus_trader.live",
    name = "LiveNodeHandle",
    frozen,
    skip_from_py_object
)]
#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")]
#[derive(Clone, Debug)]
pub struct PyLiveNodeHandle {
    inner: LiveNodeHandle,
}

#[pyo3_stub_gen::derive::gen_stub_pymethods]
#[pymethods]
impl PyLiveNodeHandle {
    /// Signals the node to stop, returning immediately.
    ///
    /// The node then runs its full shutdown sequence, so callers awaiting `run_async` observe
    /// completion only once shutdown finishes.
    #[pyo3(name = "stop")]
    fn py_stop(&self) {
        self.inner.stop();
    }

    /// Returns whether a stop has been requested.
    #[getter]
    #[pyo3(name = "is_stopping")]
    fn py_is_stopping(&self) -> bool {
        self.inner.should_stop()
    }

    /// Returns whether the node is currently running.
    #[getter]
    #[pyo3(name = "is_running")]
    fn py_is_running(&self) -> bool {
        self.inner.is_running()
    }

    /// Returns the node's current lifecycle state.
    #[getter]
    #[pyo3(name = "state")]
    fn py_state(&self) -> NodeState {
        self.inner.state()
    }

    fn __repr__(&self) -> String {
        format!("LiveNodeHandle(state={:?})", self.inner.state())
    }
}

/// How long `close` drives a still-running node before giving up.
///
/// A closed host loop can no longer resume the run, so the node is driven to completion inline.
/// Bounded so interpreter teardown cannot hang indefinitely on an unresponsive venue.
const CLOSE_DRIVE_TIMEOUT: Duration = Duration::from_secs(30);

thread_local! {
    /// Guards against a second hosted run on the same thread.
    ///
    /// The runner binds its senders into thread-local storage and the msgbus is thread-local, so
    /// two interleaved hosted nodes would cross-wire each other's events rather than fail.
    static HOSTED_RUN_ACTIVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Waker for driving a run to completion without an event loop.
///
/// The host loop is gone by the time this is used, so waking must not touch Python: a tokio worker
/// that blocked acquiring the GIL could not then wake the thread waiting here.
#[derive(Debug, Default)]
struct BlockingWake {
    woken: Mutex<bool>,
    signal: Condvar,
}

impl BlockingWake {
    /// Waits for a wake, returning `false` once the deadline passes.
    fn wait_until(&self, deadline: Instant) -> bool {
        let mut woken = self.woken.lock();
        while !*woken {
            let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
                return false;
            };

            let timeout = self.signal.wait_for(&mut woken, remaining);

            if timeout.timed_out() && !*woken {
                return false;
            }
        }

        *woken = false;
        true
    }
}

impl std::task::Wake for BlockingWake {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        *self.woken.lock() = true;
        self.signal.notify_all();
    }
}

/// Wake state shared between a hosted run and the callback that resumes it.
#[derive(Debug, Default)]
struct RunWakeState {
    pending: Mutex<Option<RunSuspension>>,
    closed: AtomicBool,
}

#[derive(Debug)]
struct RunSuspension {
    generation: u64,
    future: Py<PyAny>,
}

impl RunWakeState {
    fn suspend(&self, generation: u64, future: Py<PyAny>) {
        *self.pending.lock() = Some(RunSuspension { generation, future });
    }

    fn resume(&self, py: Python<'_>, generation: u64) -> PyResult<()> {
        let mut pending = self.pending.lock();
        let Some(suspension) = pending.as_ref() else {
            return Ok(());
        };

        if self.closed.load(Ordering::Acquire) || suspension.generation != generation {
            return Ok(());
        }

        let future = pending.take().expect("suspension presence checked").future;
        drop(pending);

        let future = future.bind(py);
        if !future
            .call_method0(intern!(py, "done"))?
            .extract::<bool>()?
        {
            future.call_method1(intern!(py, "set_result"), (py.None(),))?;
        }

        Ok(())
    }

    fn close(&self) {
        self.closed.store(true, Ordering::Release);
        self.pending.lock().take();
    }
}

/// Callable scheduled on the host event loop to resume a hosted run.
#[pyo3::pyclass(name = "NodeRunWake", frozen)]
struct PyNodeRunWake {
    state: Arc<RunWakeState>,
}

#[pymethods]
impl PyNodeRunWake {
    fn __call__(&self, py: Python<'_>, generation: u64) -> PyResult<()> {
        self.state.resume(py, generation)
    }
}

enum HostWakeSignal {
    Resume(u64),
    Shutdown,
}

struct HostWakeControl {
    sender: mpsc::Sender<HostWakeSignal>,
    active: AtomicBool,
    handle: LiveNodeHandle,
}

impl HostWakeControl {
    fn resume(&self, generation: u64) {
        if !self.active.load(Ordering::Acquire) {
            return;
        }

        if self
            .sender
            .send(HostWakeSignal::Resume(generation))
            .is_err()
            && self.active.swap(false, Ordering::AcqRel)
        {
            // Nothing can resume a suspended run once the wake pump is gone. Request a stop,
            // but the awaiting task may remain suspended.
            log::error!("Hosted run wake pump stopped unexpectedly, stopping node");
            self.handle.stop();
        }
    }

    fn close(&self) {
        if self.active.swap(false, Ordering::AcqRel) {
            let _ = self.sender.send(HostWakeSignal::Shutdown);
        }
    }
}

/// Waker that signals the host wake pump from whichever thread completed the work.
struct HostLoopWaker {
    generation: u64,
    scheduled: AtomicBool,
    control: Arc<HostWakeControl>,
}

impl std::task::Wake for HostLoopWaker {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        if !self.scheduled.swap(true, Ordering::AcqRel) {
            self.control.resume(self.generation);
        }
    }
}

/// Moves Python scheduling off the dependency thread that invoked the waker.
struct HostWakePump {
    control: Arc<HostWakeControl>,
    thread: Option<thread::JoinHandle<()>>,
}

impl HostWakePump {
    fn start(
        event_loop: Py<PyAny>,
        wake_callback: Py<PyAny>,
        handle: LiveNodeHandle,
    ) -> PyResult<Self> {
        let (sender, receiver) = mpsc::channel();
        let control = Arc::new(HostWakeControl {
            sender,
            active: AtomicBool::new(true),
            handle: handle.clone(),
        });

        let control_for_thread = control.clone();

        let thread = thread::Builder::new()
            .name("nautilus-host-wake".to_string())
            .spawn(move || {
                while let Ok(signal) = receiver.recv() {
                    match signal {
                        HostWakeSignal::Resume(generation) => {
                            if !control_for_thread.active.load(Ordering::Acquire) {
                                continue;
                            }

                            let Some(result) = Python::try_attach(|py| {
                                event_loop.bind(py).call_method1(
                                    intern!(py, "call_soon_threadsafe"),
                                    (wake_callback.bind(py), generation),
                                )?;
                                Ok::<(), PyErr>(())
                            }) else {
                                log::error!(
                                    "Python unavailable while scheduling hosted run wake-up, stopping node"
                                );
                                handle.stop();
                                break;
                            };

                            if let Err(e) = result {
                                log::error!(
                                    "Failed to schedule hosted run wake-up, stopping node: {e}"
                                );
                                handle.stop();
                                break;
                            }
                        }
                        HostWakeSignal::Shutdown => break,
                    }
                }

                control_for_thread.active.store(false, Ordering::Release);
            })
            .map_err(|e| to_pyruntime_err(format!("failed to start hosted run wake pump: {e}")))?;

        Ok(Self {
            control,
            thread: Some(thread),
        })
    }

    fn waker(&self, generation: u64) -> Waker {
        Waker::from(Arc::new(HostLoopWaker {
            generation,
            scheduled: AtomicBool::new(false),
            control: self.control.clone(),
        }))
    }

    fn close(&self) {
        self.control.close();
    }

    fn join(&mut self, py: Option<Python<'_>>) {
        let Some(thread) = self.thread.take() else {
            return;
        };
        let mut thread = Some(thread);

        let result = match py {
            Some(py) => py.detach(|| thread.take().expect("thread presence checked").join()),
            None => Python::try_attach(|py| {
                py.detach(|| thread.take().expect("thread presence checked").join())
            })
            .unwrap_or_else(|| thread.take().expect("thread presence checked").join()),
        };

        if result.is_err() {
            log::error!("Hosted run wake pump panicked while stopping");
        }
    }
}

impl Drop for HostWakePump {
    fn drop(&mut self) {
        self.close();
        self.join(None);
    }
}

struct SendPtr<T>(*mut T);

// SAFETY: the owner of a `SendPtr` holds the only reference to the pointee for the pointer's
// lifetime, and the pointee outlives every use.
#[allow(unsafe_code)]
unsafe impl<T> Send for SendPtr<T> {}

/// Awaitable driving a [`LiveNode`] on the host's asyncio event loop.
///
/// Polls the node's run future from loop callbacks, so the node shares the host's thread and never
/// blocks it. Awaiting resolves once the node has fully stopped.
#[pyo3::pyclass(name = "NodeRun", unsendable)]
pub struct PyNodeRun {
    // Declared before `node` so the future is dropped first; it borrows the node.
    future: Option<Pin<Box<dyn Future<Output = anyhow::Result<()>>>>>,
    node: Option<Box<LiveNode>>,
    owner: Rc<RefCell<Option<LiveNode>>>,
    handle: LiveNodeHandle,
    event_loop: Py<PyAny>,
    wake_pump: HostWakePump,
    state: Arc<RunWakeState>,
    generation: u64,
    pending_throw: Option<PyErr>,
}

#[allow(
    clippy::missing_fields_in_debug,
    reason = "the future and node fields have no useful debug representation"
)]
impl Debug for PyNodeRun {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(stringify!(PyNodeRun))
            .field("state", &self.handle.state())
            .field("completed", &self.future.is_none())
            .finish()
    }
}

impl Drop for PyNodeRun {
    fn drop(&mut self) {
        self.restore_node(None);
    }
}

impl PyNodeRun {
    #[allow(
        unsafe_code,
        reason = "the run future borrows the boxed node this type owns"
    )]
    fn new(
        node: LiveNode,
        owner: Rc<RefCell<Option<LiveNode>>>,
        event_loop: Bound<'_, PyAny>,
        state: Arc<RunWakeState>,
        wake_pump: HostWakePump,
    ) -> Self {
        let handle = node.handle();
        let mut node = Box::new(node);
        let node_ptr = SendPtr(std::ptr::from_mut::<LiveNode>(node.as_mut()));

        let future: Pin<Box<dyn Future<Output = anyhow::Result<()>>>> = Box::pin(async move {
            let ptr = node_ptr;
            // SAFETY: the node is boxed, so its address is stable for as long as this type owns
            // it. `run_async` moved the node out of the wrapper, so no other reference exists,
            // and `future` is declared before `node` so it is dropped first.
            unsafe { (*ptr.0).run_with_mode(NodeRunMode::Hosted).await }
        });

        Self {
            future: Some(future),
            node: Some(node),
            owner,
            handle,
            event_loop: event_loop.unbind(),
            wake_pump,
            state,
            generation: 0,
            pending_throw: None,
        }
    }

    /// Returns the node to the wrapper, dropping the future that borrows it first.
    ///
    /// Releases the per-thread run guard here rather than only on drop, so a completed run does
    /// not block the next one until the coroutine object happens to be collected.
    fn restore_node(&mut self, py: Option<Python<'_>>) {
        self.state.close();
        self.wake_pump.close();
        self.future = None;
        self.wake_pump.join(py);

        if let Some(node) = self.node.take() {
            *self.owner.borrow_mut() = Some(*node);

            // Release inside the take arm so this runs exactly once, and only for the run that
            // set the guard. Clearing unconditionally would let a late drop release a newer run's.
            HOSTED_RUN_ACTIVE.set(false);
        }
    }

    /// Returns whether the host event loop is currently running.
    ///
    /// Treats an unavailable answer as running, because blocking a live loop is the worse error.
    fn host_loop_is_running(&self, py: Python<'_>) -> bool {
        self.event_loop
            .bind(py)
            .call_method0(intern!(py, "is_running"))
            .and_then(|running| running.extract::<bool>())
            .unwrap_or(true)
    }

    /// Drives the run to completion on this thread, bounded by [`CLOSE_DRIVE_TIMEOUT`].
    fn drive_to_completion(&mut self, py: Python<'_>) {
        let signal = Arc::new(BlockingWake::default());
        let waker = Waker::from(signal.clone());
        let deadline = Instant::now() + CLOSE_DRIVE_TIMEOUT;

        loop {
            let Some(future) = self.future.as_mut() else {
                return;
            };

            let poll = {
                let _guard = get_runtime().enter();
                future.as_mut().poll(&mut Context::from_waker(&waker))
            };

            if let Poll::Ready(result) = poll {
                if let Err(e) = result {
                    log::error!("Hosted run failed during inline shutdown: {e}");
                }

                self.restore_node(Some(py));
                return;
            }

            // Release the GIL so tokio workers that need it can make progress.
            if !py.detach(|| signal.wait_until(deadline)) {
                log::error!(
                    "Hosted run did not stop within {}s of the host loop closing; abandoning it \
                     with resources still held",
                    CLOSE_DRIVE_TIMEOUT.as_secs()
                );
                return;
            }
        }
    }

    /// Polls the run future once, returning the asyncio future to suspend on when still running.
    fn step(&mut self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
        let Some(future) = self.future.as_mut() else {
            return Err(to_pyruntime_err("Hosted run has already completed"));
        };

        let generation = self
            .generation
            .checked_add(1)
            .ok_or_else(|| to_pyruntime_err("Hosted run wake generation exhausted"))?;
        self.generation = generation;

        // A distinct waker prevents a late wake from an older poll resuming this suspension
        let waker = self.wake_pump.waker(generation);

        // Timers and the reactor are only reachable inside the runtime context
        let poll = {
            let _guard = get_runtime().enter();
            future.as_mut().poll(&mut Context::from_waker(&waker))
        };

        match poll {
            Poll::Ready(result) => {
                self.restore_node(Some(py));

                if let Err(e) = &result {
                    log::error!("Hosted run failed: {e}");
                }

                if let Some(raised) = self.pending_throw.take() {
                    // Shutdown finished, so the injected exception is now honoured. Reporting
                    // success here would break `asyncio.timeout`, `wait_for`, and task groups.
                    return Err(raised);
                }

                result.map(|()| None).map_err(to_pyruntime_err)
            }
            Poll::Pending => {
                let suspended = self
                    .event_loop
                    .bind(py)
                    .call_method0(intern!(py, "create_future"))?;
                suspended.setattr(intern!(py, "_asyncio_future_blocking"), true)?;

                // `call_soon_threadsafe` queues the callback, so this publishes before it can run
                self.state.suspend(generation, suspended.clone().unbind());

                Ok(Some(suspended.unbind()))
            }
        }
    }
}

#[pymethods]
impl PyNodeRun {
    fn __await__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
        slf
    }

    fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
        slf
    }

    fn __next__(&mut self, py: Python<'_>) -> PyResult<Option<Py<PyAny>>> {
        self.step(py)
    }

    #[pyo3(signature = (value=None))]
    fn send(
        &mut self,
        py: Python<'_>,
        value: Option<&Bound<'_, PyAny>>,
    ) -> PyResult<Option<Py<PyAny>>> {
        let _ = value;
        self.step(py)
    }

    /// Converts an injected exception into a graceful stop, then re-raises once the node stopped.
    ///
    /// Later throws are absorbed while shutdown runs, so a half-stopped node is never abandoned
    /// with clients connected and channels undrained. The first exception is the one raised.
    #[pyo3(signature = (*args))]
    fn throw(&mut self, py: Python<'_>, args: &Bound<'_, PyTuple>) -> PyResult<Option<Py<PyAny>>> {
        let raised = args.get_item(0)?;

        if self.pending_throw.is_none() {
            let cancelled_type = cancelled_error_type(py)?;
            let is_cancelled = raised.is_instance(&cancelled_type)? || raised.is(&cancelled_type);
            if is_cancelled {
                log::info!("Hosted run cancelled, requesting graceful shutdown");
            } else {
                log::warn!("Exception thrown into hosted run, requesting graceful shutdown");
            }

            self.pending_throw = Some(PyErr::from_value(raised));
            self.handle.stop();
        }

        self.step(py)
    }

    /// Stops the node, and drives shutdown inline only when no host loop can finish it.
    ///
    /// Python calls this when the awaiting task is discarded. With the loop still running, this
    /// requests the stop and returns, because driving inline would block every host callback; the
    /// run is then dropped with shutdown incomplete, which the warning names. With no running loop
    /// nothing else can finish the shutdown, so it is driven here rather than dropping the node
    /// with venue connections still open.
    fn close(&mut self, py: Python<'_>) {
        if self.future.is_none() {
            return;
        }

        self.handle.stop();

        // Driving inline blocks this thread, so only do it when the host loop is not running and
        // therefore cannot finish the shutdown itself.
        if self.host_loop_is_running(py) {
            log::warn!(
                "Hosted run discarded while its event loop is running; shutdown was requested but \
                 not completed, await the run instead of discarding it"
            );
            return;
        }

        log::warn!("Hosted run closed with no running event loop, draining shutdown inline");
        self.drive_to_completion(py);
    }

    fn __repr__(&self) -> String {
        format!("{self:?}")
    }
}

/// Returns the driver that wraps a [`PyNodeRun`] in a native coroutine.
///
/// `asyncio.create_task` accepts only coroutines, so returning the awaitable directly would force
/// every caller to wrap it. Awaiting the coroutine drives the same object, and a cancellation
/// delivered to the task reaches [`PyNodeRun::throw`] unchanged.
fn node_run_driver(py: Python<'_>) -> PyResult<&Py<PyAny>> {
    static DRIVER: PyOnceLock<Py<PyAny>> = PyOnceLock::new();

    DRIVER.get_or_try_init(py, || {
        let module = PyModule::from_code(
            py,
            c_str!("async def drive(run):\n    return await run\n"),
            c_str!("nautilus_trader/live/_hosted_run.py"),
            c_str!("nautilus_trader._hosted_run"),
        )?;
        Ok(module.getattr("drive")?.unbind())
    })
}

/// Returns the `asyncio.CancelledError` type.
fn cancelled_error_type(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
    py.import("asyncio")?.getattr(intern!(py, "CancelledError"))
}

/// Reports a borrow that cannot be served because the node is busy inside a call.
fn node_busy_err() -> PyErr {
    to_pyruntime_err(
        "LiveNode is busy servicing another call; do not re-enter the node from a component \
         callback, use the cache, portfolio, and handle captured beforehand",
    )
}

fn node_consumed_err() -> PyErr {
    to_pyruntime_err(
        "LiveNode is being run by `run_async`; use the handle returned by `handle()` to stop it, \
         and the `cache` and `portfolio` captured before the run to read state",
    )
}

#[pyo3_stub_gen::derive::gen_stub_pymethods]
#[pymethods]
impl PyLiveNode {
    /// Creates a new `LiveNode` directly from a kernel name and optional configuration.
    ///
    /// This is a convenience method for creating a live node with a pre-configured
    /// kernel configuration, bypassing the builder pattern. If no config is provided,
    /// a default configuration will be used.
    ///
    /// # Errors
    ///
    /// Returns an error if kernel construction fails.
    #[staticmethod]
    #[pyo3(name = "build")]
    #[pyo3(signature = (name, config=None))]
    fn py_build(name: String, config: Option<LiveNodeConfig>) -> PyResult<Self> {
        LiveNode::build(name, config)
            .map(Self::new)
            .map_err(to_pyruntime_err)
    }

    /// Creates a new `LiveNodeBuilder` for fluent configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the environment is invalid for live trading.
    #[staticmethod]
    #[pyo3(name = "builder")]
    fn py_builder(
        name: String,
        trader_id: TraderId,
        environment: Environment,
    ) -> PyResult<PyLiveNodeBuilder> {
        match LiveNode::builder(trader_id, environment) {
            Ok(builder) => Ok(PyLiveNodeBuilder {
                state: Rc::new(Cell::new(PyLiveNodeBuilderState::Ready(Box::new(
                    builder.with_name(name),
                )))),
            }),
            Err(e) => Err(to_pyruntime_err(e)),
        }
    }

    /// Gets the node's environment.
    #[getter]
    #[pyo3(name = "environment")]
    fn py_environment(&self) -> PyResult<Environment> {
        Ok(self.node()?.environment())
    }

    /// Gets the node's trader ID.
    #[getter]
    #[pyo3(name = "trader_id")]
    fn py_trader_id(&self) -> PyResult<TraderId> {
        Ok(self.node()?.trader_id())
    }

    /// Gets the node's instance ID.
    #[getter]
    #[pyo3(name = "instance_id")]
    fn py_instance_id(&self) -> PyResult<UUID4> {
        Ok(self.node()?.instance_id())
    }

    /// Checks if the live node is currently running.
    ///
    /// Answered from the handle, so this stays truthful while a hosted run holds the node.
    #[getter]
    #[pyo3(name = "is_running")]
    fn py_is_running(&self) -> bool {
        self.handle.is_running()
    }

    /// Returns the cache shared with the kernel and registered components.
    #[getter]
    #[pyo3(name = "cache")]
    fn py_cache(&self) -> PyResult<PyCache> {
        Ok(PyCache::from_rc(self.node()?.kernel().cache()))
    }

    /// Returns the portfolio shared with the kernel and registered components.
    #[getter]
    #[pyo3(name = "portfolio")]
    fn py_portfolio(&self) -> PyResult<PyPortfolio> {
        Ok(PyPortfolio::from_rc(
            self.node()?.kernel().portfolio.clone(),
        ))
    }

    /// Returns a thread-safe handle for controlling and observing this node.
    ///
    /// The handle stays valid for the node's whole lifetime, including while `run_async` owns the
    /// node, and is the supported way to stop a hosted run.
    #[pyo3(name = "handle")]
    fn py_handle(&self) -> PyLiveNodeHandle {
        PyLiveNodeHandle {
            inner: self.handle.clone(),
        }
    }

    /// Runs the live node on the caller's asyncio event loop.
    ///
    /// Takes the node and returns an awaitable that resolves once the node has stopped. The host
    /// owns the loop and its signal handling, so this installs no signal handlers. Stop the node
    /// through the handle from `handle()`; cancelling the awaiting task requests the same graceful
    /// shutdown, waits for it to finish, then re-raises the cancellation.
    ///
    /// Capture `cache`, `portfolio`, and `handle()` before calling this. They stay usable while the
    /// node runs, whereas the node itself is owned by the returned awaitable.
    ///
    /// # Limitations
    ///
    /// A node configured with a cache database backing is rejected. Those backings wait for their
    /// worker task by blocking the calling thread, which stalls the host loop rather than merely
    /// slowing it. Use `run()` for a database-backed node until the backings can be driven without
    /// blocking a host loop.
    ///
    /// # Errors
    ///
    /// Returns an error if the node has already been taken, no event loop is running, a cache
    /// database backing is configured, or another node is already running on this loop.
    #[gen_stub(override_return_type(
        type_repr = "collections.abc.Coroutine[typing.Any, typing.Any, None]",
        imports = ("collections.abc", "typing")
    ))]
    #[pyo3(name = "run_async")]
    fn py_run_async(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let event_loop = py
            .import("asyncio")?
            .call_method0("get_running_loop")
            .map_err(|_| {
                to_pyruntime_err(
                    "`run_async` requires a running asyncio event loop; use `run` to have the node \
                     own the thread instead",
                )
            })?;

        // A node runs once. Rejecting anything past `Idle` here turns a second run into an
        // immediate error rather than a coroutine that fails only when awaited.
        let state = self.node()?.state();
        if state != NodeState::Idle {
            return Err(to_pyruntime_err(format!(
                "LiveNode cannot be run from state {state:?}; build a new node to run again"
            )));
        }

        // The Redis and SQL cache backings block the calling thread while awaiting their worker
        // task, which would freeze the host loop inside a poll rather than merely slow it down.
        // Fail before taking the node so the caller gets a clear boundary instead of a hang.
        if self.node()?.has_pending_cache_database() {
            return Err(to_pyruntime_err(
                "a cache database backing is not supported on a host event loop, because its \
                 blocking calls would stall the loop; use `run()` to have the node own the thread, \
                 or configure the node without a cache database",
            ));
        }

        if HOSTED_RUN_ACTIVE.get() {
            return Err(to_pyruntime_err(
                "another LiveNode is already running on this event loop; run one concurrent \
                 LiveNode per process, or run additional nodes in separate processes",
            ));
        }

        // Everything fallible happens before the node is taken, so a failure here cannot strand
        // it. `PyNodeRun` restores the node on drop, covering the paths after this point.
        let driver = node_run_driver(py)?.clone_ref(py);
        let state = Arc::new(RunWakeState::default());

        let wake_callback = Py::new(
            py,
            PyNodeRunWake {
                state: state.clone(),
            },
        )?
        .into_any();

        let wake_pump = HostWakePump::start(
            event_loop.clone().unbind(),
            wake_callback,
            self.handle.clone(),
        )?;

        let node = self
            .inner
            .borrow_mut()
            .take()
            .ok_or_else(node_consumed_err)?;
        let run = PyNodeRun::new(node, self.inner.clone(), event_loop, state, wake_pump);
        HOSTED_RUN_ACTIVE.set(true);

        driver.call1(py, (Py::new(py, run)?,))
    }

    /// Run the live node with automatic shutdown handling.
    ///
    /// This method starts the node, runs indefinitely, and handles graceful shutdown
    /// on interrupt signals.
    ///
    /// # Thread Safety
    ///
    /// The event loop runs directly on the current thread (not spawned) because the
    /// msgbus uses thread-local storage. Endpoints registered by the kernel are only
    /// accessible from the same thread.
    ///
    /// # Shutdown Sequence
    ///
    /// 1. Signal received (SIGINT, SIGTERM, or handle stop).
    /// 2. Trader components stopped (triggers order cancellations, etc.).
    /// 3. Event loop continues processing residual events for the configured grace period.
    /// 4. Kernel finalized, clients disconnected, remaining events drained.
    ///
    /// # Errors
    ///
    /// Returns an error if the node fails to start or encounters a runtime error.
    #[pyo3(name = "run")]
    fn py_run(&self, py: Python) -> PyResult<()> {
        if self.node()?.is_running() {
            return Err(to_pyruntime_err("LiveNode is already running"));
        }

        // Get a handle for coordinating with the signal checker
        let handle = self.node()?.handle();

        // Import signal module
        let signal_module = py.import("signal")?;
        let original_handler =
            signal_module.call_method1("signal", (2, signal_module.getattr("SIG_DFL")?))?; // Save original SIGINT handler (signal 2)

        // Set up a custom signal handler that uses our handle
        let handle_for_signal = handle;
        let signal_callback = new_sync_py_callback(
            py,
            move |_args: &pyo3::Bound<'_, PyTuple>,
                  _kwargs: Option<&pyo3::Bound<'_, PyDict>>|
                  -> PyResult<()> {
                log::info!("Python signal handler called");
                handle_for_signal.stop();
                Ok(())
            },
        )?;

        // Install our signal handler
        signal_module.call_method1("signal", (2, signal_callback))?;

        // Run the node and restore signal handler afterward
        let mut node = self.node_mut()?;
        let result = run_live_node_detached(py, &mut node);

        // Restore original signal handler
        signal_module.call_method1("signal", (2, original_handler))?;

        result
    }

    /// Stop the live node.
    ///
    /// This method stops the trader, waits for the configured grace period to allow
    /// residual events to be processed, then finalizes the shutdown sequence.
    ///
    /// # Errors
    ///
    /// Returns an error if shutdown fails.
    #[pyo3(name = "stop")]
    fn py_stop(&self, py: Python<'_>) -> PyResult<()> {
        let mut node = self.node_mut()?;
        if !node.is_running() {
            return Err(to_pyruntime_err("LiveNode is not running"));
        }

        stop_live_node_detached(py, &mut node)
    }

    /// Disposes the live node kernel and releases resources.
    ///
    /// Does nothing while a hosted run holds the node. The run returns the node when it finishes,
    /// so a `try`/`finally` cleanup that outlives the run disposes it as usual.
    #[pyo3(name = "dispose")]
    fn py_dispose(&self, py: Python<'_>) -> PyResult<()> {
        if self.is_consumed() {
            return Ok(());
        }

        let mut node = self.node_mut()?;
        let stop_result = if node.is_running() {
            stop_live_node_detached(py, &mut node)
        } else {
            Ok(())
        };

        if let Err(ref err) = stop_result {
            log::error!("Failed to stop LiveNode during dispose: {err}");
        }

        node.dispose();
        stop_result
    }

    /// Adds a constructed Python actor to the trader.
    ///
    /// # Errors
    ///
    /// Returns an error if the node is running, the actor is invalid, or registration fails.
    #[pyo3(name = "add_actor")]
    fn py_add_actor(&self, actor: &Bound<'_, PyAny>) -> PyResult<()> {
        if self.node()?.state() != NodeState::Idle {
            return Err(to_pyruntime_err(
                "Cannot add actor while node is running, add actors before running the node",
            ));
        }

        log::debug!("`add_actor` with a constructed instance");

        let actor = actor.clone().unbind();
        let actor_id = Python::attach(|py| {
            let actor = actor.bind(py);
            let config = actor
                .getattr("config")
                .ok()
                .filter(|config| !config.is_none());
            prepare_python_actor(actor, config.as_ref())
        })
        .map_err(to_pyruntime_err)?;

        self.register_python_actor(&actor, actor_id)
    }

    #[pyo3(name = "add_actor_from_config")]
    #[expect(clippy::needless_pass_by_value)]
    fn py_add_actor_from_config(&self, _py: Python, config: ImportableActorConfig) -> PyResult<()> {
        log::debug!("`add_actor_from_config` with: {config:?}");

        // Extract module and class name from actor_path
        let parts: Vec<&str> = config.actor_path.split(':').collect();
        if parts.len() != 2 {
            return Err(to_pyvalue_err(
                "actor_path must be in format 'module.path:ClassName'",
            ));
        }
        let (module_name, class_name) = (parts[0], parts[1]);

        log::info!("Importing actor from module: {module_name} class: {class_name}");

        let (python_actor, actor_id) =
            Python::attach(|py| -> anyhow::Result<(Py<PyAny>, ActorId)> {
                let actor_module = py
                    .import(module_name)
                    .map_err(|e| anyhow::anyhow!("Failed to import module {module_name}: {e}"))?;
                let actor_class = actor_module
                    .getattr(class_name)
                    .map_err(|e| anyhow::anyhow!("Failed to get class {class_name}: {e}"))?;

                let config_instance =
                    create_config_instance(py, &config.config_path, &config.config)?;

                let python_actor = if let Some(config_obj) = config_instance.as_ref() {
                    actor_class.call1((config_obj,))?
                } else {
                    actor_class.call0()?
                };

                log::debug!("Created Python actor instance: {python_actor:?}");

                let actor_id = prepare_python_actor(&python_actor, config_instance.as_ref())?;

                Ok((python_actor.unbind(), actor_id))
            })
            .map_err(to_pyruntime_err)?;

        self.register_python_actor(&python_actor, actor_id)
    }

    /// Adds a strategy to the trader.
    ///
    /// Strategies are registered in both the component registry (for lifecycle management)
    /// and the actor registry (for data callbacks via msgbus).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The node is currently running.
    /// - A strategy with the same ID is already registered.
    /// - The strategy configures one or more external order claims and the request repeats
    ///   an instrument, or either tier already contains a requested claim.
    /// - The strategy configures one or more external order claims or an OMS type override,
    ///   and the execution engine is already borrowed. A strategy configuring neither does
    ///   not take the borrow and cannot fail this way.
    #[allow(
        unsafe_code,
        reason = "Required for Python strategy component registration"
    )]
    #[pyo3(name = "add_strategy")]
    fn py_add_strategy(&self, strategy: &Bound<'_, PyAny>) -> PyResult<()> {
        if self.node()?.state() != NodeState::Idle {
            return Err(to_pyruntime_err(
                "Cannot add strategy while node is running, add strategies before running the node",
            ));
        }

        log::debug!("`add_strategy` with a constructed instance");

        let strategy = strategy.clone().unbind();

        let strategy_id = self
            .node_mut()?
            .kernel_mut()
            .trader
            .borrow_mut()
            .prepare_python_strategy_instance(&strategy)
            .map_err(to_pyruntime_err)?;

        let (external_order_claims, oms_type) = Python::attach(
            |py| -> anyhow::Result<(Option<Vec<InstrumentId>>, Option<OmsType>)> {
                let bound = strategy.bind(py);
                let config_obj = bound
                    .getattr("config")
                    .ok()
                    .filter(|config| !config.is_none());

                let mut py_strategy_ref = bound
                    .extract::<PyRefMut<PyStrategy>>()
                    .map_err(Into::<PyErr>::into)
                    .map_err(|e| anyhow::anyhow!("Failed to extract PyStrategy: {e}"))?;

                if let Some(config_obj) = config_obj.as_ref()
                    && let Some(claims) = extract_external_order_claims_config_attr(config_obj)?
                {
                    py_strategy_ref.set_external_order_claims(Some(claims));
                }

                let claims = py_strategy_ref.external_order_claims();
                let oms_type = config_obj
                    .as_ref()
                    .and_then(|cfg| cfg.getattr("oms_type").ok())
                    .filter(|value| !value.is_none())
                    .and_then(|value| value.extract::<OmsType>().ok());

                Ok((claims, oms_type))
            },
        )
        .map_err(to_pyruntime_err)?;

        if let Some(claims) = external_order_claims.filter(|claims| !claims.is_empty()) {
            self.node_mut()?
                .register_external_order_claims(strategy_id, &claims)
                .map_err(to_pyruntime_err)?;
        }

        self.node_mut()?
            .kernel_mut()
            .trader
            .borrow_mut()
            .commit_python_strategy_instance(&strategy)
            .map_err(to_pyruntime_err)?;

        if let Some(oms_type) = oms_type {
            self.node_mut()?
                .kernel()
                .exec_engine
                .borrow_mut()
                .register_oms_type(strategy_id, oms_type);
        }

        log::info!("Registered Python strategy {strategy_id}");
        Ok(())
    }

    #[pyo3(name = "add_strategy_from_config")]
    #[expect(clippy::needless_pass_by_value)]
    fn py_add_strategy_from_config(
        &self,
        _py: Python,
        config: ImportableStrategyConfig,
    ) -> PyResult<()> {
        log::debug!("`add_strategy_from_config` with: {config:?}");

        // Extract module and class name from strategy_path
        let parts: Vec<&str> = config.strategy_path.split(':').collect();
        if parts.len() != 2 {
            return Err(to_pyvalue_err(
                "strategy_path must be in format 'module.path:ClassName'",
            ));
        }
        let (module_name, class_name) = (parts[0], parts[1]);

        log::info!("Importing strategy from module: {module_name} class: {class_name}");

        // Phase 1: Create the Python strategy, then prepare it for registration so the strategy ID,
        // order ID tag, and logging flags are sourced from the same config as the instance path
        let python_strategy = Python::attach(|py| -> anyhow::Result<Py<PyAny>> {
            let strategy_module = py
                .import(module_name)
                .map_err(|e| anyhow::anyhow!("Failed to import module {module_name}: {e}"))?;
            let strategy_class = strategy_module
                .getattr(class_name)
                .map_err(|e| anyhow::anyhow!("Failed to get class {class_name}: {e}"))?;

            let config_instance = create_config_instance(py, &config.config_path, &config.config)?;

            let python_strategy = if let Some(config_obj) = config_instance {
                strategy_class.call1((config_obj,))?
            } else {
                strategy_class.call0()?
            };

            log::debug!("Created Python strategy instance: {python_strategy:?}");

            Ok(python_strategy.unbind())
        })
        .map_err(to_pyruntime_err)?;

        let strategy_id = self
            .node_mut()?
            .kernel_mut()
            .trader
            .borrow_mut()
            .prepare_python_strategy_instance(&python_strategy)
            .map_err(to_pyruntime_err)?;

        Python::attach(|py| -> anyhow::Result<()> {
            let bound = python_strategy.bind(py);
            let config_obj = bound
                .getattr("config")
                .ok()
                .filter(|config| !config.is_none());

            let mut py_strategy_ref = bound
                .extract::<PyRefMut<PyStrategy>>()
                .map_err(Into::<PyErr>::into)
                .map_err(|e| anyhow::anyhow!("Failed to extract PyStrategy: {e}"))?;

            if let Some(config_obj) = config_obj.as_ref()
                && let Some(claims) = extract_external_order_claims_config_attr(config_obj)?
            {
                py_strategy_ref.set_external_order_claims(Some(claims));
            }

            Ok(())
        })
        .map_err(to_pyruntime_err)?;

        // Phase 2: Claim external orders before committing, matching the instance path
        let external_order_claims = Python::attach(|py| -> anyhow::Result<Option<Vec<_>>> {
            let py_strategy = python_strategy.bind(py);
            let py_strategy_ref = py_strategy
                .extract::<PyRef<PyStrategy>>()
                .map_err(Into::<PyErr>::into)
                .map_err(|e| anyhow::anyhow!("Failed to extract PyStrategy: {e}"))?;

            Ok(py_strategy_ref.external_order_claims())
        })
        .map_err(to_pyruntime_err)?;

        if let Some(claims) = external_order_claims.filter(|claims| !claims.is_empty()) {
            self.node_mut()?
                .register_external_order_claims(strategy_id, &claims)
                .map_err(to_pyruntime_err)?;
        }

        // Phase 3: Register the strategy through the trader's single Python registration path
        self.node_mut()?
            .kernel_mut()
            .trader
            .borrow_mut()
            .commit_python_strategy_instance(&python_strategy)
            .map_err(to_pyruntime_err)?;

        log::info!("Registered Python strategy {strategy_id}");
        Ok(())
    }

    /// Adds an execution algorithm to the trader.
    ///
    /// Execution algorithms are registered in both the component registry (for lifecycle
    /// management) and the actor registry (for data callbacks via msgbus).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The node is currently running.
    /// - An execution algorithm with the same ID is already registered.
    #[pyo3(name = "add_exec_algorithm")]
    fn py_add_exec_algorithm(&self, exec_algorithm: &Bound<'_, PyAny>) -> PyResult<()> {
        if self.node()?.state() != NodeState::Idle {
            return Err(to_pyruntime_err(
                "Cannot add exec algorithm while node is running, add exec algorithms before running the node",
            ));
        }

        log::debug!("`add_exec_algorithm` with a constructed instance");

        let exec_algorithm = exec_algorithm.clone().unbind();
        let py_exec_algorithm = Python::attach(|py| -> anyhow::Result<PyExecutionAlgorithm> {
            let bound = exec_algorithm.bind(py);
            let config = bound
                .getattr("config")
                .ok()
                .filter(|config| !config.is_none());
            let mut py_exec_algorithm_ref = bound
                .extract::<PyRefMut<PyExecutionAlgorithm>>()
                .map_err(Into::<PyErr>::into)
                .map_err(|e| {
                    anyhow::anyhow!(
                        "LiveNode.add_exec_algorithm requires a Python v2 ExecutionAlgorithm instance; use add_exec_algorithm_from_config for DataActor-based algorithms: {e}"
                    )
                })?;

            if let Some(config) = config.as_ref() {
                py_exec_algorithm_ref.configure_from_py_config(config)?;
            }

            py_exec_algorithm_ref.set_python_instance(bound)?;
            Ok(py_exec_algorithm_ref.clone())
        })
        .map_err(to_pyruntime_err)?;

        let exec_algorithm_id = self
            .node_mut()?
            .kernel_mut()
            .trader
            .borrow_mut()
            .add_py_execution_algorithm_instance(py_exec_algorithm, &exec_algorithm)
            .map_err(to_pyruntime_err)?;

        log::info!("Registered Python exec algorithm {exec_algorithm_id}");
        Ok(())
    }

    #[pyo3(name = "add_exec_algorithm_from_config")]
    #[expect(clippy::needless_pass_by_value)]
    fn py_add_exec_algorithm_from_config(
        &self,
        _py: Python,
        config: ImportableExecutionAlgorithmConfig,
    ) -> PyResult<()> {
        if self.node()?.is_running() {
            return Err(to_pyruntime_err(
                "Cannot add exec algorithm while node is running",
            ));
        }

        log::debug!("`add_exec_algorithm_from_config` with: {config:?}");

        let parts: Vec<&str> = config.exec_algorithm_path.split(':').collect();
        if parts.len() != 2 {
            return Err(to_pyvalue_err(
                "exec_algorithm_path must be in format 'module.path:ClassName'",
            ));
        }
        let (module_name, class_name) = (parts[0], parts[1]);

        log::info!("Importing exec algorithm from module: {module_name} class: {class_name}");

        // Phase 1: Create and configure the Python exec algorithm.
        let (python_exec_algorithm, py_execution_algorithm, actor_id) = Python::attach(
            |py| -> anyhow::Result<(Py<PyAny>, Option<PyExecutionAlgorithm>, ActorId)> {
                let algo_module = py
                    .import(module_name)
                    .map_err(|e| anyhow::anyhow!("Failed to import module {module_name}: {e}"))?;
                let algo_class = algo_module
                    .getattr(class_name)
                    .map_err(|e| anyhow::anyhow!("Failed to get class {class_name}: {e}"))?;

                let config_instance =
                    create_config_instance(py, &config.config_path, &config.config)?;

                let python_exec_algorithm = if let Some(config_obj) = config_instance.clone() {
                    algo_class.call1((config_obj,))?
                } else {
                    algo_class.call0()?
                };

                log::debug!("Created Python exec algorithm instance: {python_exec_algorithm:?}");

                if let Ok(mut py_exec_algorithm_ref) =
                    python_exec_algorithm.extract::<PyRefMut<PyExecutionAlgorithm>>()
                {
                    if let Some(config_obj) = config_instance.as_ref() {
                        py_exec_algorithm_ref.configure_from_py_config(config_obj)?;
                    }

                    py_exec_algorithm_ref.set_python_instance(&python_exec_algorithm)?;
                    let actor_id =
                        ActorId::from(py_exec_algorithm_ref.exec_algorithm_id().inner().as_str());

                    return Ok((
                        python_exec_algorithm.unbind(),
                        Some(py_exec_algorithm_ref.clone()),
                        actor_id,
                    ));
                }

                let mut py_data_actor_ref = python_exec_algorithm
                    .extract::<PyRefMut<PyDataActor>>()
                    .map_err(Into::<PyErr>::into)
                    .map_err(|e| anyhow::anyhow!("Failed to extract PyDataActor: {e}"))?;

                // Extract ID from config: prefer exec_algorithm_id, fall back to actor_id
                if let Some(config_obj) = config_instance.as_ref() {
                    let id_attr = config_obj
                        .getattr("exec_algorithm_id")
                        .ok()
                        .filter(|v| !v.is_none())
                        .or_else(|| config_obj.getattr("actor_id").ok().filter(|v| !v.is_none()));

                    if let Some(id_value) = id_attr {
                        let actor_id_val = if let Ok(eaid) = id_value.extract::<ExecAlgorithmId>() {
                            ActorId::new(eaid.inner().as_str())
                        } else if let Ok(aid) = id_value.extract::<ActorId>() {
                            aid
                        } else if let Ok(aid_str) = id_value.extract::<String>() {
                            ActorId::new_checked(&aid_str)?
                        } else {
                            anyhow::bail!("Invalid `exec_algorithm_id`/`actor_id` type");
                        };
                        py_data_actor_ref.set_actor_id(actor_id_val);
                    }

                    if let Some(val) = extract_bool_config_attr(config_obj, "log_events") {
                        py_data_actor_ref.set_log_events(val);
                    }

                    if let Some(val) = extract_bool_config_attr(config_obj, "log_commands") {
                        py_data_actor_ref.set_log_commands(val);
                    }
                }

                py_data_actor_ref.set_python_instance(&python_exec_algorithm)?;

                let actor_id = py_data_actor_ref.actor_id();

                Ok((python_exec_algorithm.unbind(), None, actor_id))
            },
        )
        .map_err(to_pyruntime_err)?;

        let exec_algorithm_id = if let Some(py_execution_algorithm) = py_execution_algorithm {
            // This branch registered through `LiveNode::add_exec_algorithm` before the trader owned
            // the path, so it keeps that method's stricter state requirement
            if self.node()?.state() != NodeState::Idle {
                return Err(to_pyruntime_err(
                    "Cannot add exec algorithm while node is running, add exec algorithms before running the node",
                ));
            }

            self.node_mut()?
                .kernel_mut()
                .trader
                .borrow_mut()
                .add_py_execution_algorithm_instance(py_execution_algorithm, &python_exec_algorithm)
                .map_err(to_pyruntime_err)?
        } else {
            // Phase 2: Register the DataActor-backed algorithm through the trader's single Python
            // registration path
            self.node_mut()?
                .kernel_mut()
                .trader
                .borrow_mut()
                .add_python_exec_algorithm_instance(&python_exec_algorithm, actor_id)
                .map_err(to_pyruntime_err)?
        };

        log::info!("Registered Python exec algorithm {exec_algorithm_id}");
        Ok(())
    }

    /// Loads and registers one plug-in instance.
    ///
    /// # Errors
    ///
    /// Returns an error because dynamic plug-in hosting lives in the host-side integration.
    #[pyo3(name = "add_plugin", signature = (path, type_name, config=None, sha256=None))]
    fn py_add_plugin(
        &self,
        path: String,
        type_name: String,
        config: Option<HashMap<String, Py<PyAny>>>,
        sha256: Option<String>,
    ) -> PyResult<()> {
        let config = PluginConfig {
            path,
            type_name,
            config: match config {
                Some(config) => coerce_json_config(config)?,
                None => HashMap::new(),
            },
            sha256,
        };

        self.node_mut()?
            .add_plugin(config)
            .map_err(to_pyruntime_err)
    }

    /// Adds a built-in example actor from its type name and config.
    ///
    /// This method exists only to single-source bundled example actor code across
    /// Rust and Python tests/examples. It is not a first-class extension path for
    /// adding native actors.
    #[cfg(feature = "examples")]
    #[pyo3(name = "add_builtin_actor")]
    fn py_add_builtin_actor(&self, type_name: &str, config: &Bound<'_, PyAny>) -> PyResult<()> {
        let register = builtin_actor_register(type_name).ok_or_else(|| {
            to_pytype_err(format!("Unsupported built-in actor type: {type_name}"))
        })?;
        let mut node = self.node_mut()?;
        register(&mut node, config)
    }

    /// Adds a built-in example strategy from its type name and config.
    ///
    /// This method exists only to single-source bundled example strategy code across
    /// Rust and Python tests/examples. It is not a first-class extension path for
    /// adding native strategies.
    #[cfg(feature = "examples")]
    #[pyo3(name = "add_builtin_strategy")]
    fn py_add_builtin_strategy(&self, type_name: &str, config: &Bound<'_, PyAny>) -> PyResult<()> {
        let register = builtin_strategy_register(type_name).ok_or_else(|| {
            to_pytype_err(format!("Unsupported built-in strategy type: {type_name}"))
        })?;
        let mut node = self.node_mut()?;
        register(&mut node, config)
    }

    fn __repr__(&self) -> String {
        format!(
            "LiveNode(trader_id={}, environment={}, running={})",
            self.node()
                .map_or_else(|_| "<running>".to_string(), |n| n.trader_id().to_string()),
            self.node().map_or_else(
                |_| "<running>".to_string(),
                |n| format!("{:?}", n.environment())
            ),
            self.py_is_running()
        )
    }
}

impl PyLiveNode {
    fn register_python_actor(&self, actor: &Py<PyAny>, actor_id: ActorId) -> PyResult<()> {
        if self
            .node()?
            .kernel()
            .trader
            .borrow()
            .actor_ids()
            .contains(&actor_id)
        {
            return Err(to_pyruntime_err(format!(
                "Actor '{actor_id}' is already registered"
            )));
        }

        self.node_mut()?
            .kernel_mut()
            .trader
            .borrow_mut()
            .add_python_actor_instance(actor, actor_id)
            .map_err(to_pyruntime_err)?;

        log::info!("Registered Python actor {actor_id}");
        Ok(())
    }
}

fn new_sync_py_callback<F>(py: Python<'_>, closure: F) -> PyResult<Bound<'_, PyCFunction>>
where
    F: Fn(&Bound<'_, PyTuple>, Option<&Bound<'_, PyDict>>) -> PyResult<()> + Send + Sync + 'static,
{
    PyCFunction::new_closure(py, None, None, closure)
}

#[allow(unsafe_code)]
fn run_live_node_detached(py: Python<'_>, node: &mut LiveNode) -> PyResult<()> {
    let node_ptr = SendPtr(std::ptr::from_mut::<LiveNode>(node));

    // SAFETY: `py_run` holds the only mutable reference to `LiveNode` until
    // `run()` returns, and the detached closure completes before `py_run` can
    // access `node` again.
    unsafe {
        py.detach(move || {
            let ptr = node_ptr;
            get_runtime().block_on(async { (*ptr.0).run().await })
        })
    }
    .map_err(to_pyruntime_err)
}

#[allow(unsafe_code)]
fn stop_live_node_detached(py: Python<'_>, node: &mut LiveNode) -> PyResult<()> {
    let node_ptr = SendPtr(std::ptr::from_mut::<LiveNode>(node));

    // SAFETY: the Python binding holds the only mutable reference to `LiveNode`
    // until `stop()` returns, and the detached closure completes before the
    // caller can access `node` again.
    unsafe {
        py.detach(move || {
            let ptr = node_ptr;
            get_runtime().block_on(async { (*ptr.0).stop().await })
        })
    }
    .map_err(to_pyruntime_err)
}

/// Creates a Python config instance from a config path and config dictionary.
///
/// This helper is shared between `add_actor_from_config` and `add_strategy_from_config`.
/// It handles:
/// 1. Importing the config class from the module path
/// 2. Converting the `HashMap<String, serde_json::Value>` to a Python dict
/// 3. Trying kwargs-first construction, falling back to default + setattr
/// 4. Calling `__post_init__` for dataclasses when using the setattr path
fn create_config_instance<'py>(
    py: Python<'py>,
    config_path: &str,
    config: &HashMap<String, serde_json::Value>,
) -> anyhow::Result<Option<Bound<'py, PyAny>>> {
    if config_path.is_empty() && config.is_empty() {
        log::debug!("No config_path or empty config, using None");
        return Ok(None);
    }

    let config_parts: Vec<&str> = config_path.split(':').collect();
    if config_parts.len() != 2 {
        anyhow::bail!("config_path must be in format 'module.path:ClassName', was {config_path}");
    }
    let (config_module_name, config_class_name) = (config_parts[0], config_parts[1]);

    log::debug!(
        "Importing config class from module: {config_module_name} class: {config_class_name}"
    );

    let config_module = py
        .import(config_module_name)
        .map_err(|e| anyhow::anyhow!("Failed to import config module {config_module_name}: {e}"))?;
    let config_class = config_module
        .getattr(config_class_name)
        .map_err(|e| anyhow::anyhow!("Failed to get config class {config_class_name}: {e}"))?;

    // Convert config dict to Python dict
    let py_dict = PyDict::new(py);

    for (key, value) in config {
        let py_value = config_value_to_py(py, key, value)?;
        py_dict.set_item(key, py_value)?;
    }

    log::debug!("Created config dict: {py_dict:?}");

    // Try kwargs first, then default constructor with setattr
    let config_instance = match config_class.call((), Some(&py_dict)) {
        Ok(instance) => {
            log::debug!("Created config instance with kwargs");
            instance
        }
        Err(kwargs_err) => {
            log::debug!("Failed to create config with kwargs: {kwargs_err}");

            match config_class.call0() {
                Ok(instance) => {
                    log::debug!("Created default config instance, setting attributes");
                    for (key, value) in config {
                        let py_value = config_value_to_py(py, key, value)?;

                        if let Err(setattr_err) = instance.setattr(key, py_value) {
                            log::warn!("Failed to set attribute {key}: {setattr_err}");
                        }
                    }

                    // Only call __post_init__ if it exists (setattr path
                    // needs it, kwargs path already triggered it via __init__)
                    if instance.hasattr("__post_init__")? {
                        instance.call_method0("__post_init__")?;
                    }

                    instance
                }
                Err(default_err) => {
                    anyhow::bail!(
                        "Failed to create config instance. \
                         Tried kwargs: {kwargs_err}, default: {default_err}"
                    );
                }
            }
        }
    };

    log::debug!("Created config instance: {config_instance:?}");

    Ok(Some(config_instance))
}

fn config_value_to_py<'py>(
    py: Python<'py>,
    key: &str,
    value: &serde_json::Value,
) -> anyhow::Result<Bound<'py, PyAny>> {
    if key == "actor_id"
        && let Some(actor_id) = value.as_str()
    {
        return Ok(ActorId::new_checked(actor_id)?
            .into_pyobject(py)?
            .into_any());
    }

    let json_str = serde_json::to_string(value)
        .map_err(|e| anyhow::anyhow!("Failed to serialize config value: {e}"))?;
    Ok(PyModule::import(py, "json")?
        .call_method("loads", (json_str,), None)?
        .into_any())
}

/// Extracts an optional boolean attribute from a Python config object.
///
/// Returns `None` if the attribute doesn't exist or isn't a bool,
/// without raising an error (config fields are optional overrides).
fn extract_bool_config_attr(config_obj: &Bound<'_, PyAny>, attr: &str) -> Option<bool> {
    config_obj
        .getattr(attr)
        .ok()
        .and_then(|val| val.extract::<bool>().ok())
}

fn extract_external_order_claims_config_attr(
    config_obj: &Bound<'_, PyAny>,
) -> anyhow::Result<Option<Vec<InstrumentId>>> {
    let Ok(claims) = config_obj.getattr("external_order_claims") else {
        return Ok(None);
    };

    if claims.is_none() {
        return Ok(None);
    }

    if let Ok(claims) = claims.extract::<Vec<InstrumentId>>() {
        return Ok(Some(claims));
    }

    let claim_strings = claims
        .extract::<Vec<String>>()
        .map_err(|e| anyhow::anyhow!("Invalid `external_order_claims` type: {e}"))?;
    let claims = claim_strings
        .into_iter()
        .map(|claim| {
            InstrumentId::from_str(&claim).map_err(|e| {
                anyhow::anyhow!("Invalid `external_order_claims` instrument ID {claim}: {e}")
            })
        })
        .collect::<anyhow::Result<Vec<_>>>()?;

    Ok(Some(claims))
}

#[cfg(feature = "examples")]
type BuiltinActorRegister = for<'py> fn(&mut LiveNode, &Bound<'py, PyAny>) -> PyResult<()>;

#[cfg(feature = "examples")]
type BuiltinStrategyRegister = for<'py> fn(&mut LiveNode, &Bound<'py, PyAny>) -> PyResult<()>;

#[cfg(feature = "examples")]
fn builtin_actor_register(type_name: &str) -> Option<BuiltinActorRegister> {
    match type_name {
        "BookImbalanceActor" => Some(register_book_imbalance_actor),
        "DataTester" => Some(register_data_tester),
        _ => None,
    }
}

#[cfg(feature = "examples")]
fn builtin_strategy_register(type_name: &str) -> Option<BuiltinStrategyRegister> {
    match type_name {
        "CompositeMarketMaker" => Some(register_composite_market_maker),
        "DeltaNeutralVol" => Some(register_delta_neutral_vol),
        "EmaCross" => Some(register_ema_cross),
        "ExecTester" => Some(register_exec_tester),
        "GridMarketMaker" => Some(register_grid_market_maker),
        "HurstVpinDirectional" => Some(register_hurst_vpin_directional),
        _ => None,
    }
}

#[cfg(feature = "examples")]
fn register_composite_market_maker(node: &mut LiveNode, config: &Bound<'_, PyAny>) -> PyResult<()> {
    let config = config.extract::<CompositeMarketMakerConfig>()?;
    node.add_strategy(CompositeMarketMaker::new(config))
        .map_err(to_pyruntime_err)
}

#[cfg(feature = "examples")]
fn register_delta_neutral_vol(node: &mut LiveNode, config: &Bound<'_, PyAny>) -> PyResult<()> {
    let config = config.extract::<DeltaNeutralVolConfig>()?;
    node.add_strategy(DeltaNeutralVol::new(config))
        .map_err(to_pyruntime_err)
}

#[cfg(feature = "examples")]
fn register_ema_cross(node: &mut LiveNode, config: &Bound<'_, PyAny>) -> PyResult<()> {
    let config = config.extract::<EmaCrossConfig>()?;
    node.add_strategy(EmaCross::from_config(config))
        .map_err(to_pyruntime_err)
}

#[cfg(feature = "examples")]
fn register_exec_tester(node: &mut LiveNode, config: &Bound<'_, PyAny>) -> PyResult<()> {
    let config = config.extract::<ExecTesterConfig>()?;
    node.add_strategy(ExecTester::new(config))
        .map_err(to_pyruntime_err)
}

#[cfg(feature = "examples")]
fn register_grid_market_maker(node: &mut LiveNode, config: &Bound<'_, PyAny>) -> PyResult<()> {
    let config = config.extract::<GridMarketMakerConfig>()?;
    node.add_strategy(GridMarketMaker::new(config))
        .map_err(to_pyruntime_err)
}

#[cfg(feature = "examples")]
fn register_hurst_vpin_directional(node: &mut LiveNode, config: &Bound<'_, PyAny>) -> PyResult<()> {
    let config = config.extract::<HurstVpinDirectionalConfig>()?;
    node.add_strategy(HurstVpinDirectional::new(config))
        .map_err(to_pyruntime_err)
}

#[cfg(feature = "examples")]
fn register_book_imbalance_actor(node: &mut LiveNode, config: &Bound<'_, PyAny>) -> PyResult<()> {
    let config = config.extract::<BookImbalanceActorConfig>()?;
    node.add_actor(BookImbalanceActor::from_config(config))
        .map_err(to_pyruntime_err)
}

#[cfg(feature = "examples")]
fn register_data_tester(node: &mut LiveNode, config: &Bound<'_, PyAny>) -> PyResult<()> {
    let config = config.extract::<DataTesterConfig>()?;
    node.add_actor(DataTester::new(config))
        .map_err(to_pyruntime_err)
}

/// Python wrapper for `LiveNodeBuilder` that uses interior mutability
/// to work around PyO3's shared ownership model.
#[pyclass(name = "LiveNodeBuilder", module = "nautilus_trader.live", unsendable)]
#[pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.live")]
pub struct PyLiveNodeBuilder {
    state: Rc<Cell<PyLiveNodeBuilderState>>,
}

#[pyo3_stub_gen::derive::gen_stub_pymethods]
#[pymethods]
impl PyLiveNodeBuilder {
    #[pyo3(name = "with_instance_id")]
    fn py_with_instance_id(&self, instance_id: UUID4) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_instance_id(instance_id))
    }

    #[pyo3(name = "with_load_state")]
    fn py_with_load_state(&self, load_state: bool) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_load_state(load_state))
    }

    #[pyo3(name = "with_save_state")]
    fn py_with_save_state(&self, save_state: bool) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_save_state(save_state))
    }

    #[pyo3(name = "with_timeout_connection")]
    fn py_with_timeout_connection(&self, timeout_secs: u64) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_timeout_connection(timeout_secs))
    }

    #[pyo3(name = "with_timeout_reconciliation")]
    fn py_with_timeout_reconciliation(&self, timeout_secs: u64) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_timeout_reconciliation(timeout_secs))
    }

    #[pyo3(name = "with_timeout_portfolio")]
    fn py_with_timeout_portfolio(&self, timeout_secs: u64) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_timeout_portfolio(timeout_secs))
    }

    #[pyo3(name = "with_timeout_disconnection_secs")]
    fn py_with_timeout_disconnection_secs(&self, timeout_secs: u64) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_timeout_disconnection_secs(timeout_secs))
    }

    #[pyo3(name = "with_delay_post_stop_secs")]
    fn py_with_delay_post_stop_secs(&self, delay_secs: u64) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_delay_post_stop_secs(delay_secs))
    }

    #[pyo3(name = "with_delay_shutdown_secs")]
    fn py_with_delay_shutdown_secs(&self, delay_secs: u64) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_delay_shutdown_secs(delay_secs))
    }

    #[pyo3(name = "with_reconciliation")]
    fn py_with_reconciliation(&self, reconciliation: bool) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_reconciliation(reconciliation))
    }

    #[pyo3(name = "with_controller")]
    fn py_with_controller(&self, controller: ImportableControllerConfig) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_controller(controller))
    }

    #[pyo3(name = "with_reconciliation_lookback_mins")]
    fn py_with_reconciliation_lookback_mins(&self, mins: u32) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_reconciliation_lookback_mins(mins))
    }

    #[pyo3(name = "with_cache_config")]
    fn py_with_cache_config(&self, config: CacheConfig) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_cache_config(config))
    }

    #[pyo3(name = "with_cache_database_factory")]
    fn py_with_cache_database_factory(&self, factory: Py<PyAny>) -> PyResult<Self> {
        let mut operation = self.begin_operation()?;
        let factory =
            Python::attach(|py| get_global_cache_database_factory_registry().extract(py, factory))?;
        let builder = operation.take_builder()?;
        operation.complete(builder.with_cache_database_factory(factory));
        Ok(self.shared())
    }

    #[pyo3(name = "with_msgbus_config")]
    fn py_with_msgbus_config(&self, config: MessageBusConfig) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_msgbus_config(config))
    }

    #[pyo3(name = "with_external_msgbus_factory")]
    fn py_with_external_msgbus_factory(&self, factory: Py<PyAny>) -> PyResult<Self> {
        let mut operation = self.begin_operation()?;
        let factory =
            Python::attach(|py| get_global_msgbus_factory_registry().extract(py, factory))?;
        let builder = operation.take_builder()?;
        operation.complete(builder.with_external_msgbus_factory(factory));
        Ok(self.shared())
    }

    #[pyo3(name = "with_portfolio_config")]
    fn py_with_portfolio_config(&self, config: PortfolioConfig) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_portfolio_config(config))
    }

    #[pyo3(name = "with_data_engine_config")]
    fn py_with_data_engine_config(&self, config: LiveDataEngineConfig) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_data_engine_config(config))
    }

    #[pyo3(name = "with_risk_engine_config")]
    fn py_with_risk_engine_config(&self, config: LiveRiskEngineConfig) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_risk_engine_config(config))
    }

    #[pyo3(name = "with_exec_engine_config")]
    fn py_with_exec_engine_config(&self, config: LiveExecutionEngineConfig) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_exec_engine_config(config))
    }

    #[pyo3(name = "with_logging")]
    fn py_with_logging(&self, logging: LoggerConfig) -> PyResult<Self> {
        self.update_builder(|builder| builder.with_logging(logging))
    }

    #[pyo3(name = "add_data_client", signature = (name, factory, config, routing=None))]
    #[expect(clippy::needless_pass_by_value)]
    fn py_add_data_client(
        &self,
        name: Option<String>,
        factory: Py<PyAny>,
        config: Py<PyAny>,
        routing: Option<RoutingConfig>,
    ) -> PyResult<Self> {
        let mut operation = self.begin_operation()?;
        Python::attach(|py| -> PyResult<Self> {
            let registry = get_global_pyo3_registry();
            let boxed_factory = registry.extract_factory(py, factory.clone_ref(py))?;
            let boxed_config = registry.extract_config(py, config.clone_ref(py))?;
            let factory_name = factory
                .getattr(py, "name")?
                .call0(py)?
                .extract::<String>(py)?;
            let client_name = name.unwrap_or(factory_name);
            let builder = operation.take_builder()?;
            let updated_builder = match routing {
                Some(routing) => builder.add_data_client_with_routing(
                    Some(client_name),
                    boxed_factory,
                    boxed_config,
                    routing,
                ),
                None => builder.add_data_client(Some(client_name), boxed_factory, boxed_config),
            }
            .map_err(|e| to_pyruntime_err(format!("Failed to add data client: {e}")))?;
            operation.complete(updated_builder);
            Ok(self.shared())
        })
    }

    #[pyo3(name = "add_exec_client", signature = (name, factory, config, routing=None))]
    #[expect(clippy::needless_pass_by_value)]
    fn py_add_exec_client(
        &self,
        name: Option<String>,
        factory: Py<PyAny>,
        config: Py<PyAny>,
        routing: Option<RoutingConfig>,
    ) -> PyResult<Self> {
        let mut operation = self.begin_operation()?;
        Python::attach(|py| -> PyResult<Self> {
            let registry = get_global_pyo3_registry();
            let boxed_factory = registry.extract_exec_factory(py, factory.clone_ref(py))?;
            let boxed_config = registry.extract_config(py, config.clone_ref(py))?;
            let factory_name = factory
                .getattr(py, "name")?
                .call0(py)?
                .extract::<String>(py)?;
            let client_name = name.unwrap_or(factory_name);
            let builder = operation.take_builder()?;
            let updated_builder = match routing {
                Some(routing) => builder.add_exec_client_with_routing(
                    Some(client_name),
                    boxed_factory,
                    boxed_config,
                    routing,
                ),
                None => builder.add_exec_client(Some(client_name), boxed_factory, boxed_config),
            }
            .map_err(|e| to_pyruntime_err(format!("Failed to add exec client: {e}")))?;
            operation.complete(updated_builder);
            Ok(self.shared())
        })
    }

    #[pyo3(name = "add_simulated_exec_client")]
    #[expect(clippy::needless_pass_by_value)]
    fn py_add_simulated_exec_client(
        &self,
        name: Option<String>,
        factory: Py<PyAny>,
        config: Py<PyAny>,
    ) -> PyResult<Self> {
        let mut operation = self.begin_operation()?;
        Python::attach(|py| -> PyResult<Self> {
            let registry = get_global_pyo3_registry();
            let boxed_factory = registry.extract_sim_exec_factory(py, factory.clone_ref(py))?;
            let boxed_config = registry.extract_config(py, config.clone_ref(py))?;
            let factory_name = factory
                .getattr(py, "name")?
                .call0(py)?
                .extract::<String>(py)?;
            let client_name = name.unwrap_or(factory_name);
            let builder = operation.take_builder()?;
            let updated_builder = builder
                .add_simulated_exec_client(Some(client_name), boxed_factory, boxed_config)
                .map_err(|e| {
                    to_pyruntime_err(format!("Failed to add simulated exec client: {e}"))
                })?;
            operation.complete(updated_builder);
            Ok(self.shared())
        })
    }

    #[pyo3(name = "build")]
    fn py_build(&self) -> PyResult<PyLiveNode> {
        let mut operation = self.begin_operation()?;
        let builder = operation.take_builder()?;
        builder
            .build()
            .map(PyLiveNode::new)
            .map_err(to_pyruntime_err)
    }

    fn __repr__(&self) -> String {
        format!("{self:?}")
    }
}

const BUILDER_OPERATION_IN_PROGRESS: &str = "Builder operation already in progress";
const BUILDER_OPERATION_VALUE_TAKEN: &str = "Builder operation value already taken";

enum PyLiveNodeBuilderState {
    Ready(Box<LiveNodeBuilder>),
    InProgress,
    Consumed,
}

struct PyLiveNodeBuilderOperation<'a> {
    state: &'a Cell<PyLiveNodeBuilderState>,
    builder: Option<LiveNodeBuilder>,
}

impl PyLiveNodeBuilder {
    fn begin_operation(&self) -> PyResult<PyLiveNodeBuilderOperation<'_>> {
        match self.state.replace(PyLiveNodeBuilderState::InProgress) {
            PyLiveNodeBuilderState::Ready(builder) => Ok(PyLiveNodeBuilderOperation {
                state: &self.state,
                builder: Some(*builder),
            }),
            PyLiveNodeBuilderState::InProgress => {
                self.state.set(PyLiveNodeBuilderState::InProgress);
                Err(to_pyruntime_err(BUILDER_OPERATION_IN_PROGRESS))
            }
            PyLiveNodeBuilderState::Consumed => {
                self.state.set(PyLiveNodeBuilderState::Consumed);
                Err(to_pyruntime_err("Builder already consumed"))
            }
        }
    }

    fn update_builder<F>(&self, update: F) -> PyResult<Self>
    where
        F: FnOnce(LiveNodeBuilder) -> LiveNodeBuilder,
    {
        let mut operation = self.begin_operation()?;
        let builder = operation.take_builder()?;
        operation.complete(update(builder));
        Ok(self.shared())
    }

    fn shared(&self) -> Self {
        Self {
            state: self.state.clone(),
        }
    }
}

impl Debug for PyLiveNodeBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Preserve the existing Python repr despite the internal state change
        let state = self.state.replace(PyLiveNodeBuilderState::InProgress);
        let result = match &state {
            PyLiveNodeBuilderState::Ready(builder) => write!(
                f,
                "PyLiveNodeBuilder {{ inner: RefCell {{ value: Some({builder:?}) }} }}"
            ),
            PyLiveNodeBuilderState::InProgress => {
                f.write_str("PyLiveNodeBuilder { inner: <operation active> }")
            }
            PyLiveNodeBuilderState::Consumed => {
                f.write_str("PyLiveNodeBuilder { inner: RefCell { value: None } }")
            }
        };
        self.state.set(state);
        result
    }
}

impl PyLiveNodeBuilderOperation<'_> {
    fn take_builder(&mut self) -> PyResult<LiveNodeBuilder> {
        self.builder
            .take()
            .ok_or_else(|| to_pyruntime_err(BUILDER_OPERATION_VALUE_TAKEN))
    }

    fn complete(&mut self, builder: LiveNodeBuilder) {
        self.builder = Some(builder);
    }
}

impl Drop for PyLiveNodeBuilderOperation<'_> {
    fn drop(&mut self) {
        self.state.set(match self.builder.take() {
            Some(builder) => PyLiveNodeBuilderState::Ready(Box::new(builder)),
            None => PyLiveNodeBuilderState::Consumed,
        });
    }
}

#[cfg(all(test, feature = "python"))]
#[allow(
    clippy::await_holding_refcell_ref,
    reason = "each test owns its node exclusively, so the wrapper borrow cannot contend"
)]
mod tests {
    use std::{
        any::Any,
        cell::RefCell,
        collections::HashMap,
        ffi::CString,
        fmt::Debug,
        rc::Rc,
        sync::{
            Arc,
            atomic::{AtomicBool, AtomicUsize, Ordering},
            mpsc,
        },
        thread,
        time::{Duration, Instant},
    };

    use async_trait::async_trait;
    use indexmap::IndexMap;
    use nautilus_common::{
        actor::DataActor,
        cache::{
            CacheConfig, CacheView,
            database::{CacheDatabaseAdapter, CacheDatabaseFactory},
        },
        clients::DataClient,
        clock::Clock,
        enums::Environment,
        factories::{ClientConfig, DataClientFactory},
        live::{runner::get_data_event_sender, runtime::get_runtime},
        messages::{
            DataEvent, DataResponse,
            data::{BarsResponse, RequestBars},
            execution::{CancelAllOrders, SubmitOrder, TradingCommand},
        },
        msgbus::{
            BusMessage, MessageBusBacking, MessageBusBackingFactory, MessageBusConfig,
            MessagingSwitchboard, get_message_bus,
        },
        python::{
            actor::PyDataActor, cache::get_global_cache_database_factory_registry,
            msgbus::get_global_msgbus_factory_registry,
        },
        runner::{TradingCommandMessage, get_trading_cmd_sender},
    };
    use nautilus_core::{UUID4, UnixNanos};
    use nautilus_execution::engine::stubs::StubExecutionClient;
    use nautilus_model::{
        data::{Bar, BarType},
        enums::{OmsType, OrderStatus, OrderType},
        identifiers::{
            AccountId, ActorId, ClientId, InstrumentId, PositionId, StrategyId, TraderId, Venue,
        },
        instruments::{Instrument, InstrumentAny, stubs::crypto_perpetual_ethusdt},
        orders::{Order, OrderTestBuilder},
        types::{Price, Quantity},
    };
    use nautilus_testkit::cache::{TestCacheDatabase, TestCacheDatabaseControl};
    use nautilus_trading::{
        ImportableStrategyConfig, nautilus_strategy,
        python::strategy::PyStrategy,
        strategy::{StrategyConfig, StrategyCore},
    };
    use parking_lot::Mutex;
    use pyo3::{
        Py, PyRef, Python,
        ffi::c_str,
        types::{PyAnyMethods, PyDict, PyModule, PyModuleMethods},
    };
    use rstest::rstest;

    use super::{
        BUILDER_OPERATION_IN_PROGRESS, LiveNode, PyLiveNode, PyLiveNodeBuilder,
        PyLiveNodeBuilderState, get_global_pyo3_registry,
    };
    use crate::node::config::RoutingConfig;

    #[derive(Clone, Copy, Debug)]
    enum ShutdownRunPath {
        Native,
        PyO3,
    }

    static TEST_MSGBUS_FACTORY_CALLS: AtomicUsize = AtomicUsize::new(0);

    #[derive(Debug, Clone)]
    #[pyo3::pyclass(name = "TestMessageBusFactory", from_py_object)]
    struct TestMessageBusFactory;

    impl MessageBusBackingFactory for TestMessageBusFactory {
        fn create(
            &self,
            trader_id: TraderId,
            _instance_id: UUID4,
            config: MessageBusConfig,
        ) -> anyhow::Result<Box<dyn MessageBusBacking>> {
            TEST_MSGBUS_FACTORY_CALLS.fetch_add(1, Ordering::SeqCst);

            anyhow::ensure!(
                trader_id == TraderId::from("TESTER-001"),
                "unexpected trader ID: {trader_id}"
            );
            anyhow::ensure!(
                config.external_streams == Some(vec!["external-stream".to_string()]),
                "unexpected external streams: {:?}",
                config.external_streams
            );

            let (_tx, rx) = tokio::sync::mpsc::channel(1);
            Ok(Box::new(TestMessageBusBacking {
                rx: Some(rx),
                closed: false,
            }))
        }
    }

    #[derive(Debug)]
    struct TestMessageBusBacking {
        rx: Option<tokio::sync::mpsc::Receiver<BusMessage>>,
        closed: bool,
    }

    impl MessageBusBacking for TestMessageBusBacking {
        fn is_closed(&self) -> bool {
            self.closed
        }

        fn publish(&self, _message: BusMessage) {}

        fn take_receiver(&mut self) -> anyhow::Result<tokio::sync::mpsc::Receiver<BusMessage>> {
            self.rx
                .take()
                .ok_or_else(|| anyhow::anyhow!("Stream receiver already taken"))
        }

        fn close(&mut self) {
            self.closed = true;
        }
    }

    #[expect(clippy::needless_pass_by_value)]
    fn extract_test_msgbus_factory(
        py: Python<'_>,
        factory: Py<pyo3::PyAny>,
    ) -> pyo3::PyResult<Box<dyn MessageBusBackingFactory>> {
        Ok(Box::new(factory.extract::<TestMessageBusFactory>(py)?))
    }

    #[rstest]
    fn test_python_builder_installs_external_msgbus_factory() {
        TEST_MSGBUS_FACTORY_CALLS.store(0, Ordering::SeqCst);
        get_global_msgbus_factory_registry()
            .register(
                "TestMessageBusFactory".to_string(),
                extract_test_msgbus_factory,
            )
            .unwrap();
        Python::initialize();

        Python::attach(|py| {
            let factory = Py::new(py, TestMessageBusFactory).unwrap().into_any();
            let builder = PyLiveNode::py_builder(
                "TEST".to_string(),
                TraderId::from("TESTER-001"),
                Environment::Sandbox,
            )
            .unwrap()
            .py_with_msgbus_config(MessageBusConfig {
                external_streams: Some(vec!["external-stream".to_string()]),
                ..Default::default()
            })
            .unwrap()
            .py_with_external_msgbus_factory(factory)
            .unwrap();

            let node = builder.py_build().unwrap();
            let consumed_error = builder
                .py_with_msgbus_config(MessageBusConfig::default())
                .unwrap_err();

            assert!(!node.node_mut().unwrap().is_running());
            assert_eq!(TEST_MSGBUS_FACTORY_CALLS.load(Ordering::SeqCst), 1);
            assert_eq!(
                consumed_error.to_string(),
                "RuntimeError: Builder already consumed"
            );
            assert_eq!(
                builder.__repr__(),
                "PyLiveNodeBuilder { inner: RefCell { value: None } }"
            );
            get_message_bus().borrow_mut().dispose();
        });
    }

    static TEST_CACHE_DATABASE_FACTORY_CALLS: AtomicUsize = AtomicUsize::new(0);

    #[derive(Debug, Clone)]
    #[pyo3::pyclass(name = "TestCacheDatabaseFactory", from_py_object)]
    struct TestCacheDatabaseFactory {
        database: Arc<parking_lot::Mutex<Option<TestCacheDatabase>>>,
        instance_id: Arc<parking_lot::Mutex<Option<UUID4>>>,
    }

    impl TestCacheDatabaseFactory {
        fn new(database: Option<TestCacheDatabase>) -> Self {
            Self {
                database: Arc::new(parking_lot::Mutex::new(database)),
                instance_id: Arc::new(parking_lot::Mutex::new(None)),
            }
        }

        fn received_instance_id(&self) -> Option<UUID4> {
            *self.instance_id.lock()
        }
    }

    #[async_trait]
    impl CacheDatabaseFactory for TestCacheDatabaseFactory {
        async fn create(
            &self,
            trader_id: TraderId,
            instance_id: UUID4,
            config: CacheConfig,
        ) -> anyhow::Result<Box<dyn CacheDatabaseAdapter>> {
            TEST_CACHE_DATABASE_FACTORY_CALLS.fetch_add(1, Ordering::SeqCst);
            *self.instance_id.lock() = Some(instance_id);

            anyhow::ensure!(
                trader_id == TraderId::from("TESTER-001"),
                "unexpected trader ID: {trader_id}"
            );
            anyhow::ensure!(
                config.buffer_interval_ms == Some(25),
                "unexpected buffer interval: {:?}",
                config.buffer_interval_ms
            );

            let database = self
                .database
                .lock()
                .take()
                .ok_or_else(|| anyhow::anyhow!("Test cache database unavailable"))?;
            Ok(Box::new(database))
        }
    }

    #[expect(clippy::needless_pass_by_value)]
    fn extract_test_cache_database_factory(
        py: Python<'_>,
        factory: Py<pyo3::PyAny>,
    ) -> pyo3::PyResult<Box<dyn CacheDatabaseFactory>> {
        Ok(Box::new(factory.extract::<TestCacheDatabaseFactory>(py)?))
    }

    fn state_factory_builder(factory: &TestCacheDatabaseFactory) -> PyLiveNodeBuilder {
        Python::attach(|py| {
            PyLiveNode::py_builder(
                "TEST".to_string(),
                TraderId::from("TESTER-001"),
                Environment::Sandbox,
            )
            .unwrap()
            .py_with_cache_config(CacheConfig {
                buffer_interval_ms: Some(25),
                ..Default::default()
            })
            .unwrap()
            .py_with_cache_database_factory(Py::new(py, factory.clone()).unwrap().into_any())
            .unwrap()
            .py_with_reconciliation(false)
            .unwrap()
            .py_with_timeout_connection(0)
            .unwrap()
            .py_with_timeout_reconciliation(0)
            .unwrap()
            .py_with_timeout_portfolio(0)
            .unwrap()
            .py_with_timeout_disconnection_secs(0)
            .unwrap()
            .py_with_delay_post_stop_secs(0)
            .unwrap()
            .py_with_delay_shutdown_secs(0)
            .unwrap()
        })
    }

    #[tokio::test]
    async fn test_python_builder_installs_cache_database_factory_on_start() {
        TEST_CACHE_DATABASE_FACTORY_CALLS.store(0, Ordering::SeqCst);
        get_global_cache_database_factory_registry()
            .register(
                "TestCacheDatabaseFactory".to_string(),
                extract_test_cache_database_factory,
            )
            .unwrap();
        Python::initialize();

        let (database, control) = TestCacheDatabaseControl::create();
        let actor_id = ActorId::from("PY-CACHE-FACTORY-ACTOR");
        let actor_state = IndexMap::from([("loaded".to_string(), b"value".to_vec())]);
        control.set_actor_state(actor_id, &actor_state);
        let factory = TestCacheDatabaseFactory::new(Some(database));

        let node = state_factory_builder(&factory).py_build().unwrap();

        assert_eq!(TEST_CACHE_DATABASE_FACTORY_CALLS.load(Ordering::SeqCst), 0);
        assert!(
            !node
                .node_mut()
                .unwrap()
                .kernel()
                .cache()
                .borrow()
                .has_backing()
        );

        node.node_mut().unwrap().start().await.unwrap();

        assert_eq!(TEST_CACHE_DATABASE_FACTORY_CALLS.load(Ordering::SeqCst), 1);
        assert_eq!(
            factory.received_instance_id(),
            Some(node.node_mut().unwrap().instance_id())
        );
        assert!(
            node.node_mut()
                .unwrap()
                .kernel()
                .cache()
                .borrow()
                .has_backing()
        );
        assert_eq!(
            node.node_mut()
                .unwrap()
                .kernel()
                .cache()
                .borrow()
                .load_actor_state(&actor_id)
                .unwrap(),
            Some(actor_state)
        );

        node.node_mut().unwrap().stop().await.unwrap();
        node.node_mut().unwrap().dispose();
        get_message_bus().borrow_mut().dispose();
    }

    #[tokio::test]
    async fn test_python_builder_propagates_cache_database_factory_error_on_start() {
        get_global_cache_database_factory_registry()
            .register(
                "TestCacheDatabaseFactory".to_string(),
                extract_test_cache_database_factory,
            )
            .unwrap();
        Python::initialize();

        let factory = TestCacheDatabaseFactory::new(None);
        let node = state_factory_builder(&factory).py_build().unwrap();

        let error = node.node_mut().unwrap().start().await.unwrap_err();

        assert_eq!(
            format!("{error:#}"),
            "failed to create cache database backing: Test cache database unavailable"
        );
        assert!(
            !node
                .node_mut()
                .unwrap()
                .kernel()
                .cache()
                .borrow()
                .has_backing()
        );

        let retry_error = node.node_mut().unwrap().start().await.unwrap_err();

        assert_eq!(
            format!("{retry_error:#}"),
            "failed to create cache database backing: Test cache database unavailable"
        );
        assert!(
            !node
                .node_mut()
                .unwrap()
                .kernel()
                .cache()
                .borrow()
                .has_backing()
        );

        node.node_mut().unwrap().dispose();
        get_message_bus().borrow_mut().dispose();
    }

    #[rstest]
    fn test_python_builder_rejects_unregistered_cache_database_factory() {
        Python::initialize();

        Python::attach(|py| {
            let factory = PyDict::new(py).unbind().into_any();
            let builder = PyLiveNode::py_builder(
                "TEST".to_string(),
                TraderId::from("TESTER-001"),
                Environment::Sandbox,
            )
            .unwrap();

            let error = builder.py_with_cache_database_factory(factory).unwrap_err();

            assert_eq!(
                error.to_string(),
                "NotImplementedError: No cache database factory extractor registered for 'dict'"
            );
            builder
                .py_with_cache_config(CacheConfig::default())
                .unwrap();
        });
    }

    #[rstest]
    fn test_python_builder_restores_state_after_factory_type_reentry() {
        Python::initialize();

        Python::attach(|py| {
            let builder = Py::new(
                py,
                PyLiveNode::py_builder(
                    "TEST".to_string(),
                    TraderId::from("TESTER-001"),
                    Environment::Sandbox,
                )
                .unwrap(),
            )
            .unwrap();
            let locals = PyDict::new(py);
            locals.set_item("builder", &builder).unwrap();
            py.run(
                pyo3::ffi::c_str!(
                    "class ReentrantFactory:\n    def __getattribute__(self, name):\n        if name == '__class__':\n            builder.with_load_state(True)\n        return object.__getattribute__(self, name)\n\nfactory = ReentrantFactory()"
                ),
                Some(&locals),
                None,
            )
            .unwrap();
            let factory = locals.get_item("factory").unwrap();

            let error = builder
                .call_method1(py, "with_cache_database_factory", (factory,))
                .unwrap_err();

            assert_eq!(
                error.to_string(),
                format!("RuntimeError: {BUILDER_OPERATION_IN_PROGRESS}")
            );
            let builder_ref = builder.borrow(py);
            let state = builder_ref
                .state
                .replace(PyLiveNodeBuilderState::InProgress);
            let is_ready = matches!(&state, PyLiveNodeBuilderState::Ready(_));
            builder_ref.state.set(state);
            assert!(is_ready);
            locals.call_method0("clear").unwrap();
        });
    }

    #[rstest]
    fn test_python_builder_rejects_unregistered_external_msgbus_factory() {
        Python::initialize();

        Python::attach(|py| {
            let factory = PyDict::new(py).unbind().into_any();
            let builder = PyLiveNode::py_builder(
                "TEST".to_string(),
                TraderId::from("TESTER-001"),
                Environment::Sandbox,
            )
            .unwrap();

            let error = builder
                .py_with_external_msgbus_factory(factory)
                .unwrap_err();

            assert_eq!(
                error.to_string(),
                "NotImplementedError: No message bus factory extractor registered for 'dict'"
            );
            builder
                .py_with_msgbus_config(MessageBusConfig::default())
                .unwrap();
        });
    }

    #[derive(Debug)]
    struct ShutdownCancelStrategy {
        core: StrategyCore,
        instrument_id: InstrumentId,
    }

    impl ShutdownCancelStrategy {
        fn new(instrument_id: InstrumentId) -> Self {
            Self {
                core: StrategyCore::new(StrategyConfig {
                    strategy_id: Some(StrategyId::from("SHUTDOWN-CANCEL-001")),
                    ..Default::default()
                }),
                instrument_id,
            }
        }
    }

    nautilus_strategy!(ShutdownCancelStrategy);

    impl DataActor for ShutdownCancelStrategy {
        fn on_stop(&mut self) -> anyhow::Result<()> {
            get_trading_cmd_sender().execute(TradingCommandMessage::new(
                MessagingSwitchboard::exec_engine_execute(),
                TradingCommand::CancelAllOrders(CancelAllOrders::new(
                    TraderId::from("TESTER-001"),
                    None,
                    StrategyId::from("SHUTDOWN-CANCEL-001"),
                    self.instrument_id,
                    None,
                    UUID4::new(),
                    UnixNanos::default(),
                    None,
                    None,
                )),
            ));
            Ok(())
        }
    }
    #[derive(Debug, Default)]
    struct TestDataClientConfig;

    impl ClientConfig for TestDataClientConfig {
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[derive(Debug)]
    #[expect(
        clippy::struct_field_names,
        reason = "test counters intentionally share the count postfix"
    )]
    struct TestHistoricalBarsDataClientFactory {
        request_count: Arc<AtomicUsize>,
        response_sent_count: Arc<AtomicUsize>,
        handler_visible_count: Arc<AtomicUsize>,
    }

    impl TestHistoricalBarsDataClientFactory {
        fn new(
            request_count: Arc<AtomicUsize>,
            response_sent_count: Arc<AtomicUsize>,
            handler_visible_count: Arc<AtomicUsize>,
        ) -> Self {
            Self {
                request_count,
                response_sent_count,
                handler_visible_count,
            }
        }
    }

    impl DataClientFactory for TestHistoricalBarsDataClientFactory {
        fn create(
            &self,
            name: &str,
            _config: &dyn ClientConfig,
            _cache: CacheView,
            _clock: Rc<RefCell<dyn Clock>>,
        ) -> anyhow::Result<Box<dyn DataClient>> {
            Ok(Box::new(TestHistoricalBarsDataClient::new(
                ClientId::from(name),
                Venue::from("SIM"),
                self.request_count.clone(),
                self.response_sent_count.clone(),
                self.handler_visible_count.clone(),
            )))
        }

        fn name(&self) -> &'static str {
            "TEST_DATA"
        }

        fn config_type(&self) -> &'static str {
            "TestDataClientConfig"
        }
    }

    #[derive(Debug)]
    struct TestDisconnectFailureDataClientFactory {
        dispose_count: Arc<AtomicUsize>,
    }

    impl TestDisconnectFailureDataClientFactory {
        fn new(dispose_count: Arc<AtomicUsize>) -> Self {
            Self { dispose_count }
        }
    }

    impl DataClientFactory for TestDisconnectFailureDataClientFactory {
        fn create(
            &self,
            name: &str,
            _config: &dyn ClientConfig,
            _cache: CacheView,
            _clock: Rc<RefCell<dyn Clock>>,
        ) -> anyhow::Result<Box<dyn DataClient>> {
            Ok(Box::new(TestDisconnectFailureDataClient::new(
                ClientId::from(name),
                Venue::from("SIM"),
                self.dispose_count.clone(),
            )))
        }

        fn name(&self) -> &'static str {
            "TEST_DISCONNECT_FAILURE"
        }

        fn config_type(&self) -> &'static str {
            "TestDataClientConfig"
        }
    }

    #[derive(Debug)]
    struct TestDisconnectFailureDataClient {
        client_id: ClientId,
        venue: Venue,
        connected: Arc<AtomicBool>,
        dispose_count: Arc<AtomicUsize>,
    }

    impl TestDisconnectFailureDataClient {
        fn new(client_id: ClientId, venue: Venue, dispose_count: Arc<AtomicUsize>) -> Self {
            Self {
                client_id,
                venue,
                connected: Arc::new(AtomicBool::new(false)),
                dispose_count,
            }
        }
    }

    #[async_trait(?Send)]
    impl DataClient for TestDisconnectFailureDataClient {
        fn client_id(&self) -> ClientId {
            self.client_id
        }

        fn venue(&self) -> Option<Venue> {
            Some(self.venue)
        }

        fn start(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn stop(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn reset(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn dispose(&mut self) -> anyhow::Result<()> {
            self.dispose_count.fetch_add(1, Ordering::Relaxed);
            Ok(())
        }

        fn is_connected(&self) -> bool {
            self.connected.load(Ordering::Relaxed)
        }

        fn is_disconnected(&self) -> bool {
            !self.is_connected()
        }

        async fn connect(&mut self) -> anyhow::Result<()> {
            self.connected.store(true, Ordering::Relaxed);
            Ok(())
        }

        async fn disconnect(&mut self) -> anyhow::Result<()> {
            self.connected.store(false, Ordering::Relaxed);
            anyhow::bail!("test disconnect failed")
        }
    }

    struct VenueLessDataClient {
        client_id: ClientId,
    }

    impl VenueLessDataClient {
        fn new(client_id: ClientId) -> Self {
            Self { client_id }
        }
    }

    #[async_trait(?Send)]
    impl DataClient for VenueLessDataClient {
        fn client_id(&self) -> ClientId {
            self.client_id
        }

        fn venue(&self) -> Option<Venue> {
            None
        }

        fn start(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn stop(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn reset(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn dispose(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn is_connected(&self) -> bool {
            true
        }

        fn is_disconnected(&self) -> bool {
            false
        }

        async fn connect(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        async fn disconnect(&mut self) -> anyhow::Result<()> {
            Ok(())
        }
    }

    #[derive(Debug)]
    struct VenueLessDataClientFactory;

    impl DataClientFactory for VenueLessDataClientFactory {
        fn create(
            &self,
            name: &str,
            _config: &dyn ClientConfig,
            _cache: CacheView,
            _clock: Rc<RefCell<dyn Clock>>,
        ) -> anyhow::Result<Box<dyn DataClient>> {
            Ok(Box::new(VenueLessDataClient::new(ClientId::from(name))))
        }

        fn name(&self) -> &'static str {
            "VENUE_LESS"
        }

        fn config_type(&self) -> &'static str {
            "TestDataClientConfig"
        }
    }

    #[expect(
        clippy::unnecessary_wraps,
        reason = "signature must match the factory extractor function pointer"
    )]
    fn extract_reentrant_data_client_factory(
        _py: Python<'_>,
        _factory: Py<pyo3::PyAny>,
    ) -> pyo3::PyResult<Box<dyn DataClientFactory>> {
        Ok(Box::new(VenueLessDataClientFactory))
    }

    #[expect(
        clippy::unnecessary_wraps,
        reason = "signature must match the config extractor function pointer"
    )]
    fn extract_reentrant_data_client_config(
        _py: Python<'_>,
        _config: Py<pyo3::PyAny>,
    ) -> pyo3::PyResult<Box<dyn ClientConfig>> {
        Ok(Box::new(TestDataClientConfig))
    }

    #[rstest]
    fn test_python_builder_blocks_factory_name_reentry() {
        get_global_pyo3_registry()
            .register_factory_extractor(
                "REENTRANT_DATA".to_string(),
                extract_reentrant_data_client_factory,
            )
            .unwrap();
        get_global_pyo3_registry()
            .register_config_extractor(
                "ReentrantDataClientConfig".to_string(),
                extract_reentrant_data_client_config,
            )
            .unwrap();
        Python::initialize();

        Python::attach(|py| {
            let builder = Py::new(
                py,
                PyLiveNode::py_builder(
                    "TEST".to_string(),
                    TraderId::from("TESTER-001"),
                    Environment::Sandbox,
                )
                .unwrap(),
            )
            .unwrap();
            let locals = PyDict::new(py);
            locals.set_item("builder", &builder).unwrap();
            py.run(
                pyo3::ffi::c_str!(
                    "class ReentrantDataClientFactory:\n    def __init__(self):\n        self.reprs = []\n        self.results = []\n\n    def name(self):\n        self.reprs.append(repr(builder))\n        try:\n            builder.with_save_state(True)\n        except RuntimeError as e:\n            self.results.append((type(e).__name__, str(e)))\n        return 'REENTRANT_DATA'\n\nclass ReentrantDataClientConfig:\n    pass\n\nfactory = ReentrantDataClientFactory()\nconfig = ReentrantDataClientConfig()"
                ),
                Some(&locals),
                None,
            )
            .unwrap();
            let factory = locals.get_item("factory").unwrap();
            let config = locals.get_item("config").unwrap();

            builder
                .call_method1(py, "add_data_client", (py.None(), &factory, &config))
                .unwrap();

            let results = factory
                .getattr("results")
                .unwrap()
                .extract::<Vec<(String, String)>>()
                .unwrap();
            assert_eq!(
                results,
                vec![
                    (
                        "RuntimeError".to_string(),
                        BUILDER_OPERATION_IN_PROGRESS.to_string(),
                    ),
                    (
                        "RuntimeError".to_string(),
                        BUILDER_OPERATION_IN_PROGRESS.to_string(),
                    ),
                ]
            );
            assert_eq!(
                factory
                    .getattr("reprs")
                    .unwrap()
                    .extract::<Vec<String>>()
                    .unwrap(),
                vec!["PyLiveNodeBuilder { inner: <operation active> }"; 2]
            );
            let builder_ref = builder.borrow(py);
            let state = builder_ref
                .state
                .replace(PyLiveNodeBuilderState::InProgress);
            let is_ready = matches!(&state, PyLiveNodeBuilderState::Ready(_));
            builder_ref.state.set(state);
            assert!(is_ready);
            drop(builder_ref);

            let duplicate_error = builder
                .call_method1(py, "add_data_client", (py.None(), factory, config))
                .unwrap_err();

            assert_eq!(
                duplicate_error.to_string(),
                "RuntimeError: Failed to add data client: Data client 'REENTRANT_DATA' is already registered"
            );
            let builder_ref = builder.borrow(py);
            let state = builder_ref
                .state
                .replace(PyLiveNodeBuilderState::InProgress);
            let is_consumed = matches!(&state, PyLiveNodeBuilderState::Consumed);
            builder_ref.state.set(state);
            assert!(is_consumed);
            locals.call_method0("clear").unwrap();
        });
    }

    #[derive(Debug)]
    struct TestHistoricalBarsDataClient {
        client_id: ClientId,
        venue: Venue,
        connected: Arc<AtomicBool>,
        request_count: Arc<AtomicUsize>,
        response_sent_count: Arc<AtomicUsize>,
        handler_visible_count: Arc<AtomicUsize>,
    }

    impl TestHistoricalBarsDataClient {
        fn new(
            client_id: ClientId,
            venue: Venue,
            request_count: Arc<AtomicUsize>,
            response_sent_count: Arc<AtomicUsize>,
            handler_visible_count: Arc<AtomicUsize>,
        ) -> Self {
            Self {
                client_id,
                venue,
                connected: Arc::new(AtomicBool::new(false)),
                request_count,
                response_sent_count,
                handler_visible_count,
            }
        }

        fn make_bar(bar_type: BarType) -> Bar {
            Bar::new(
                bar_type,
                Price::from("1.0000"),
                Price::from("1.1000"),
                Price::from("0.9000"),
                Price::from("1.0500"),
                Quantity::from("1000"),
                UnixNanos::from(1_700_000_000_000_000_000u64),
                UnixNanos::from(1_700_000_000_000_000_001u64),
            )
        }
    }

    #[async_trait(?Send)]
    impl DataClient for TestHistoricalBarsDataClient {
        fn client_id(&self) -> ClientId {
            self.client_id
        }

        fn venue(&self) -> Option<Venue> {
            Some(self.venue)
        }

        fn start(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn stop(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn reset(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn dispose(&mut self) -> anyhow::Result<()> {
            Ok(())
        }

        fn is_connected(&self) -> bool {
            self.connected.load(Ordering::Relaxed)
        }

        fn is_disconnected(&self) -> bool {
            !self.is_connected()
        }

        async fn connect(&mut self) -> anyhow::Result<()> {
            self.connected.store(true, Ordering::Relaxed);
            Ok(())
        }

        async fn disconnect(&mut self) -> anyhow::Result<()> {
            self.connected.store(false, Ordering::Relaxed);
            Ok(())
        }

        fn request_bars(&self, request: RequestBars) -> anyhow::Result<()> {
            self.request_count.fetch_add(1, Ordering::Relaxed);

            if get_message_bus()
                .borrow()
                .get_response_handler(&request.request_id)
                .is_some()
            {
                self.handler_visible_count.fetch_add(1, Ordering::Relaxed);
            }

            let sender = get_data_event_sender();
            let client_id = self.client_id;
            let response_sent_count = self.response_sent_count.clone();
            let response = BarsResponse::new(
                request.request_id,
                client_id,
                request.bar_type,
                vec![Self::make_bar(request.bar_type)],
                None,
                None,
                UnixNanos::from(1_700_000_000_000_000_002u64),
                None,
            );

            tokio::spawn(async move {
                tokio::time::sleep(Duration::from_millis(10)).await;
                response_sent_count.fetch_add(1, Ordering::Relaxed);
                sender
                    .send(DataEvent::Response(DataResponse::Bars(response)))
                    .expect("test bars response should send");
            });

            Ok(())
        }
    }

    fn install_tracking_strategy_module(py: Python<'_>, module_name: &str) {
        let module = PyModule::new(py, module_name).expect("test module should create");
        module
            .setattr("Strategy", py.get_type::<PyStrategy>())
            .expect("Strategy type should bind");
        module
            .setattr("BarType", py.get_type::<BarType>())
            .expect("BarType type should bind");
        module
            .setattr("RESULTS", PyDict::new(py))
            .expect("RESULTS should bind");

        let code = CString::new(
            r#"
RESULTS["on_start"] = 0
RESULTS["on_historical_bars"] = 0
RESULTS["historical_bar_count"] = 0
RESULTS["last_request_id"] = ""

class HistoricalBarsStrategy(Strategy):
    def __init__(self):
        super().__init__()
        self.bar_type = BarType.from_str("AUDUSD.SIM-1-MINUTE-LAST-EXTERNAL")

    def on_start(self):
        RESULTS["on_start"] += 1
        RESULTS["last_request_id"] = self.request_bars(self.bar_type)

    def on_stop(self):
        pass

    def on_historical_bars(self, bars):
        RESULTS["on_historical_bars"] += 1
        RESULTS["historical_bar_count"] += len(bars)
"#,
        )
        .expect("python test code should be valid CString");

        py.run(code.as_c_str(), Some(&module.dict()), None)
            .expect("test strategy code should execute");

        let sys_modules = py
            .import("sys")
            .expect("sys should import")
            .getattr("modules")
            .expect("sys.modules should exist");
        sys_modules
            .set_item(module_name, module)
            .expect("test strategy module should register");
    }

    fn get_results(py: Python<'_>, module_name: &str) -> (usize, usize, usize) {
        let module = py
            .import(module_name)
            .expect("test strategy module should import");
        let results_obj = module.getattr("RESULTS").expect("RESULTS should exist");
        let results = results_obj
            .cast::<PyDict>()
            .expect("RESULTS should be a dict");

        let on_start = results
            .get_item("on_start")
            .expect("on_start key should exist")
            .extract::<usize>()
            .expect("on_start should extract");
        let on_historical_bars = results
            .get_item("on_historical_bars")
            .expect("on_historical_bars key should exist")
            .extract::<usize>()
            .expect("on_historical_bars should extract");
        let historical_bar_count = results
            .get_item("historical_bar_count")
            .expect("historical_bar_count key should exist")
            .extract::<usize>()
            .expect("historical_bar_count should extract");

        (on_start, on_historical_bars, historical_bar_count)
    }

    fn install_timer_strategy_module(py: Python<'_>, module_name: &str) {
        let module = PyModule::new(py, module_name).expect("test module should create");
        module
            .setattr("Strategy", py.get_type::<PyStrategy>())
            .expect("Strategy type should bind");
        module
            .setattr("RESULTS", PyDict::new(py))
            .expect("RESULTS should bind");

        let code = CString::new(
            r#"
RESULTS["on_start"] = 0
RESULTS["callback_timer_count"] = 0
RESULTS["default_timer_count"] = 0
RESULTS["callback_event_type"] = ""
RESULTS["default_event_type"] = ""
RESULTS["callback_event_name"] = ""
RESULTS["default_event_name"] = ""

class LiveTimerStrategy(Strategy):
    def __init__(self):
        super().__init__()

    def on_start(self):
        RESULTS["on_start"] += 1
        self.clock.set_timer_ns(
            "explicit_timer",
            1_000_000,
            callback=self._on_timer,
            fire_immediately=True,
        )
        self.clock.set_timer_ns(
            "default_timer",
            1_000_000,
            fire_immediately=True,
        )

    def on_stop(self):
        pass

    def _on_timer(self, event):
        RESULTS["callback_timer_count"] += 1
        RESULTS["callback_event_type"] = type(event).__name__
        RESULTS["callback_event_name"] = event.name

    def on_time_event(self, event):
        RESULTS["default_timer_count"] += 1
        RESULTS["default_event_type"] = type(event).__name__
        RESULTS["default_event_name"] = event.name
"#,
        )
        .expect("python test code should be valid CString");

        py.run(code.as_c_str(), Some(&module.dict()), None)
            .expect("test strategy code should execute");

        let sys_modules = py
            .import("sys")
            .expect("sys should import")
            .getattr("modules")
            .expect("sys.modules should exist");
        sys_modules
            .set_item(module_name, module)
            .expect("test strategy module should register");
    }

    fn install_claim_strategy_module(py: Python<'_>, module_name: &str) {
        let module = PyModule::new(py, module_name).expect("test module should create");
        module
            .setattr("Strategy", py.get_type::<PyStrategy>())
            .expect("Strategy type should bind");

        let code = CString::new(
            "
class ClaimsConfig:
    def __init__(
        self,
        strategy_id=None,
        order_id_tag=None,
        external_order_claims=None,
        oms_type=None,
    ):
        self.strategy_id = strategy_id
        self.order_id_tag = order_id_tag
        self.external_order_claims = external_order_claims
        self.oms_type = oms_type

class ClaimsStrategy(Strategy):
    def __init__(self, config):
        super().__init__(config)
",
        )
        .expect("python test code should be valid CString");

        py.run(code.as_c_str(), Some(&module.dict()), None)
            .expect("test strategy code should execute");

        let sys_modules = py
            .import("sys")
            .expect("sys should import")
            .getattr("modules")
            .expect("sys.modules should exist");
        sys_modules
            .set_item(module_name, module)
            .expect("test strategy module should register");
    }

    #[derive(Debug)]
    struct TimerStrategyResults {
        on_start: usize,
        callback_timer_count: usize,
        default_timer_count: usize,
        callback_event_type: String,
        default_event_type: String,
        callback_event_name: String,
        default_event_name: String,
    }

    fn get_timer_results(py: Python<'_>, module_name: &str) -> TimerStrategyResults {
        let module = py
            .import(module_name)
            .expect("test strategy module should import");
        let results_obj = module.getattr("RESULTS").expect("RESULTS should exist");
        let results = results_obj
            .cast::<PyDict>()
            .expect("RESULTS should be a dict");

        TimerStrategyResults {
            on_start: results
                .get_item("on_start")
                .expect("on_start key should exist")
                .extract::<usize>()
                .expect("on_start should extract"),
            callback_timer_count: results
                .get_item("callback_timer_count")
                .expect("callback_timer_count key should exist")
                .extract::<usize>()
                .expect("callback_timer_count should extract"),
            default_timer_count: results
                .get_item("default_timer_count")
                .expect("default_timer_count key should exist")
                .extract::<usize>()
                .expect("default_timer_count should extract"),
            callback_event_type: results
                .get_item("callback_event_type")
                .expect("callback_event_type key should exist")
                .extract::<String>()
                .expect("callback_event_type should extract"),
            default_event_type: results
                .get_item("default_event_type")
                .expect("default_event_type key should exist")
                .extract::<String>()
                .expect("default_event_type should extract"),
            callback_event_name: results
                .get_item("callback_event_name")
                .expect("callback_event_name key should exist")
                .extract::<String>()
                .expect("callback_event_name should extract"),
            default_event_name: results
                .get_item("default_event_name")
                .expect("default_event_name key should exist")
                .extract::<String>()
                .expect("default_event_name should extract"),
        }
    }

    #[cfg(feature = "examples")]
    #[rstest]
    #[case("CompositeMarketMaker")]
    #[case("DeltaNeutralVol")]
    #[case("EmaCross")]
    #[case("ExecTester")]
    #[case("GridMarketMaker")]
    #[case("HurstVpinDirectional")]
    fn test_builtin_strategy_register_accepts_supported_names(#[case] type_name: &str) {
        assert!(super::builtin_strategy_register(type_name).is_some());
    }

    #[cfg(feature = "examples")]
    #[rstest]
    #[case("BookImbalanceActor")]
    #[case("DataTester")]
    fn test_builtin_actor_register_accepts_supported_names(#[case] type_name: &str) {
        assert!(super::builtin_actor_register(type_name).is_some());
    }

    #[cfg(feature = "examples")]
    #[rstest]
    fn test_builtin_register_rejects_unknown_names() {
        assert!(super::builtin_strategy_register("UnknownStrategy").is_none());
        assert!(super::builtin_actor_register("UnknownActor").is_none());
    }

    #[rstest]
    fn test_inspection_wrappers_share_kernel_state() {
        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        let cache = node.py_cache().unwrap();
        let portfolio = node.py_portfolio().unwrap();

        assert!(Rc::ptr_eq(
            &cache.cache_rc(),
            &node.node_mut().unwrap().kernel().cache
        ));
        assert!(Rc::ptr_eq(
            &portfolio.portfolio_rc(),
            &node.node_mut().unwrap().kernel().portfolio
        ));
    }

    #[cfg(feature = "examples")]
    #[rstest]
    fn test_builtin_strategy_register_rejects_mismatched_config() {
        Python::initialize();

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        Python::attach(|py| {
            let register = super::builtin_strategy_register("EmaCross").unwrap();
            let config = PyDict::new(py);
            let error = register(&mut node.node_mut().unwrap(), config.as_any()).unwrap_err();

            assert!(error.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
        });
    }

    #[cfg(feature = "examples")]
    #[rstest]
    fn test_builtin_actor_register_rejects_mismatched_config() {
        Python::initialize();

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        Python::attach(|py| {
            let register = super::builtin_actor_register("DataTester").unwrap();
            let config = PyDict::new(py);
            let error = register(&mut node.node_mut().unwrap(), config.as_any()).unwrap_err();

            assert!(error.is_instance_of::<pyo3::exceptions::PyTypeError>(py));
        });
    }

    #[rstest]
    #[case(ShutdownRunPath::Native)]
    #[case(ShutdownRunPath::PyO3)]
    fn test_native_and_python_shutdown_paths_drain_cancel_command(
        #[case] run_path: ShutdownRunPath,
    ) {
        Python::initialize();

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(1)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();
        node.node_mut()
            .unwrap()
            .add_strategy(ShutdownCancelStrategy::new(InstrumentId::from(
                "TEST.POLYMARKET",
            )))
            .unwrap();

        let handle = node.node_mut().unwrap().handle();
        let stop_handle = handle.clone();

        let stop_thread = thread::spawn(move || {
            let deadline = Instant::now() + Duration::from_secs(5);
            while !stop_handle.is_running() && Instant::now() < deadline {
                thread::sleep(Duration::from_millis(10));
            }
            stop_handle.stop();
        });

        match run_path {
            ShutdownRunPath::Native => get_runtime()
                .block_on(node.node_mut().unwrap().run())
                .expect("native LiveNode run should stop cleanly"),
            ShutdownRunPath::PyO3 => Python::attach(|py| {
                super::run_live_node_detached(py, &mut node.node_mut().unwrap())
                    .expect("Python LiveNode run should stop cleanly");
            }),
        }

        stop_thread.join().expect("stop thread should join");
        let metrics = handle.metrics_snapshot();

        assert_eq!(metrics.exec_commands.dispatched, 1);
        assert_eq!(metrics.exec_commands.queue_depth, 0);
        assert!(!handle.is_running());
    }

    #[rstest]
    fn test_run_live_node_detached_releases_gil() {
        Python::initialize();

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        let handle = node.node_mut().unwrap().handle();
        let (gil_tx, gil_rx) = mpsc::channel();
        let acquired_before_stop = Arc::new(AtomicBool::new(false));
        let acquired_before_stop_for_thread = acquired_before_stop.clone();

        let stop_thread = thread::spawn(move || {
            if gil_rx.recv_timeout(Duration::from_secs(1)).is_ok() {
                acquired_before_stop_for_thread.store(true, Ordering::SeqCst);
            }
            handle.stop();
        });

        let gil_thread = thread::spawn(move || {
            Python::attach(|_| {});
            let _ = gil_tx.send(());
        });

        Python::attach(|py| {
            super::run_live_node_detached(py, &mut node.node_mut().unwrap())
                .expect("node should run cleanly");
        });

        stop_thread.join().expect("stop thread should join");
        gil_thread.join().expect("GIL thread should join");

        assert!(
            acquired_before_stop.load(Ordering::SeqCst),
            "worker thread should acquire the GIL while LiveNode::run is blocked"
        );
    }

    #[rstest]
    fn test_host_loop_waker_coalesces_redundant_wakes() {
        let (waker, receiver, _) = host_loop_waker_probe();

        std::task::Wake::wake(waker.clone());
        let consuming_wake = receiver.recv_timeout(Duration::from_secs(1));
        std::task::Wake::wake_by_ref(&waker);
        let redundant_wake = receiver.try_recv();

        assert!(matches!(
            consuming_wake,
            Ok(super::HostWakeSignal::Resume(7))
        ));
        assert!(matches!(redundant_wake, Err(mpsc::TryRecvError::Empty)));
    }

    #[rstest]
    fn test_host_loop_waker_ignores_wake_after_close() {
        let (waker, receiver, handle) = host_loop_waker_probe();
        waker.control.close();

        std::task::Wake::wake_by_ref(&waker);

        assert!(matches!(
            receiver.recv().unwrap(),
            super::HostWakeSignal::Shutdown
        ));
        assert!(matches!(
            receiver.try_recv(),
            Err(mpsc::TryRecvError::Empty)
        ));
        assert!(!handle.should_stop());
    }

    #[rstest]
    fn test_host_loop_waker_stops_node_when_pump_is_gone() {
        let (waker, receiver, handle) = host_loop_waker_probe();
        drop(receiver);

        std::task::Wake::wake_by_ref(&waker);

        assert!(!waker.control.active.load(Ordering::Acquire));
        assert!(handle.should_stop());
    }

    fn host_loop_waker_probe() -> (
        Arc<super::HostLoopWaker>,
        mpsc::Receiver<super::HostWakeSignal>,
        crate::node::LiveNodeHandle,
    ) {
        let (sender, receiver) = mpsc::channel();
        let handle = crate::node::LiveNodeHandle::new();
        let control = Arc::new(super::HostWakeControl {
            sender,
            active: AtomicBool::new(true),
            handle: handle.clone(),
        });
        let waker = Arc::new(super::HostLoopWaker {
            generation: 7,
            scheduled: AtomicBool::new(false),
            control,
        });

        (waker, receiver, handle)
    }

    #[rstest]
    fn test_host_loop_waker_breaks_gil_dependency_lock_cycle() {
        Python::initialize();

        let (waker, mut wake_pump, event_loop) = Python::attach(|py| {
            let event_loop = py
                .import("asyncio")
                .unwrap()
                .call_method0("new_event_loop")
                .unwrap();
            let state = Arc::new(super::RunWakeState::default());
            let wake_callback = Py::new(py, super::PyNodeRunWake { state })
                .unwrap()
                .into_any();
            let event_loop = event_loop.unbind();
            let wake_pump = super::HostWakePump::start(
                event_loop.clone_ref(py),
                wake_callback,
                crate::node::LiveNodeHandle::new(),
            )
            .unwrap();
            let waker = wake_pump.waker(1);

            (waker, wake_pump, event_loop)
        });
        let (start_tx, start_rx) = mpsc::channel();
        let (locked_tx, locked_rx) = mpsc::channel();
        let dependency_lock = Arc::new(Mutex::new(()));
        let dependency_lock_for_thread = dependency_lock.clone();
        let wake_thread = thread::spawn(move || {
            let _guard = dependency_lock_for_thread.lock();
            locked_tx.send(()).unwrap();
            start_rx.recv().unwrap();
            waker.wake_by_ref();
        });
        locked_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("wake thread should hold the dependency lock");

        let dependency_released_while_gil_held = Python::attach(|_| {
            start_tx.send(()).unwrap();
            let deadline = Instant::now() + Duration::from_secs(1);

            loop {
                match dependency_lock.try_lock() {
                    Some(_) => break true,
                    None if Instant::now() < deadline => {
                        thread::yield_now();
                    }
                    None => break false,
                }
            }
        });
        wake_thread.join().unwrap();
        Python::attach(|py| {
            wake_pump.close();
            wake_pump.join(Some(py));
            event_loop.bind(py).call_method0("close").unwrap();
        });

        assert!(dependency_released_while_gil_held);
    }

    #[rstest]
    fn test_run_wake_state_ignores_stale_generation() {
        Python::initialize();

        Python::attach(|py| {
            let event_loop = py
                .import("asyncio")
                .unwrap()
                .call_method0("new_event_loop")
                .unwrap();
            let future = event_loop.call_method0("create_future").unwrap();
            let state = super::RunWakeState::default();
            state.suspend(2, future.clone().unbind());

            state.resume(py, 1).unwrap();
            let done_after_stale: bool = future.call_method0("done").unwrap().extract().unwrap();
            state.resume(py, 2).unwrap();
            let done_after_current: bool = future.call_method0("done").unwrap().extract().unwrap();
            event_loop.call_method0("close").unwrap();

            assert!(!done_after_stale);
            assert!(done_after_current);
        });
    }

    #[rstest]
    fn test_host_wake_pump_resumes_current_suspension() {
        Python::initialize();

        Python::attach(|py| {
            let asyncio = py.import("asyncio").unwrap();
            let event_loop = asyncio.call_method0("new_event_loop").unwrap();
            let future = event_loop.call_method0("create_future").unwrap();
            let state = Arc::new(super::RunWakeState::default());
            state.suspend(7, future.clone().unbind());
            let wake_callback = Py::new(py, super::PyNodeRunWake { state })
                .unwrap()
                .into_any();
            let mut wake_pump = super::HostWakePump::start(
                event_loop.clone().unbind(),
                wake_callback,
                crate::node::LiveNodeHandle::new(),
            )
            .unwrap();

            wake_pump.waker(7).wake_by_ref();
            let wait_for = asyncio.call_method1("wait_for", (&future, 1.0)).unwrap();
            let result = event_loop
                .call_method1("run_until_complete", (wait_for,))
                .unwrap();
            wake_pump.close();
            wake_pump.join(Some(py));
            event_loop.call_method0("close").unwrap();

            assert!(result.is_none());
        });
    }

    #[rstest]
    fn test_host_wake_pump_stops_node_when_loop_is_closed() {
        Python::initialize();

        Python::attach(|py| {
            let event_loop = py
                .import("asyncio")
                .unwrap()
                .call_method0("new_event_loop")
                .unwrap();
            event_loop.call_method0("close").unwrap();
            let state = Arc::new(super::RunWakeState::default());
            let wake_callback = Py::new(py, super::PyNodeRunWake { state })
                .unwrap()
                .into_any();
            let handle = crate::node::LiveNodeHandle::new();
            let mut wake_pump =
                super::HostWakePump::start(event_loop.unbind(), wake_callback, handle.clone())
                    .unwrap();

            wake_pump.waker(1).wake_by_ref();
            wake_pump.join(Some(py));

            assert!(handle.should_stop());
        });
    }

    #[rstest]
    fn test_hosted_run_completes_after_stop() {
        Python::initialize();

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_delay_shutdown_secs(0)
            .with_timeout_connection(0)
            .with_timeout_disconnection_secs(0)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        Python::attach(|py| {
            let locals = PyDict::new(py);
            let py_node = Py::new(py, node).unwrap();
            locals.set_item("node", &py_node).unwrap();
            py.run(
                pyo3::ffi::c_str!(
                    "import asyncio\n\nasync def run_node():\n    handle = node.handle()\n    asyncio.get_running_loop().call_soon(handle.stop)\n    await asyncio.wait_for(node.run_async(), timeout=5)\n\nasyncio.run(run_node())"
                ),
                Some(&locals),
                None,
            )
            .unwrap();

            let node = py_node.borrow(py);
            assert!(!node.is_consumed());
            assert_eq!(
                node.node().unwrap().state(),
                crate::node::NodeState::Stopped
            );
        });
        get_message_bus().borrow_mut().dispose();
    }

    #[rstest]
    fn test_build_routes_venue_less_data_client_with_venue_routing() {
        Python::initialize();

        let routing = RoutingConfig::builder()
            .venues(vec!["IBIS".to_string()])
            .build();
        let node = LiveNode::builder(TraderId::from("TEST-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_timeout_connection(1)
            .add_data_client_with_routing(
                Some("IB".to_string()),
                Box::new(VenueLessDataClientFactory),
                Box::new(TestDataClientConfig),
                routing,
            )
            .unwrap()
            .build();

        assert!(node.is_ok(), "build should succeed: {:?}", node.err());
    }

    #[rstest]
    fn test_build_routes_venue_less_data_client_with_default_and_venues() {
        Python::initialize();

        let routing = RoutingConfig::builder()
            .default(true)
            .venues(vec!["IBIS".to_string()])
            .build();
        let node = LiveNode::builder(TraderId::from("TEST-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_timeout_connection(1)
            .add_data_client_with_routing(
                Some("IB".to_string()),
                Box::new(VenueLessDataClientFactory),
                Box::new(TestDataClientConfig),
                routing,
            )
            .unwrap()
            .build();

        assert!(node.is_ok(), "build should succeed: {:?}", node.err());
    }

    #[rstest]
    fn test_stop_live_node_detached_releases_gil() {
        Python::initialize();

        let node = LiveNode::builder(TraderId::from("TESTER-002"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(1)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        get_runtime()
            .block_on(async { node.node_mut().unwrap().start().await })
            .expect("node should start");

        let (attempt_tx, attempt_rx) = mpsc::channel();
        let acquired_before_stop_return = Arc::new(AtomicBool::new(false));
        let acquired_before_stop_return_for_thread = acquired_before_stop_return.clone();
        let stop_returned = Arc::new(AtomicBool::new(false));
        let stop_returned_for_thread = stop_returned.clone();
        let mut gil_thread = None;

        Python::attach(|py| {
            gil_thread = Some(thread::spawn(move || {
                attempt_tx
                    .send(())
                    .expect("GIL acquisition attempt should send");
                Python::attach(|_| {});

                if !stop_returned_for_thread.load(Ordering::SeqCst) {
                    acquired_before_stop_return_for_thread.store(true, Ordering::SeqCst);
                }
            }));

            attempt_rx
                .recv_timeout(Duration::from_secs(1))
                .expect("worker thread should attempt to acquire the GIL");

            super::stop_live_node_detached(py, &mut node.node_mut().unwrap())
                .expect("node should stop cleanly");
            stop_returned.store(true, Ordering::SeqCst);
        });

        gil_thread
            .expect("GIL worker thread should be spawned")
            .join()
            .expect("GIL worker thread should join");

        assert!(
            acquired_before_stop_return.load(Ordering::SeqCst),
            "worker thread should acquire the GIL while LiveNode::stop is blocked"
        );
        assert!(!node.node_mut().unwrap().is_running());
    }

    #[rstest]
    fn test_py_dispose_disposes_kernel_after_stop_error() {
        Python::initialize();

        let dispose_count = Arc::new(AtomicUsize::new(0));
        let factory = TestDisconnectFailureDataClientFactory::new(dispose_count.clone());
        let config = TestDataClientConfig;
        let node = LiveNode::builder(TraderId::from("TESTER-003"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .with_timeout_disconnection_secs(0)
            .add_data_client(
                Some("TEST_DISCONNECT_FAILURE".to_string()),
                Box::new(factory),
                Box::new(config),
            )
            .unwrap()
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        let dispose_result = Python::attach(|py| {
            get_runtime()
                .block_on(async { node.node_mut().unwrap().start().await })
                .expect("node should start");
            assert!(node.node_mut().unwrap().is_running());

            node.py_dispose(py)
        });

        let error = dispose_result.expect_err("dispose should return the stop error");

        assert!(error.to_string().contains("test disconnect failed"));
        assert_eq!(dispose_count.load(Ordering::Relaxed), 1);
        assert!(!node.node_mut().unwrap().is_running());
    }

    #[rstest]
    fn test_live_node_pystrategy_timer_callbacks_run_on_event_loop() {
        Python::initialize();

        let module_name = "test_live_node_timer_strategy";
        Python::attach(|py| install_timer_strategy_module(py, module_name));

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        let importable = ImportableStrategyConfig {
            strategy_path: format!("{module_name}:LiveTimerStrategy"),
            config_path: String::new(),
            config: HashMap::new(),
        };

        Python::attach(|py| {
            node.py_add_strategy_from_config(py, importable)
                .expect("strategy should register");
        });

        let handle = node.node_mut().unwrap().handle();
        let stop_handle = handle.clone();
        let watchdog_handle = handle;
        let (done_tx, done_rx) = mpsc::channel();
        let module_name_for_stop = module_name.to_string();

        let stop_thread = thread::spawn(move || {
            let deadline = Instant::now() + Duration::from_secs(5);

            loop {
                let fired = Python::attach(|py| {
                    let results = get_timer_results(py, &module_name_for_stop);
                    results.callback_timer_count > 0 && results.default_timer_count > 0
                });

                if fired || Instant::now() >= deadline {
                    break;
                }

                thread::sleep(Duration::from_millis(20));
            }

            stop_handle.stop();
        });

        let watchdog_thread = thread::spawn(move || {
            if done_rx.recv_timeout(Duration::from_secs(5)).is_err() {
                watchdog_handle.stop();
            }
        });

        Python::attach(|py| {
            super::run_live_node_detached(py, &mut node.node_mut().unwrap())
                .expect("node should run cleanly");
        });

        let _ = done_tx.send(());
        stop_thread.join().expect("stop thread should join");
        watchdog_thread.join().expect("watchdog thread should join");

        let results = Python::attach(|py| get_timer_results(py, module_name));

        assert_eq!(results.on_start, 1);
        assert!(results.callback_timer_count > 0);
        assert!(results.default_timer_count > 0);
        assert_eq!(results.callback_event_type, "TimeEvent");
        assert_eq!(results.default_event_type, "TimeEvent");
        assert_eq!(results.callback_event_name, "explicit_timer");
        assert_eq!(results.default_event_name, "default_timer");
    }

    #[rstest]
    fn test_add_actor_registers_constructed_python_instance() {
        Python::initialize();

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();
        let actor_id = ActorId::from("ACTOR-INSTANCE-001");

        Python::attach(|py| {
            let config = py
                .eval(c_str!("type('_Cfg', (), {})()"), None, None)
                .unwrap();
            config.setattr("actor_id", actor_id.to_string()).unwrap();
            let actor = py
                .get_type::<PyDataActor>()
                .as_any()
                .call1((config,))
                .unwrap();

            node.py_add_actor(&actor).expect("actor should register");

            let actor = actor.extract::<PyRef<PyDataActor>>().unwrap();
            assert_eq!(actor.actor_id(), actor_id);
            assert!(actor.is_registered());
        });

        assert_eq!(
            node.node_mut()
                .unwrap()
                .kernel()
                .trader
                .borrow()
                .actor_ids(),
            vec![actor_id]
        );
    }

    #[rstest]
    fn test_add_actor_rejects_non_idle_node() {
        Python::initialize();

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        Python::attach(|py| {
            let actor = py.get_type::<PyDataActor>().call0().unwrap();
            node.handle.set_starting();

            let error = node
                .py_add_actor(&actor)
                .expect_err("a non-idle node should reject actor registration");
            let actor = actor.extract::<PyRef<PyDataActor>>().unwrap();

            assert_eq!(
                error.to_string(),
                "RuntimeError: Cannot add actor while node is running, add actors before running the node"
            );
            assert!(!actor.is_registered());
        });

        assert!(
            node.node()
                .unwrap()
                .kernel()
                .trader
                .borrow()
                .actor_ids()
                .is_empty()
        );
    }

    #[rstest]
    fn test_add_strategy_from_config_registers_external_order_claims() {
        Python::initialize();

        let module_name = "test_live_node_claim_strategy";
        Python::attach(|py| install_claim_strategy_module(py, module_name));

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        let instrument_id = InstrumentId::from("AUDUSD.SIM");
        let strategy_id = StrategyId::from("CLAIMS-001");
        let mut config = HashMap::new();
        config.insert(
            "strategy_id".to_string(),
            serde_json::json!(strategy_id.to_string()),
        );
        config.insert(
            "external_order_claims".to_string(),
            serde_json::json!([instrument_id.to_string()]),
        );
        let importable = ImportableStrategyConfig {
            strategy_path: format!("{module_name}:ClaimsStrategy"),
            config_path: format!("{module_name}:ClaimsConfig"),
            config,
        };

        Python::attach(|py| {
            node.py_add_strategy_from_config(py, importable)
                .expect("strategy should register");
        });

        {
            let guard = node.node_mut().unwrap();
            let exec_engine = guard.kernel().exec_engine.borrow();
            assert_eq!(
                exec_engine.get_external_order_claim(&instrument_id),
                Some(strategy_id)
            );
        }

        let result = node
            .node_mut()
            .unwrap()
            .exec_manager_mut()
            .claim_external_orders(instrument_id, StrategyId::from("OTHER-001"));

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("already exists for CLAIMS-001")
        );
    }

    #[rstest]
    fn test_add_strategy_registers_constructed_python_instance() {
        Python::initialize();

        let module_name = "test_live_node_add_strategy_instance";
        Python::attach(|py| install_claim_strategy_module(py, module_name));

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        let instrument_id = InstrumentId::from("AUDUSD.SIM");
        let strategy_id = StrategyId::from("CLAIMS-002");

        Python::attach(|py| {
            let module = py.import(module_name).expect("test module should import");
            let kwargs = PyDict::new(py);
            kwargs
                .set_item("strategy_id", strategy_id.to_string())
                .unwrap();
            kwargs
                .set_item("external_order_claims", vec![instrument_id.to_string()])
                .unwrap();
            let config = module
                .getattr("ClaimsConfig")
                .unwrap()
                .call((), Some(&kwargs))
                .unwrap();
            let strategy = module
                .getattr("ClaimsStrategy")
                .unwrap()
                .call1((config,))
                .unwrap();

            node.py_add_strategy(&strategy)
                .expect("strategy should register");
        });

        {
            let guard = node.node_mut().unwrap();
            let exec_engine = guard.kernel().exec_engine.borrow();
            assert_eq!(
                exec_engine.get_external_order_claim(&instrument_id),
                Some(strategy_id)
            );
        }
    }

    #[rstest]
    fn test_add_strategy_constructed_python_instance_registers_oms_type() {
        Python::initialize();

        let module_name = "test_live_node_add_strategy_instance_oms_type";
        Python::attach(|py| install_claim_strategy_module(py, module_name));

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();
        let strategy_id = StrategyId::from("FUNDING_ARBITRAGE-003");

        Python::attach(|py| {
            let module = py.import(module_name).expect("test module should import");
            let kwargs = PyDict::new(py);
            kwargs
                .set_item("strategy_id", strategy_id.to_string())
                .unwrap();
            kwargs.set_item("oms_type", OmsType::Hedging).unwrap();
            let config = module
                .getattr("ClaimsConfig")
                .unwrap()
                .call((), Some(&kwargs))
                .unwrap();
            let strategy = module
                .getattr("ClaimsStrategy")
                .unwrap()
                .call1((config,))
                .unwrap();

            node.py_add_strategy(&strategy)
                .expect("strategy should register");
        });

        let instrument = crypto_perpetual_ethusdt();
        let instrument_id = instrument.id();
        let client_id = ClientId::from("STUB");

        node.node_mut()
            .unwrap()
            .kernel()
            .cache
            .borrow_mut()
            .add_instrument(InstrumentAny::CryptoPerpetual(instrument))
            .unwrap();
        node.node_mut()
            .unwrap()
            .kernel()
            .exec_engine
            .borrow_mut()
            .register_client(Box::new(StubExecutionClient::new(
                client_id,
                AccountId::from("TEST-ACCOUNT"),
                instrument_id.venue,
                OmsType::Netting,
                None,
            )))
            .unwrap();

        let order = OrderTestBuilder::new(OrderType::Market)
            .trader_id(node.node_mut().unwrap().trader_id())
            .strategy_id(strategy_id)
            .instrument_id(instrument_id)
            .quantity(Quantity::from("1.000"))
            .build();
        let position_id = PositionId::new("CUSTOM-POSITION-003");

        node.node_mut()
            .unwrap()
            .kernel()
            .cache
            .borrow_mut()
            .add_order(order.clone(), Some(position_id), Some(client_id), true)
            .unwrap();

        let submit_order = SubmitOrder::new(
            order.trader_id(),
            Some(client_id),
            strategy_id,
            instrument_id,
            order.client_order_id(),
            order.init_event().clone(),
            order.exec_algorithm_id(),
            Some(position_id),
            None,
            UUID4::new(),
            UnixNanos::default(),
            None,
        );

        node.node_mut()
            .unwrap()
            .kernel()
            .exec_engine
            .borrow()
            .execute(TradingCommand::SubmitOrder(submit_order));

        let guard = node.node_mut().unwrap();
        let exec_engine = guard.kernel().exec_engine.borrow();
        let cache = exec_engine.cache().borrow();
        let cached_order = cache
            .order(&order.client_order_id())
            .expect("Order should be cached");

        assert_eq!(cached_order.status(), OrderStatus::Initialized);
    }

    #[rstest]
    fn test_add_strategy_constructed_python_instance_claim_conflict_does_not_register() {
        Python::initialize();

        let module_name = "test_live_node_add_strategy_instance_claim_conflict";
        Python::attach(|py| install_claim_strategy_module(py, module_name));

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();
        let instrument_id = InstrumentId::from("AUDUSD.SIM");
        let first_strategy_id = StrategyId::from("CLAIMS-PRIMARY-001");
        let conflicting_strategy_id = StrategyId::from("CLAIMS-CONFLICT-002");

        let (error, conflicting_strategy_registered) = Python::attach(|py| {
            let module = py.import(module_name).expect("test module should import");
            let first_kwargs = PyDict::new(py);
            first_kwargs
                .set_item("strategy_id", first_strategy_id.to_string())
                .unwrap();
            first_kwargs
                .set_item("external_order_claims", vec![instrument_id.to_string()])
                .unwrap();
            let first_config = module
                .getattr("ClaimsConfig")
                .unwrap()
                .call((), Some(&first_kwargs))
                .unwrap();
            let first_strategy = module
                .getattr("ClaimsStrategy")
                .unwrap()
                .call1((first_config,))
                .unwrap();
            node.py_add_strategy(&first_strategy)
                .expect("first strategy should register");

            let conflicting_kwargs = PyDict::new(py);
            conflicting_kwargs
                .set_item("strategy_id", conflicting_strategy_id.to_string())
                .unwrap();
            conflicting_kwargs
                .set_item("external_order_claims", vec![instrument_id.to_string()])
                .unwrap();
            let conflicting_config = module
                .getattr("ClaimsConfig")
                .unwrap()
                .call((), Some(&conflicting_kwargs))
                .unwrap();
            let conflicting_strategy = module
                .getattr("ClaimsStrategy")
                .unwrap()
                .call1((conflicting_config,))
                .unwrap();
            let error = node
                .py_add_strategy(&conflicting_strategy)
                .expect_err("conflicting claim should fail");
            let is_registered = conflicting_strategy
                .extract::<PyRef<PyStrategy>>()
                .unwrap()
                .is_registered();

            (error, is_registered)
        });

        let strategy_ids = node
            .node_mut()
            .unwrap()
            .kernel()
            .trader
            .borrow()
            .strategy_ids();
        let manager_claim = node
            .node_mut()
            .unwrap()
            .exec_manager()
            .get_external_order_claim(&instrument_id);
        let engine_claim = node
            .node_mut()
            .unwrap()
            .kernel()
            .exec_engine
            .borrow()
            .get_external_order_claim(&instrument_id);

        assert!(
            error
                .to_string()
                .contains("already exists for CLAIMS-PRIMARY-001")
        );
        assert!(!conflicting_strategy_registered);
        assert_eq!(strategy_ids, vec![first_strategy_id]);
        assert_eq!(manager_claim, Some(first_strategy_id));
        assert_eq!(engine_claim, Some(first_strategy_id));
    }

    #[rstest]
    fn test_add_strategy_constructed_python_instance_duplicate_tag_does_not_register() {
        Python::initialize();

        let module_name = "test_live_node_add_strategy_instance_duplicate_tag";
        Python::attach(|py| install_claim_strategy_module(py, module_name));

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .build()
            .map(PyLiveNode::new)
            .unwrap();
        let first_strategy_id = StrategyId::from("TAGGED-FIRST-777");

        let (error, duplicate_strategy_registered) = Python::attach(|py| {
            let module = py.import(module_name).expect("test module should import");
            let first_kwargs = PyDict::new(py);
            first_kwargs
                .set_item("strategy_id", "TAGGED-FIRST")
                .unwrap();
            first_kwargs.set_item("order_id_tag", "777").unwrap();
            let first_config = module
                .getattr("ClaimsConfig")
                .unwrap()
                .call((), Some(&first_kwargs))
                .unwrap();
            let first_strategy = module
                .getattr("ClaimsStrategy")
                .unwrap()
                .call1((first_config,))
                .unwrap();
            node.py_add_strategy(&first_strategy)
                .expect("first strategy should register");

            let duplicate_kwargs = PyDict::new(py);
            duplicate_kwargs
                .set_item("strategy_id", "TAGGED-SECOND")
                .unwrap();
            duplicate_kwargs.set_item("order_id_tag", "777").unwrap();
            let duplicate_config = module
                .getattr("ClaimsConfig")
                .unwrap()
                .call((), Some(&duplicate_kwargs))
                .unwrap();
            let duplicate_strategy = module
                .getattr("ClaimsStrategy")
                .unwrap()
                .call1((duplicate_config,))
                .unwrap();
            let error = node
                .py_add_strategy(&duplicate_strategy)
                .expect_err("duplicate order ID tag should fail");
            let is_registered = duplicate_strategy
                .extract::<PyRef<PyStrategy>>()
                .unwrap()
                .is_registered();

            (error, is_registered)
        });

        let strategy_ids = node
            .node_mut()
            .unwrap()
            .kernel()
            .trader
            .borrow()
            .strategy_ids();

        assert!(error.to_string().contains("order_id_tag conflict"));
        assert!(!duplicate_strategy_registered);
        assert_eq!(strategy_ids, vec![first_strategy_id]);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_live_node_pystrategy_request_bars_dispatches_on_historical_bars() {
        Python::initialize();

        let module_name = "test_live_node_historical_bars_strategy";
        Python::attach(|py| install_tracking_strategy_module(py, module_name));

        let request_count = Arc::new(AtomicUsize::new(0));
        let response_sent_count = Arc::new(AtomicUsize::new(0));
        let handler_visible_count = Arc::new(AtomicUsize::new(0));
        let factory = TestHistoricalBarsDataClientFactory::new(
            request_count.clone(),
            response_sent_count.clone(),
            handler_visible_count.clone(),
        );
        let config = TestDataClientConfig;

        let node = LiveNode::builder(TraderId::from("TESTER-001"), Environment::Sandbox)
            .unwrap()
            .with_reconciliation(false)
            .with_delay_post_stop_secs(0)
            .with_timeout_connection(1)
            .add_data_client(
                Some("TEST_DATA".to_string()),
                Box::new(factory),
                Box::new(config),
            )
            .unwrap()
            .build()
            .map(PyLiveNode::new)
            .unwrap();

        let importable = ImportableStrategyConfig {
            strategy_path: format!("{module_name}:HistoricalBarsStrategy"),
            config_path: String::new(),
            config: HashMap::new(),
        };

        Python::attach(|py| {
            node.py_add_strategy_from_config(py, importable)
                .expect("strategy should register");
        });

        let handle = node.node_mut().unwrap().handle();
        let stop_handle = handle.clone();
        let response_sent_count_for_stop = response_sent_count.clone();

        tokio::spawn(async move {
            let deadline = tokio::time::Instant::now() + Duration::from_secs(5);

            loop {
                if response_sent_count_for_stop.load(Ordering::Relaxed) == 1
                    || tokio::time::Instant::now() >= deadline
                {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
            tokio::time::sleep(Duration::from_millis(250)).await;
            stop_handle.stop();
        });

        node.node_mut()
            .unwrap()
            .run()
            .await
            .expect("node should run cleanly");

        let (on_start, on_historical_bars, historical_bar_count) =
            Python::attach(|py| get_results(py, module_name));

        assert_eq!(request_count.load(Ordering::Relaxed), 1);
        assert_eq!(handler_visible_count.load(Ordering::Relaxed), 1);
        assert_eq!(response_sent_count.load(Ordering::Relaxed), 1);
        assert_eq!(on_start, 1);
        assert_eq!(on_historical_bars, 1);
        assert_eq!(historical_bar_count, 1);
    }
}