nautilus_execution/
trailing.rs

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
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

// TODO: We'll use anyhow for now, but would be best to implement some specific Error(s)
use anyhow;
use nautilus_model::{
    enums::{OrderSideSpecified, OrderType, TrailingOffsetType, TriggerType},
    orders::{base::OrderError, OrderAny},
    types::Price,
};
use rust_decimal::{prelude::*, Decimal};

pub fn trailing_stop_calculate(
    price_increment: Price,
    order: &OrderAny,
    bid: Option<Price>,
    ask: Option<Price>,
    last: Option<Price>,
) -> anyhow::Result<(Option<Price>, Option<Price>)> {
    let order_side = order.order_side_specified();
    let order_type = order.order_type();
    if !matches!(
        order_type,
        OrderType::TrailingStopMarket | OrderType::TrailingStopLimit
    ) {
        anyhow::bail!("Invalid `OrderType` {order_type} for trailing stop calculation");
    }

    // SAFETY: TrailingStop order guaranteed to have trigger_type and offset properties
    let trigger_type = order.trigger_type().unwrap();
    let trailing_offset = order.trailing_offset().unwrap();
    let trailing_offset_type = order.trailing_offset_type().unwrap();
    assert!(trigger_type != TriggerType::NoTrigger);
    assert!(trailing_offset_type != TrailingOffsetType::NoTrailingOffset,);

    let mut trigger_price = order.trigger_price();
    let mut price = None;
    let mut new_trigger_price = None;
    let mut new_price = None;

    if order_type == OrderType::TrailingStopLimit {
        price = order.price();
    }

    match trigger_type {
        TriggerType::Default | TriggerType::LastPrice | TriggerType::MarkPrice => {
            let last = last.ok_or(OrderError::InvalidStateTransition)?;

            let temp_trigger_price = trailing_stop_calculate_with_last(
                price_increment,
                trailing_offset_type,
                order_side,
                trailing_offset,
                last,
            )?;

            match order_side {
                OrderSideSpecified::Buy => {
                    if let Some(trigger) = trigger_price {
                        if trigger > temp_trigger_price {
                            new_trigger_price = Some(temp_trigger_price);
                        }
                    } else {
                        new_trigger_price = Some(temp_trigger_price);
                    }

                    if order_type == OrderType::TrailingStopLimit {
                        let temp_price = trailing_stop_calculate_with_last(
                            price_increment,
                            trailing_offset_type,
                            order_side,
                            order.limit_offset().expect("Invalid order"),
                            last,
                        )?;
                        if let Some(p) = price {
                            if p > temp_price {
                                new_price = Some(temp_price);
                            }
                        } else {
                            new_price = Some(temp_price);
                        }
                    }
                }
                OrderSideSpecified::Sell => {
                    if let Some(trigger) = trigger_price {
                        if trigger < temp_trigger_price {
                            new_trigger_price = Some(temp_trigger_price);
                        }
                    } else {
                        new_trigger_price = Some(temp_trigger_price);
                    }

                    if order_type == OrderType::TrailingStopLimit {
                        let temp_price = trailing_stop_calculate_with_last(
                            price_increment,
                            trailing_offset_type,
                            order_side,
                            order.limit_offset().expect("Invalid order"),
                            last,
                        )?;
                        if let Some(p) = price {
                            if p < temp_price {
                                new_price = Some(temp_price);
                            }
                        } else {
                            new_price = Some(temp_price);
                        }
                    }
                }
            }
        }
        TriggerType::BidAsk => {
            let bid =
                bid.ok_or_else(|| anyhow::anyhow!("`BidAsk` calculation requires `bid` price"))?;
            let ask =
                ask.ok_or_else(|| anyhow::anyhow!("`BidAsk` calculation requires `ask` price"))?;

            let temp_trigger_price = trailing_stop_calculate_with_bid_ask(
                price_increment,
                trailing_offset_type,
                order_side,
                trailing_offset,
                bid,
                ask,
            )?;

            match order_side {
                OrderSideSpecified::Buy => {
                    if let Some(trigger) = trigger_price {
                        if trigger > temp_trigger_price {
                            new_trigger_price = Some(temp_trigger_price);
                        }
                    } else {
                        new_trigger_price = Some(temp_trigger_price);
                    }

                    if order.order_type() == OrderType::TrailingStopLimit {
                        let temp_price = trailing_stop_calculate_with_bid_ask(
                            price_increment,
                            trailing_offset_type,
                            order_side,
                            order.limit_offset().expect("Invalid order"),
                            bid,
                            ask,
                        )?;
                        if let Some(p) = price {
                            if p > temp_price {
                                new_price = Some(temp_price);
                            }
                        } else {
                            new_price = Some(temp_price);
                        }
                    }
                }
                OrderSideSpecified::Sell => {
                    if let Some(trigger) = trigger_price {
                        if trigger < temp_trigger_price {
                            new_trigger_price = Some(temp_trigger_price);
                        }
                    } else {
                        new_trigger_price = Some(temp_trigger_price);
                    }

                    if order_type == OrderType::TrailingStopLimit {
                        let temp_price = trailing_stop_calculate_with_bid_ask(
                            price_increment,
                            trailing_offset_type,
                            order_side,
                            order.limit_offset().expect("Invalid order"),
                            bid,
                            ask,
                        )?;
                        if let Some(p) = price {
                            if p < temp_price {
                                new_price = Some(temp_price);
                            }
                        } else {
                            new_price = Some(temp_price);
                        }
                    }
                }
            }
        }
        TriggerType::LastOrBidAsk => {
            let bid = bid.ok_or_else(|| {
                anyhow::anyhow!("`LastOrBidAsk` calculation requires `bid` price")
            })?;
            let ask = ask.ok_or_else(|| {
                anyhow::anyhow!("`LastOrBidAsk` calculation requires `ask` price")
            })?;
            let last = last.ok_or_else(|| {
                anyhow::anyhow!("`LastOrBidAsk` calculation requires `last` price")
            })?;

            let mut temp_trigger_price = trailing_stop_calculate_with_last(
                price_increment,
                trailing_offset_type,
                order_side,
                trailing_offset,
                last,
            )?;

            match order_side {
                OrderSideSpecified::Buy => {
                    if let Some(trigger) = trigger_price {
                        if trigger > temp_trigger_price {
                            new_trigger_price = Some(temp_trigger_price);
                            trigger_price = new_trigger_price;
                        }
                    } else {
                        new_trigger_price = Some(temp_trigger_price);
                        trigger_price = new_trigger_price;
                    }
                    if order.order_type() == OrderType::TrailingStopLimit {
                        let temp_price = trailing_stop_calculate_with_last(
                            price_increment,
                            trailing_offset_type,
                            order_side,
                            order.limit_offset().expect("Invalid order"),
                            last,
                        )?;
                        if let Some(p) = price {
                            if p > temp_price {
                                new_price = Some(temp_price);
                                price = new_price;
                            }
                        } else {
                            new_price = Some(temp_price);
                            price = new_price;
                        }
                    }
                    temp_trigger_price = trailing_stop_calculate_with_bid_ask(
                        price_increment,
                        trailing_offset_type,
                        order_side,
                        trailing_offset,
                        bid,
                        ask,
                    )?;
                    if let Some(trigger) = trigger_price {
                        if trigger > temp_trigger_price {
                            new_trigger_price = Some(temp_trigger_price);
                        }
                    } else {
                        new_trigger_price = Some(temp_trigger_price);
                    }
                    if order_type == OrderType::TrailingStopLimit {
                        let temp_price = trailing_stop_calculate_with_bid_ask(
                            price_increment,
                            trailing_offset_type,
                            order_side,
                            order.limit_offset().expect("Invalid order"),
                            bid,
                            ask,
                        )?;
                        if let Some(p) = price {
                            if p > temp_price {
                                new_price = Some(temp_price);
                            }
                        } else {
                            new_price = Some(temp_price);
                        }
                    }
                }
                OrderSideSpecified::Sell => {
                    if let Some(trigger) = trigger_price {
                        if trigger < temp_trigger_price {
                            new_trigger_price = Some(temp_trigger_price);
                            trigger_price = new_trigger_price;
                        }
                    } else {
                        new_trigger_price = Some(temp_trigger_price);
                        trigger_price = new_trigger_price;
                    }

                    if order.order_type() == OrderType::TrailingStopLimit {
                        let temp_price = trailing_stop_calculate_with_last(
                            price_increment,
                            trailing_offset_type,
                            order_side,
                            order.limit_offset().expect("Invalid order"),
                            last,
                        )?;
                        if let Some(p) = price {
                            if p < temp_price {
                                new_price = Some(temp_price);
                                price = new_price;
                            }
                        } else {
                            new_price = Some(temp_price);
                            price = new_price;
                        }
                    }
                    temp_trigger_price = trailing_stop_calculate_with_bid_ask(
                        price_increment,
                        trailing_offset_type,
                        order_side,
                        trailing_offset,
                        bid,
                        ask,
                    )?;
                    if let Some(trigger) = trigger_price {
                        if trigger < temp_trigger_price {
                            new_trigger_price = Some(temp_trigger_price);
                        }
                    } else {
                        new_trigger_price = Some(temp_trigger_price);
                    }
                    if order_type == OrderType::TrailingStopLimit {
                        let temp_price = trailing_stop_calculate_with_bid_ask(
                            price_increment,
                            trailing_offset_type,
                            order_side,
                            order.limit_offset().expect("Invalid order"),
                            bid,
                            ask,
                        )?;
                        if let Some(p) = price {
                            if p < temp_price {
                                new_price = Some(temp_price);
                            }
                        } else {
                            new_price = Some(temp_price);
                        }
                    }
                }
            }
        }
        _ => anyhow::bail!("`TriggerType` {trigger_type} not currently supported"),
    }

    Ok((new_trigger_price, new_price))
}

