rungbot-exec 0.5.7

Live order execution for rungbot: an idempotent order journal, hard caps, reconcile, and Gate.io, Revolut X and Binance spot clients. Opt-in.
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
//! What a live run does before it looks at a single new signal.
//!
//! [`run`] takes the journal, the ladder state, the stale-order flags, the P&L ledger and
//! the venue balances, and does, in this order:
//!
//! 1. **Reconcile** ([`crate::reconcile`](mod@crate::reconcile)), then book every new fill:
//!    * a filled market buy sets the fill-based cost basis and pairs a resting limit sell
//!      at fill +target net of the sell fee (no pair while the bull sell policy governs
//!      the coin: the buy is a core add);
//!    * a filled deploy buy is a core add: cost basis, no pair, no trade window. A fill on
//!      Revolut X for a coin routed elsewhere stays out of the ladder state;
//!    * a filled sell is logged to the P&L ledger and opens a sell window.
//! 2. **Retry failed limit sells**: adopt the order when it rests at the venue after all
//!    (same id, or a price within 0.3%), else place it again, five tries at most.
//! 3. **Manage resting limit sells**: move a sell whose price fell below the current
//!    cost-basis target up to it (a trailing coin's target rides the venue price instead),
//!    restoring the old cover at once if the venue refuses the new price; flag orders
//!    older than the regime's TTL, once per re-nag window.
//! 4. **Holding drift**: compare each coin's venue holding with the last snapshot plus
//!    what the journal booked since, per order. Venues whose balance read failed are
//!    skipped and carry their snapshot forward. The first run with no per-order snapshot
//!    only writes one.
//!
//! Steps 2 and 3 place orders and are skipped while trading is blocked; drift always runs.
//! Every step reports [`Outcome`]s whose texts are the mail and decision-log lines.
//!
//! A step that fails outright (an unknown venue, an order that cannot be printed) ends
//! that step with one `reconcile: …` or `housekeeping: …` error, and what it changed
//! before stays changed. Nothing here opens a file: the caller hands in a [`Persist`],
//! and every row recorded or changed ahead of a venue call is written through it before
//! the call, every venue result right after it, and the P&L ledger after each append.
//! Once a journal write fails, nothing more is placed: the step stops, and the caller
//! reports the run as fatal.

use std::collections::{BTreeMap, BTreeSet};

use indexmap::IndexMap;
use rungbot_core::housekeeping::{self as hk, Fees};
use serde_json::{json, Map, Value};

use crate::ids;
use crate::journal::{client_id, suffixed, Journal, Order, Side};
use crate::pyfmt::{self, g};
use crate::reconcile::{reconcile, settle_cancel, Settled, VenueSource};
use crate::venue::{venue_id_matches, Balance, ParsedOrder, Venue};

/// Venues balances are read from, in this order.
pub const BALANCE_VENUES: [&str; 3] = ["binance", "gate", "revx"];

/// A limit sell whose placement failed is retried this many times, then handed over.
pub const MAX_SELL_RETRIES: i64 = 5;

/// A resting order this close to a failed sell's price is that sell (0.3%).
pub const ADOPT_PRICE_TOLERANCE: f64 = 0.003;

/// Reprice when the order sits below this share of its target; a trailing coin uses
/// the wider band so a climbing price does not churn a cancel and re-place every run.
pub const REPRICE_BAND: f64 = 0.999;
pub const REPRICE_BAND_TRAILING: f64 = 0.98;

/// Text for a value that is missing where a line has to print it.
const NONE_FORMAT: &str = "unsupported format string passed to NoneType.__format__";

/// Where each coin trades.
#[derive(Debug, Clone, PartialEq)]
pub struct Route {
    pub sym: String,
    pub exch: String,
    pub pair: String,
    pub quote: String,
}

/// The knobs housekeeping reads. Defaults are the documented defaults.
#[derive(Debug, Clone, PartialEq)]
pub struct Settings {
    /// Take-profit over the fill, in percent, net of the sell fee.
    pub target_pct: f64,
    pub fees: Fees,
    /// How long a filled sell blocks the buy side, in hours.
    pub window_hours: f64,
    /// Stale-order warning age in a bull market, days. 0 turns the warning off.
    pub limit_ttl_days: f64,
    pub limit_ttl_days_bear: f64,
    pub limit_ttl_days_chop: f64,
    /// Re-flag a still-stale order after this many days. 0 = flag once, ever.
    pub ttl_renag_days: f64,
    /// Coin -> venue and pair, in the order drift reports coins.
    pub routing: Vec<Route>,
    /// Seed cost basis per coin, used until the state records one.
    pub entries: BTreeMap<String, f64>,
}

impl Default for Settings {
    fn default() -> Self {
        Settings {
            target_pct: 10.0,
            fees: Fees::default(),
            window_hours: 24.0,
            limit_ttl_days: 14.0,
            limit_ttl_days_bear: 45.0,
            limit_ttl_days_chop: 30.0,
            ttl_renag_days: 30.0,
            routing: Vec::new(),
            entries: BTreeMap::new(),
        }
    }
}

