ibapi 2.11.1

A Rust implementation of the Interactive Brokers TWS API, providing a reliable and user friendly interface for TWS and IB Gateway. Designed with a focus on simplicity and performance.
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
//! Builder structs for IB algorithmic order strategies.
//!
//! This module provides type-safe builders for common IB algo strategies:
//! VWAP, TWAP, Percentage of Volume, and Arrival Price.

use super::types::ValidationError;
use crate::contracts::TagValue;

/// Convert a boolean to IB's string representation ("1" or "0").
fn bool_param(v: bool) -> String {
    if v { "1" } else { "0" }.to_string()
}

/// Minimum allowed participation rate (10%).
pub const MIN_PCT_VOL: f64 = 0.1;
/// Maximum allowed participation rate (50%).
pub const MAX_PCT_VOL: f64 = 0.5;

/// Validate percentage is within IB's allowed range.
fn validate_pct_vol(field: &'static str, value: f64) -> Result<(), ValidationError> {
    if !(MIN_PCT_VOL..=MAX_PCT_VOL).contains(&value) {
        Err(ValidationError::InvalidPercentage {
            field,
            value,
            min: MIN_PCT_VOL,
            max: MAX_PCT_VOL,
        })
    } else {
        Ok(())
    }
}

/// Parameters for an algorithmic order strategy.
#[derive(Debug, Clone, Default)]
pub struct AlgoParams {
    /// The algorithm strategy name (e.g., "Vwap", "Twap")
    pub strategy: String,
    /// The algorithm parameters as tag-value pairs
    pub params: Vec<TagValue>,
}

impl From<String> for AlgoParams {
    fn from(strategy: String) -> Self {
        Self {
            strategy,
            params: Vec::new(),
        }
    }
}

impl From<&str> for AlgoParams {
    fn from(strategy: &str) -> Self {
        Self {
            strategy: strategy.to_string(),
            params: Vec::new(),
        }
    }
}

// === VWAP Builder ===

/// Builder for VWAP (Volume Weighted Average Price) algorithmic orders.
///
/// VWAP seeks to achieve the volume-weighted average price from order
/// submission to market close.
///
/// # Example
///
/// ```no_run
/// use ibapi::orders::builder::vwap;
///
/// let algo = vwap()
///     .max_pct_vol(0.2)
///     .start_time("09:00:00 US/Eastern")
///     .end_time("16:00:00 US/Eastern")
///     .build()?;
/// # Ok::<(), ibapi::orders::builder::ValidationError>(())
/// ```
#[derive(Debug, Clone, Default)]
pub struct VwapBuilder {
    max_pct_vol: Option<f64>,
    start_time: Option<String>,
    end_time: Option<String>,
    allow_past_end_time: Option<bool>,
    no_take_liq: Option<bool>,
    speed_up: Option<bool>,
}

impl VwapBuilder {
    /// Create a new VWAP builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum participation rate (must be 10-50% per IB requirements).
    pub fn max_pct_vol(mut self, pct: f64) -> Self {
        self.max_pct_vol = Some(pct);
        self
    }

    /// Set start time (format: "HH:MM:SS TZ", e.g., "09:00:00 US/Eastern").
    pub fn start_time(mut self, time: impl Into<String>) -> Self {
        self.start_time = Some(time.into());
        self
    }

    /// Set end time (format: "HH:MM:SS TZ", e.g., "16:00:00 US/Eastern").
    pub fn end_time(mut self, time: impl Into<String>) -> Self {
        self.end_time = Some(time.into());
        self
    }

    /// Allow trading past the end time.
    pub fn allow_past_end_time(mut self, allow: bool) -> Self {
        self.allow_past_end_time = Some(allow);
        self
    }

    /// Passive only - do not take liquidity.
    pub fn no_take_liq(mut self, no_take: bool) -> Self {
        self.no_take_liq = Some(no_take);
        self
    }

    /// Speed up execution in momentum.
    pub fn speed_up(mut self, speed_up: bool) -> Self {
        self.speed_up = Some(speed_up);
        self
    }

