openpit 0.5.0

Embeddable pre-trade risk SDK
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
// Copyright The Pit Project Owners. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
//
// Please see https://openpit.dev and the OWNERS file for details.

// Engine-side runtime reconfiguration: builds a FullSync engine with various
// built-in policies, then drives each through `Engine::configure()`.
// Covers rate-limit retune, P&L-bounds kill-switch (including pre-barrier
// accumulation guarantee), order-size-limit retune, spot-funds retune, the
// three `ConfigureError` paths, and the per-mode `Send`/`Sync` contract of
// `Configurator`.

use std::sync::Arc;
use std::time::Duration;

use openpit::marketdata::{InstrumentId, MarketDataBuilder, Quote, QuoteTtl};
use openpit::param::{
    AccountId, AdjustmentAmount, Asset, Fee, Pnl, PositionSize, Price, Quantity, Side, TradeAmount,
    Volume,
};
use openpit::pretrade::policies::pnl_bounds_killswitch::PnlBoundsAccountAssetBarrierUpdate;
use openpit::pretrade::policies::{
    OrderSizeAccountAssetBarrier, OrderSizeAssetBarrier, OrderSizeBrokerBarrier, OrderSizeLimit,
    OrderSizeLimitPolicy, OrderSizeLimitPolicyError, OrderSizeLimitSettings,
    PnlBoundsAccountAssetBarrier, PnlBoundsBrokerBarrier, PnlBoundsKillSwitchPolicy,
    PnlBoundsKillSwitchPolicyError, PnlBoundsKillSwitchSettings, RateLimit, RateLimitAssetBarrier,
    RateLimitBrokerBarrier, RateLimitPolicy, RateLimitPolicyError, RateLimitSettings,
    SpotFundsOverride, SpotFundsOverrideTarget, SpotFundsPolicy, SpotFundsPricingSource,
    SpotFundsSettings,
};
use openpit::pretrade::{PreTradePolicy, DEFAULT_POLICY_GROUP_ID};
use openpit::storage::{FullLocking, IndexLocking, NoLocking};
use openpit::{
    AccountKeyConstraint, AccountSync, AccountSyncEngine, Configurator, ConfigureError, Engine,
    ExecutionReportOperation, FinancialImpact, FullSync, FullSyncEngine,
    HasAccountAdjustmentBalance, HasAccountAdjustmentBalanceAverageEntryPrice,
    HasAccountAdjustmentBalanceLowerBound, HasAccountAdjustmentBalanceRealizedPnl,
    HasAccountAdjustmentBalanceUpperBound, HasAccountAdjustmentHeld,
    HasAccountAdjustmentHeldLowerBound, HasAccountAdjustmentHeldUpperBound,
    HasAccountAdjustmentIncoming, HasAccountAdjustmentIncomingLowerBound,
    HasAccountAdjustmentIncomingUpperBound, HasBalanceAsset, Instrument, LocalEngine, LocalSync,
    OrderOperation, RequestFieldAccessError, SpotFundsConfigError, SpotFundsMarketData,
    WithExecutionReportFillDetails, WithExecutionReportOperation, WithFinancialImpact,
};

type AccountLocking = IndexLocking<AccountKeyConstraint>;

struct CustomPolicy;

impl PreTradePolicy<OrderOperation, (), (), LocalSync> for CustomPolicy {
    fn name(&self) -> &str {
        "CustomPolicy"
    }
}

fn order(account: u64) -> OrderOperation {
    OrderOperation {
        instrument: Instrument::new(
            Asset::new("AAPL").expect("asset code must be valid"),
            Asset::new("USD").expect("asset code must be valid"),
        ),
        account_id: AccountId::from_u64(account),
        side: Side::Buy,
        trade_amount: TradeAmount::Quantity(
            Quantity::from_str("1").expect("quantity literal must be valid"),
        ),
        price: None,
    }
}

fn broker_settings(max_orders: usize) -> RateLimitSettings {
    RateLimitSettings::new(
        Some(RateLimitBrokerBarrier {
            limit: RateLimit {
                max_orders,
                // Wide window so every order in the test shares one window.
                window: Duration::from_secs(60),
            },
        }),
        [],
        [],
        [],
    )
    .expect("broker barrier is a valid configuration")
}

fn build_engine(max_orders: usize) -> FullSyncEngine<OrderOperation> {
    let builder = Engine::builder::<OrderOperation, (), ()>().full_sync();
    let policy =
        RateLimitPolicy::<FullLocking>::new(broker_settings(max_orders), builder.storage_builder());
    builder
        .pre_trade(policy)
        .build()
        .expect("engine must build")
}

fn build_local_engine(max_orders: usize) -> LocalEngine<OrderOperation> {
    let builder = Engine::builder::<OrderOperation, (), ()>().no_sync();
    let policy =
        RateLimitPolicy::<NoLocking>::new(broker_settings(max_orders), builder.storage_builder());
    builder
        .pre_trade(policy)
        .build()
        .expect("engine must build")
}

fn build_account_engine(max_orders: usize) -> AccountSyncEngine<OrderOperation> {
    let builder = Engine::builder::<OrderOperation, (), ()>().account_sync();
    let policy = RateLimitPolicy::<AccountLocking>::new(
        broker_settings(max_orders),
        builder.storage_builder(),
    );
    builder
        .pre_trade(policy)
        .build()
        .expect("engine must build")
}