pub fn trailing_stop_calculate_with_last(
    price_increment: Price,
    trailing_offset_type: TrailingOffsetType,
    side: OrderSideSpecified,
    offset: Decimal,
    last: Price,
) -> anyhow::Result<Price> {
    let mut offset_value = offset.to_f64().expect("Invalid `offset` value");
    let last_f64 = last.as_f64();

    match trailing_offset_type {
        TrailingOffsetType::Price => {} // Offset already calculated
        TrailingOffsetType::BasisPoints => {
            offset_value = last_f64 * (offset_value / 100.0) / 100.0;
        }
        TrailingOffsetType::Ticks => {
            offset_value *= price_increment.as_f64();
        }
        _ => anyhow::bail!("`TrailingOffsetType` {trailing_offset_type} not currently supported"),
    }

    let price_value = match side {
        OrderSideSpecified::Buy => last_f64 + offset_value,
        OrderSideSpecified::Sell => last_f64 - offset_value,
    };

    Ok(Price::new(price_value, price_increment.precision))
}

pub fn trailing_stop_calculate_with_bid_ask(
    price_increment: Price,
    trailing_offset_type: TrailingOffsetType,
    side: OrderSideSpecified,
    offset: Decimal,
    bid: Price,
    ask: Price,
) -> anyhow::Result<Price> {
    let mut offset_value = offset.to_f64().expect("Invalid `offset` value");
    let bid_f64 = bid.as_f64();
    let ask_f64 = ask.as_f64();

    match trailing_offset_type {
        TrailingOffsetType::Price => {} // Offset already calculated
        TrailingOffsetType::BasisPoints => match side {
            OrderSideSpecified::Buy => offset_value = ask_f64 * (offset_value / 100.0) / 100.0,
            OrderSideSpecified::Sell => offset_value = bid_f64 * (offset_value / 100.0) / 100.0,
        },
        TrailingOffsetType::Ticks => {
            offset_value *= price_increment.as_f64();
        }
        _ => anyhow::bail!("`TrailingOffsetType` {trailing_offset_type} not currently supported"),
    }

    let price_value = match side {
        OrderSideSpecified::Buy => ask_f64 + offset_value,
        OrderSideSpecified::Sell => bid_f64 - offset_value,
    };

    Ok(Price::new(price_value, price_increment.precision))
}

