stockholm 0.2.16

An algorithmic trading bot.
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
use clap::{Args as ClapArgs, ValueEnum};
use std::{error::Error, fs, path::PathBuf};

// These strategies can be evaluated by a backtest.
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum Strategy {
    BuyAndHold,
    MarketMaker,
    MarketMakerGrid,
}

// These arguments configure a backtest run.
#[derive(ClapArgs)]
pub struct Args {
    /// Trading strategy to evaluate. Required for every backtest.
    #[arg(long, value_enum)]
    strategy: Strategy,

    /// CSV files containing historical market data. Required by every strategy.
    #[arg(long, required = true, num_args = 1..)]
    data_paths: Vec<PathBuf>,

    /// Starting cash used by market-maker and market-maker-grid.
    #[arg(long, default_value_t = 1_000_000.0, value_parser = parse_positive_f64)]
    initial_cash: f64,

    /// Buy-order lifetime used by market-maker. Ignored by other strategies.
    #[arg(long, default_value_t = 3_600)]
    buy_ttl: u64,

    /// Sell-order lifetime used by market-maker. Ignored by other strategies.
    #[arg(long, default_value_t = 14_400)]
    sell_ttl: u64,

    /// Buy-limit discount used by market-maker. Ignored by other strategies.
    #[arg(long, default_value_t = 0.25, value_parser = parse_discount_percent)]
    discount_percent: f64,

    /// Sell-limit markup used by market-maker. Ignored by other strategies.
    #[arg(long, default_value_t = 0.25, value_parser = parse_nonnegative_f64)]
    markup_percent: f64,

    /// Buy-order lifetimes searched by market-maker-grid. Ignored by other strategies.
    #[arg(
        long,
        value_delimiter = ',',
        num_args = 1..,
        default_value = "5,15,30,60,120,300,900,3600,7200,14400,43200,86400"
    )]
    buy_ttls: Vec<u64>,

    /// Sell-order lifetimes searched by market-maker-grid. Ignored by other strategies.
    #[arg(
        long,
        value_delimiter = ',',
        num_args = 1..,
        default_value = "5,15,30,60,120,300,900,3600,7200,14400,43200,86400"
    )]
    sell_ttls: Vec<u64>,

    /// Buy-limit discounts searched by market-maker-grid. Ignored by other strategies.
    #[arg(
        long,
        value_delimiter = ',',
        num_args = 1..,
        default_value = "0.01,0.03,0.1,0.3,1,3,10",
        value_parser = parse_discount_percent
    )]
    discount_percentages: Vec<f64>,

    /// Sell-limit markups searched by market-maker-grid. Ignored by other strategies.
    #[arg(
        long,
        value_delimiter = ',',
        num_args = 1..,
        default_value = "0.01,0.03,0.1,0.3,1,3,10",
        value_parser = parse_nonnegative_f64
    )]
    markup_percentages: Vec<f64>,

    /// Number of final rows liquidated in each file. Used by both market-maker strategies.
    #[arg(long, default_value_t = 900)]
    liquidation_seconds: usize,

    /// Maximum shares of each eligible order filled per bar. Used by both market-maker strategies.
    #[arg(long, default_value_t = 1_000.0, value_parser = parse_positive_f64)]
    bar_volume_limit: f64,
}

// This bar contains the prices needed to simulate limit-order fills.
struct Bar {
    low: f64,
    high: f64,
    close: f64,
    liquidate: bool,
}

// This order reserves either cash or shares until it fills or expires.
struct LimitOrder {
    placed_at: u64,
    shares: f64,
    limit: f64,
}

// This configuration defines one market-maker simulation candidate.
#[derive(Clone, Copy)]
struct MarketMakerConfig {
    initial_cash: f64,
    buy_ttl: u64,
    sell_ttl: u64,
    discount_percent: f64,
    markup_percent: f64,
    bar_volume_limit: f64,
}

// This result identifies the most profitable grid candidate.
struct GridResult {
    config: MarketMakerConfig,
    profit: f64,
}

