Skip to main content

polyester/codecs/decode/
triggers.rs

1//! Trigger response decoders.
2
3use super::enums::enum_value_side;
4use super::money::{decode_price_ticks, decode_qty_scaled};
5use crate::codecs::scalars::format_uint64_id;
6use crate::models::{
7    Trigger, TriggerDetails, TriggerEvent, TriggerEventsList, TriggerLadderDetails,
8    TriggerMutationResult, TriggerStopDetails, TriggerTrailingDetails, TriggerTwapDetails,
9    TriggersList,
10};
11use crate::proto::orders::v1::{
12    FeeAsset, SelfTradePreventionMode, TriggerDirection, TriggerPriceSource,
13};
14use crate::proto::triggers::v1::{
15    CancelTriggerResponse, ConditionalTrigger, CreateTriggerResponse, GetTriggerResponse,
16    LadderDistribution, ListTriggerEventsResponse, ListTriggersResponse, ModifyTriggerResponse,
17    PauseTriggerResponse, ResumeTriggerResponse, Trigger as ProtoTrigger,
18    TriggerEvent as ProtoTriggerEvent, TriggerStatus, conditional_child_execution, trigger,
19    twap_trigger,
20};
21use crate::types::Price;
22use buffa::Enumeration;
23use buffa_types::google::protobuf::Timestamp;
24
25pub fn trigger_status_label(status: TriggerStatus) -> &'static str {
26    match status {
27        TriggerStatus::StatusCreated => "created",
28        TriggerStatus::StatusArmed => "armed",
29        TriggerStatus::StatusRunning => "running",
30        TriggerStatus::StatusCompleted => "completed",
31        TriggerStatus::StatusCanceled => "cancelled",
32        TriggerStatus::StatusFailed => "failed",
33        TriggerStatus::StatusPaused => "paused",
34        TriggerStatus::StatusUnspecified => "",
35    }
36}
37
38/// Parse a trigger status filter label into a proto enum.
39pub fn trigger_status_from_label(label: &str) -> Result<TriggerStatus, String> {
40    match label.trim().to_ascii_lowercase().as_str() {
41        "created" => Ok(TriggerStatus::StatusCreated),
42        "armed" => Ok(TriggerStatus::StatusArmed),
43        "running" => Ok(TriggerStatus::StatusRunning),
44        "completed" => Ok(TriggerStatus::StatusCompleted),
45        "cancelled" | "canceled" => Ok(TriggerStatus::StatusCanceled),
46        "failed" => Ok(TriggerStatus::StatusFailed),
47        "paused" => Ok(TriggerStatus::StatusPaused),
48        other => Err(format!(
49            "invalid trigger status {other:?}; expected one of: created, armed, running, completed, cancelled, failed, paused"
50        )),
51    }
52}
53
54fn enum_value_trigger_status(value: buffa::EnumValue<TriggerStatus>) -> String {
55    value
56        .as_known()
57        .map(trigger_status_label)
58        .map(str::to_owned)
59        .unwrap_or_else(|| format!("UNKNOWN({})", value.to_i32()))
60}
61
62fn trigger_price_source_label(value: buffa::EnumValue<TriggerPriceSource>) -> String {
63    match value.as_known() {
64        Some(TriggerPriceSource::LastPrice) => "last".to_owned(),
65        Some(TriggerPriceSource::IndexPrice) => "index".to_owned(),
66        Some(TriggerPriceSource::MarkPrice) => "mark".to_owned(),
67        Some(_) => String::new(),
68        None => format!("UNKNOWN({})", value.to_i32()),
69    }
70}
71
72fn trigger_direction_label(value: buffa::EnumValue<TriggerDirection>) -> String {
73    match value.as_known() {
74        Some(TriggerDirection::Above) => "above".to_owned(),
75        Some(TriggerDirection::Below) => "below".to_owned(),
76        Some(_) => String::new(),
77        None => format!("UNKNOWN({})", value.to_i32()),
78    }
79}
80
81fn fee_asset_label(value: buffa::EnumValue<FeeAsset>) -> String {
82    match value.as_known() {
83        Some(FeeAsset::Quote) => "quote".to_owned(),
84        Some(FeeAsset::Base) => "base".to_owned(),
85        Some(_) => String::new(),
86        None => format!("UNKNOWN({})", value.to_i32()),
87    }
88}
89
90fn stp_mode_label(value: buffa::EnumValue<SelfTradePreventionMode>) -> String {
91    match value.as_known() {
92        Some(SelfTradePreventionMode::ExpireTaker) => "expire_taker".to_owned(),
93        Some(SelfTradePreventionMode::ExpireMaker) => "expire_maker".to_owned(),
94        Some(SelfTradePreventionMode::ExpireBoth) => "expire_both".to_owned(),
95        Some(_) => String::new(),
96        None => format!("UNKNOWN({})", value.to_i32()),
97    }
98}
99
100fn ladder_distribution_label(value: buffa::EnumValue<LadderDistribution>) -> String {
101    match value.as_known() {
102        Some(LadderDistribution::Linear) => "linear".to_owned(),
103        Some(LadderDistribution::Geometric) => "geometric".to_owned(),
104        Some(LadderDistribution::WeightedFavorable) => "weighted_favorable".to_owned(),
105        Some(_) => String::new(),
106        None => format!("UNKNOWN({})", value.to_i32()),
107    }
108}
109
110fn clone_timestamp(ts: Option<&Timestamp>) -> Option<Timestamp> {
111    ts.map(|t| Timestamp {
112        seconds: t.seconds,
113        nanos: t.nanos,
114        ..Default::default()
115    })
116}
117
118fn trigger_details_from_proto(
119    msg: &ProtoTrigger,
120    symbol: Option<String>,
121    symbol_id_opt: Option<u32>,
122) -> Option<TriggerDetails> {
123    match msg.runtime_details.as_ref() {
124        Some(trigger::RuntimeDetails::Stop(stop)) => {
125            Some(TriggerDetails::Stop(TriggerStopDetails {
126                trigger_price: decode_price_ticks(stop.trigger_price_ticks, symbol.clone()),
127                trigger_price_source: trigger_price_source_label(stop.trigger_price_source),
128                trigger_direction: trigger_direction_label(stop.trigger_direction),
129            }))
130        }
131        Some(trigger::RuntimeDetails::Trailing(trailing)) => {
132            Some(TriggerDetails::Trailing(TriggerTrailingDetails {
133                trailing_distance: if trailing.trailing_distance_ticks > 0 {
134                    decode_price_ticks(trailing.trailing_distance_ticks, symbol.clone())
135                } else {
136                    None
137                },
138                trailing_distance_bps: trailing.trailing_distance_bps,
139                activation_price: if trailing.activation_price_ticks > 0 {
140                    decode_price_ticks(trailing.activation_price_ticks, symbol.clone())
141                } else {
142                    None
143                },
144                peak_price: if trailing.peak_price_ticks > 0 {
145                    decode_price_ticks(trailing.peak_price_ticks, symbol.clone())
146                } else {
147                    None
148                },
149                trough_price: if trailing.trough_price_ticks > 0 {
150                    decode_price_ticks(trailing.trough_price_ticks, symbol.clone())
151                } else {
152                    None
153                },
154                max_slippage: if trailing.max_slippage_ticks > 0 {
155                    decode_price_ticks(i64::from(trailing.max_slippage_ticks), symbol.clone())
156                } else {
157                    None
158                },
159                max_slippage_bps: trailing.max_slippage_bps,
160                trigger_price_source: trigger_price_source_label(trailing.trigger_price_source),
161                trigger_direction: trigger_direction_label(trailing.trigger_direction),
162            }))
163        }
164        Some(trigger::RuntimeDetails::TwapState(twap)) => {
165            Some(TriggerDetails::Twap(TriggerTwapDetails {
166                twap_duration_ms: twap.twap_duration_ms,
167                twap_slice_interval_ms: twap.twap_slice_interval_ms,
168                slice_idx: twap.slice_idx,
169                slice_count: twap.slice_count,
170                executed_qty: decode_qty_scaled(
171                    twap.executed_qty_scaled,
172                    None,
173                    symbol.clone(),
174                    symbol_id_opt,
175                ),
176            }))
177        }
178        Some(trigger::RuntimeDetails::LadderState(ladder)) => {
179            Some(TriggerDetails::Ladder(TriggerLadderDetails {
180                ladder_price_min: if ladder.ladder_price_min_ticks > 0 {
181                    decode_price_ticks(ladder.ladder_price_min_ticks, symbol.clone())
182                } else {
183                    None
184                },
185                ladder_price_max: if ladder.ladder_price_max_ticks > 0 {
186                    decode_price_ticks(ladder.ladder_price_max_ticks, symbol.clone())
187                } else {
188                    None
189                },
190                ladder_levels: ladder.ladder_levels,
191                ladder_distribution: ladder_distribution_label(ladder.ladder_distribution),
192            }))
193        }
194        None => None,
195    }
196}
197
198fn trigger_price_from_details(details: &Option<TriggerDetails>) -> Option<Price> {
199    match details {
200        Some(TriggerDetails::Stop(stop)) => stop.trigger_price.clone(),
201        _ => None,
202    }
203}
204
205/// Flat public trigger fields derived from the immutable `Configuration` oneof.
206#[derive(Default)]
207struct TriggerConfigProjection {
208    trigger_type: String,
209    side: String,
210    order_type: String,
211    time_in_force: String,
212    post_only: bool,
213    limit_price: Option<Price>,
214    trigger_price: Option<Price>,
215}
216
217/// Derive flat child fields (side/order_type/tif/post_only/limit_price) from a
218/// stop-loss / take-profit `ConditionalTrigger` configuration.
219fn conditional_child_projection(
220    cond: &ConditionalTrigger,
221    symbol: Option<String>,
222) -> (String, String, String, bool, Option<Price>) {
223    let side = enum_value_side(cond.side).to_owned();
224    let mut order_type = String::new();
225    let mut time_in_force = String::new();
226    let mut post_only = false;
227    let mut limit_price = None;
228    if let Some(child) = cond.child.as_option() {
229        match child.execution.as_ref() {
230            Some(conditional_child_execution::Execution::MarketIoc(_)) => {
231                order_type = "market".to_owned();
232                time_in_force = "ioc".to_owned();
233            }
234            Some(conditional_child_execution::Execution::LimitGtc(limit)) => {
235                order_type = "limit".to_owned();
236                time_in_force = "gtc".to_owned();
237                post_only = limit.post_only;
238                limit_price = decode_price_ticks(limit.price_ticks, symbol);
239            }
240            Some(conditional_child_execution::Execution::LimitIoc(limit)) => {
241                order_type = "limit".to_owned();
242                time_in_force = "ioc".to_owned();
243                limit_price = decode_price_ticks(limit.price_ticks, symbol);
244            }
245            Some(conditional_child_execution::Execution::LimitFok(limit)) => {
246                order_type = "limit".to_owned();
247                time_in_force = "fok".to_owned();
248                limit_price = decode_price_ticks(limit.price_ticks, symbol);
249            }
250            None => {}
251        }
252    }
253    (side, order_type, time_in_force, post_only, limit_price)
254}
255
256/// Derive the flat public trigger fields (type/side/order_type/tif/post_only/
257/// limit_price/trigger_price) from the immutable `Configuration` oneof.
258fn trigger_config_projection(
259    msg: &ProtoTrigger,
260    symbol: Option<String>,
261) -> TriggerConfigProjection {
262    let mut proj = TriggerConfigProjection::default();
263    match msg.configuration.as_ref() {
264        Some(trigger::Configuration::StopLoss(cond)) => {
265            proj.trigger_type = "stop_loss".to_owned();
266            let (side, order_type, tif, post_only, limit_price) =
267                conditional_child_projection(cond, symbol.clone());
268            proj.side = side;
269            proj.order_type = order_type;
270            proj.time_in_force = tif;
271            proj.post_only = post_only;
272            proj.limit_price = limit_price;
273            if cond.trigger_price_ticks != 0 {
274                proj.trigger_price = decode_price_ticks(cond.trigger_price_ticks, symbol);
275            }
276        }
277        Some(trigger::Configuration::TakeProfit(cond)) => {
278            proj.trigger_type = "take_profit".to_owned();
279            let (side, order_type, tif, post_only, limit_price) =
280                conditional_child_projection(cond, symbol.clone());
281            proj.side = side;
282            proj.order_type = order_type;
283            proj.time_in_force = tif;
284            proj.post_only = post_only;
285            proj.limit_price = limit_price;
286            if cond.trigger_price_ticks != 0 {
287                proj.trigger_price = decode_price_ticks(cond.trigger_price_ticks, symbol);
288            }
289        }
290        Some(trigger::Configuration::TrailingStop(trailing)) => {
291            // Trailing stop is market-IOC; side is carried on the wire (standalone
292            // creates are SELL; attached risk may be either side opposite parent).
293            proj.trigger_type = "trailing_stop".to_owned();
294            proj.side = enum_value_side(trailing.side).to_owned();
295            if proj.side.is_empty() {
296                proj.side = "sell".to_owned();
297            }
298            proj.order_type = "market".to_owned();
299            proj.time_in_force = "ioc".to_owned();
300        }
301        Some(trigger::Configuration::Twap(twap)) => {
302            proj.trigger_type = "twap".to_owned();
303            proj.side = enum_value_side(twap.side).to_owned();
304            match twap.execution.as_ref() {
305                Some(twap_trigger::Execution::LimitGtc(limit)) => {
306                    proj.order_type = "limit".to_owned();
307                    proj.time_in_force = "gtc".to_owned();
308                    proj.limit_price = decode_price_ticks(limit.price_ticks, symbol);
309                }
310                Some(twap_trigger::Execution::MarketIoc(_)) => {
311                    proj.order_type = "market".to_owned();
312                    proj.time_in_force = "ioc".to_owned();
313                }
314                None => {}
315            }
316        }
317        Some(trigger::Configuration::Ladder(ladder)) => {
318            proj.trigger_type = "ladder".to_owned();
319            proj.side = enum_value_side(ladder.side).to_owned();
320            proj.order_type = "limit".to_owned();
321            proj.time_in_force = "gtc".to_owned();
322            proj.post_only = ladder.post_only;
323        }
324        None => {}
325    }
326    proj
327}
328
329pub fn trigger_from_proto(msg: &ProtoTrigger) -> Trigger {
330    let symbol_id = msg.symbol_id;
331    let symbol_id_opt = if symbol_id == 0 {
332        None
333    } else {
334        Some(symbol_id)
335    };
336    let symbol = if msg.symbol.is_empty() {
337        None
338    } else {
339        Some(msg.symbol.clone())
340    };
341    let details = trigger_details_from_proto(msg, symbol.clone(), symbol_id_opt);
342    let proj = trigger_config_projection(msg, symbol.clone());
343    // Fall back to stop runtime details for the trigger-price convenience field.
344    let trigger_price = proj
345        .trigger_price
346        .clone()
347        .or_else(|| trigger_price_from_details(&details));
348    Trigger {
349        trigger_id: format_uint64_id(msg.trigger_id),
350        subaccount_id: format_uint64_id(msg.subaccount_id),
351        symbol_id,
352        symbol: msg.symbol.clone(),
353        trigger_type: proj.trigger_type,
354        status: enum_value_trigger_status(msg.status),
355        parent_order_id: msg.parent_order_id.map(format_uint64_id),
356        side: proj.side,
357        order_type: proj.order_type,
358        time_in_force: proj.time_in_force,
359        qty: decode_qty_scaled(msg.qty_scaled, None, symbol.clone(), symbol_id_opt),
360        limit_price: proj.limit_price,
361        fee_asset: fee_asset_label(msg.fee_asset),
362        self_trade_prevention_mode: stp_mode_label(msg.self_trade_prevention_mode),
363        post_only: proj.post_only,
364        trigger_price,
365        client_trigger_id: msg.client_trigger_id.clone(),
366        created_at: clone_timestamp(msg.created_at.as_option()),
367        updated_at: clone_timestamp(msg.updated_at.as_option()),
368        armed_at: clone_timestamp(msg.armed_at.as_option()),
369        completed_at: clone_timestamp(msg.completed_at.as_option()),
370        child_order_ids: msg
371            .child_order_ids
372            .iter()
373            .copied()
374            .map(format_uint64_id)
375            .collect(),
376        details,
377    }
378}
379
380pub fn triggers_list_from_proto(msg: &ListTriggersResponse) -> TriggersList {
381    let triggers: Vec<_> = msg.triggers.iter().map(trigger_from_proto).collect();
382    let total = triggers.len();
383    TriggersList {
384        triggers,
385        total,
386        next_page_token: msg.next_page_token.clone(),
387    }
388}
389
390pub fn get_trigger_from_proto(msg: &GetTriggerResponse) -> Option<Trigger> {
391    msg.trigger.as_option().map(trigger_from_proto)
392}
393
394fn trigger_mutation(
395    trigger_id: u64,
396    status: buffa::EnumValue<TriggerStatus>,
397) -> crate::errors::Result<TriggerMutationResult> {
398    let status = enum_value_trigger_status(status);
399    if trigger_id == 0 || status.is_empty() {
400        return Err(crate::Error::transport(
401            "invalid trigger mutation response: missing trigger_id or status",
402        ));
403    }
404    Ok(TriggerMutationResult {
405        trigger_id: format_uint64_id(trigger_id),
406        client_trigger_id: String::new(),
407        status,
408    })
409}
410
411/// `CreateTriggerResponse` acknowledges admission only and no longer carries a
412/// status field; synthesize `"accepted"`.
413pub fn trigger_mutation_from_create(
414    msg: &CreateTriggerResponse,
415) -> crate::errors::Result<TriggerMutationResult> {
416    if msg.trigger_id == 0 || msg.client_trigger_id.trim().is_empty() {
417        return Err(crate::Error::transport(
418            "invalid CreateTrigger response: missing trigger_id or client_trigger_id",
419        ));
420    }
421    Ok(TriggerMutationResult {
422        trigger_id: format_uint64_id(msg.trigger_id),
423        client_trigger_id: msg.client_trigger_id.clone(),
424        status: "accepted".to_owned(),
425    })
426}
427
428pub fn trigger_mutation_from_cancel(
429    msg: &CancelTriggerResponse,
430) -> crate::errors::Result<TriggerMutationResult> {
431    trigger_mutation(msg.trigger_id, msg.status)
432}
433
434pub fn trigger_mutation_from_pause(
435    msg: &PauseTriggerResponse,
436) -> crate::errors::Result<TriggerMutationResult> {
437    trigger_mutation(msg.trigger_id, msg.status)
438}
439
440pub fn trigger_mutation_from_resume(
441    msg: &ResumeTriggerResponse,
442) -> crate::errors::Result<TriggerMutationResult> {
443    trigger_mutation(msg.trigger_id, msg.status)
444}
445
446pub fn trigger_mutation_from_modify(
447    msg: &ModifyTriggerResponse,
448) -> crate::errors::Result<TriggerMutationResult> {
449    trigger_mutation(msg.trigger_id, msg.status)
450}
451
452fn enum_proto_name<E: Enumeration>(value: buffa::EnumValue<E>) -> String {
453    value
454        .as_known()
455        .map(|e| e.proto_name().to_owned())
456        .unwrap_or_else(|| format!("UNKNOWN({})", value.to_i32()))
457}
458
459pub fn trigger_event_from_proto(msg: &ProtoTriggerEvent) -> TriggerEvent {
460    TriggerEvent {
461        trigger_id: format_uint64_id(msg.trigger_id),
462        event_type: enum_proto_name(msg.event_type),
463        ts_ns: if msg.ts_ns == 0 {
464            String::new()
465        } else {
466            msg.ts_ns.to_string()
467        },
468    }
469}
470
471pub fn trigger_events_list_from_proto(msg: &ListTriggerEventsResponse) -> TriggerEventsList {
472    TriggerEventsList {
473        events: msg.events.iter().map(trigger_event_from_proto).collect(),
474        next_page_token: msg.next_page_token.clone(),
475    }
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481    use crate::proto::orders::v1::Side;
482    use crate::proto::triggers::v1::{
483        ConditionalChildExecution, ConditionalTrigger, GetTriggerResponse,
484        ListTriggerEventsResponse, ListTriggersResponse, StopDetails, TriggerEventType,
485        TriggerLimitGtc,
486    };
487
488    #[test]
489    fn trigger_from_proto_projects_attached_trailing_stop_side_and_parent() {
490        use crate::proto::triggers::v1::TrailingStopTrigger;
491
492        let msg = ProtoTrigger {
493            trigger_id: 77,
494            subaccount_id: 9,
495            symbol_id: 3,
496            symbol: "ETH-USDT".into(),
497            status: TriggerStatus::StatusArmed.into(),
498            parent_order_id: Some(9001),
499            qty_scaled: 100,
500            client_trigger_id: "trail-attached".into(),
501            configuration: Some(trigger::Configuration::TrailingStop(Box::new(
502                TrailingStopTrigger {
503                    side: Side::Buy.into(),
504                    trailing_distance: Some(
505                        crate::proto::triggers::v1::trailing_stop_trigger::TrailingDistance::TrailingDistanceBps(
506                            50,
507                        ),
508                    ),
509                    ..Default::default()
510                },
511            ))),
512            ..Default::default()
513        };
514        let t = trigger_from_proto(&msg);
515        assert_eq!(t.trigger_type, "trailing_stop");
516        assert_eq!(t.side, "buy");
517        assert_eq!(t.order_type, "market");
518        assert_eq!(t.time_in_force, "ioc");
519        assert_eq!(t.parent_order_id, Some(format_uint64_id(9001)));
520    }
521
522    #[test]
523    fn trigger_from_proto_maps_status_and_stop_price() {
524        let msg = ProtoTrigger {
525            trigger_id: 42,
526            subaccount_id: 9,
527            symbol_id: 3,
528            symbol: "ETH-USDT".into(),
529            status: TriggerStatus::StatusArmed.into(),
530            qty_scaled: 100,
531            client_trigger_id: "cid".into(),
532            configuration: Some(trigger::Configuration::StopLoss(Box::new(
533                ConditionalTrigger {
534                    trigger_price_ticks: 5000,
535                    side: Side::Buy.into(),
536                    child: ConditionalChildExecution {
537                        execution: Some(conditional_child_execution::Execution::LimitGtc(
538                            Box::new(TriggerLimitGtc {
539                                price_ticks: 4990,
540                                post_only: true,
541                                ..Default::default()
542                            }),
543                        )),
544                        ..Default::default()
545                    }
546                    .into(),
547                    ..Default::default()
548                },
549            ))),
550            runtime_details: Some(trigger::RuntimeDetails::Stop(Box::new(StopDetails {
551                trigger_price_ticks: 5000,
552                ..Default::default()
553            }))),
554            ..Default::default()
555        };
556        let t = trigger_from_proto(&msg);
557        assert_eq!(t.trigger_id, format_uint64_id(42));
558        assert_eq!(t.subaccount_id, format_uint64_id(9));
559        assert_eq!(t.trigger_type, "stop_loss");
560        assert_eq!(t.status, "armed");
561        assert_eq!(t.side, "buy");
562        assert_eq!(t.order_type, "limit");
563        assert_eq!(t.time_in_force, "gtc");
564        assert!(t.post_only);
565        assert_eq!(t.limit_price.as_ref().unwrap().as_ticks(), 4990);
566        assert_eq!(t.qty.as_ref().unwrap().as_scaled(), 100);
567        assert_eq!(t.trigger_price.as_ref().unwrap().as_ticks(), 5000);
568        assert_eq!(t.client_trigger_id, "cid");
569        assert!(matches!(t.details, Some(TriggerDetails::Stop(_))));
570    }
571
572    #[test]
573    fn trigger_from_proto_projects_twap_child_orders_and_executed_qty() {
574        use crate::proto::triggers::v1::{TwapDetails, TwapTrigger};
575
576        let msg = ProtoTrigger {
577            trigger_id: 11,
578            symbol_id: 1,
579            symbol: "BTC-USDT".into(),
580            status: TriggerStatus::StatusRunning.into(),
581            qty_scaled: 100_000_000,
582            client_trigger_id: "twap-1".into(),
583            child_order_ids: vec![101, 202],
584            configuration: Some(trigger::Configuration::Twap(Box::new(TwapTrigger {
585                side: Side::Buy.into(),
586                duration_ms: 60_000,
587                slice_interval_ms: 5_000,
588                execution: Some(twap_trigger::Execution::MarketIoc(Box::default())),
589                ..Default::default()
590            }))),
591            runtime_details: Some(trigger::RuntimeDetails::TwapState(Box::new(TwapDetails {
592                twap_duration_ms: 60_000,
593                twap_slice_interval_ms: 5_000,
594                slice_idx: 2,
595                slice_count: 12,
596                executed_qty_scaled: 25_000_000,
597                ..Default::default()
598            }))),
599            ..Default::default()
600        };
601        let t = trigger_from_proto(&msg);
602        assert_eq!(t.trigger_type, "twap");
603        assert_eq!(t.side, "buy");
604        assert_eq!(t.order_type, "market");
605        assert_eq!(
606            t.child_order_ids,
607            vec![format_uint64_id(101), format_uint64_id(202)]
608        );
609        let Some(TriggerDetails::Twap(twap)) = t.details.as_ref() else {
610            panic!("expected twap details");
611        };
612        assert_eq!(twap.slice_idx, 2);
613        assert_eq!(twap.slice_count, 12);
614        assert_eq!(twap.executed_qty.as_ref().unwrap().as_scaled(), 25_000_000);
615    }
616
617    #[test]
618    fn trigger_status_from_label_validates() {
619        assert_eq!(
620            trigger_status_from_label("armed").unwrap(),
621            TriggerStatus::StatusArmed
622        );
623        assert_eq!(
624            trigger_status_from_label("cancelled").unwrap(),
625            TriggerStatus::StatusCanceled
626        );
627        assert!(trigger_status_from_label("nope").is_err());
628    }
629
630    #[test]
631    fn singular_trigger_mutations_reject_empty_success_responses() {
632        assert!(trigger_mutation_from_create(&CreateTriggerResponse::default()).is_err());
633        assert!(trigger_mutation_from_cancel(&CancelTriggerResponse::default()).is_err());
634        assert!(trigger_mutation_from_pause(&PauseTriggerResponse::default()).is_err());
635        assert!(trigger_mutation_from_resume(&ResumeTriggerResponse::default()).is_err());
636        assert!(trigger_mutation_from_modify(&ModifyTriggerResponse::default()).is_err());
637
638        let created = trigger_mutation_from_create(&CreateTriggerResponse {
639            trigger_id: 7,
640            client_trigger_id: "stable-trigger".into(),
641            ..Default::default()
642        })
643        .unwrap();
644        assert_eq!(created.client_trigger_id, "stable-trigger");
645    }
646
647    #[test]
648    fn triggers_list_and_get() {
649        let listed = triggers_list_from_proto(&ListTriggersResponse {
650            triggers: vec![ProtoTrigger {
651                trigger_id: 1,
652                symbol_id: 1,
653                ..Default::default()
654            }],
655            next_page_token: "trig-page-2".into(),
656            ..Default::default()
657        });
658        assert_eq!(listed.triggers.len(), 1);
659        assert_eq!(listed.total, 1);
660        assert_eq!(listed.next_page_token, "trig-page-2");
661
662        let got = get_trigger_from_proto(&GetTriggerResponse {
663            trigger: ProtoTrigger {
664                trigger_id: 3,
665                symbol_id: 1,
666                ..Default::default()
667            }
668            .into(),
669            ..Default::default()
670        });
671        assert_eq!(got.unwrap().trigger_id, format_uint64_id(3));
672    }
673
674    #[test]
675    fn trigger_events_list_keeps_next_page_token() {
676        let listed = trigger_events_list_from_proto(&ListTriggerEventsResponse {
677            events: vec![ProtoTriggerEvent {
678                trigger_id: 1,
679                event_type: TriggerEventType::EventFired.into(),
680                ts_ns: 123,
681                ..Default::default()
682            }],
683            next_page_token: "evt-page-2".into(),
684            ..Default::default()
685        });
686        assert_eq!(listed.events.len(), 1);
687        assert_eq!(listed.next_page_token, "evt-page-2");
688    }
689
690    #[test]
691    fn trigger_event_preserves_unknown_event_type_number() {
692        let event = trigger_event_from_proto(&ProtoTriggerEvent {
693            trigger_id: 1,
694            event_type: buffa::EnumValue::Unknown(321),
695            ..Default::default()
696        });
697        assert_eq!(event.event_type, "UNKNOWN(321)");
698    }
699}