impl Settings {
    fn route(&self, sym: &str) -> Option<&Route> {
        self.routing.iter().find(|r| r.sym == sym)
    }

    pub fn limit_target(&self, fill_price: f64, exch: &str) -> f64 {
        hk::limit_target(fill_price, self.target_pct, self.fees.pct(exch))
    }
}

/// How a result reads: done, warn or err.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Level {
    Done,
    Warn,
    Err,
}

impl Level {
    pub fn as_str(&self) -> &'static str {
        match self {
            Level::Done => "done",
            Level::Warn => "warn",
            Level::Err => "err",
        }
    }
}

/// One result line. `hk` marks housekeeping (never rolled back with a signal);
/// `committed` means an order went to a venue.
#[derive(Debug, Clone, PartialEq)]
pub struct Outcome {
    pub sym: Option<String>,
    pub side: Option<String>,
    pub mode: String,
    pub hk: bool,
    pub committed: bool,
    pub level: Level,
    pub text: String,
}

impl Outcome {
    fn new(sym: Option<&str>, level: Level, text: String) -> Outcome {
        Outcome {
            sym: sym.map(str::to_string),
            side: None,
            mode: "live".into(),
            hk: true,
            committed: false,
            level,
            text,
        }
    }

    fn side(mut self, side: &str) -> Outcome {
        self.side = Some(side.into());
        self
    }

    fn committed(mut self) -> Outcome {
        self.committed = true;
        self
    }

    /// The result as a JSON object: `{sym, side, mode, hk, committed, done|warn|err}`,
    /// absent keys left out.
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        if let Some(s) = &self.sym {
            m.insert("sym".into(), json!(s));
        }
        if let Some(s) = &self.side {
            m.insert("side".into(), json!(s));
        }
        m.insert("mode".into(), json!(self.mode));
        if self.hk {
            m.insert("hk".into(), json!(true));
        }
        if self.committed {
            m.insert("committed".into(), json!(true));
        }
        m.insert(self.level.as_str().into(), json!(self.text));
        Value::Object(m)
    }
}

/// The ladder state: `{SYM: {...}, "_bal": {...}, ...}`. Housekeeping reads and writes
/// `cost_basis`, `win_until` and `win_dir` per coin and the `_bal` snapshot, and keeps
/// every other key as it found it.
pub type LadderState = Map<String, Value>;

/// Stale-order flags: client id -> when it was last flagged.
pub type TtlWarned = IndexMap<String, f64>;

/// The realized-P&L ledger, one record per filled sell, oldest first.
pub type PnlLedger = Vec<Value>;

type SaveJournal = Box<dyn FnMut(&Journal) -> Result<(), String>>;
type SavePnl = Box<dyn FnMut(&PnlLedger) -> Result<(), String>>;

/// Writes the journal and the P&L ledger to disk while a run places orders.
///
/// The journal write is the one that stops a double trade: a row the venue holds but the
/// disk does not is an order the next run cannot see. So a failed journal write sticks:
/// every later [`Persist::journal`] fails with the same error without trying, and every
/// caller treats that as "place nothing more". A failed P&L write is kept as a warning;
/// the run saves the ledger again at its end.
pub struct Persist {
    save_journal: SaveJournal,
    save_pnl: SavePnl,
    failed: Option<String>,
    pnl_failed: Option<String>,
}

impl Persist {
    pub fn new(
        journal: impl FnMut(&Journal) -> Result<(), String> + 'static,
        pnl: impl FnMut(&PnlLedger) -> Result<(), String> + 'static,
    ) -> Persist {
        Persist {
            save_journal: Box::new(journal),
            save_pnl: Box::new(pnl),
            failed: None,
            pnl_failed: None,
        }
    }

    /// Writes to these two files.
    pub fn to_files(journal: std::path::PathBuf, pnl: std::path::PathBuf) -> Persist {
        Persist::new(
            move |j| crate::store::save_journal(&journal, j),
            move |p| crate::store::save_pnl(&pnl, p),
        )
    }

    /// Writes nothing: a dry run, or a test that only looks at memory.
    pub fn none() -> Persist {
        Persist::new(|_| Ok(()), |_| Ok(()))
    }

    /// Write the journal. After the first failure, fails at once with that error.
    pub fn journal(&mut self, j: &Journal) -> Result<(), String> {
        if let Some(e) = &self.failed {
            return Err(e.clone());
        }
        (self.save_journal)(j).map_err(|e| {
            let msg = format!("journal write failed: {e}");
            self.failed = Some(msg.clone());
            msg
        })
    }

    /// Write the P&L ledger, best effort.
    pub fn pnl(&mut self, p: &PnlLedger) {
        self.pnl_failed = (self.save_pnl)(p).err();
    }

    /// The journal write that failed, if one did.
    pub fn failed(&self) -> Option<&str> {
        self.failed.as_deref()
    }

    /// The last P&L write's error, if it failed.
    pub fn pnl_failed(&self) -> Option<&str> {
        self.pnl_failed.as_deref()
    }
}