////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
    use nautilus_model::{
        enums::{OrderSide, OrderType, TrailingOffsetType, TriggerType},
        orders::builder::OrderTestBuilder,
        types::Quantity,
    };
    use rstest::rstest;
    use rust_decimal::prelude::*;
    use rust_decimal_macros::dec;

    use super::*;

    #[rstest]
    fn test_calculate_with_invalid_order_type() {
        let order = OrderTestBuilder::new(OrderType::Market)
            .instrument_id("BTCUSDT-PERP.BINANCE".into())
            .side(OrderSide::Buy)
            .quantity(Quantity::from(1))
            .build();

        let result = trailing_stop_calculate(Price::new(0.01, 2), &order, None, None, None);

        // TODO: Basic error assert for now
        assert!(result.is_err());
    }

    #[rstest]
    #[case(OrderSide::Buy)]
    #[case(OrderSide::Sell)]
    fn test_calculate_with_last_price_no_last(#[case] side: OrderSide) {
        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
            .instrument_id("BTCUSDT-PERP.BINANCE".into())
            .side(side)
            .trigger_price(Price::new(100.0, 2))
            .trailing_offset_type(TrailingOffsetType::Price)
            .trailing_offset(dec!(1.0))
            .trigger_type(TriggerType::LastPrice)
            .quantity(Quantity::from(1))
            .build();

        let result = trailing_stop_calculate(Price::new(0.01, 2), &order, None, None, None);

        // TODO: Basic error assert for now
        assert!(result.is_err());
    }

    #[rstest]
    #[case(OrderSide::Buy)]
    #[case(OrderSide::Sell)]
    fn test_calculate_with_bid_ask_no_bid_ask(#[case] side: OrderSide) {
        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
            .instrument_id("BTCUSDT-PERP.BINANCE".into())
            .side(side)
            .trigger_price(Price::new(100.0, 2))
            .trailing_offset_type(TrailingOffsetType::Price)
            .trailing_offset(dec!(1.0))
            .trigger_type(TriggerType::BidAsk)
            .quantity(Quantity::from(1))
            .build();

        let result = trailing_stop_calculate(Price::new(0.01, 2), &order, None, None, None);

        // TODO: Basic error assert for now
        assert!(result.is_err());
    }

    #[rstest]
    fn test_calculate_with_unsupported_trigger_type() {
        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
            .instrument_id("BTCUSDT-PERP.BINANCE".into())
            .side(OrderSide::Buy)
            .trigger_price(Price::new(100.0, 2))
            .trailing_offset_type(TrailingOffsetType::Price)
            .trailing_offset(dec!(1.0))
            .trigger_type(TriggerType::IndexPrice)
            .quantity(Quantity::from(1))
            .build();

        let result = trailing_stop_calculate(Price::new(0.01, 2), &order, None, None, None);

        // TODO: Basic error assert for now
        assert!(result.is_err());
    }

    #[rstest]
    #[case(OrderSide::Buy, 100.0, 1.0, 99.0, None)] // Last price 99 > trigger 98, no update needed
    #[case(OrderSide::Buy, 100.0, 1.0, 98.0, Some(99.0))] // Last price 98 < trigger 100, update to 98 + 1
    #[case(OrderSide::Sell, 100.0, 1.0, 101.0, None)] // Last price 101 < trigger 102, no update needed
    #[case(OrderSide::Sell, 100.0, 1.0, 102.0, Some(101.0))] // Last price 102 > trigger 100, update to 102 - 1
    fn test_trailing_stop_market_last_price(
        #[case] side: OrderSide,
        #[case] initial_trigger: f64,
        #[case] offset: f64,
        #[case] last_price: f64,
        #[case] expected_trigger: Option<f64>,
    ) {
        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
            .instrument_id("BTCUSDT-PERP.BINANCE".into())
            .side(side)
            .trigger_price(Price::new(initial_trigger, 2))
            .trailing_offset_type(TrailingOffsetType::Price)
            .trailing_offset(Decimal::from_f64(offset).unwrap())
            .trigger_type(TriggerType::LastPrice)
            .quantity(Quantity::from(1))
            .build();

        let result = trailing_stop_calculate(
            Price::new(0.01, 2),
            &order,
            None,
            None,
            Some(Price::new(last_price, 2)),
        );

        let actual_trigger = result.unwrap().0;
        match (actual_trigger, expected_trigger) {
            (Some(actual), Some(expected)) => assert_eq!(actual.as_f64(), expected),
            (None, None) => (),
            _ => panic!("Expected trigger {expected_trigger:?} but got {actual_trigger:?}"),
        }
    }

    #[rstest]
    #[case(OrderSide::Buy, 100.0, 50.0, 98.0, Some(98.49))] // 50bp = 0.5% of 98 = 0.49
    #[case(OrderSide::Buy, 100.0, 100.0, 97.0, Some(97.97))] // 100bp = 1% of 97 = 0.97
    #[case(OrderSide::Sell, 100.0, 50.0, 102.0, Some(101.49))] // 50bp = 0.5% of 102 = 0.51
    #[case(OrderSide::Sell, 100.0, 100.0, 103.0, Some(101.97))] // 100bp = 1% of 103 = 1.03
    fn test_trailing_stop_market_basis_points(
        #[case] side: OrderSide,
        #[case] initial_trigger: f64,
        #[case] basis_points: f64,
        #[case] last_price: f64,
        #[case] expected_trigger: Option<f64>,
    ) {
        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
            .instrument_id("BTCUSDT-PERP.BINANCE".into())
            .side(side)
            .trigger_price(Price::new(initial_trigger, 2))
            .trailing_offset_type(TrailingOffsetType::BasisPoints)
            .trailing_offset(Decimal::from_f64(basis_points).unwrap())
            .trigger_type(TriggerType::LastPrice)
            .quantity(Quantity::from(1))
            .build();

        let result = trailing_stop_calculate(
            Price::new(0.01, 2),
            &order,
            None,
            None,
            Some(Price::new(last_price, 2)),
        );

        let actual_trigger = result.unwrap().0;
        match (actual_trigger, expected_trigger) {
            (Some(actual), Some(expected)) => assert_eq!(actual.as_f64(), expected),
            (None, None) => (),
            _ => panic!("Expected trigger {expected_trigger:?} but got {actual_trigger:?}"),
        }
    }

    #[rstest]
    #[case(OrderSide::Buy, 100.0, 1.0, 98.0, 99.0, None)] // Ask 99 > trigger 100, no update
    #[case(OrderSide::Buy, 100.0, 1.0, 97.0, 98.0, Some(99.0))] // Ask 98 < trigger 100, update to 98 + 1
    #[case(OrderSide::Sell, 100.0, 1.0, 101.0, 102.0, None)] // Bid 101 < trigger 100, no update
    #[case(OrderSide::Sell, 100.0, 1.0, 102.0, 103.0, Some(101.0))] // Bid 102 > trigger 100, update to 102 - 1
    fn test_trailing_stop_market_bid_ask(
        #[case] side: OrderSide,
        #[case] initial_trigger: f64,
        #[case] offset: f64,
        #[case] bid: f64,
        #[case] ask: f64,
        #[case] expected_trigger: Option<f64>,
    ) {
        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
            .instrument_id("BTCUSDT-PERP.BINANCE".into())
            .side(side)
            .trigger_price(Price::new(initial_trigger, 2))
            .trailing_offset_type(TrailingOffsetType::Price)
            .trailing_offset(Decimal::from_f64(offset).unwrap())
            .trigger_type(TriggerType::BidAsk)
            .quantity(Quantity::from(1))
            .build();

        let result = trailing_stop_calculate(
            Price::new(0.01, 2),
            &order,
            Some(Price::new(bid, 2)),
            Some(Price::new(ask, 2)),
            None, // last price not needed for BidAsk trigger type
        );

        let actual_trigger = result.unwrap().0;
        match (actual_trigger, expected_trigger) {
            (Some(actual), Some(expected)) => assert_eq!(actual.as_f64(), expected),
            (None, None) => (),
            _ => panic!("Expected trigger {expected_trigger:?} but got {actual_trigger:?}"),
        }
    }

    #[rstest]
    #[case(OrderSide::Buy, 100.0, 5, 98.0, Some(98.05))] // 5 ticks * 0.01 = 0.05 offset
    #[case(OrderSide::Buy, 100.0, 10, 97.0, Some(97.10))] // 10 ticks * 0.01 = 0.10 offset
    #[case(OrderSide::Sell, 100.0, 5, 102.0, Some(101.95))] // 5 ticks * 0.01 = 0.05 offset
    #[case(OrderSide::Sell, 100.0, 10, 103.0, Some(102.90))] // 10 ticks * 0.01 = 0.10 offset
    fn test_trailing_stop_market_ticks(
        #[case] side: OrderSide,
        #[case] initial_trigger: f64,
        #[case] ticks: u32,
        #[case] last_price: f64,
        #[case] expected_trigger: Option<f64>,
    ) {
        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
            .instrument_id("BTCUSDT-PERP.BINANCE".into())
            .side(side)
            .trigger_price(Price::new(initial_trigger, 2))
            .trailing_offset_type(TrailingOffsetType::Ticks)
            .trailing_offset(Decimal::from_u32(ticks).unwrap())
            .trigger_type(TriggerType::LastPrice)
            .quantity(Quantity::from(1))
            .build();

        let result = trailing_stop_calculate(
            Price::new(0.01, 2),
            &order,
            None,
            None,
            Some(Price::new(last_price, 2)),
        );

        let actual_trigger = result.unwrap().0;
        match (actual_trigger, expected_trigger) {
            (Some(actual), Some(expected)) => assert_eq!(actual.as_f64(), expected),
            (None, None) => (),
            _ => panic!("Expected trigger {expected_trigger:?} but got {actual_trigger:?}"),
        }
    }

    #[rstest]
    #[case(OrderSide::Buy, 100.0, 1.0, 98.0, 97.0, 98.0, Some(99.0))] // Last price gives higher trigger
    #[case(OrderSide::Buy, 100.0, 1.0, 97.0, 96.0, 99.0, Some(98.0))] // Bid/Ask gives higher trigger
    #[case(OrderSide::Sell, 100.0, 1.0, 102.0, 102.0, 103.0, Some(101.0))] // Last price gives lower trigger
    #[case(OrderSide::Sell, 100.0, 1.0, 103.0, 101.0, 102.0, Some(102.0))] // Bid/Ask gives lower trigger
    fn test_trailing_stop_last_or_bid_ask(
        #[case] side: OrderSide,
        #[case] initial_trigger: f64,
        #[case] offset: f64,
        #[case] last_price: f64,
        #[case] bid: f64,
        #[case] ask: f64,
        #[case] expected_trigger: Option<f64>,
    ) {
        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
            .instrument_id("BTCUSDT-PERP.BINANCE".into())
            .side(side)
            .trigger_price(Price::new(initial_trigger, 2))
            .trailing_offset_type(TrailingOffsetType::Price)
            .trailing_offset(Decimal::from_f64(offset).unwrap())
            .trigger_type(TriggerType::LastOrBidAsk)
            .quantity(Quantity::from(1))
            .build();

        let result = trailing_stop_calculate(
            Price::new(0.01, 2),
            &order,
            Some(Price::new(bid, 2)),
            Some(Price::new(ask, 2)),
            Some(Price::new(last_price, 2)),
        );

        let actual_trigger = result.unwrap().0;
        match (actual_trigger, expected_trigger) {
            (Some(actual), Some(expected)) => assert_eq!(actual.as_f64(), expected),
            (None, None) => (),
            _ => panic!("Expected trigger {expected_trigger:?} but got {actual_trigger:?}"),
        }
    }
}