#[test]
fn configure_retunes_live_policy_behavior() {
    let engine = build_engine(5);
    let name = RateLimitPolicy::<FullLocking>::NAME;

    // Generous limit of 5: the first three orders pass (broker count 1..=3).
    for account in 0..3 {
        engine
            .execute_pre_trade(order(account))
            .expect("order within the generous limit must pass");
    }

    // Tighten the broker limit to 2 through the engine. The fourth order
    // (count 4) would have passed under the old limit of 5, so its rejection
    // proves the live policy now reads the new value.
    engine
        .configure()
        .rate_limit::<RateLimitPolicyError>(name, |settings| {
            settings.set_broker(Some(RateLimitBrokerBarrier {
                limit: RateLimit {
                    max_orders: 2,
                    window: Duration::from_secs(60),
                },
            }))
        })
        .expect("retune must publish");

    let rejects = match engine.execute_pre_trade(order(3)) {
        Ok(_) => panic!("order beyond the tightened limit must be rejected"),
        Err(rejects) => rejects,
    };
    assert_eq!(rejects[0].reason, "rate limit exceeded: broker barrier");
}

#[test]
fn configure_rate_limit_retune_does_not_reset_surviving_broker_counter() {
    let engine = build_engine(5);
    let name = RateLimitPolicy::<FullLocking>::NAME;

    engine
        .execute_pre_trade(order(0))
        .expect("first order under initial limit must pass");
    engine
        .execute_pre_trade(order(1))
        .expect("second order under initial limit must pass");

    engine
        .configure()
        .rate_limit::<RateLimitPolicyError>(name, |settings| {
            settings.set_broker(Some(RateLimitBrokerBarrier {
                limit: RateLimit {
                    max_orders: 2,
                    window: Duration::from_secs(60),
                },
            }))
        })
        .expect("retune must publish without replacing the counter");

    let rejects = engine
        .execute_pre_trade(order(2))
        .err()
        .expect("third order in the surviving window must be rejected");
    assert_eq!(rejects[0].reason, "rate limit exceeded: broker barrier");
    assert!(rejects[0].details.contains("submitted 3 orders"));
}

#[test]
fn configure_adds_asset_barrier_at_runtime() {
    // Headline capability: a barrier on a previously-unconfigured axis is
    // added through the engine without a rebuild and enforced immediately.
    let engine = build_engine(100);
    let name = RateLimitPolicy::<FullLocking>::NAME;

    engine
        .configure()
        .rate_limit::<RateLimitPolicyError>(name, |settings| {
            settings.set_asset_barriers([RateLimitAssetBarrier {
                settlement_asset: Asset::new("USD").expect("asset code must be valid"),
                limit: RateLimit {
                    max_orders: 1,
                    window: Duration::from_secs(60),
                },
            }])
        })
        .expect("adding an asset barrier must publish");

    // The new USD barrier admits one order, then rejects the next.
    engine
        .execute_pre_trade(order(0))
        .expect("first USD order under the new barrier must pass");
    let rejects = match engine.execute_pre_trade(order(1)) {
        Ok(_) => panic!("second USD order must breach the new asset barrier"),
        Err(rejects) => rejects,
    };
    assert_eq!(rejects[0].reason, "rate limit exceeded: asset barrier");
}

#[test]
fn configure_unknown_policy_name_is_reported() {
    let engine = build_engine(5);

    let error = engine
        .configure()
        .rate_limit::<RateLimitPolicyError>("does-not-exist", |settings| {
            settings.set_broker(Some(RateLimitBrokerBarrier {
                limit: RateLimit {
                    max_orders: 1,
                    window: Duration::from_secs(60),
                },
            }))
        })
        .expect_err("an unknown policy name must be rejected");
    assert_eq!(
        error,
        ConfigureError::UnknownPolicy {
            name: "does-not-exist".to_owned(),
        }
    );
}

#[test]
fn configure_type_mismatch_is_reported() {
    let engine = build_engine(5);
    let name = RateLimitPolicy::<FullLocking>::NAME;

    // The policy under `name` is a RateLimitPolicy, but `spot_funds` targets
    // SpotFundsSettings, so the downcast must fail with a type mismatch.
    let error = engine
        .configure()
        .spot_funds::<std::convert::Infallible>(name, |_settings| Ok(()))
        .expect_err("a typed method against the wrong settings type must fail");
    assert!(
        matches!(&error, ConfigureError::PolicyTypeMismatch { name: n, .. } if n.as_str() == name),
        "expected PolicyTypeMismatch, got {error:?}"
    );
}

#[test]
fn configure_validation_failure_keeps_prior_value() {
    let engine = build_engine(2);
    let name = RateLimitPolicy::<FullLocking>::NAME;

    // A zero window is rejected by the setter; the update must not publish.
    let error = engine
        .configure()
        .rate_limit::<RateLimitPolicyError>(name, |settings| {
            settings.set_broker(Some(RateLimitBrokerBarrier {
                limit: RateLimit {
                    max_orders: 1_000,
                    window: Duration::ZERO,
                },
            }))
        })
        .expect_err("an invalid window must be rejected");
    assert!(
        matches!(&error, ConfigureError::Validation { name: n, .. } if n.as_str() == name),
        "expected Validation, got {error:?}"
    );

    // The prior limit of 2 still applies: two orders pass, the third is
    // rejected, proving the failed update left the live value intact.
    engine
        .execute_pre_trade(order(0))
        .expect("first order under the retained limit must pass");
    engine
        .execute_pre_trade(order(0))
        .expect("second order under the retained limit must pass");
    assert!(
        engine.execute_pre_trade(order(0)).is_err(),
        "third order must still breach the retained limit of 2"
    );
}