/// What housekeeping changes.
pub struct Books<'a> {
    pub journal: &'a mut Journal,
    pub ladder: &'a mut LadderState,
    pub ttl: &'a mut TtlWarned,
    pub pnl: &'a mut PnlLedger,
}

/// Venue balances for this run.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Balances {
    /// venue -> asset -> free and locked.
    pub full: BTreeMap<String, BTreeMap<String, Balance>>,
    /// Venues whose balance read failed this run.
    pub failed: BTreeSet<String>,
}

impl Balances {
    /// The free amount of `asset` on `exch`, 0 when unknown.
    pub fn free(&self, exch: &str, asset: &str) -> f64 {
        self.full
            .get(exch)
            .and_then(|b| b.get(asset))
            .map_or(0.0, |b| b.free)
    }
}

/// Read every venue's balances. A venue that fails is recorded in `failed` with an empty
/// book, and reported as `{venue} balances: {error}` (not housekeeping: it is mailed as
/// an error every run the venue stays down).
pub fn fetch_balances(venues: &dyn VenueSource, mode: &str) -> (Balances, Vec<Outcome>) {
    let mut b = Balances::default();
    let mut out = Vec::new();
    for name in BALANCE_VENUES {
        let read = venues
            .venue(name)
            .and_then(|v| v.balances_full().map_err(|e| e.to_string()));
        match read {
            Ok(full) => {
                b.full.insert(name.into(), full);
            }
            Err(e) => {
                b.full.insert(name.into(), BTreeMap::new());
                b.failed.insert(name.into());
                out.push(Outcome {
                    sym: None,
                    side: None,
                    mode: mode.into(),
                    hk: false,
                    committed: false,
                    level: Level::Err,
                    text: format!("{name} balances: {e}"),
                });
            }
        }
    }
    (b, out)
}

/// What this run knows besides the stores.
#[derive(Debug, Clone, Copy)]
pub struct RunCtx<'a> {
    pub now: f64,
    /// Trading is blocked (disarmed or halted): no retry, no reprice.
    pub blocked: bool,
    /// The regime's market label (`bull`, `bear`, `chop`, ...), `None` when unreadable.
    pub market: Option<&'a str>,
    /// Coins whose sell side trails the price this run.
    pub trailing: &'a BTreeSet<String>,
    /// Coins the bull sell policy governs this run.
    pub policy: &'a BTreeSet<String>,
}

/// Run every housekeeping step; see the module docs.
pub fn run(
    s: &Settings,
    ctx: &RunCtx,
    bal: &Balances,
    books: &mut Books,
    venues: &dyn VenueSource,
    p: &mut Persist,
) -> Vec<Outcome> {
    let mut out = Vec::new();
    let rec = reconcile(books.journal, venues, ctx.now);
    for a in &rec.adopted {
        let o = &a.order;
        out.push(
            Outcome::new(
                Some(&o.sym),
                Level::Done,
                format!(
                    "ZONE RESIZED AT THE VENUE: {} rung {} @ ${} is now ${} (was ${}) — adopted \
                     the replacement order, the level is unchanged",
                    o.sym,
                    o.rung.map_or("None".into(), |r| r.to_string()),
                    g(o.price.unwrap_or(0.0), 6),
                    pyfmt::fixed(o.quote.unwrap_or(0.0), 2),
                    pyfmt::fixed(a.was_quote, 2),
                ),
            )
            .committed(),
        );
    }
    // What reconcile booked goes to disk before anything is placed on top of it.
    if rec.changed {
        let _ = p.journal(books.journal);
    }
    if let Err(e) = book_fills(s, ctx, bal, books, venues, &rec.filled, &mut out, p) {
        out.push(Outcome::new(None, Level::Err, format!("reconcile: {e}")));
    }
    let steps = (|| {
        if !ctx.blocked {
            retry_failed_limit_sells(books.journal, venues, &mut out, p)?;
            manage_resting_sells(s, ctx, books, venues, &mut out, p)?;
        }
        detect_drift(s, ctx.now, bal, books.journal, books.ladder, &mut out);
        Ok::<(), String>(())
    })();
    if let Err(e) = steps {
        out.push(Outcome::new(None, Level::Err, format!("housekeeping: {e}")));
    }
    out
}

/// The client for `exch`. A venue the run does not trade is an error that is just its
/// name, quoted: `'kraken'`.
fn client<'a>(venues: &'a dyn VenueSource, exch: &str) -> Result<&'a dyn Venue, String> {
    if !BALANCE_VENUES.contains(&exch) {
        return Err(pyfmt::repr_str(exch));
    }
    venues.venue(exch)
}

fn nonzero(v: Option<f64>) -> Option<f64> {
    v.filter(|x| *x != 0.0)
}

/// The recorded cost basis of `sym`, if any (zero counts as none).
pub fn cost_basis(state: &LadderState, sym: &str) -> Option<f64> {
    nonzero(
        state
            .get(sym)
            .and_then(Value::as_object)
            .and_then(|c| c.get("cost_basis"))
            .and_then(Value::as_f64),
    )
}