    /// Build the algo parameters.
    ///
    /// Returns an error if `max_pct_vol` is set but outside the 10-50% range.
    pub fn build(self) -> Result<AlgoParams, ValidationError> {
        let mut params = Vec::new();

        if let Some(v) = self.max_pct_vol {
            validate_pct_vol("max_pct_vol", v)?;
            params.push(TagValue {
                tag: "maxPctVol".to_string(),
                value: v.to_string(),
            });
        }
        if let Some(v) = self.start_time {
            params.push(TagValue {
                tag: "startTime".to_string(),
                value: v,
            });
        }
        if let Some(v) = self.end_time {
            params.push(TagValue {
                tag: "endTime".to_string(),
                value: v,
            });
        }
        if let Some(v) = self.allow_past_end_time {
            params.push(TagValue {
                tag: "allowPastEndTime".to_string(),
                value: bool_param(v),
            });
        }
        if let Some(v) = self.no_take_liq {
            params.push(TagValue {
                tag: "noTakeLiq".to_string(),
                value: bool_param(v),
            });
        }
        if let Some(v) = self.speed_up {
            params.push(TagValue {
                tag: "speedUp".to_string(),
                value: bool_param(v),
            });
        }

        Ok(AlgoParams {
            strategy: "Vwap".to_string(),
            params,
        })
    }
}

impl TryFrom<VwapBuilder> for AlgoParams {
    type Error = ValidationError;

    fn try_from(builder: VwapBuilder) -> Result<Self, Self::Error> {
        builder.build()
    }
}

// === TWAP Builder ===

/// Strategy type for TWAP orders.
#[derive(Debug, Clone, Copy, Default)]
pub enum TwapStrategyType {
    /// Default TWAP strategy
    #[default]
    Marketable,
    /// Match midpoint
    MatchingMidpoint,
    /// Match same side
    MatchingSameSide,
    /// Match last
    MatchingLast,
}

impl TwapStrategyType {
    fn as_str(&self) -> &'static str {
        match self {
            TwapStrategyType::Marketable => "Marketable",
            TwapStrategyType::MatchingMidpoint => "Matching Midpoint",
            TwapStrategyType::MatchingSameSide => "Matching Same Side",
            TwapStrategyType::MatchingLast => "Matching Last",
        }
    }
}

/// Builder for TWAP (Time Weighted Average Price) algorithmic orders.
///
/// TWAP seeks to achieve the time-weighted average price.
///
/// # Example
///
/// ```no_run
/// use ibapi::orders::builder::twap;
///
/// let algo = twap()
///     .start_time("09:00:00 US/Eastern")
///     .end_time("16:00:00 US/Eastern")
///     .build()?;
/// # Ok::<(), ibapi::orders::builder::ValidationError>(())
/// ```
#[derive(Debug, Clone, Default)]
pub struct TwapBuilder {
    strategy_type: Option<TwapStrategyType>,
    start_time: Option<String>,
    end_time: Option<String>,
    allow_past_end_time: Option<bool>,
}

impl TwapBuilder {
    /// Create a new TWAP builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the TWAP strategy type.
    pub fn strategy_type(mut self, strategy: TwapStrategyType) -> Self {
        self.strategy_type = Some(strategy);
        self
    }

    /// Set start time (format: "HH:MM:SS TZ", e.g., "09:00:00 US/Eastern").
    pub fn start_time(mut self, time: impl Into<String>) -> Self {
        self.start_time = Some(time.into());
        self
    }

    /// Set end time (format: "HH:MM:SS TZ", e.g., "16:00:00 US/Eastern").
    pub fn end_time(mut self, time: impl Into<String>) -> Self {
        self.end_time = Some(time.into());
        self
    }

    /// Allow trading past the end time.
    pub fn allow_past_end_time(mut self, allow: bool) -> Self {
        self.allow_past_end_time = Some(allow);
        self
    }

    /// Build the algo parameters.
    pub fn build(self) -> Result<AlgoParams, ValidationError> {
        let mut params = Vec::new();

        if let Some(v) = self.strategy_type {
            params.push(TagValue {
                tag: "strategyType".to_string(),
                value: v.as_str().to_string(),
            });
        }
        if let Some(v) = self.start_time {
            params.push(TagValue {
                tag: "startTime".to_string(),
                value: v,
            });
        }
        if let Some(v) = self.end_time {
            params.push(TagValue {
                tag: "endTime".to_string(),
                value: v,
            });
        }
        if let Some(v) = self.allow_past_end_time {
            params.push(TagValue {
                tag: "allowPastEndTime".to_string(),
                value: bool_param(v),
            });
        }

        Ok(AlgoParams {
            strategy: "Twap".to_string(),
            params,
        })
    }
}

impl TryFrom<TwapBuilder> for AlgoParams {
    type Error = ValidationError;

    fn try_from(builder: TwapBuilder) -> Result<Self, Self::Error> {
        builder.build()
    }
}

// === Percentage of Volume Builder ===