#[test]
fn configurator_send_sync_per_mode() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    // FullSync: shareable across threads.
    assert_send::<Configurator<FullSync>>();
    assert_sync::<Configurator<FullSync>>();
    // AccountSync: movable between threads, not shareable.
    assert_send::<Configurator<AccountSync>>();
}

#[test]
fn built_in_configuration_works_in_every_sync_mode() {
    let local = build_local_engine(5);
    local
        .configure()
        .rate_limit::<RateLimitPolicyError>(RateLimitPolicy::<NoLocking>::NAME, |settings| {
            settings.set_broker(Some(RateLimitBrokerBarrier {
                limit: RateLimit {
                    max_orders: 1,
                    window: Duration::from_secs(60),
                },
            }))
        })
        .expect("LocalSync retune must publish");
    local
        .execute_pre_trade(order(0))
        .expect("first LocalSync order must pass");
    assert!(local.execute_pre_trade(order(1)).is_err());

    let account = build_account_engine(5);
    account
        .configure()
        .rate_limit::<RateLimitPolicyError>(RateLimitPolicy::<AccountLocking>::NAME, |settings| {
            settings.set_broker(Some(RateLimitBrokerBarrier {
                limit: RateLimit {
                    max_orders: 1,
                    window: Duration::from_secs(60),
                },
            }))
        })
        .expect("AccountSync retune must publish");
    account
        .execute_pre_trade(order(0))
        .expect("first AccountSync order must pass");
    assert!(account.execute_pre_trade(order(1)).is_err());

    let full = build_engine(5);
    full.configure()
        .rate_limit::<RateLimitPolicyError>(RateLimitPolicy::<FullLocking>::NAME, |settings| {
            settings.set_broker(Some(RateLimitBrokerBarrier {
                limit: RateLimit {
                    max_orders: 1,
                    window: Duration::from_secs(60),
                },
            }))
        })
        .expect("FullSync retune must publish");
    full.execute_pre_trade(order(0))
        .expect("first FullSync order must pass");
    assert!(full.execute_pre_trade(order(1)).is_err());
}

#[test]
fn nested_configuration_is_rejected_per_engine_without_poisoning_other_engines() {
    let engine = build_engine(5);
    let other = build_engine(5);
    let name = RateLimitPolicy::<FullLocking>::NAME;
    let mut nested_error = None;

    let outer = engine
        .configure()
        .rate_limit::<ConfigureError>(name, |settings| {
            nested_error = Some(
                engine
                    .configure()
                    .rate_limit::<RateLimitPolicyError>(name, |nested_settings| {
                        nested_settings.set_broker(Some(RateLimitBrokerBarrier {
                            limit: RateLimit {
                                max_orders: 1,
                                window: Duration::from_secs(60),
                            },
                        }))
                    })
                    .expect_err("same-engine nested configure must be rejected"),
            );

            other
                .configure()
                .rate_limit::<RateLimitPolicyError>(name, |other_settings| {
                    other_settings.set_broker(Some(RateLimitBrokerBarrier {
                        limit: RateLimit {
                            max_orders: 1,
                            window: Duration::from_secs(60),
                        },
                    }))
                })?;

            settings
                .set_broker(Some(RateLimitBrokerBarrier {
                    limit: RateLimit {
                        max_orders: 2,
                        window: Duration::from_secs(60),
                    },
                }))
                .expect("valid outer retune");
            Ok(())
        });

    assert!(
        matches!(nested_error, Some(ConfigureError::NestedConfiguration)),
        "expected NestedConfiguration, got {nested_error:?}"
    );
    assert!(outer.is_ok(), "outer configure must publish: {outer:?}");
    assert!(
        other.execute_pre_trade(order(0)).is_ok(),
        "first order on other engine must pass"
    );
    assert!(
        other.execute_pre_trade(order(1)).is_err(),
        "other engine retune inside callback must take effect"
    );
}

#[test]
fn configure_dispatches_by_policy_name_in_multi_policy_engine() {
    let builder = Engine::builder::<OrderOperation, (), ()>().full_sync();
    let rate_limit =
        RateLimitPolicy::<FullLocking>::new(broker_settings(100), builder.storage_builder());
    let order_size = OrderSizeLimitPolicy::<FullLocking>::new(
        OrderSizeLimitSettings::new(
            None,
            [OrderSizeAssetBarrier {
                limit: OrderSizeLimit {
                    max_quantity: Quantity::from_str("100")
                        .expect("quantity literal must be valid"),
                    max_notional: Volume::from_str("100000").expect("volume literal must be valid"),
                },
                settlement_asset: Asset::new("USD").expect("asset code must be valid"),
            }],
            [],
        )
        .expect("settings must be valid"),
    );
    let engine = builder
        .pre_trade(rate_limit)
        .pre_trade(order_size)
        .build()
        .expect("engine must build");

    engine
        .configure()
        .order_size_limit::<OrderSizeLimitPolicyError>(
            OrderSizeLimitPolicy::<FullLocking>::NAME,
            |settings| {
                settings.set_asset_barriers([OrderSizeAssetBarrier {
                    limit: OrderSizeLimit {
                        max_quantity: Quantity::from_str("10")
                            .expect("quantity literal must be valid"),
                        max_notional: Volume::from_str("100000")
                            .expect("volume literal must be valid"),
                    },
                    settlement_asset: Asset::new("USD").expect("asset code must be valid"),
                }])
            },
        )
        .expect("order-size retune must dispatch to the named policy");

    let rejects = engine
        .execute_pre_trade(order_with_price(1, "15", "100"))
        .err()
        .expect("order must be rejected by the retuned order-size policy");
    assert_eq!(rejects[0].reason, "order quantity exceeded");

    let mismatch = engine
        .configure()
        .rate_limit::<RateLimitPolicyError>(
            OrderSizeLimitPolicy::<FullLocking>::NAME,
            |_settings| Ok(()),
        )
        .expect_err("same engine must still reject wrong typed dispatch");
    assert!(
        matches!(mismatch, ConfigureError::PolicyTypeMismatch { .. }),
        "expected PolicyTypeMismatch, got {mismatch:?}"
    );
}