/// Fold a buy fill into `sym`'s cost basis. See [`hk::weighted_cost_basis`].
pub fn set_cost_basis(
    s: &Settings,
    state: &mut LadderState,
    sym: &str,
    held: f64,
    fill_quote: f64,
    fill_base: f64,
    fill_price: f64,
) {
    let new = hk::weighted_cost_basis(
        cost_basis(state, sym),
        s.entries.get(sym).copied(),
        held,
        fill_quote,
        fill_base,
        fill_price,
    );
    let coin = state
        .entry(sym.to_string())
        .or_insert_with(|| Value::Object(Map::new()));
    if !coin.is_object() {
        *coin = Value::Object(Map::new());
    }
    if let Some(c) = coin.as_object_mut() {
        c.insert("cost_basis".into(), json!(new));
    }
}

fn place(
    v: &dyn Venue,
    pair: &str,
    base: f64,
    price: f64,
    cid: &str,
) -> Result<ParsedOrder, String> {
    v.limit_sell(pair, base, price, Some(cid))
        .and_then(|raw| v.parse_order(&raw))
        .map_err(|e| e.to_string())
}

fn status_or_open(p: &ParsedOrder) -> String {
    if p.status.is_empty() {
        "open".into()
    } else {
        p.status.clone()
    }
}

fn limit_sell_row(cid: &str, sym: &str, exch: &str, pair: &str, base: f64, price: f64) -> Order {
    Order {
        client_id: cid.into(),
        sym: sym.into(),
        exch: exch.into(),
        pair: pair.into(),
        side: "sell".into(),
        kind: "limit_sell".into(),
        base: Some(base),
        price: Some(price),
        ..Default::default()
    }
}

/// Place the resting limit sell paired with a buy fill of `fill_base` at `fill_price`:
/// at fill +target net of the sell fee, journaled as `pending` and written to disk
/// before the venue call, and written again with the venue's answer. The id is this
/// slot's sell id for `rung` plus `cid_suffix`. The outcome is not marked housekeeping;
/// a caller booking a reconciled fill marks it.
///
/// When the journal cannot be written the sell is not placed: the row is left as a
/// failed placement, which the retry step places once the journal writes again.
#[allow(clippy::too_many_arguments)]
pub fn pair_limit_sell(
    s: &Settings,
    j: &mut Journal,
    p: &mut Persist,
    v: &dyn Venue,
    exch: &str,
    pair: &str,
    sym: &str,
    fill_base: f64,
    fill_price: f64,
    now: f64,
    rung: i64,
    cid_suffix: &str,
) -> Result<Outcome, String> {
    let lim = s.limit_target(fill_price, exch);
    let scid = ids::safe_cid(&(client_id(sym, Side::Sell, now, rung) + cid_suffix))
        .map_err(|e| e.to_string())?;
    let mut row = limit_sell_row(&scid, sym, exch, pair, fill_base, lim);
    row.status = "pending".into();
    row.rung = Some(rung);
    row.ts = Some(now);
    j.record(row);
    if let Err(e) = p.journal(j) {
        j.update(&scid, |o| {
            o.status = "error".into();
            o.last_error = Some(format!("not placed: {e}"));
        });
        let mut res = Outcome::new(
            Some(sym),
            Level::Err,
            format!("LIMIT-SELL FAILED (auto-retries next runs): not placed, {e}"),
        );
        res.hk = false;
        return Ok(res);
    }
    let placed = place(v, pair, fill_base, lim, &scid);
    let mut res = match placed {
        Ok(lf) => {
            j.update(&scid, |o| {
                o.status = status_or_open(&lf);
                o.order_id = Some(lf.order_id.clone());
            });
            Outcome::new(
                Some(sym),
                Level::Done,
                format!("LIMIT SELL placed @ ${}", g(lim, 6)),
            )
        }
        Err(e) => {
            j.update(&scid, |o| {
                o.status = "error".into();
                o.last_error = Some(e.clone());
            });
            Outcome::new(
                Some(sym),
                Level::Err,
                format!("LIMIT-SELL FAILED (auto-retries next runs): {e}"),
            )
        }
    };
    // The order is at the venue now; a failed write here stops the rest of the run.
    let _ = p.journal(j);
    res.hk = false;
    Ok(res)
}

/// Append a realized-P&L record for a filled sell and return the realized USD (`None`
/// without a cost basis).
#[allow(clippy::too_many_arguments)]
pub fn log_pnl(
    ledger: &mut PnlLedger,
    sym: &str,
    qty: f64,
    quote: f64,
    avg_price: Option<f64>,
    cost_basis: Option<f64>,
    now: f64,
    kind: &str,
) -> Option<f64> {
    let realized = hk::realized(qty, quote, cost_basis);
    ledger.push(json!({
        "ts": now,
        "iso": rungbot_core::iso8601_micros(now),
        "sym": sym,
        "kind": kind,
        "qty": qty,
        "quote": quote,
        "avg_price": avg_price,
        "cost_basis": cost_basis,
        "realized_usd": realized,
        "realized_pct": hk::realized_pct(avg_price, cost_basis),
    }));
    realized
}