/// Builder for Percentage of Volume (PctVol) algorithmic orders.
///
/// Controls participation rate to minimize market impact.
///
/// # Example
///
/// ```no_run
/// use ibapi::orders::builder::pct_vol;
///
/// let algo = pct_vol()
///     .pct_vol(0.1)
///     .start_time("09:00:00 US/Eastern")
///     .end_time("16:00:00 US/Eastern")
///     .build()?;
/// # Ok::<(), ibapi::orders::builder::ValidationError>(())
/// ```
#[derive(Debug, Clone, Default)]
pub struct PctVolBuilder {
    pct_vol: Option<f64>,
    start_time: Option<String>,
    end_time: Option<String>,
    no_take_liq: Option<bool>,
}

impl PctVolBuilder {
    /// Create a new PctVol builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set target participation rate (must be 10-50% per IB requirements).
    pub fn pct_vol(mut self, pct: f64) -> Self {
        self.pct_vol = Some(pct);
        self
    }

    /// Set start time (format: "HH:MM:SS TZ", e.g., "09:00:00 US/Eastern").
    pub fn start_time(mut self, time: impl Into<String>) -> Self {
        self.start_time = Some(time.into());
        self
    }

    /// Set end time (format: "HH:MM:SS TZ", e.g., "16:00:00 US/Eastern").
    pub fn end_time(mut self, time: impl Into<String>) -> Self {
        self.end_time = Some(time.into());
        self
    }

    /// Passive only - do not take liquidity.
    pub fn no_take_liq(mut self, no_take: bool) -> Self {
        self.no_take_liq = Some(no_take);
        self
    }

    /// Build the algo parameters.
    ///
    /// Returns an error if `pct_vol` is set but outside the 10-50% range.
    pub fn build(self) -> Result<AlgoParams, ValidationError> {
        let mut params = Vec::new();

        if let Some(v) = self.pct_vol {
            validate_pct_vol("pct_vol", v)?;
            params.push(TagValue {
                tag: "pctVol".to_string(),
                value: v.to_string(),
            });
        }
        if let Some(v) = self.start_time {
            params.push(TagValue {
                tag: "startTime".to_string(),
                value: v,
            });
        }
        if let Some(v) = self.end_time {
            params.push(TagValue {
                tag: "endTime".to_string(),
                value: v,
            });
        }
        if let Some(v) = self.no_take_liq {
            params.push(TagValue {
                tag: "noTakeLiq".to_string(),
                value: bool_param(v),
            });
        }

        Ok(AlgoParams {
            strategy: "PctVol".to_string(),
            params,
        })
    }
}

impl TryFrom<PctVolBuilder> for AlgoParams {
    type Error = ValidationError;

    fn try_from(builder: PctVolBuilder) -> Result<Self, Self::Error> {
        builder.build()
    }
}

// === Arrival Price Builder ===

/// Risk aversion level for Arrival Price orders.
#[derive(Debug, Clone, Copy, Default)]
pub enum RiskAversion {
    /// Get Done - complete order quickly
    GetDone,
    /// Aggressive - favor speed over price
    Aggressive,
    /// Neutral - balance speed and price
    #[default]
    Neutral,
    /// Passive - favor price over speed
    Passive,
}

impl RiskAversion {
    fn as_str(&self) -> &'static str {
        match self {
            RiskAversion::GetDone => "Get Done",
            RiskAversion::Aggressive => "Aggressive",
            RiskAversion::Neutral => "Neutral",
            RiskAversion::Passive => "Passive",
        }
    }
}

/// Builder for Arrival Price algorithmic orders.
///
/// Achieves the bid/ask midpoint at order arrival time.
///
/// # Example
///
/// ```no_run
/// use ibapi::orders::builder::{arrival_price, RiskAversion};
///
/// let algo = arrival_price()
///     .max_pct_vol(0.1)
///     .risk_aversion(RiskAversion::Neutral)
///     .start_time("09:00:00 US/Eastern")
///     .end_time("16:00:00 US/Eastern")
///     .build()?;
/// # Ok::<(), ibapi::orders::builder::ValidationError>(())
/// ```
#[derive(Debug, Clone, Default)]
pub struct ArrivalPriceBuilder {
    max_pct_vol: Option<f64>,
    risk_aversion: Option<RiskAversion>,
    start_time: Option<String>,
    end_time: Option<String>,
    force_completion: Option<bool>,
    allow_past_end_time: Option<bool>,
}

impl ArrivalPriceBuilder {
    /// Create a new Arrival Price builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum participation rate (must be 10-50% per IB requirements).
    pub fn max_pct_vol(mut self, pct: f64) -> Self {
        self.max_pct_vol = Some(pct);
        self
    }