// Backtest a trading strategy.
pub fn run(args: &Args) -> Result<(), Box<dyn Error>> {
    // Sort by filename so every strategy receives the data in chronological order.
    let mut data_paths = args.data_paths.iter().collect::<Vec<_>>();
    data_paths.sort();

    // Load every sorted file before dispatching to the selected strategy.
    let files = data_paths
        .into_iter()
        .map(|path| {
            let contents = fs::read_to_string(path)
                .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
            Ok((path.clone(), contents))
        })
        .collect::<Result<Vec<_>, Box<dyn Error>>>()?;

    // Evaluate the selected strategy and print its result to standard output.
    match args.strategy {
        Strategy::BuyAndHold => {
            let change = buy_and_hold(&files)?;
            println!("{change}");
        }
        Strategy::MarketMaker => {
            let profit = market_maker(&files, args)?;
            println!("{profit}");
        }
        Strategy::MarketMakerGrid => {
            let result = market_maker_grid(&files, args)?;
            write_grid_result(&result)?;
        }
    }

    Ok(())
}

// Simulate repeatedly buying below and selling above the current market price.
fn market_maker(files: &[(PathBuf, String)], args: &Args) -> Result<f64, Box<dyn Error>> {
    // Parse every chronological bar before changing the simulated portfolio.
    let bars = parse_bars(files, args.liquidation_seconds)?;
    simulate_market_maker(&bars, market_maker_config(args))
}

// Evaluate nearby parameter combinations and return the most profitable one.
fn market_maker_grid(
    files: &[(PathBuf, String)],
    args: &Args,
) -> Result<GridResult, Box<dyn Error>> {
    // Parse the historical bars once because every candidate uses identical market data.
    let bars = parse_bars(files, args.liquidation_seconds)?;

    // Track completed candidates while keeping progress messages separate from CSV output.
    let candidates_per_ttl_pair = args.discount_percentages.len() * args.markup_percentages.len();
    let total_candidates = args.buy_ttls.len() * args.sell_ttls.len() * candidates_per_ttl_pair;
    let mut completed_candidates = 0_usize;
    eprintln!("Searching {total_candidates} market-maker configurations...");

    // Search the Cartesian product while retaining the first candidate in a tie.
    let mut best = None::<GridResult>;
    for &buy_ttl in &args.buy_ttls {
        for &sell_ttl in &args.sell_ttls {
            for &discount_percent in &args.discount_percentages {
                for &markup_percent in &args.markup_percentages {
                    let config = MarketMakerConfig {
                        initial_cash: args.initial_cash,
                        buy_ttl,
                        sell_ttl,
                        discount_percent,
                        markup_percent,
                        bar_volume_limit: args.bar_volume_limit,
                    };
                    let profit = simulate_market_maker(&bars, config)?;
                    if best.as_ref().is_none_or(|result| profit > result.profit) {
                        best = Some(GridResult { config, profit });
                    }
                }
            }
            completed_candidates += candidates_per_ttl_pair;
            let progress_tenths = 1_000 * completed_candidates / total_candidates;
            eprintln!(
                "Searched {completed_candidates}/{total_candidates} configurations ({}.{:01}%)",
                progress_tenths / 10,
                progress_tenths % 10,
            );
        }
    }

    best.ok_or_else(|| "the parameter grid contains no valid candidates".into())
}