/// `; realized +1.23 USD (+4.5%)`, or nothing without a realized amount.
pub fn pnl_tail(realized: Option<f64>, cost_basis: Option<f64>, avg_price: Option<f64>) -> String {
    let Some(r) = realized else {
        return String::new();
    };
    let pct = hk::realized_pct(avg_price, cost_basis)
        .map(|p| format!(" ({p:+.1}%)"))
        .unwrap_or_default();
    format!("; realized {r:+.2} USD{pct}")
}

/// Step 1's second half: book each fill reconcile returned. See the module docs.
#[allow(clippy::too_many_arguments)]
fn book_fills(
    s: &Settings,
    ctx: &RunCtx,
    bal: &Balances,
    books: &mut Books,
    venues: &dyn VenueSource,
    fills: &[Order],
    out: &mut Vec<Outcome>,
    p: &mut Persist,
) -> Result<(), String> {
    let now = ctx.now;
    for o in fills {
        let sym = o.sym.as_str();
        let fb = o.filled_base.unwrap_or(0.0);
        let fq = o.filled_quote.unwrap_or(0.0);
        let fill_price = || nonzero(o.avg_price).unwrap_or(if fb != 0.0 { fq / fb } else { 0.0 });
        let head = format!("~{} {sym} (~${}", g(fb, 6), pyfmt::fixed(fq, 2));
        match o.kind.as_str() {
            "market_buy" => {
                let fp = fill_price();
                // The balance was read after this fill landed: leave it out of "held".
                let held = (bal.free(&o.exch, sym) - fb).max(0.0);
                set_cost_basis(s, books.ladder, sym, held, fq, fb, fp);
                if ctx.policy.contains(sym) {
                    out.push(
                        Outcome::new(
                            Some(sym),
                            Level::Done,
                            format!(
                                "BUY FILLED {head}); core add under the bull sell policy (no pair)"
                            ),
                        )
                        .side("buy")
                        .committed(),
                    );
                    continue;
                }
                let v = client(venues, &o.exch)?;
                let mut res = pair_limit_sell(
                    s,
                    books.journal,
                    p,
                    v,
                    &o.exch,
                    &o.pair,
                    sym,
                    fb,
                    fp,
                    now,
                    o.rung.unwrap_or(1),
                    "d",
                )?;
                res.text = format!("BUY FILLED {head}); {}", res.text);
                res.hk = true;
                out.push(res.side("buy").committed());
            }
            "deploy_buy" => {
                if o.exch == "revx" && s.route(sym).is_none_or(|r| r.exch != "revx") {
                    out.push(
                        Outcome::new(
                            Some(sym),
                            Level::Done,
                            format!(
                                "REVX DEPLOY FILLED {head}) — held on revx, outside ladder-state"
                            ),
                        )
                        .side("buy")
                        .committed(),
                    );
                    continue;
                }
                let fp = fill_price();
                let held = (bal.free(&o.exch, sym) - fb).max(0.0);
                set_cost_basis(s, books.ladder, sym, held, fq, fb, fp);
                let partial = if o.partial == Some(true) {
                    " (partial, the rest was cancelled)"
                } else {
                    ""
                };
                out.push(
                    Outcome::new(
                        Some(sym),
                        Level::Done,
                        format!(
                            "DEPLOY BUY FILLED {head} @ ${}){partial} — core add: cost basis \
                             updated, no paired sell",
                            g(fp, 6)
                        ),
                    )
                    .side("buy")
                    .committed(),
                );
            }
            kind => {
                let cb = cost_basis(books.ladder, sym).or(nonzero(s.entries.get(sym).copied()));
                let kind = if kind.is_empty() { "limit_sell" } else { kind };
                let realized = log_pnl(books.pnl, sym, fb, fq, o.avg_price, cb, now, kind);
                p.pnl(books.pnl);
                out.push(
                    Outcome::new(
                        Some(sym),
                        Level::Done,
                        format!(
                            "LIMIT SELL FILLED {head}){}",
                            pnl_tail(realized, cb, o.avg_price)
                        ),
                    )
                    .side("sell")
                    .committed(),
                );
                if let Some(c) = books.ladder.get_mut(sym).and_then(Value::as_object_mut) {
                    c.insert("win_until".into(), json!(now + s.window_hours * 3600.0));
                    c.insert("win_dir".into(), json!("sell"));
                }
            }
        }
    }
    Ok(())
}