#[test]
fn custom_policy_needs_no_configuration_plumbing() {
    Engine::builder::<OrderOperation, (), ()>()
        .no_sync()
        .pre_trade(CustomPolicy)
        .build()
        .expect("custom policy must build without configuration hooks");
}

// ─── P&L-bounds kill-switch ───────────────────────────────────────────────────

// Execution-report type that carries `(instrument, account_id, pnl, fee)`.
// Used only for the P&L-bounds configure tests.
type PnlReport = WithExecutionReportOperation<WithFinancialImpact<()>>;

fn pnl_report(account: u64, settlement: &str, pnl: &str, fee: &str) -> PnlReport {
    WithExecutionReportOperation {
        inner: WithFinancialImpact {
            inner: (),
            financial_impact: FinancialImpact {
                pnl: Pnl::from_str(pnl).expect("pnl literal must be valid"),
                fee: Fee::from_str(fee).expect("fee literal must be valid"),
            },
        },
        operation: ExecutionReportOperation {
            instrument: Instrument::new(
                Asset::new("AAPL").expect("asset code must be valid"),
                Asset::new(settlement).expect("asset code must be valid"),
            ),
            account_id: AccountId::from_u64(account),
            side: Side::Buy,
        },
    }
}

fn build_pnl_engine(
    account_barriers: impl IntoIterator<Item = PnlBoundsAccountAssetBarrier>,
) -> FullSyncEngine<OrderOperation, PnlReport> {
    let builder = Engine::builder::<OrderOperation, PnlReport, ()>().full_sync();
    let settings =
        PnlBoundsKillSwitchSettings::new([], account_barriers).expect("settings must be valid");
    let policy = PnlBoundsKillSwitchPolicy::<FullLocking>::new(settings, builder.storage_builder());
    builder
        .pre_trade(policy)
        .build()
        .expect("engine must build")
}

// Adds a broker barrier via configure and asserts an order that was passing
// before is now rejected with the verbatim broker-axis reason.
// The accumulation is seeded BEFORE the barrier is installed so that
// `apply_execution_report` does not trigger an account block (which would
// mask the pre-trade reject reason with "account blocked").
#[test]
fn configure_pnl_bounds_broker_barrier_added_at_runtime_triggers_reject() {
    // Start with an account+asset barrier on account 2 to satisfy the
    // constructor's "at least one barrier" requirement, while account 1 has no
    // coverage and its orders pass freely.
    let engine = build_pnl_engine([PnlBoundsAccountAssetBarrier {
        barrier: PnlBoundsBrokerBarrier {
            settlement_asset: Asset::new("USD").expect("asset code must be valid"),
            lower_bound: Some(Pnl::from_str("-500").expect("pnl literal must be valid")),
            upper_bound: None,
        },
        account_id: AccountId::from_u64(2),
        initial_pnl: Pnl::ZERO,
    }]);
    let name = PnlBoundsKillSwitchPolicy::<FullLocking>::NAME;

    // Accumulate a loss for account 1 while no broker barrier is present.
    // apply_execution_report sees no barrier for (account 1, USD) and stores
    // the running total without issuing an AccountBlock.
    engine.apply_execution_report(&pnl_report(1, "USD", "-10", "0"));

    // Account 1 order still passes before the broker barrier is installed.
    engine
        .execute_pre_trade(order(1))
        .expect("order with no barrier must pass before configure");

    // Add a broker barrier on USD whose lower bound is already breached by
    // the accumulated -10.
    engine
        .configure()
        .pnl_bounds_killswitch::<PnlBoundsKillSwitchPolicyError>(name, |settings| {
            settings.set_broker_barriers([PnlBoundsBrokerBarrier {
                settlement_asset: Asset::new("USD").expect("asset code must be valid"),
                lower_bound: Some(Pnl::from_str("-1").expect("pnl literal must be valid")),
                upper_bound: None,
            }])
        })
        .expect("adding broker barrier must publish");

    // The pre-trade check now sees the broker barrier and the accumulated -10
    // breaches lower bound -1 → reject with the verbatim broker-axis reason.
    let rejects = engine
        .execute_pre_trade(order(1))
        .err()
        .expect("order past broker barrier must be rejected");
    assert_eq!(
        rejects[0].reason,
        "pnl kill switch triggered: broker barrier"
    );
}