// Simulate one market-maker configuration over already parsed bars.
fn simulate_market_maker(bars: &[Bar], config: MarketMakerConfig) -> Result<f64, Box<dyn Error>> {
    // Start each independent candidate with the same entirely liquid portfolio.
    let mut available_cash = config.initial_cash;
    let mut available_shares = 0.0_f64;
    let mut buy_orders = Vec::<LimitOrder>::new();
    let mut sell_orders = Vec::<LimitOrder>::new();

    // Cancel, fill, and replace orders once for every one-second bar.
    for (second, bar) in bars.iter().enumerate() {
        let second = u64::try_from(second)?;

        // Cancel pending orders and sell up to one bar's volume at the current close.
        if bar.liquidate {
            available_cash += buy_orders
                .drain(..)
                .map(|order| order.shares * order.limit)
                .sum::<f64>();
            available_shares += sell_orders.drain(..).map(|order| order.shares).sum::<f64>();
            let filled_shares = available_shares.min(config.bar_volume_limit);
            available_cash += filled_shares * bar.close;
            available_shares -= filled_shares;
            continue;
        }

        // Return resources reserved by orders older than their configured lifetimes.
        buy_orders.retain(|order| {
            if second.saturating_sub(order.placed_at) > config.buy_ttl {
                available_cash += order.shares * order.limit;
                false
            } else {
                true
            }
        });
        sell_orders.retain(|order| {
            if second.saturating_sub(order.placed_at) > config.sell_ttl {
                available_shares += order.shares;
                false
            } else {
                true
            }
        });

        // Partially fill each eligible buy order by at most one bar's configured volume.
        for order in &mut buy_orders {
            if bar.low <= order.limit {
                let filled_shares = order.shares.min(config.bar_volume_limit);
                available_shares += filled_shares;
                order.shares -= filled_shares;
            }
        }
        buy_orders.retain(|order| order.shares > 0.0_f64);

        // Partially fill each eligible sell order by at most one bar's configured volume.
        for order in &mut sell_orders {
            if bar.high >= order.limit {
                let filled_shares = order.shares.min(config.bar_volume_limit);
                available_cash += filled_shares * order.limit;
                order.shares -= filled_shares;
            }
        }
        sell_orders.retain(|order| order.shares > 0.0_f64);

        // Reserve available cash for the largest whole-share discounted buy order.
        let buy_limit = bar.close * (1.0_f64 - config.discount_percent / 100.0_f64);
        let buy_shares = (available_cash / buy_limit).floor();
        if buy_shares >= 1.0_f64 {
            available_cash -= buy_shares * buy_limit;
            buy_orders.push(LimitOrder {
                placed_at: second,
                shares: buy_shares,
                limit: buy_limit,
            });
        }

        // Reserve every available share for one marked-up sell order.
        if available_shares > 0.0_f64 {
            let sell_limit = bar.close * (1.0_f64 + config.markup_percent / 100.0_f64);
            sell_orders.push(LimitOrder {
                placed_at: second,
                shares: available_shares,
                limit: sell_limit,
            });
            available_shares = 0.0_f64;
        }
    }

    // Mark reserved cash and all held shares to the final close before reporting profit.
    let final_price = bars.last().unwrap().close;
    let reserved_cash = buy_orders
        .iter()
        .map(|order| order.shares * order.limit)
        .sum::<f64>();
    let reserved_shares = sell_orders.iter().map(|order| order.shares).sum::<f64>();
    let final_value =
        available_cash + reserved_cash + (available_shares + reserved_shares) * final_price;

    Ok(final_value - config.initial_cash)
}

// Copy market-maker command-line values into one simulation configuration.
fn market_maker_config(args: &Args) -> MarketMakerConfig {
    // Keep simulation code independent from unrelated backtest arguments.
    MarketMakerConfig {
        initial_cash: args.initial_cash,
        buy_ttl: args.buy_ttl,
        sell_ttl: args.sell_ttl,
        discount_percent: args.discount_percent,
        markup_percent: args.markup_percent,
        bar_volume_limit: args.bar_volume_limit,
    }
}

// Print the winning grid candidate as one machine-readable CSV record.
fn write_grid_result(result: &GridResult) -> Result<(), Box<dyn Error>> {
    // Include every fixed and searched value needed to reproduce the result.
    let mut writer = csv::Writer::from_writer(std::io::stdout().lock());
    writer.write_record([
        "profit",
        "initial_cash",
        "buy_ttl",
        "sell_ttl",
        "discount_percent",
        "markup_percent",
        "bar_volume_limit",
    ])?;
    writer.write_record([
        result.profit.to_string(),
        result.config.initial_cash.to_string(),
        result.config.buy_ttl.to_string(),
        result.config.sell_ttl.to_string(),
        result.config.discount_percent.to_string(),
        result.config.markup_percent.to_string(),
        result.config.bar_volume_limit.to_string(),
    ])?;
    writer.flush()?;

    Ok(())
}