/// Step 2: retry every limit sell whose placement failed. See the module docs.
pub fn retry_failed_limit_sells(
    j: &mut Journal,
    venues: &dyn VenueSource,
    out: &mut Vec<Outcome>,
    p: &mut Persist,
) -> Result<(), String> {
    let rows: Vec<Order> = j.errored(Some("limit_sell")).into_iter().cloned().collect();
    for o in rows {
        if p.failed().is_some() {
            return Ok(());
        }
        let (sym, exch, pair, cid) = (&o.sym, &o.exch, &o.pair, &o.client_id);
        let (Some(base), Some(lim)) = (nonzero(o.base), nonzero(o.price)) else {
            continue;
        };
        if sym.is_empty() || exch.is_empty() || pair.is_empty() || cid.is_empty() {
            continue;
        }
        let tries = o.retries.unwrap_or(0);
        if tries >= MAX_SELL_RETRIES {
            if o.gave_up != Some(true) {
                j.update(cid, |r| r.gave_up = Some(true));
                out.push(Outcome::new(
                    Some(sym),
                    Level::Warn,
                    format!(
                        "limit sell failed {tries}x, giving up -- place ~{} {sym} @ ${} manually",
                        g(base, 6),
                        g(lim, 6)
                    ),
                ));
            }
            continue;
        }
        let v = client(venues, exch)?;
        let resting = match v.open_orders(pair) {
            Ok(r) => r,
            Err(e) => {
                out.push(Outcome::new(
                    Some(sym),
                    Level::Warn,
                    format!("limit-sell retry: open_orders failed: {e}"),
                ));
                continue;
            }
        };
        let adopted = resting.iter().find(|x| {
            venue_id_matches(exch, &x.client_id, cid)
                || nonzero(x.price).is_some_and(|p| (p / lim - 1.0).abs() < ADOPT_PRICE_TOLERANCE)
        });
        if let Some(a) = adopted {
            j.update(cid, |r| {
                r.status = "open".into();
                r.order_id = Some(a.order_id.clone());
                r.last_error = None;
            });
            let price = a.price.ok_or(NONE_FORMAT)?;
            out.push(Outcome::new(
                Some(sym),
                Level::Done,
                format!(
                    "adopted resting limit sell @ ${} (original placement had succeeded)",
                    g(price, 6)
                ),
            ));
            continue;
        }
        let rcid = ids::safe_cid(&format!("{cid}x{}", tries + 1)).map_err(|e| e.to_string());
        // Everything changed so far is on disk before the venue sees the order. A crash
        // after the call leaves the row failed; the next run adopts the resting order.
        if p.journal(j).is_err() {
            return Ok(());
        }
        let placed = rcid.and_then(|rcid| place(v, pair, base, lim, &rcid));
        match placed {
            Ok(lf) => {
                j.update(cid, |r| {
                    r.status = status_or_open(&lf);
                    r.order_id = Some(lf.order_id.clone());
                    r.retries = Some(tries + 1);
                    r.last_error = None;
                });
                out.push(
                    Outcome::new(
                        Some(sym),
                        Level::Done,
                        format!("RETRY OK: limit sell {} {sym} @ ${}", g(base, 6), g(lim, 6)),
                    )
                    .committed(),
                );
            }
            Err(e) => {
                j.update(cid, |r| {
                    r.retries = Some(tries + 1);
                    r.last_error = Some(e.clone());
                });
                out.push(Outcome::new(
                    Some(sym),
                    Level::Warn,
                    format!(
                        "limit-sell retry {}/{MAX_SELL_RETRIES} failed: {e}",
                        tries + 1
                    ),
                ));
            }
        }
        let _ = p.journal(j);
    }
    Ok(())
}

/// Should `cid` be flagged stale now? Records the flag when it says yes, and prunes the
/// flags of orders no longer in `open` (when given).
pub fn ttl_should_warn(
    ttl: &mut TtlWarned,
    cid: &str,
    now: f64,
    open: Option<&BTreeSet<String>>,
    renag_days: f64,
) -> bool {
    if !hk::ttl_due(ttl.get(cid).copied(), now, renag_days) {
        return false;
    }
    ttl.insert(cid.to_string(), now);
    if let Some(open) = open {
        ttl.retain(|k, _| open.contains(k) || k == cid);
    }
    true
}

/// The 30-minute slot a reprice or restore id is suffixed with.
fn slot(now: f64) -> i64 {
    ((now / 1800.0).floor() as i64) % 100_000
}