#[test]
fn configure_pnl_bounds_pre_barrier_accumulation_seen_by_new_account_asset_barrier() {
    let engine = build_pnl_engine([PnlBoundsAccountAssetBarrier {
        barrier: PnlBoundsBrokerBarrier {
            settlement_asset: Asset::new("USD").expect("asset code must be valid"),
            lower_bound: Some(Pnl::from_str("-500").expect("pnl literal must be valid")),
            upper_bound: None,
        },
        account_id: AccountId::from_u64(2),
        initial_pnl: Pnl::ZERO,
    }]);
    let name = PnlBoundsKillSwitchPolicy::<FullLocking>::NAME;

    engine.apply_execution_report(&pnl_report(1, "USD", "-80", "0"));
    engine.apply_execution_report(&pnl_report(1, "USD", "-40", "0"));
    engine
        .execute_pre_trade(order(1))
        .expect("no barrier yet: order must pass");

    engine
        .configure()
        .pnl_bounds_killswitch::<PnlBoundsKillSwitchPolicyError>(name, |settings| {
            settings.set_account_barriers([
                PnlBoundsAccountAssetBarrierUpdate {
                    barrier: PnlBoundsBrokerBarrier {
                        settlement_asset: Asset::new("USD").expect("asset code must be valid"),
                        lower_bound: Some(
                            Pnl::from_str("-500").expect("pnl literal must be valid"),
                        ),
                        upper_bound: None,
                    },
                    account_id: AccountId::from_u64(2),
                },
                PnlBoundsAccountAssetBarrierUpdate {
                    barrier: PnlBoundsBrokerBarrier {
                        settlement_asset: Asset::new("USD").expect("asset code must be valid"),
                        lower_bound: Some(
                            Pnl::from_str("-100").expect("pnl literal must be valid"),
                        ),
                        upper_bound: None,
                    },
                    account_id: AccountId::from_u64(1),
                },
            ])
        })
        .expect("barrier add must publish");

    let rejects = engine
        .execute_pre_trade(order(1))
        .err()
        .expect("order must be rejected by the newly-configured barrier");
    assert_eq!(
        rejects[0].reason,
        "pnl kill switch triggered: account + asset barrier"
    );
}

// `set_account_pnl` force-sets the live accumulator through the engine, and the
// override is observed on the next hot-path check: forcing one account past the
// bound rejects its next order, while forcing a different (never-breached)
// account to a value inside the bound lets its order pass. This is the
// deliberate force-set path, separate from the bounds retune above.
//
// The two directions use different accounts on purpose: a P&L-bounds breach is
// a kill switch, so once account 1's order is rejected the engine latches the
// account-level block. Force-setting the ledger back inside the bound does not
// clear that latch (only an explicit admin unblock does), so the "inside the
// bound passes" direction is exercised on account 2, which was never latched.
#[test]
fn configure_set_account_pnl_overrides_accumulated_pnl() {
    let engine = build_pnl_engine([
        PnlBoundsAccountAssetBarrier {
            barrier: PnlBoundsBrokerBarrier {
                settlement_asset: Asset::new("USD").expect("asset code must be valid"),
                lower_bound: Some(Pnl::from_str("-100").expect("pnl literal must be valid")),
                upper_bound: None,
            },
            account_id: AccountId::from_u64(1),
            initial_pnl: Pnl::ZERO,
        },
        PnlBoundsAccountAssetBarrier {
            barrier: PnlBoundsBrokerBarrier {
                settlement_asset: Asset::new("USD").expect("asset code must be valid"),
                lower_bound: Some(Pnl::from_str("-100").expect("pnl literal must be valid")),
                upper_bound: None,
            },
            account_id: AccountId::from_u64(2),
            initial_pnl: Pnl::ZERO,
        },
    ]);
    let name = PnlBoundsKillSwitchPolicy::<FullLocking>::NAME;
    let usd = Asset::new("USD").expect("asset code must be valid");

    // Zero accumulated P&L is within [-100, ∞): the order passes.
    engine
        .execute_pre_trade(order(1))
        .expect("order must pass at zero P&L")
        .rollback();

    // Force account 1's accumulator below the lower bound; its next order is
    // rejected and the engine latches the account-level block.
    engine
        .configure()
        .set_account_pnl(
            name,
            AccountId::from_u64(1),
            usd.clone(),
            Pnl::from_str("-150").expect("pnl literal must be valid"),
        )
        .expect("force-set must publish");
    let rejects = engine
        .execute_pre_trade(order(1))
        .err()
        .expect("order must be rejected after the override breaches the bound");
    assert_eq!(
        rejects[0].reason,
        "pnl kill switch triggered: account + asset barrier"
    );

    // Force account 2's accumulator inside the bound; its order passes, proving
    // the override is observed in the passing direction too.
    engine
        .configure()
        .set_account_pnl(
            name,
            AccountId::from_u64(2),
            usd,
            Pnl::from_str("-10").expect("pnl literal must be valid"),
        )
        .expect("force-set inside bounds must publish");
    engine
        .execute_pre_trade(order(2))
        .expect("order must pass after the accumulator is set inside bounds")
        .rollback();
}

// `set_account_pnl` creates the entry on demand for a previously-untracked
// `(account, settlement_asset)` pair, mirroring the construction-time seed.
#[test]
fn configure_set_account_pnl_creates_absent_entry() {
    let engine = build_pnl_engine([PnlBoundsAccountAssetBarrier {
        barrier: PnlBoundsBrokerBarrier {
            settlement_asset: Asset::new("USD").expect("asset code must be valid"),
            lower_bound: Some(Pnl::from_str("-100").expect("pnl literal must be valid")),
            upper_bound: None,
        },
        account_id: AccountId::from_u64(2),
        initial_pnl: Pnl::ZERO,
    }]);
    let name = PnlBoundsKillSwitchPolicy::<FullLocking>::NAME;

    // Account 2 has never traded and has no stored entry; force it past the
    // bound and the next order is rejected, proving the upsert created it.
    engine
        .configure()
        .set_account_pnl(
            name,
            AccountId::from_u64(2),
            Asset::new("USD").expect("asset code must be valid"),
            Pnl::from_str("-150").expect("pnl literal must be valid"),
        )
        .expect("force-set on an absent entry must publish");
    let rejects = engine
        .execute_pre_trade(order(2))
        .err()
        .expect("order must be rejected after the created entry breaches the bound");
    assert_eq!(
        rejects[0].reason,
        "pnl kill switch triggered: account + asset barrier"
    );
}