// Parse the low, high, and closing prices from every input row.
fn parse_bars(
    files: &[(PathBuf, String)],
    liquidation_seconds: usize,
) -> Result<Vec<Bar>, Box<dyn Error>> {
    // Preserve the already sorted file and record order while validating each price.
    let mut bars = Vec::new();
    for (path, contents) in files {
        let mut reader = csv::Reader::from_reader(contents.as_bytes());
        let headers = reader.headers()?;
        let low_index = column_index(headers, path, "low")?;
        let high_index = column_index(headers, path, "high")?;
        let close_index = column_index(headers, path, "close")?;
        let records = reader.records().collect::<Result<Vec<_>, _>>()?;
        if records.is_empty() {
            return Err(format!("{} must contain at least one data row", path.display()).into());
        }
        let liquidation_start = records.len().saturating_sub(liquidation_seconds);
        for (index, record) in records.iter().enumerate() {
            let line = index + 2;
            bars.push(Bar {
                low: parse_price(record.get(low_index), path, &format!("low on line {line}"))?,
                high: parse_price(
                    record.get(high_index),
                    path,
                    &format!("high on line {line}"),
                )?,
                close: parse_price(
                    record.get(close_index),
                    path,
                    &format!("close on line {line}"),
                )?,
                liquidate: liquidation_seconds > 0
                    && records.len() >= liquidation_seconds
                    && index >= liquidation_start,
            });
        }
    }
    if bars.is_empty() {
        return Err("at least one data file is required".into());
    }

    Ok(bars)
}

// Locate one required CSV price column.
fn column_index(
    headers: &csv::StringRecord,
    path: &std::path::Path,
    name: &str,
) -> Result<usize, Box<dyn Error>> {
    // Report the source file when a required market-data field is absent.
    headers
        .iter()
        .position(|header| header == name)
        .ok_or_else(|| format!("{} must contain a {name} column", path.display()).into())
}

// Calculate the absolute price change produced by buying first and selling last.
fn buy_and_hold(files: &[(PathBuf, String)]) -> Result<f64, Box<dyn Error>> {
    // Read the first open and final close while requiring data in every input file.
    let mut first_open = None;
    let mut last_close = None;
    for (path, contents) in files {
        let mut reader = csv::Reader::from_reader(contents.as_bytes());
        let headers = reader.headers()?;
        let open_index = headers
            .iter()
            .position(|header| header == "open")
            .ok_or_else(|| format!("{} must contain an open column", path.display()))?;
        let close_index = headers
            .iter()
            .position(|header| header == "close")
            .ok_or_else(|| format!("{} must contain a close column", path.display()))?;
        let records = reader.records().collect::<Result<Vec<_>, _>>()?;
        let first_record = records
            .first()
            .ok_or_else(|| format!("{} must contain at least one data row", path.display()))?;
        let last_record = records.last().unwrap();

        // Parse finite positive prices before using the boundary records.
        let open = parse_price(first_record.get(open_index), path, "opening")?;
        let close = parse_price(last_record.get(close_index), path, "closing")?;
        first_open.get_or_insert(open);
        last_close = Some(close);
    }

    let first_open = first_open.ok_or("at least one data file is required")?;
    Ok(last_close.unwrap() - first_open)
}

// Parse one required boundary price with a contextual error.
fn parse_price(
    value: Option<&str>,
    path: &std::path::Path,
    description: &str,
) -> Result<f64, Box<dyn Error>> {
    // Reject missing, nonnumeric, nonfinite, and nonpositive prices consistently.
    let value =
        value.ok_or_else(|| format!("{} is missing its {description} price", path.display()))?;
    let price = value
        .parse::<f64>()
        .map_err(|error| format!("invalid {description} price in {}: {error}", path.display()))?;
    if !price.is_finite() || price <= 0.0_f64 {
        return Err(format!(
            "{description} price in {} must be finite and positive",
            path.display(),
        )
        .into());
    }

    Ok(price)
}

// Parse a finite positive floating-point command-line argument.
fn parse_positive_f64(value: &str) -> Result<f64, String> {
    // Reject values that cannot represent usable starting capital.
    let value = value.parse::<f64>().map_err(|error| error.to_string())?;
    if !value.is_finite() || value <= 0.0_f64 {
        return Err("value must be finite and greater than zero".to_string());
    }

    Ok(value)
}

