longtrader-worker 0.2.1

Local strategy host running portable strategies against pluggable backends (exchange daemon / terminal API / mock)
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
//! Strategy registry (single owner for construction dispatch).
//!
//! Extracted from `strategies::mod`: adding a strategy means appending one
//! entry here — no string dispatch elsewhere (open/closed).
//!
//! The registry is the single owner: it is a `OnceLock`-initialized static
//! table built once on first access. Adding a strategy means appending one
//! entry to the `vec!` below; there is intentionally no dynamic `register()`
//! API so construction stays auditable in one place.

use std::sync::{Arc, OnceLock};

use color_eyre::Result;

use super::{
    Strategy, adx_trend, amm_arb, apt_mm, autoborrow, avellaneda_mm_v2, balance_align, basis_mm,
    bb_keltner_squeeze, boll_grid, bollinger_v2, convert, cross_depth_maker, cross_exchange_mm,
    cross_fixed_maker, cross_maker, cvd_divergence, darvas_box, dca_executor, dca_scheduler,
    deposit_transfer, dman_v3, dual_thrust, ema_cross, fixed_maker, glft_mm, grid_strike, hedge,
    hedge_grid, ichimoku, irr, liquidity_mining, macd_bb, market_cap, mean_reversion,
    momentum_factor, nav_recorder, obi_mm, params::params_from_table, perpetual_mm, pmm_dynamic,
    premium_monitor, pure_market_making, queue_mm, random_entry, rebalance, sentinel, simple_grid,
    simplified_glft_mm, skewed_grid, spot_perp_arb, stat_arb, supertrend, twap_executor,
    vwap_executor, xfunding_lite,
};
use crate::{
    config::Config,
    ports::{
        FundingRateSource, MarketDataSource, TradingGateway, TriggerOrderGateway, VenueOpInvoker,
        WalletGateway,
    },
};

/// Ports a strategy may consume. All are sourced from one backend adapter,
/// keeping a single backend connection per session.
pub struct StrategyContext {
    pub config: Config,
    pub gateway: Arc<dyn TradingGateway>,
    pub market: Arc<dyn MarketDataSource>,
    pub funding: Arc<dyn FundingRateSource>,
    pub triggers: Arc<dyn TriggerOrderGateway>,
    pub ops: Arc<dyn VenueOpInvoker>,
    pub wallet: Arc<dyn WalletGateway>,
}

/// Builds a strategy from its [`StrategyContext`]. Pure function of the config
/// plus ports; never touches global state.
pub type StrategyFactory = fn(&StrategyContext) -> Result<Box<dyn Strategy>>;

/// Self-describing registration record for one strategy.
pub struct StrategyDescriptor {
    pub name: &'static str,
    pub factory: StrategyFactory,
}

static REGISTRY: OnceLock<Vec<StrategyDescriptor>> = OnceLock::new();

/// Builds the DCA scheduler — the single factory behind both `dca_scheduler`
/// and its historical alias `dca`.
///
/// One function, not one closure per name: two copies of the same construction
/// could drift, and the alias exists precisely so old configs keep behaving
/// identically.
fn build_dca_scheduler(ctx: &StrategyContext) -> Result<Box<dyn Strategy>> {
    let cfg = dca_scheduler::DcaSchedulerConfig::from_params(ctx.config.strategy.params.table())?;
    Ok(Box::new(dca_scheduler::DcaScheduler::new(cfg, ctx.gateway.clone())))
}