    /// Set risk aversion level.
    pub fn risk_aversion(mut self, risk: RiskAversion) -> Self {
        self.risk_aversion = Some(risk);
        self
    }

    /// Set start time (format: "HH:MM:SS TZ", e.g., "09:00:00 US/Eastern").
    pub fn start_time(mut self, time: impl Into<String>) -> Self {
        self.start_time = Some(time.into());
        self
    }

    /// Set end time (format: "HH:MM:SS TZ", e.g., "16:00:00 US/Eastern").
    pub fn end_time(mut self, time: impl Into<String>) -> Self {
        self.end_time = Some(time.into());
        self
    }

    /// Force completion by end time.
    pub fn force_completion(mut self, force: bool) -> Self {
        self.force_completion = Some(force);
        self
    }

    /// Allow trading past the end time.
    pub fn allow_past_end_time(mut self, allow: bool) -> Self {
        self.allow_past_end_time = Some(allow);
        self
    }

    /// Build the algo parameters.
    ///
    /// Returns an error if `max_pct_vol` is set but outside the 10-50% range.
    pub fn build(self) -> Result<AlgoParams, ValidationError> {
        let mut params = Vec::new();

        if let Some(v) = self.max_pct_vol {
            validate_pct_vol("max_pct_vol", v)?;
            params.push(TagValue {
                tag: "maxPctVol".to_string(),
                value: v.to_string(),
            });
        }
        if let Some(v) = self.risk_aversion {
            params.push(TagValue {
                tag: "riskAversion".to_string(),
                value: v.as_str().to_string(),
            });
        }
        if let Some(v) = self.start_time {
            params.push(TagValue {
                tag: "startTime".to_string(),
                value: v,
            });
        }
        if let Some(v) = self.end_time {
            params.push(TagValue {
                tag: "endTime".to_string(),
                value: v,
            });
        }
        if let Some(v) = self.force_completion {
            params.push(TagValue {
                tag: "forceCompletion".to_string(),
                value: bool_param(v),
            });
        }
        if let Some(v) = self.allow_past_end_time {
            params.push(TagValue {
                tag: "allowPastEndTime".to_string(),
                value: bool_param(v),
            });
        }

        Ok(AlgoParams {
            strategy: "ArrivalPx".to_string(),
            params,
        })
    }
}

impl TryFrom<ArrivalPriceBuilder> for AlgoParams {
    type Error = ValidationError;