// Parse a finite nonnegative floating-point command-line argument.
fn parse_nonnegative_f64(value: &str) -> Result<f64, String> {
    // Permit a zero markup while rejecting negative and nonfinite percentages.
    let value = value.parse::<f64>().map_err(|error| error.to_string())?;
    if !value.is_finite() || value < 0.0_f64 {
        return Err("value must be finite and nonnegative".to_string());
    }

    Ok(value)
}

// Parse a discount percentage that always produces a positive limit price.
fn parse_discount_percent(value: &str) -> Result<f64, String> {
    // Reject discounts at or above one hundred percent to keep buy limits valid.
    let value = parse_nonnegative_f64(value)?;
    if value >= 100.0_f64 {
        return Err("value must be less than 100".to_string());
    }

    Ok(value)
}

#[cfg(test)]
mod tests {
    use super::{
        Args, Bar, MarketMakerConfig, Strategy, buy_and_hold, market_maker, market_maker_grid,
        simulate_market_maker,
    };
    use crate::{Cli, Subcommand};
    use clap::Parser;
    use std::path::PathBuf;

    #[test]
    fn parse_backtest_subcommand() {
        // Confirm the backtest mode accepts the buy-and-hold strategy.
        let cli = Cli::try_parse_from([
            "stockholm",
            "backtest",
            "--strategy",
            "buy-and-hold",
            "--data-paths",
            "monday.csv",
            "tuesday.csv",
        ])
        .unwrap();

        let Some(Subcommand::Backtest(args)) = cli.command else {
            panic!("expected backtest subcommand");
        };
        assert_eq!(args.strategy, Strategy::BuyAndHold);
        assert_eq!(
            args.data_paths,
            vec![PathBuf::from("monday.csv"), PathBuf::from("tuesday.csv")],
        );
        assert!((args.initial_cash - 1_000_000.0).abs() < f64::EPSILON);
        assert_eq!(args.buy_ttl, 3_600);
        assert_eq!(args.sell_ttl, 14_400);
        assert!((args.discount_percent - 0.25).abs() < f64::EPSILON);
        assert!((args.markup_percent - 0.25).abs() < f64::EPSILON);
        assert_eq!(args.buy_ttls.len(), 12);
        assert_eq!(args.buy_ttls.first(), Some(&5));
        assert_eq!(args.buy_ttls.last(), Some(&86_400));
        assert_eq!(args.sell_ttls.len(), 12);
        assert_eq!(args.sell_ttls.first(), Some(&5));
        assert_eq!(args.sell_ttls.last(), Some(&86_400));
        assert_eq!(args.discount_percentages.len(), 7);
        assert_eq!(args.discount_percentages.first(), Some(&0.01_f64));
        assert_eq!(args.discount_percentages.last(), Some(&10.0_f64));
        assert_eq!(args.markup_percentages.len(), 7);
        assert_eq!(args.markup_percentages.first(), Some(&0.01_f64));
        assert_eq!(args.markup_percentages.last(), Some(&10.0_f64));
        assert_eq!(args.liquidation_seconds, 900);
        assert!((args.bar_volume_limit - 1_000.0).abs() < f64::EPSILON);
    }

    #[test]
    fn calculate_buy_and_hold_from_chronological_files() {
        // Confirm the strategy uses the first open and final close it receives.
        let files = vec![
            (
                PathBuf::from("monday.csv"),
                "open,close\n100,110\n110,120\n".to_string(),
            ),
            (
                PathBuf::from("tuesday.csv"),
                "open,close\n200,210\n210,230\n".to_string(),
            ),
        ];

        assert!((buy_and_hold(&files).unwrap() - 130.0).abs() < f64::EPSILON);
    }

    #[test]
    fn fill_market_maker_orders() {
        // Confirm discounted buys and marked-up sells reserve and return resources.
        let files = vec![(
            PathBuf::from("prices.csv"),
            concat!(
                "low,high,close\n",
                "100,100,100\n",
                "99,100,100\n",
                "100,101,100\n",
            )
            .to_string(),
        )];
        let args = market_maker_args(1_000.0, 3_600, 14_400);

        assert!((market_maker(&files, &args).unwrap() - 20.0).abs() < f64::EPSILON);
    }