/// All known strategies. Order is irrelevant; lookup is by `name`.
///
/// Uses `OnceLock` for lazy initialization. The registry is initialized once
/// on first access and reused thereafter.
pub fn registry() -> &'static [StrategyDescriptor] {
    REGISTRY.get_or_init(|| {
        vec![
            StrategyDescriptor {
                name: "simple_grid",
                factory: |ctx| {
                    let cfg = simple_grid::SimpleGridConfig::from_config(&ctx.config)?;
                    Ok(Box::new(simple_grid::SimpleGrid::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "adx_trend",
                factory: |ctx| {
                    let cfg =
                        adx_trend::AdxTrendConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(adx_trend::AdxTrend::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "bb_keltner_squeeze",
                factory: |ctx| {
                    let cfg = bb_keltner_squeeze::BbKeltnerSqueezeConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(bb_keltner_squeeze::BbKeltnerSqueeze::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "cvd_divergence",
                factory: |ctx| {
                    let cfg = cvd_divergence::CvdDivergenceConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(cvd_divergence::CvdDivergence::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "darvas_box",
                factory: |ctx| {
                    let cfg = darvas_box::DarvasBoxConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(darvas_box::DarvasBox::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "dual_thrust",
                factory: |ctx| {
                    let cfg = dual_thrust::DualThrustConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(dual_thrust::DualThrust::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "ichimoku",
                factory: |ctx| {
                    let cfg =
                        ichimoku::IchimokuConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(ichimoku::Ichimoku::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "mean_reversion",
                factory: |ctx| {
                    let cfg = mean_reversion::MeanReversionConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(mean_reversion::MeanReversion::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "momentum_factor",
                factory: |ctx| {
                    let cfg = momentum_factor::MomentumFactorConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(momentum_factor::MomentumFactor::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "ema_cross",
                factory: |ctx| {
                    let cfg =
                        ema_cross::EmaCrossConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(ema_cross::EmaCross::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "supertrend",
                factory: |ctx| {
                    let cfg = supertrend::SupertrendConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(supertrend::Supertrend::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "boll_grid",
                factory: |ctx| {
                    let cfg =
                        boll_grid::BollGridConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(boll_grid::BollGrid::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor { name: "dca_scheduler", factory: build_dca_scheduler },
            // `dca` is the historical alias of `dca_scheduler`: same factory,
            // kept so existing configs keep working. The behavioral test
            // `the_dca_alias_behaves_identically_to_dca_scheduler` pins the
            // equivalence; the alias shares the factory function above rather
            // than carrying a second copy of it.
            StrategyDescriptor { name: "dca", factory: build_dca_scheduler },
            StrategyDescriptor {
                name: "fixed_maker",
                factory: |ctx| {
                    let cfg = fixed_maker::FixedMakerConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(fixed_maker::FixedMaker::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "random_entry",
                factory: |ctx| {
                    let cfg = random_entry::RandomEntryConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(random_entry::RandomEntry::new(cfg, ctx.gateway.clone())))
                },
            },
            StrategyDescriptor {
                name: "xfunding_lite",
                factory: |ctx| {
                    let cfg = xfunding_lite::XfundingLiteConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(xfunding_lite::XfundingLite::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.funding.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "sentinel",
                factory: |ctx| {
                    let cfg =
                        sentinel::SentinelConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(sentinel::Sentinel::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "autoborrow",
                factory: |ctx| {
                    let cfg = autoborrow::AutoborrowConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(autoborrow::Autoborrow::new(cfg, ctx.ops.clone())))
                },
            },
            StrategyDescriptor {
                name: "convert",
                factory: |ctx| {
                    let cfg =
                        convert::ConvertConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(convert::Convert::new(cfg, ctx.ops.clone())))
                },
            },
            StrategyDescriptor {
                name: "deposit_transfer",
                factory: |ctx| {
                    let cfg = deposit_transfer::DepositTransferConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(deposit_transfer::DepositTransfer::new(cfg, ctx.wallet.clone())))
                },
            },
            StrategyDescriptor {
                name: "cross_fixed_maker",
                factory: |ctx| {
                    let cfg = params_from_table(ctx.config.strategy.params.table())?;
                    Ok(Box::new(cross_fixed_maker::CrossFixedMaker::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "cross_depth_maker",
                factory: |ctx| {
                    let cfg = params_from_table(ctx.config.strategy.params.table())?;
                    Ok(Box::new(cross_depth_maker::CrossDepthMaker::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "cross_maker",
                factory: |ctx| {
                    let cfg = params_from_table(ctx.config.strategy.params.table())?;
                    Ok(Box::new(cross_maker::CrossMaker::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "hedge_grid",
                factory: |ctx| {
                    let cfg = params_from_table(ctx.config.strategy.params.table())?;
                    Ok(Box::new(hedge_grid::HedgeGrid::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "balance_align",
                factory: |ctx| {
                    let cfg = params_from_table(ctx.config.strategy.params.table())?;
                    Ok(Box::new(balance_align::BalanceAlign::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.wallet.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "premium_monitor",
                factory: |ctx| {
                    let cfg: premium_monitor::PremiumMonitorConfig =
                        params_from_table(ctx.config.strategy.params.table())?;
                    Ok(Box::new(premium_monitor::PremiumMonitor::new(cfg, ctx.market.clone())))
                },
            },
            StrategyDescriptor {
                name: "nav_recorder",
                factory: |ctx| {
                    let cfg = nav_recorder::NavRecorderConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(nav_recorder::NavRecorder::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "rebalance",
                factory: |ctx| {
                    let cfg = rebalance::RebalanceConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(rebalance::Rebalance::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "market_cap",
                factory: |ctx| {
                    let cfg = market_cap::MarketCapConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(market_cap::MarketCap::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "irr",
                factory: |ctx| {
                    let cfg = irr::IrrConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(irr::Irr::new(cfg, ctx.gateway.clone())))
                },
            },
            StrategyDescriptor {
                name: "skewed_grid",
                factory: |ctx| {
                    let cfg = skewed_grid::SkewedGridConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(skewed_grid::SkewedGrid::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "obi_mm",
                factory: |ctx| {
                    let cfg = obi_mm::ObiMmConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(obi_mm::ObiMm::new(cfg, ctx.gateway.clone(), ctx.market.clone())))
                },
            },
            StrategyDescriptor {
                name: "basis_mm",
                factory: |ctx| {
                    let cfg =
                        basis_mm::BasisMmConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(basis_mm::BasisMm::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "apt_mm",
                factory: |ctx| {
                    let cfg = apt_mm::AptMmConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(apt_mm::AptMm::new(cfg, ctx.gateway.clone(), ctx.market.clone())))
                },
            },
            StrategyDescriptor {
                name: "queue_mm",
                factory: |ctx| {
                    let cfg =
                        queue_mm::QueueMmConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(queue_mm::QueueMm::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "glft_mm",
                factory: |ctx| {
                    let cfg =
                        glft_mm::GlftMmConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(glft_mm::GlftMm::new(cfg, ctx.gateway.clone(), ctx.market.clone())))
                },
            },
            StrategyDescriptor {
                name: "simplified_glft_mm",
                factory: |ctx| {
                    let cfg = simplified_glft_mm::SimplifiedGlftMmConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(simplified_glft_mm::SimplifiedGlftMm::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "pure_market_making",
                factory: |ctx| {
                    let cfg = pure_market_making::PmmConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(pure_market_making::Pmm::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "avellaneda_mm_v2",
                factory: |ctx| {
                    let cfg = avellaneda_mm_v2::AvellanedaMmV2Config::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(avellaneda_mm_v2::AvellanedaMmV2::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "perpetual_mm",
                factory: |ctx| {
                    let cfg = perpetual_mm::PerpMmConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(perpetual_mm::PerpMm::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                        ctx.funding.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "cross_exchange_mm",
                factory: |ctx| {
                    let cfg = params_from_table(ctx.config.strategy.params.table())?;
                    Ok(Box::new(cross_exchange_mm::Xemm::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "amm_arb",
                factory: |ctx| {
                    let cfg =
                        amm_arb::AmmArbConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(amm_arb::AmmArb::new(cfg, ctx.gateway.clone(), ctx.market.clone())))
                },
            },
            StrategyDescriptor {
                name: "spot_perp_arb",
                factory: |ctx| {
                    let cfg = spot_perp_arb::SpotPerpArbConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(spot_perp_arb::SpotPerpArb::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "hedge",
                factory: |ctx| {
                    let cfg = hedge::HedgeConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(hedge::Hedge::new(cfg, ctx.gateway.clone(), ctx.market.clone())))
                },
            },
            StrategyDescriptor {
                name: "liquidity_mining",
                factory: |ctx| {
                    let cfg = liquidity_mining::LiqMiningConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(liquidity_mining::LiqMining::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "bollinger_v2",
                factory: |ctx| {
                    let cfg = bollinger_v2::BollingerV2Config::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(bollinger_v2::BollingerV2::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "dman_v3",
                factory: |ctx| {
                    let cfg =
                        dman_v3::DmanV3Config::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(dman_v3::DmanV3::new(cfg, ctx.gateway.clone(), ctx.market.clone())))
                },
            },
            StrategyDescriptor {
                name: "macd_bb",
                factory: |ctx| {
                    let cfg =
                        macd_bb::MacdBbConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(macd_bb::MacdBb::new(cfg, ctx.gateway.clone(), ctx.market.clone())))
                },
            },
            StrategyDescriptor {
                name: "grid_strike",
                factory: |ctx| {
                    let cfg = grid_strike::GridStrikeConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(grid_strike::GridStrike::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "stat_arb",
                factory: |ctx| {
                    let cfg =
                        stat_arb::StatArbConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(stat_arb::StatArb::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "pmm_dynamic",
                factory: |ctx| {
                    let cfg = pmm_dynamic::PmmDynamicConfig::from_params(
                        ctx.config.strategy.params.table(),
                    )?;
                    Ok(Box::new(pmm_dynamic::PmmDynamic::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "twap_executor",
                factory: |ctx| {
                    let cfg =
                        twap_executor::TwapConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(twap_executor::TwapExecutor::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "dca_executor",
                factory: |ctx| {
                    let cfg =
                        dca_executor::DcaConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(dca_executor::DcaExecutor::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
            StrategyDescriptor {
                name: "vwap_executor",
                factory: |ctx| {
                    let cfg =
                        vwap_executor::VwapConfig::from_params(ctx.config.strategy.params.table())?;
                    Ok(Box::new(vwap_executor::VwapExecutor::new(
                        cfg,
                        ctx.gateway.clone(),
                        ctx.market.clone(),
                    )))
                },
            },
        ]
    })
}

/// Resolve and build the configured strategy by name.
///
/// # Errors
///
/// Returns an error when `strategy.type` is empty of unknown.
pub fn build_strategy(ctx: &StrategyContext) -> Result<Box<dyn Strategy>> {
    let kind = if ctx.config.strategy.strategy_type.is_empty() {
        "simple_grid"
    } else {
        ctx.config.strategy.strategy_type.as_str()
    };
    let descriptor = registry()
        .iter()
        .find(|d| d.name == kind)
        .ok_or_else(|| color_eyre::eyre::eyre!("unknown strategy type: {kind}"))?;
    (descriptor.factory)(ctx)
}

#[cfg(test)]
mod tests {
    use std::{collections::HashSet, time::Duration};

    use buffa::EnumValue;
    use rust_decimal_macros::dec;

    use super::*;
    use crate::{adapters::MockAdapter, proto::trading, strategies::Strategy};

    /// Every parameter any registered strategy declares, in one table. Deserializers
    /// ignore keys they do not model, so one superset builds all of them and a
    /// missing key is the only way a factory can fail.
    const ALL_PARAMS: &str = "\
symbol = \"BTC/USDT\"
exchange_id = \"mock\"
lower_price = \"90\"
upper_price = \"110\"
num_levels = 4
qty_per_level = \"0.1\"
grid_tick = \"1\"
perp_symbol = \"BTC/USDT:USDT\"
lead_symbol = \"BTC/USDT:USDT\"
lag_symbol = \"BTC/USDT\"
primary = { exchange_id = \"mock\", label = \"\" }
hedge = { exchange_id = \"mock\", label = \"\" }
asset = \"USDT\"
threshold = \"1\"
min_balance = \"100\"
repay_above = \"1000\"
from_asset = \"USDT\"
to_asset = \"USDC\"
min_amount = \"10\"
dest_label = \"futures\"
inventory_cap = \"1\"
alert_threshold = \"0.01\"
targets = { BTC = \"1\" }
weights = { BTC = \"0.6\" }
signal_file = \"/tmp/longtrader-registry-irr-signal\"
spot_symbol = \"BTC/USDT\"
total_amount = \"1\"
prices = [\"99\", \"98\", \"97\"]
amounts_quote = [\"100\", \"100\", \"100\"]
symbol_a = \"BTC/USDT\"
symbol_b = \"ETH/USDT\"
";

    /// Only `simple_grid` quotes this table immediately: every other registered
    /// strategy either needs a key the table lacks or waits for a signal before
    /// trading. Combined with the `grid-` client-order namespace — which only
    /// `simple_grid` emits — this turns "the default was applied" into an
    /// assertion rather than a restatement of the source.
    const GRID_ONLY_PARAMS: &str = "\
symbol = \"BTC/USDT\"
lower_price = \"90\"
upper_price = \"110\"
num_levels = 4
qty_per_level = \"0.1\"
";

    /// A `Config` with `strategy.type = kind` carrying `params`.
    fn config_of(kind: &str, params: &str) -> Config {
        let doc = format!(
            "daemon_endpoint = \"http://127.0.0.1:1\"\n\
             [strategy]\ntype = \"{kind}\"\n\
             [strategy.params]\n{params}"
        );
        toml::from_str(&doc).expect("the fixture config must parse")
    }

    /// A `StrategyContext` over a caller-supplied backend, so a test can observe
    /// what the built strategy did to the venue.
    fn context_over(adapter: Arc<MockAdapter>, config: Config) -> StrategyContext {
        StrategyContext {
            config,
            gateway: Arc::clone(&adapter) as Arc<dyn TradingGateway>,
            market: Arc::clone(&adapter) as Arc<dyn MarketDataSource>,
            funding: Arc::clone(&adapter) as Arc<dyn FundingRateSource>,
            triggers: Arc::clone(&adapter) as Arc<dyn TriggerOrderGateway>,
            ops: Arc::clone(&adapter) as Arc<dyn VenueOpInvoker>,
            wallet: Arc::clone(&adapter) as Arc<dyn WalletGateway>,
        }
    }

    /// `kind`'s context, with every one of the five ports served by one mock.
    fn context(kind: &str) -> StrategyContext {
        let adapter = Arc::new(MockAdapter::new(dec!(100)));
        context_over(adapter, config_of(kind, ALL_PARAMS))
    }

    /// `kind`'s context plus a handle to the mock behind it.
    fn context_with_adapter(kind: &str) -> (Arc<MockAdapter>, StrategyContext) {
        let adapter = Arc::new(MockAdapter::new(dec!(100)));
        let ctx = context_over(Arc::clone(&adapter), config_of(kind, ALL_PARAMS));
        (adapter, ctx)
    }

    /// The failure text for `kind`, asserted to exist and to name the kind.
    fn build_error(kind: &str) {
        let outcome = build_strategy(&context(kind)).err();
        let rendered = match outcome {
            Some(err) => format!("{err:#}"),
            None => String::new(),
        };
        assert!(!rendered.is_empty(), "{kind} must not resolve to a strategy");
        assert!(
            rendered.contains(kind),
            "the error must name the kind it could not build: {rendered}"
        );
    }

    /// Every registered name must build. A factory that cannot parse the
    /// documented parameters is dead weight the operator only discovers at
    /// startup, which is the worst possible moment.
    #[test]
    fn every_registered_strategy_builds() {
        assert!(!registry().is_empty(), "the registry must not be empty");
        for descriptor in registry() {
            let outcome = build_strategy(&context(descriptor.name)).err();
            assert!(outcome.is_none(), "{} must build, got {outcome:?}", descriptor.name);
        }
    }

    /// An omitted `strategy.type` must resolve to the documented default rather
    /// than failing: a config file that omits the key is the simplest thing a user
    /// can write, and it should not be a startup failure.
    #[tokio::test]
    async fn an_omitted_strategy_type_defaults_to_simple_grid() {
        let adapter = Arc::new(MockAdapter::new(dec!(100)));
        let ctx = context_over(Arc::clone(&adapter), config_of("", GRID_ONLY_PARAMS));
        let strategy =
            build_strategy(&ctx).expect("an omitted strategy.type must not fail startup");

        let orders = orders_after_first_tick(strategy, &adapter).await;
        assert!(!orders.is_empty(), "the default strategy must start quoting");
        assert!(
            orders.iter().all(|o| o.client_order_id.starts_with("grid-")),
            "the default must be the grid, not another registered name: {:?}",
            orders.iter().map(|o| &o.client_order_id).collect::<Vec<_>>()
        );
        assert_eq!(orders[0].r#type, EnumValue::Known(trading::OrderType::Limit));
    }

    /// An unknown kind is the operator's typo, and the error has to say which word
    /// was wrong — otherwise the only clue is which strategies do exist.
    #[test]
    fn an_unknown_strategy_type_is_refused_and_names_the_kind() {
        build_error("not-a-strategy");
    }

    /// A duplicate name is unreachable through the `find` lookup, so one of the two
    /// entries is silently dead and which one wins is decided by array order.
    #[test]
    fn the_registry_has_no_duplicate_names() {
        let mut seen = HashSet::new();
        for descriptor in registry() {
            assert!(seen.insert(descriptor.name), "duplicate registry name: {}", descriptor.name);
        }
        assert_eq!(seen.len(), registry().len(), "every entry must have a distinct name");
        assert!(
            seen.contains("dca") && seen.contains("dca_scheduler"),
            "both DCA spellings must stay registered"
        );
    }

    /// Every executable strategy must be visible to the terminal UI: the catalog
    /// is the only way a strategy gains a configuration form. A registry entry
    /// without a catalog descriptor can only be configured by hand-written TOML.
    #[test]
    fn every_registered_strategy_is_visible_in_the_catalog() {
        let catalog = longtrader_catalog::builtin_descriptors();
        let catalog_ids: HashSet<&str> = catalog.iter().map(|d| d.id.as_str()).collect();
        // `WORKER_STRATEGY_IDS` is the catalog's copy of this registry; both
        // must agree so neither drifts.
        let worker_ids: HashSet<&str> =
            longtrader_catalog::WORKER_STRATEGY_IDS.into_iter().collect();
        let registry_ids: HashSet<&str> = registry().iter().map(|d| d.name).collect();
        assert_eq!(registry_ids, worker_ids, "registry and catalog WORKER_STRATEGY_IDS drifted");
        for name in registry_ids {
            assert!(
                catalog_ids.contains(name),
                "registry strategy {name:?} has no catalog descriptor"
            );
        }
    }

    /// Drive a built strategy's `run()` until the mock has an open order, then stop
    /// it. The DCA cadence is configured far in the future, so the initial tick is
    /// the only one that fires.
    async fn orders_after_first_tick(
        strategy: Box<dyn Strategy>,
        adapter: &Arc<MockAdapter>,
    ) -> Vec<trading::Order> {
        let task = tokio::spawn(async move { strategy.run().await });
        let mut placed = Vec::new();
        for _ in 0..100 {
            let open = adapter
                .fetch_open_orders(trading::FetchOpenOrdersRequest::default())
                .await
                .expect("the mock must answer an open-orders read");
            if !open.is_empty() {
                placed = open;
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        task.abort();
        placed
    }

    /// `dca` is an alias for `dca_scheduler`. The two factories are separate
    /// entries, so only behaviour can prove they are the same strategy — and
    /// behaviour is what a divergence would actually cost a client: two DCA
    /// schedules quoting the same account.
    #[tokio::test]
    async fn the_dca_alias_behaves_identically_to_dca_scheduler() {
        let (adapter_alias, ctx_alias) = context_with_adapter("dca");
        let (adapter_canonical, ctx_canonical) = context_with_adapter("dca_scheduler");
        let alias = build_strategy(&ctx_alias).expect("the dca alias must build");
        let canonical = build_strategy(&ctx_canonical).expect("dca_scheduler must build");

        let from_alias = orders_after_first_tick(alias, &adapter_alias).await;
        let from_canonical = orders_after_first_tick(canonical, &adapter_canonical).await;
        assert_eq!(from_alias.len(), 1, "the alias must place exactly one order");
        assert_eq!(from_canonical.len(), 1, "the canonical name must place exactly one order");

        for orders in [&from_alias, &from_canonical] {
            assert!(
                orders[0].client_order_id.starts_with("dca-"),
                "both spellings must use the DCA order namespace: {}",
                orders[0].client_order_id
            );
            assert_eq!(orders[0].side, EnumValue::Known(trading::OrderSide::Buy));
            assert_eq!(orders[0].r#type, EnumValue::Known(trading::OrderType::Market));
            assert_eq!(orders[0].symbol, "BTC/USDT");
        }
        assert_eq!(
            longtrader_contract::ext::common_to_decimal(
                from_alias[0].amount.as_option().expect("amount")
            )
            .expect("decodes"),
            longtrader_contract::ext::common_to_decimal(
                from_canonical[0].amount.as_option().expect("amount")
            )
            .expect("decodes"),
            "the alias must size the same order as the canonical name"
        );
    }
}

#[cfg(test)]
mod catalog_sync_tests {
    use super::registry;

    /// The terminal's schema-driven catalog must name exactly the strategies
    /// the registry can build.
    ///
    /// The catalog list is hand-maintained (the terminal renders it without
    /// linking the worker), so without this check a registry addition silently
    /// leaves the strategy missing from the UI, and a removal leaves a dead
    /// entry that fails only at runtime.
    #[test]
    fn the_catalog_names_exactly_the_registry_strategies() {
        let mut registry_names: Vec<&str> =
            registry().iter().map(|descriptor| descriptor.name).collect();
        registry_names.sort_unstable();
        let mut catalog_names: Vec<&str> =
            longtrader_catalog::WORKER_STRATEGY_IDS.iter().copied().collect();
        catalog_names.sort_unstable();
        assert_eq!(
            catalog_names, registry_names,
            "longtrader_catalog::WORKER_STRATEGY_IDS must mirror the registry exactly"
        );
    }
}