    fn try_from(builder: ArrivalPriceBuilder) -> Result<Self, Self::Error> {
        builder.build()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_algo_params_from_string() {
        let params: AlgoParams = "Vwap".into();
        assert_eq!(params.strategy, "Vwap");
        assert!(params.params.is_empty());
    }

    #[test]
    fn test_vwap_builder() {
        let params = VwapBuilder::new()
            .max_pct_vol(0.2)
            .start_time("09:00:00 US/Eastern")
            .end_time("16:00:00 US/Eastern")
            .allow_past_end_time(true)
            .no_take_liq(true)
            .speed_up(true)
            .build()
            .unwrap();

        assert_eq!(params.strategy, "Vwap");
        assert_eq!(params.params.len(), 6);

        let find_param = |tag: &str| params.params.iter().find(|p| p.tag == tag).map(|p| &p.value);
        assert_eq!(find_param("maxPctVol"), Some(&"0.2".to_string()));
        assert_eq!(find_param("startTime"), Some(&"09:00:00 US/Eastern".to_string()));
        assert_eq!(find_param("endTime"), Some(&"16:00:00 US/Eastern".to_string()));
        assert_eq!(find_param("allowPastEndTime"), Some(&"1".to_string()));
        assert_eq!(find_param("noTakeLiq"), Some(&"1".to_string()));
        assert_eq!(find_param("speedUp"), Some(&"1".to_string()));
    }

    #[test]
    fn test_twap_builder() {
        let params = TwapBuilder::new()
            .strategy_type(TwapStrategyType::MatchingMidpoint)
            .start_time("09:00:00 US/Eastern")
            .end_time("16:00:00 US/Eastern")
            .allow_past_end_time(false)
            .build()
            .unwrap();

        assert_eq!(params.strategy, "Twap");
        assert_eq!(params.params.len(), 4);

        let find_param = |tag: &str| params.params.iter().find(|p| p.tag == tag).map(|p| &p.value);
        assert_eq!(find_param("strategyType"), Some(&"Matching Midpoint".to_string()));
        assert_eq!(find_param("allowPastEndTime"), Some(&"0".to_string()));
    }

    #[test]
    fn test_pct_vol_builder() {
        let params = PctVolBuilder::new()
            .pct_vol(0.15)
            .start_time("09:30:00 US/Eastern")
            .end_time("15:30:00 US/Eastern")
            .no_take_liq(false)
            .build()
            .unwrap();

        assert_eq!(params.strategy, "PctVol");
        assert_eq!(params.params.len(), 4);

        let find_param = |tag: &str| params.params.iter().find(|p| p.tag == tag).map(|p| &p.value);
        assert_eq!(find_param("pctVol"), Some(&"0.15".to_string()));
        assert_eq!(find_param("noTakeLiq"), Some(&"0".to_string()));
    }

    #[test]
    fn test_arrival_price_builder() {
        let params = ArrivalPriceBuilder::new()
            .max_pct_vol(0.1)
            .risk_aversion(RiskAversion::Aggressive)
            .start_time("09:00:00 US/Eastern")
            .end_time("16:00:00 US/Eastern")
            .force_completion(true)
            .allow_past_end_time(true)
            .build()
            .unwrap();

        assert_eq!(params.strategy, "ArrivalPx");
        assert_eq!(params.params.len(), 6);

        let find_param = |tag: &str| params.params.iter().find(|p| p.tag == tag).map(|p| &p.value);
        assert_eq!(find_param("riskAversion"), Some(&"Aggressive".to_string()));
        assert_eq!(find_param("forceCompletion"), Some(&"1".to_string()));
    }

    #[test]
    fn test_builder_minimal() {
        // Test that builders work with no params set
        let vwap = VwapBuilder::new().build().unwrap();
        assert_eq!(vwap.strategy, "Vwap");
        assert!(vwap.params.is_empty());

        let twap = TwapBuilder::new().build().unwrap();
        assert_eq!(twap.strategy, "Twap");
        assert!(twap.params.is_empty());
    }

    #[test]
    fn test_pct_vol_out_of_range_errors() {
        // Values above 0.5 should return error
        let result = PctVolBuilder::new().pct_vol(0.8).build();
        assert!(matches!(result, Err(ValidationError::InvalidPercentage { field: "pct_vol", .. })));

        let result = VwapBuilder::new().max_pct_vol(1.0).build();
        assert!(matches!(result, Err(ValidationError::InvalidPercentage { field: "max_pct_vol", .. })));

        // Values below 0.1 should return error
        let result = PctVolBuilder::new().pct_vol(0.05).build();
        assert!(matches!(result, Err(ValidationError::InvalidPercentage { field: "pct_vol", .. })));

        let result = ArrivalPriceBuilder::new().max_pct_vol(0.01).build();
        assert!(matches!(result, Err(ValidationError::InvalidPercentage { field: "max_pct_vol", .. })));
    }

    #[test]
    fn test_pct_vol_valid_values_succeed() {
        // Values within 0.1-0.5 should pass through unchanged
        let params = PctVolBuilder::new().pct_vol(0.25).build().unwrap();
        let find_param = |tag: &str| params.params.iter().find(|p| p.tag == tag).map(|p| &p.value);
        assert_eq!(find_param("pctVol"), Some(&"0.25".to_string()));

        let params = VwapBuilder::new().max_pct_vol(0.1).build().unwrap();
        let find_param = |tag: &str| params.params.iter().find(|p| p.tag == tag).map(|p| &p.value);
        assert_eq!(find_param("maxPctVol"), Some(&"0.1".to_string()));

        let params = VwapBuilder::new().max_pct_vol(0.5).build().unwrap();
        let find_param = |tag: &str| params.params.iter().find(|p| p.tag == tag).map(|p| &p.value);
        assert_eq!(find_param("maxPctVol"), Some(&"0.5".to_string()));
    }

    #[test]
    fn test_pct_vol_boundary_values() {
        // Exactly 0.1 should succeed
        assert!(VwapBuilder::new().max_pct_vol(0.1).build().is_ok());
        assert!(PctVolBuilder::new().pct_vol(0.1).build().is_ok());
        assert!(ArrivalPriceBuilder::new().max_pct_vol(0.1).build().is_ok());

        // Exactly 0.5 should succeed
        assert!(VwapBuilder::new().max_pct_vol(0.5).build().is_ok());
        assert!(PctVolBuilder::new().pct_vol(0.5).build().is_ok());
        assert!(ArrivalPriceBuilder::new().max_pct_vol(0.5).build().is_ok());

        // Just outside boundaries should fail
        assert!(VwapBuilder::new().max_pct_vol(0.09).build().is_err());
        assert!(VwapBuilder::new().max_pct_vol(0.51).build().is_err());
    }
}