    #[test]
    fn refund_expired_market_maker_orders() {
        // Confirm canceling an expired buy restores its reserved cash.
        let files = vec![(
            PathBuf::from("prices.csv"),
            "low,high,close\n100,100,100\n200,200,200\n".to_string(),
        )];
        let args = market_maker_args(1_000.0, 0, 14_400);

        assert!(market_maker(&files, &args).unwrap().abs() < f64::EPSILON);
    }

    #[test]
    fn liquidate_market_maker_inventory() {
        // Confirm the liquidation window cancels orders and sells every held share at the close.
        let bars = vec![
            Bar {
                low: 100.0,
                high: 100.0,
                close: 100.0,
                liquidate: false,
            },
            Bar {
                low: 99.0,
                high: 100.0,
                close: 100.0,
                liquidate: false,
            },
            Bar {
                low: 90.0,
                high: 90.0,
                close: 90.0,
                liquidate: true,
            },
        ];
        let config = MarketMakerConfig {
            initial_cash: 1_000.0,
            buy_ttl: 3_600,
            sell_ttl: 14_400,
            discount_percent: 1.0,
            markup_percent: 1.0,
            bar_volume_limit: 1_000.0,
        };

        assert!((simulate_market_maker(&bars, config).unwrap() + 90.0).abs() < f64::EPSILON);
    }

    #[test]
    fn select_best_market_maker_grid_candidate() {
        // Confirm the grid chooses the most profitable reproducible parameters.
        let files = vec![(
            PathBuf::from("prices.csv"),
            concat!(
                "low,high,close\n",
                "100,100,100\n",
                "99,100,100\n",
                "100,102,100\n",
            )
            .to_string(),
        )];
        let args = market_maker_args(1_000.0, 10, 10);
        let result = market_maker_grid(&files, &args).unwrap();

        assert!((result.profit - 20.0).abs() < f64::EPSILON);
        assert!((result.config.discount_percent - 1.0).abs() < f64::EPSILON);
        assert!((result.config.markup_percent - 1.0).abs() < f64::EPSILON);
        assert_eq!(result.config.buy_ttl, 5);
        assert_eq!(result.config.sell_ttl, 5);
    }

    #[test]
    fn partially_fill_market_maker_orders() {
        // Confirm an eligible order needs multiple bars when it exceeds the volume limit.
        let bars = vec![
            Bar {
                low: 100.0,
                high: 100.0,
                close: 100.0,
                liquidate: false,
            },
            Bar {
                low: 99.0,
                high: 100.0,
                close: 100.0,
                liquidate: false,
            },
            Bar {
                low: 100.0,
                high: 101.0,
                close: 100.0,
                liquidate: false,
            },
        ];
        let config = MarketMakerConfig {
            initial_cash: 1_000.0,
            buy_ttl: 3_600,
            sell_ttl: 14_400,
            discount_percent: 1.0,
            markup_percent: 1.0,
            bar_volume_limit: 5.0,
        };

        assert!((simulate_market_maker(&bars, config).unwrap() - 10.0).abs() < f64::EPSILON);
    }

    // Construct focused market-maker settings without invoking command-line parsing.
    fn market_maker_args(initial_cash: f64, buy_ttl: u64, sell_ttl: u64) -> Args {
        Args {
            strategy: Strategy::MarketMaker,
            data_paths: Vec::new(),
            initial_cash,
            buy_ttl,
            sell_ttl,
            discount_percent: 1.0,
            markup_percent: 1.0,
            buy_ttls: vec![
                5, 15, 30, 60, 120, 300, 900, 3_600, 7_200, 14_400, 43_200, 86_400,
            ],
            sell_ttls: vec![
                5, 15, 30, 60, 120, 300, 900, 3_600, 7_200, 14_400, 43_200, 86_400,
            ],
            discount_percentages: vec![0.01, 0.03, 0.1, 0.3, 1.0, 3.0, 10.0],
            markup_percentages: vec![0.01, 0.03, 0.1, 0.3, 1.0, 3.0, 10.0],
            liquidation_seconds: 900,
            bar_volume_limit: 1_000.0,
        }
    }
}