#[test]
fn configure_set_account_pnl_unknown_policy_name_is_reported() {
    let engine = build_pnl_engine([PnlBoundsAccountAssetBarrier {
        barrier: PnlBoundsBrokerBarrier {
            settlement_asset: Asset::new("USD").expect("asset code must be valid"),
            lower_bound: Some(Pnl::from_str("-100").expect("pnl literal must be valid")),
            upper_bound: None,
        },
        account_id: AccountId::from_u64(1),
        initial_pnl: Pnl::ZERO,
    }]);

    let error = engine
        .configure()
        .set_account_pnl(
            "does-not-exist",
            AccountId::from_u64(1),
            Asset::new("USD").expect("asset code must be valid"),
            Pnl::ZERO,
        )
        .expect_err("an unknown policy name must be rejected");
    assert_eq!(
        error,
        ConfigureError::UnknownPolicy {
            name: "does-not-exist".to_owned(),
        }
    );
}

#[test]
fn configure_set_account_pnl_type_mismatch_is_reported() {
    // The engine here carries a RateLimitPolicy, so targeting its name with the
    // P&L force-set must fail with a type mismatch.
    let engine = build_engine(5);
    let name = RateLimitPolicy::<FullLocking>::NAME;

    let error = engine
        .configure()
        .set_account_pnl(
            name,
            AccountId::from_u64(1),
            Asset::new("USD").expect("asset code must be valid"),
            Pnl::ZERO,
        )
        .expect_err("targeting the wrong policy type must fail");
    assert!(
        matches!(&error, ConfigureError::PolicyTypeMismatch { name: n, .. } if n.as_str() == name),
        "expected PolicyTypeMismatch, got {error:?}"
    );
}

// ─── Order-size-limit ─────────────────────────────────────────────────────────

fn order_with_price(account: u64, quantity: &str, price: &str) -> OrderOperation {
    OrderOperation {
        instrument: Instrument::new(
            Asset::new("AAPL").expect("asset code must be valid"),
            Asset::new("USD").expect("asset code must be valid"),
        ),
        account_id: AccountId::from_u64(account),
        side: Side::Buy,
        trade_amount: TradeAmount::Quantity(
            Quantity::from_str(quantity).expect("quantity literal must be valid"),
        ),
        price: Some(Price::from_str(price).expect("price literal must be valid")),
    }
}

fn build_order_size_engine(
    account_id: u64,
    max_quantity: &str,
    max_notional: &str,
) -> FullSyncEngine<OrderOperation> {
    let builder = Engine::builder::<OrderOperation, (), ()>().full_sync();
    let settings = OrderSizeLimitSettings::new(
        None,
        [],
        [OrderSizeAccountAssetBarrier {
            limit: OrderSizeLimit {
                max_quantity: Quantity::from_str(max_quantity)
                    .expect("max_quantity literal must be valid"),
                max_notional: Volume::from_str(max_notional)
                    .expect("max_notional literal must be valid"),
            },
            account_id: AccountId::from_u64(account_id),
            settlement_asset: Asset::new("USD").expect("asset code must be valid"),
        }],
    )
    .expect("settings must be valid");
    let policy = OrderSizeLimitPolicy::<FullLocking>::new(settings);
    builder
        .pre_trade(policy)
        .build()
        .expect("engine must build")
}

// Tighten the account+asset barrier for account 1 via configure.  An order
// that the generous initial limit admitted is rejected under the tightened one.
// The broker axis is absent so only the account+asset axis triggers.
#[test]
fn configure_order_size_limit_account_asset_barrier_tightened_rejects_previously_admitted_order() {
    let engine = build_order_size_engine(1, "20", "100000");
    let name = OrderSizeLimitPolicy::<FullLocking>::NAME;

    // qty=15 is within the generous limit of 20: passes.
    engine
        .execute_pre_trade(order_with_price(1, "15", "100"))
        .expect("order within the generous limit must pass");

    // Tighten the account+asset barrier for account 1 to qty=10 via configure.
    engine
        .configure()
        .order_size_limit::<OrderSizeLimitPolicyError>(name, |settings| {
            settings.set_account_asset_barriers([OrderSizeAccountAssetBarrier {
                limit: OrderSizeLimit {
                    max_quantity: Quantity::from_str("10")
                        .expect("max_quantity literal must be valid"),
                    max_notional: Volume::from_str("100000")
                        .expect("max_notional literal must be valid"),
                },
                account_id: AccountId::from_u64(1),
                settlement_asset: Asset::new("USD").expect("asset code must be valid"),
            }])
        })
        .expect("tightening barrier must publish");

    // qty=15 now exceeds the tightened limit of 10.
    let rejects = engine
        .execute_pre_trade(order_with_price(1, "15", "100"))
        .err()
        .expect("order beyond the tightened limit must be rejected");
    assert_eq!(rejects[0].reason, "order quantity exceeded");
    assert!(rejects[0].details.contains("max allowed: 10"));

    // Account 2 has no account+asset barrier and no broker barrier: passes.
    engine
        .execute_pre_trade(order_with_price(2, "15", "100"))
        .expect("account 2 with no barrier must still pass");
}