/// Step 3: move resting limit sells up to a risen target, flag stale ones. See the
/// module docs.
pub fn manage_resting_sells(
    s: &Settings,
    ctx: &RunCtx,
    books: &mut Books,
    venues: &dyn VenueSource,
    out: &mut Vec<Outcome>,
    p: &mut Persist,
) -> Result<(), String> {
    let now = ctx.now;
    let ttl_days = hk::effective_ttl_days(
        s.limit_ttl_days,
        s.limit_ttl_days_bear,
        s.limit_ttl_days_chop,
        ctx.market,
    );
    let rows: Vec<Order> = books
        .journal
        .open_orders(Some("limit_sell"))
        .into_iter()
        .cloned()
        .collect();
    let open: BTreeSet<String> = rows.iter().map(|o| o.client_id.clone()).collect();
    for o in rows {
        let (sym, exch, pair, cid) = (&o.sym, &o.exch, &o.pair, &o.client_id);
        let Some(order_id) = o.order_id.clone().filter(|id| !id.is_empty()) else {
            continue;
        };
        if sym.is_empty() || exch.is_empty() || pair.is_empty() || cid.is_empty() {
            continue;
        }
        let (base, price) = (o.base, o.price);
        let mut tgt = cost_basis(books.ladder, sym).map(|cb| s.limit_target(cb, exch));
        let v = client(venues, exch)?;
        let mut band = REPRICE_BAND;
        if ctx.trailing.contains(sym) {
            if let Ok(p) = v.price(pair) {
                tgt = Some(tgt.unwrap_or(0.0).max(s.limit_target(p, exch)));
                band = REPRICE_BAND_TRAILING;
            }
        }
        let reprice = match (nonzero(tgt), nonzero(price), nonzero(base)) {
            (Some(t), Some(p), Some(b)) if p < t * band => Some((t, p, b)),
            _ => None,
        };
        if let Some((tgt, price, base)) = reprice {
            let ncid = suffixed(cid, &format!("u{}", slot(now)));
            if books.journal.exists(&ncid) {
                continue;
            }
            // A journal that cannot be written now would leave the position uncovered
            // after the cancel: check before taking the cover down.
            if p.journal(books.journal).is_err() {
                return Ok(());
            }
            if let Err(e) = v.cancel(pair, &order_id) {
                out.push(Outcome::new(
                    Some(sym),
                    Level::Warn,
                    format!(
                        "reprice: cancel failed (may have just filled, reconciles next run): {e}"
                    ),
                ));
                continue;
            }
            books.journal.update(cid, |r| {
                r.status = "canceled".into();
                r.note = Some("repriced up to new cost-basis target".into());
            });
            let mut base = base;
            if let Settled::Booked(done) = settle_cancel(books.journal, v, cid, now) {
                // Part sold before the cancel: that part is booked (its P&L comes with the
                // next reconcile); re-place only what is still held.
                base = (base - done.filled_base.unwrap_or(0.0)).max(0.0);
                if base <= 0.0 {
                    let _ = p.journal(books.journal);
                    continue;
                }
            }
            let rung = o.rung.unwrap_or(1);
            let mut row = limit_sell_row(&ncid, sym, exch, pair, base, tgt);
            row.status = "pending".into();
            row.rung = Some(rung);
            row.ts = Some(now);
            books.journal.record(row);
            if let Err(e) = p.journal(books.journal) {
                // The cancel went through and the new sell cannot be journaled: leave
                // it as a failed placement, which the retry step places next run.
                books.journal.update(&ncid, |r| {
                    r.status = "error".into();
                    r.last_error = Some(format!("not placed: {e}"));
                });
                out.push(Outcome::new(
                    Some(sym),
                    Level::Warn,
                    format!(
                        "reprice: cancelled, but the new sell was not placed ({e}) -- {} \
                         {sym} is UNPROTECTED until the retry places it @ ${}",
                        g(base, 6),
                        g(tgt, 6)
                    ),
                ));
                return Ok(());
            }
            let placed = place(v, pair, base, tgt, &ncid);
            match placed {
                Ok(lf) => {
                    books.journal.update(&ncid, |r| {
                        r.status = status_or_open(&lf);
                        r.order_id = Some(lf.order_id.clone());
                    });
                    let _ = p.journal(books.journal);
                    out.push(
                        Outcome::new(
                            Some(sym),
                            Level::Done,
                            format!(
                                "REPRICED limit sell up: ${} -> ${} (cost basis rose; never \
                                 sell below entry +{}%)",
                                g(price, 6),
                                g(tgt, 6),
                                pyfmt::fixed(s.target_pct, 0)
                            ),
                        )
                        .committed(),
                    );
                }
                Err(e) => {
                    books.journal.update(&ncid, |r| {
                        r.status = "error".into();
                        r.last_error = Some(e.clone());
                    });
                    // The cancel went through, so the position is uncovered right now.
                    // Restore cover at the old price, the one the venue already accepted.
                    let rcid = suffixed(cid, &format!("v{}", slot(now)));
                    if books.journal.exists(&rcid) {
                        let _ = p.journal(books.journal);
                        continue;
                    }
                    // Journaled before the venue call like every other placement.
                    let mut row = limit_sell_row(&rcid, sym, exch, pair, base, price);
                    row.status = "pending".into();
                    row.rung = Some(rung);
                    row.ts = Some(now);
                    row.note = Some(format!(
                        "cover restored at prior price after {ncid} was rejected"
                    ));
                    books.journal.record(row);
                    if let Err(e2) = p.journal(books.journal) {
                        books.journal.orders.shift_remove(&rcid);
                        out.push(Outcome::new(
                            Some(sym),
                            Level::Warn,
                            format!(
                                "reprice re-place failed ({e}) AND restore not placed ({e2}) \
                                 -- {} {sym} is UNPROTECTED, place @ ${} manually",
                                g(base, 6),
                                g(price, 6)
                            ),
                        ));
                        return Ok(());
                    }
                    let restored = place(v, pair, base, price, &rcid);
                    match restored {
                        Ok(rf) => {
                            books.journal.update(&rcid, |r| {
                                r.status = status_or_open(&rf);
                                r.order_id = Some(rf.order_id.clone());
                            });
                            // Retire the failed one so the retry path cannot add a second cover.
                            books.journal.update(&ncid, |r| {
                                r.status = "canceled".into();
                                r.note = Some(format!("cover restored as {rcid}"));
                            });
                            let _ = p.journal(books.journal);
                            out.push(
                                Outcome::new(
                                    Some(sym),
                                    Level::Warn,
                                    format!(
                                        "reprice to ${} rejected ({e}); cover RESTORED at ${} -- \
                                         position is protected, retries next run",
                                        g(tgt, 6),
                                        g(price, 6)
                                    ),
                                )
                                .committed(),
                            );
                        }
                        Err(e2) => {
                            // The venue refused it: no such order, so no such row. The
                            // failed reprice stays errored and is retried next run.
                            books.journal.orders.shift_remove(&rcid);
                            let _ = p.journal(books.journal);
                            out.push(Outcome::new(
                                Some(sym),
                                Level::Warn,
                                format!(
                                    "reprice re-place failed ({e}) AND restore failed ({e2}) \
                                     -- {} {sym} is UNPROTECTED, place @ ${} manually",
                                    g(base, 6),
                                    g(price, 6)
                                ),
                            ))
                        }
                    }
                }
            }
        } else if ttl_days > 0.0
            && now - nonzero(o.ts).unwrap_or(now) > ttl_days * 86_400.0
            && ttl_should_warn(books.ttl, cid, now, Some(&open), s.ttl_renag_days)
        {
            let (base, price) = (base.ok_or(NONE_FORMAT)?, price.ok_or(NONE_FORMAT)?);
            out.push(Outcome::new(
                Some(sym),
                Level::Warn,
                format!(
                    "resting limit sell ({} {sym} @ ${}) is older than {}d -- price never \
                     reached the target even for this regime; review whether to keep it",
                    g(base, 6),
                    g(price, 6),
                    pyfmt::fixed(ttl_days, 0)
                ),
            ));
        }
    }
    Ok(())
}