#[test]
fn configure_order_size_limit_broker_barrier_added_rejects_all_accounts() {
    let engine = build_order_size_engine(1, "100", "100000");
    let name = OrderSizeLimitPolicy::<FullLocking>::NAME;

    engine
        .execute_pre_trade(order_with_price(2, "15", "100"))
        .expect("account without account+asset barrier must pass before broker limit");

    engine
        .configure()
        .order_size_limit::<OrderSizeLimitPolicyError>(name, |settings| {
            settings.set_broker(Some(OrderSizeBrokerBarrier {
                limit: OrderSizeLimit {
                    max_quantity: Quantity::from_str("10")
                        .expect("max_quantity literal must be valid"),
                    max_notional: Volume::from_str("100000")
                        .expect("max_notional literal must be valid"),
                },
            }))
        })
        .expect("broker barrier add must publish");

    let rejects = engine
        .execute_pre_trade(order_with_price(2, "15", "100"))
        .err()
        .expect("broker limit must reject every account");
    assert_eq!(rejects[0].reason, "order quantity exceeded");
}

#[test]
fn configure_order_size_limit_asset_barrier_added_rejects_matching_settlement() {
    let engine = build_order_size_engine(1, "100", "100000");
    let name = OrderSizeLimitPolicy::<FullLocking>::NAME;

    engine
        .execute_pre_trade(order_with_price(2, "15", "100"))
        .expect("account without account+asset barrier must pass before asset limit");

    engine
        .configure()
        .order_size_limit::<OrderSizeLimitPolicyError>(name, |settings| {
            settings.set_asset_barriers([OrderSizeAssetBarrier {
                limit: OrderSizeLimit {
                    max_quantity: Quantity::from_str("10")
                        .expect("max_quantity literal must be valid"),
                    max_notional: Volume::from_str("100000")
                        .expect("max_notional literal must be valid"),
                },
                settlement_asset: Asset::new("USD").expect("asset code must be valid"),
            }])
        })
        .expect("asset barrier add must publish");

    let rejects = engine
        .execute_pre_trade(order_with_price(2, "15", "100"))
        .err()
        .expect("USD asset limit must reject matching settlement");
    assert_eq!(rejects[0].reason, "order quantity exceeded");
}

// ─── Spot funds ───────────────────────────────────────────────────────────────

// Minimal account-adjustment stub for SpotFunds seeding.
struct SpotAdjustment {
    asset: Asset,
    balance: Option<AdjustmentAmount>,
    balance_average_entry_price: Option<Price>,
    balance_realized_pnl: Option<Pnl>,
}

impl HasBalanceAsset for SpotAdjustment {
    fn balance_asset(&self) -> Result<&Asset, RequestFieldAccessError> {
        Ok(&self.asset)
    }
}

impl HasAccountAdjustmentBalance for SpotAdjustment {
    fn balance(&self) -> Result<Option<AdjustmentAmount>, RequestFieldAccessError> {
        Ok(self.balance)
    }
}

impl HasAccountAdjustmentBalanceAverageEntryPrice for SpotAdjustment {
    fn balance_average_entry_price(&self) -> Result<Option<Price>, RequestFieldAccessError> {
        Ok(self.balance_average_entry_price)
    }
}

impl HasAccountAdjustmentBalanceRealizedPnl for SpotAdjustment {
    fn balance_realized_pnl(&self) -> Result<Option<Pnl>, RequestFieldAccessError> {
        Ok(self.balance_realized_pnl)
    }
}

impl HasAccountAdjustmentBalanceLowerBound for SpotAdjustment {
    fn balance_lower(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(None)
    }
}

impl HasAccountAdjustmentBalanceUpperBound for SpotAdjustment {
    fn balance_upper(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(None)
    }
}

impl HasAccountAdjustmentHeld for SpotAdjustment {
    fn held(&self) -> Result<Option<AdjustmentAmount>, RequestFieldAccessError> {
        Ok(None)
    }
}

impl HasAccountAdjustmentHeldLowerBound for SpotAdjustment {
    fn held_lower(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(None)
    }
}

impl HasAccountAdjustmentHeldUpperBound for SpotAdjustment {
    fn held_upper(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(None)
    }
}

impl HasAccountAdjustmentIncoming for SpotAdjustment {
    fn incoming(&self) -> Result<Option<AdjustmentAmount>, RequestFieldAccessError> {
        Ok(None)
    }
}

impl HasAccountAdjustmentIncomingLowerBound for SpotAdjustment {
    fn incoming_lower(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(None)
    }
}

impl HasAccountAdjustmentIncomingUpperBound for SpotAdjustment {
    fn incoming_upper(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(None)
    }
}

fn spot_balance(asset_code: &str, amount: &str) -> SpotAdjustment {
    SpotAdjustment {
        asset: Asset::new(asset_code).expect("asset code must be valid"),
        balance: Some(AdjustmentAmount::Absolute(
            PositionSize::from_str(amount).expect("position size literal must be valid"),
        )),
        balance_average_entry_price: None,
        balance_realized_pnl: None,
    }
}

type SpotReport = WithExecutionReportOperation<WithExecutionReportFillDetails<()>>;
type SpotEngine = FullSyncEngine<OrderOperation, SpotReport, SpotAdjustment>;

fn build_spot_engine(slippage_bps: u16) -> SpotEngine {
    let builder = Engine::builder::<OrderOperation, SpotReport, SpotAdjustment>().full_sync();
    let settings = SpotFundsSettings::new(slippage_bps, SpotFundsPricingSource::Mark, [])
        .expect("settings must be valid");
    let policy = SpotFundsPolicy::<FullSync, FullSync>::new(
        settings,
        None::<SpotFundsMarketData<FullSync>>,
        builder.storage_builder(),
    );
    builder
        .pre_trade(policy)
        .build()
        .expect("engine must build")
}