/// Step 4: holding drift. See the module docs.
pub fn detect_drift(
    s: &Settings,
    now: f64,
    bal: &Balances,
    j: &Journal,
    state: &mut LadderState,
    out: &mut Vec<Outcome>,
) {
    let snap = state
        .get("_bal")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    let prev_ts = snap.get("ts").and_then(Value::as_f64).unwrap_or(0.0);
    let prev_hold = snap
        .get("hold")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    let prev_booked = snap.get("booked").and_then(Value::as_object);
    let num = |v: Option<&Value>| v.and_then(Value::as_f64);

    let mut cur: IndexMap<String, f64> = IndexMap::new();
    let mut skipped: BTreeSet<&str> = BTreeSet::new();
    for r in &s.routing {
        if bal.failed.contains(&r.exch) {
            skipped.insert(&r.sym);
            if let Some(v) = num(prev_hold.get(&r.sym)) {
                cur.insert(r.sym.clone(), v);
            }
            continue;
        }
        let b = bal
            .full
            .get(&r.exch)
            .and_then(|b| b.get(&r.sym))
            .copied()
            .unwrap_or_default();
        cur.insert(r.sym.clone(), b.free + b.locked);
    }
    let mut booked = Map::new();
    let mut explained: IndexMap<String, f64> = cur.keys().map(|k| (k.clone(), 0.0)).collect();
    for o in j.orders.values() {
        let sign = if o.side == "buy" { 1.0 } else { -1.0 };
        let mut q = o.booked_base() * sign;
        let was = prev_booked
            .and_then(|b| num(b.get(&o.client_id)))
            .unwrap_or(0.0);
        if skipped.contains(o.sym.as_str()) {
            q = was; // the recovery run explains it
        } else if let Some(e) = explained.get_mut(&o.sym) {
            *e += q - was;
        }
        if q != 0.0 {
            booked.insert(o.client_id.clone(), json!(q));
        }
    }
    // No per-order snapshot yet: write one, judge next run.
    if prev_ts != 0.0 && prev_booked.is_some() {
        for (sym, have) in &cur {
            let Some(prev) = num(prev_hold.get(sym)) else {
                continue;
            };
            if skipped.contains(sym.as_str()) {
                continue;
            }
            let expect = prev + explained[sym];
            if hk::drift_exceeds(*have, expect) {
                out.push(Outcome::new(
                    Some(sym),
                    Level::Warn,
                    format!(
                        "holding drift: have ~{}, journal expects ~{} -- manual trade or \
                         transfer? cost basis and ladder ledgers may be stale for {sym}",
                        g(*have, 6),
                        g(expect, 6)
                    ),
                ));
            }
        }
    }
    let hold: Map<String, Value> = cur.iter().map(|(k, v)| (k.clone(), json!(v))).collect();
    state.insert(
        "_bal".into(),
        json!({"ts": now, "hold": hold, "booked": booked}),
    );
}