fn build_spot_market_engine(slippage_bps: u16, mark: &str) -> (SpotEngine, InstrumentId) {
    let builder = Engine::builder::<OrderOperation, SpotReport, SpotAdjustment>().full_sync();
    let service = MarketDataBuilder::<FullSync>::new(QuoteTtl::Infinite).build();
    let instrument = Instrument::new(
        Asset::new("AAPL").expect("asset code must be valid"),
        Asset::new("USD").expect("asset code must be valid"),
    );
    let instrument_id = service
        .register(instrument)
        .expect("instrument registration must succeed");
    service
        .push(
            instrument_id,
            Quote::new().with_mark(Price::from_str(mark).expect("price literal must be valid")),
        )
        .expect("quote push must succeed");
    let settings = SpotFundsSettings::new(slippage_bps, SpotFundsPricingSource::Mark, [])
        .expect("settings must be valid");
    let policy = SpotFundsPolicy::<FullSync, FullSync>::new(
        settings,
        Some(SpotFundsMarketData::new(Arc::clone(&service))),
        builder.storage_builder(),
    );
    let engine = builder
        .pre_trade(policy)
        .build()
        .expect("engine must build");
    (engine, instrument_id)
}

fn seed_spot(engine: &SpotEngine, account: u64, asset_code: &str, amount: &str) {
    let adj = spot_balance(asset_code, amount);
    engine
        .apply_account_adjustment(AccountId::from_u64(account), &[adj])
        .expect("seed must succeed");
}

fn assert_market_buy_locks_price(engine: &SpotEngine, account: u64, expected: &str) {
    let mut reservation = engine
        .execute_pre_trade(order(account))
        .expect("market buy must pass with seeded funds");
    let lock_price = reservation
        .lock()
        .prices_of(DEFAULT_POLICY_GROUP_ID)
        .next()
        .expect("market buy must record a lock price");
    reservation.rollback();
    assert_eq!(
        lock_price,
        Price::from_str(expected).expect("price literal must be valid")
    );
}

// Build a SpotFunds engine, seed a balance, confirm a limit order passes, then
// retune the settings via configure (changing the pricing source, which is
// observable via the settings cell update path) and confirm that:
// 1. The configure call succeeds, proving the cell is properly wired.
// 2. A subsequent limit order with sufficient balance still passes, proving
//    the live policy reads from the updated cell without corruption.
// 3. A validation rejection from configure (out-of-range slippage) leaves
//    the engine functional.
#[test]
fn configure_spot_funds_settings_retune_takes_effect() {
    let engine = build_spot_engine(0);
    let name = SpotFundsPolicy::<FullSync, FullSync>::NAME;
    let account_id = 1u64;

    // Seed 1000 USD for account 1.
    seed_spot(&engine, account_id, "USD", "1000");

    // A limit buy of 5 AAPL @ 100 USD (cost = 500 USD) must pass.
    engine
        .execute_pre_trade(order_with_price(account_id, "5", "100"))
        .expect("order within funded balance must pass")
        .rollback();

    // Retune: change the pricing source to BookTop. The engine must accept
    // the update without error and without resetting holdings.
    engine
        .configure()
        .spot_funds::<SpotFundsConfigError>(name, |settings| {
            settings.set_pricing_source(SpotFundsPricingSource::BookTop);
            Ok(())
        })
        .expect("pricing-source retune must publish");

    // After the retune the limit order (unaffected by pricing source) still
    // passes — the holdings were not touched by the settings update.
    engine
        .execute_pre_trade(order_with_price(account_id, "5", "100"))
        .expect("limit order must pass after pricing-source retune")
        .rollback();

    // A validation failure (out-of-range slippage) must not corrupt the cell.
    let validation_err = engine
        .configure()
        .spot_funds::<SpotFundsConfigError>(name, |settings| {
            settings.set_global_slippage_bps(20_000)
        })
        .expect_err("out-of-range slippage must be rejected");
    assert!(
        matches!(&validation_err, ConfigureError::Validation { .. }),
        "expected Validation error, got {validation_err:?}"
    );

    // Engine must still be functional after the failed retune.
    engine
        .execute_pre_trade(order_with_price(account_id, "5", "100"))
        .expect("engine must remain functional after failed retune")
        .rollback();
}

#[test]
fn configure_spot_funds_global_slippage_retune_changes_market_lock_price() {
    let (engine, _instrument_id) = build_spot_market_engine(0, "100");
    let name = SpotFundsPolicy::<FullSync, FullSync>::NAME;
    let account_id = 1u64;
    seed_spot(&engine, account_id, "USD", "1000");

    assert_market_buy_locks_price(&engine, account_id, "100");

    engine
        .configure()
        .spot_funds::<SpotFundsConfigError>(name, |settings| settings.set_global_slippage_bps(1000))
        .expect("global slippage retune must publish");

    assert_market_buy_locks_price(&engine, account_id, "110");
}

#[test]
fn configure_spot_funds_override_retune_changes_market_lock_price() {
    let (engine, instrument_id) = build_spot_market_engine(0, "100");
    let name = SpotFundsPolicy::<FullSync, FullSync>::NAME;
    let account_id = 1u64;
    seed_spot(&engine, account_id, "USD", "1000");

    assert_market_buy_locks_price(&engine, account_id, "100");

    engine
        .configure()
        .spot_funds::<SpotFundsConfigError>(name, |settings| {
            settings.set_override(
                SpotFundsOverrideTarget::Instrument(instrument_id),
                SpotFundsOverride {
                    slippage_bps: Some(2500),
                },
            )
        })
        .expect("instrument override retune must publish");

    assert_market_buy_locks_price(&engine, account_id, "125");
}