Skip to main content

nautilus_kalshi/execution/
submit.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::sync::{
17    Arc, Mutex,
18    atomic::{AtomicBool, Ordering},
19};
20
21use anyhow::Context;
22use nautilus_core::{Params, UnixNanos};
23use nautilus_live::{ExecutionEventEmitter, execution::failure::CommandFailure};
24use nautilus_model::{
25    enums::{OrderSide, OrderStatus, OrderType, TimeInForce},
26    events::OrderDeniedReason,
27    identifiers::VenueOrderId,
28    instruments::BinaryOption,
29    orders::{Order, OrderAny},
30};
31use rust_decimal::Decimal;
32use tokio_util::sync::CancellationToken;
33
34use super::{account, context::PrivateState};
35use crate::{
36    common::{
37        enums::{MarketStatus, MarketType},
38        parse::KalshiPriceGrid,
39    },
40    http::{
41        client::KalshiHttpClient,
42        error::KalshiHttpError,
43        models::{
44            BookSide, CreateOrderResponse, Field, FixedPoint, SelfTradePrevention,
45            TimeInForce as VenueTimeInForce, VenueError,
46        },
47        query::CreateOrderRequest,
48    },
49    websocket::client::KalshiWebSocketClient,
50};
51
52pub(super) struct Submission {
53    pub(super) order: OrderAny,
54    pub(super) position_qty: Option<Decimal>,
55    pub(super) definition: BinaryOption,
56    pub(super) request: CreateOrderRequest,
57    pub(super) http: KalshiHttpClient,
58    pub(super) state: Arc<Mutex<PrivateState>>,
59    pub(super) emitter: ExecutionEventEmitter,
60    pub(super) ready: Arc<AtomicBool>,
61    pub(super) ws_client: KalshiWebSocketClient,
62    pub(super) refresh: tokio::sync::mpsc::UnboundedSender<()>,
63    pub(super) session: String,
64    pub(super) cancellation: CancellationToken,
65}
66
67impl Submission {
68    pub(super) async fn run(mut self) {
69        let prepared = tokio::select! {
70            biased;
71            () = self.cancellation.cancelled() => Err(anyhow::anyhow!("Kalshi submission canceled before dispatch")),
72            result = prepare(&self.http, &self.order, &self.definition, &self.request) => result,
73        };
74
75        let state = Arc::clone(&self.state);
76        let admission = prepared.and_then(|hold| {
77            let mut state = state.lock().expect("private state lock is not poisoned");
78            self.admit(&mut state, hold)
79        });
80
81        if let Err(e) = admission {
82            let reason = OrderDeniedReason::ValidationFailed {
83                detail: e.to_string(),
84            };
85
86            self.deny(&reason.to_string());
87            return;
88        }
89
90        self.http = transport(
91            &self.http,
92            &self.state,
93            &self.ws_client,
94            &self.cancellation,
95            &self.session,
96        );
97        let result = self.http.create_order(&self.request).await;
98
99        self.resolve(result);
100    }
101
102    pub(super) fn admit(&mut self, state: &mut PrivateState, hold: Decimal) -> anyhow::Result<()> {
103        anyhow::ensure!(
104            self.ready.load(Ordering::Acquire)
105                && state.session == self.session
106                && state.epoch.is_some()
107                && state.epoch == self.ws_client.connection_epoch()
108                && !state
109                    .barrier
110                    .lock()
111                    .expect("settlement barrier lock")
112                    .is_blocked(),
113            "Kalshi submission requires current-session readiness"
114        );
115        expiry(
116            &self.order,
117            nautilus_core::time::get_atomic_clock_realtime().get_time_ns(),
118        )?;
119        state.submit(&mut self.order, hold, self.position_qty, &self.emitter)
120    }
121
122    pub(super) fn resolve(&self, result: Result<CreateOrderResponse, KalshiHttpError>) -> bool {
123        let reason = result.as_ref().err().map(rejection_reason);
124
125        let (outcome, due_post_only) = match result {
126            Ok(ack) => (
127                self.acknowledge(&ack)
128                    .map_err(|e| CommandFailure::ambiguous(e.to_string())),
129                false,
130            ),
131            Err(e) => {
132                let due_post_only = post_only_rejection(&e);
133                (Err(classify_failure(&e)), due_post_only)
134            }
135        };
136
137        let resolved = !matches!(&outcome, Err(CommandFailure::Ambiguous(_)));
138
139        if let Err(failure) = outcome {
140            match failure {
141                CommandFailure::NotSent(_) | CommandFailure::VenueRejected(_) => {
142                    self.reject(reason.as_deref().unwrap_or("Order rejected"), due_post_only);
143                }
144                CommandFailure::Ambiguous(reason) => {
145                    self.invalidate();
146                    log::warn!("Kalshi submission requires recovery: {reason}");
147                }
148            }
149        }
150
151        if !self.cancellation.is_cancelled() && self.refresh.send(()).is_err() {
152            log::warn!("Kalshi submission recovery stopped");
153        }
154
155        resolved
156    }
157
158    pub(super) fn invalidate(&self) {
159        self.ready.store(false, Ordering::Release);
160        self.state
161            .lock()
162            .expect("private state lock is not poisoned")
163            .invalidate();
164    }
165
166    pub(super) fn reject(&self, reason: &str, due_post_only: bool) {
167        let result = self
168            .state
169            .lock()
170            .expect("private state lock is not poisoned")
171            .reject_submission(
172                self.order.client_order_id(),
173                reason,
174                due_post_only,
175                &self.emitter,
176            );
177
178        if let Err(e) = result {
179            log::warn!("Kalshi submission retains venue evidence: {e}");
180        }
181    }
182
183    pub(super) fn deny(&mut self, reason: &str) {
184        let result = self
185            .state
186            .lock()
187            .expect("private state lock is not poisoned")
188            .deny_submission(&mut self.order, reason, &self.emitter);
189
190        if let Err(e) = result {
191            log::warn!("Kalshi submission denial could not be routed: {e}");
192        }
193    }
194
195    fn acknowledge(&self, ack: &CreateOrderResponse) -> anyhow::Result<()> {
196        anyhow::ensure!(
197            ack.client_order_id == Field::Value(self.order.client_order_id().to_string()),
198            "Kalshi acknowledgement client identity mismatch"
199        );
200        let venue_id = VenueOrderId::new_checked(&ack.order_id)?;
201        anyhow::ensure!(
202            ack.fill_count.0 >= Decimal::ZERO
203                && ack.remaining_count.0 >= Decimal::ZERO
204                && ack.fill_count.0.normalize().scale() <= 2
205                && ack.remaining_count.0.normalize().scale() <= 2
206                && ack
207                    .fill_count
208                    .0
209                    .checked_add(ack.remaining_count.0)
210                    .is_some_and(|qty| qty <= self.request.count.0),
211            "Kalshi acknowledgement counts are invalid"
212        );
213        let nanos = u64::try_from(ack.ts_ms)?
214            .checked_mul(1_000_000)
215            .context("Kalshi acknowledgement timestamp overflow")?;
216        let ts_event = UnixNanos::from(nanos);
217        self.state
218            .lock()
219            .expect("private state lock is not poisoned")
220            .acknowledge(
221                self.order.client_order_id(),
222                venue_id,
223                ts_event,
224                &self.emitter,
225            )
226    }
227}
228
229impl Drop for Submission {
230    fn drop(&mut self) {
231        if self.order.status() == OrderStatus::Initialized {
232            let reason = OrderDeniedReason::ValidationFailed {
233                detail: "Kalshi submission canceled before dispatch".into(),
234            };
235
236            self.deny(&reason.to_string());
237        }
238    }
239}
240
241pub(super) fn transport(
242    http: &KalshiHttpClient,
243    state: &Arc<Mutex<PrivateState>>,
244    ws_client: &KalshiWebSocketClient,
245    cancellation: &CancellationToken,
246    session: &str,
247) -> KalshiHttpClient {
248    let state = Arc::clone(state);
249    let epoch = state
250        .lock()
251        .expect("private state lock is not poisoned")
252        .epoch;
253    let ws_client = ws_client.clone();
254    let cancellation = cancellation.clone();
255    let session = session.to_owned();
256    http.clone()
257        .with_dispatch_check(cancellation.clone(), move || {
258            let state = state.lock().expect("private state lock is not poisoned");
259            !cancellation.is_cancelled()
260                && state.session == session
261                && epoch.is_some()
262                && state.epoch == epoch
263                && ws_client.connection_epoch() == epoch
264                && !state
265                    .barrier
266                    .lock()
267                    .expect("settlement barrier lock")
268                    .is_blocked()
269        })
270}
271
272pub(super) async fn prepare(
273    http: &KalshiHttpClient,
274    order: &OrderAny,
275    definition: &BinaryOption,
276    request: &CreateOrderRequest,
277) -> anyhow::Result<Decimal> {
278    let market = http.get_market(&request.ticker).await?.market;
279    anyhow::ensure!(
280        market.ticker == request.ticker
281            && market.event_ticker
282                == definition
283                    .event_id
284                    .context("Kalshi event identity missing")?
285                    .as_str()
286            && market.exchange_index == Field::Value(i32::try_from(request.exchange_index)?)
287            && market.market_type == MarketType::Binary
288            && market.notional_value_dollars.0 == Decimal::ONE,
289        "Kalshi submission market identity mismatch"
290    );
291    let qty = order.quantity();
292    anyhow::ensure!(
293        qty.as_decimal() % definition.size_increment.as_decimal() == Decimal::ZERO
294            && definition.min_quantity.is_none_or(|min| qty >= min)
295            && definition.max_quantity.is_none_or(|max| qty <= max),
296        "Kalshi quantity violates instrument limits"
297    );
298    let now = nautilus_core::time::get_atomic_clock_realtime().get_time_ns();
299    anyhow::ensure!(
300        market.status == MarketStatus::Active
301            && nautilus_core::datetime::try_datetime_to_unix_nanos(market.open_time)? <= now
302            && now < nautilus_core::datetime::try_datetime_to_unix_nanos(market.close_time)?,
303        "Kalshi market is not open for trading"
304    );
305    anyhow::ensure!(
306        KalshiPriceGrid::new(&market.price_ranges)?.contains(request.price.0),
307        "Kalshi price is off the market grid"
308    );
309    let exchange = http.get_status().await?;
310    anyhow::ensure!(
311        exchange.exchange_active && exchange.trading_active,
312        "Kalshi exchange is not trading"
313    );
314    let shard = i32::try_from(request.exchange_index)?;
315
316    if let Field::Value(statuses) = exchange.exchange_index_statuses {
317        anyhow::ensure!(
318            statuses.iter().any(|status| status.exchange_index == shard
319                && status.exchange_active
320                && status.trading_active),
321            "Kalshi shard is not trading"
322        );
323    } else {
324        anyhow::ensure!(
325            request.exchange_index == 0,
326            "Kalshi shard availability is unknown"
327        );
328    }
329
330    account::hold(
331        http,
332        definition,
333        order.order_side(),
334        order.leaves_qty().as_decimal(),
335        request.price.0,
336    )
337    .await
338}
339
340/// Builds the V2 limit request the execution client sends for one order.
341///
342/// Prices use at most four decimal places and counts at most two. A GTD expiry must be a future
343/// whole Unix second on the realtime clock. The returned request is not sent and does not reserve
344/// funds.
345///
346/// # Errors
347///
348/// Returns an error if the order type, time in force, quantity mode, instruction combination,
349/// expiry, ticker, submission parameter, or exact price or count is unsupported.
350pub fn request(
351    order: &OrderAny,
352    params: Option<&Params>,
353    shard: u32,
354    subaccount: u32,
355) -> Result<CreateOrderRequest, OrderDeniedReason> {
356    if order.order_type() != OrderType::Limit {
357        return Err(OrderDeniedReason::UnsupportedOrderType {
358            order_type: order.order_type(),
359        });
360    }
361
362    if !matches!(
363        order.time_in_force(),
364        TimeInForce::Gtc | TimeInForce::Ioc | TimeInForce::Fok | TimeInForce::Gtd
365    ) {
366        return Err(OrderDeniedReason::UnsupportedTimeInForce(
367            order.time_in_force(),
368        ));
369    }
370
371    if order.is_reduce_only() && order.time_in_force() != TimeInForce::Ioc {
372        return Err(OrderDeniedReason::UnsupportedReduceOnly);
373    }
374
375    if order.is_quote_quantity() {
376        return Err(OrderDeniedReason::unsupported_quote_quantity());
377    }
378
379    let validated = (|| -> anyhow::Result<_> {
380        anyhow::ensure!(
381            order.display_qty().is_none()
382                && !order.is_contingency()
383                && order.linked_order_ids().is_none()
384                && order.parent_order_id().is_none()
385                && !order.is_emulated()
386                && order.exec_algorithm_id().is_none(),
387            "unsupported Kalshi limit instruction combination"
388        );
389        anyhow::ensure!(
390            !order.is_post_only()
391                || matches!(order.time_in_force(), TimeInForce::Gtc | TimeInForce::Gtd),
392            "Kalshi post-only requires GTC or GTD"
393        );
394        let expiration_time = expiry(
395            order,
396            nautilus_core::time::get_atomic_clock_realtime().get_time_ns(),
397        )?;
398        let price = order
399            .price()
400            .context("Kalshi limit price missing")?
401            .as_decimal()
402            .normalize();
403        let count = order.quantity().as_decimal().normalize();
404        anyhow::ensure!(
405            price > Decimal::ZERO
406                && price < Decimal::ONE
407                && price.scale() <= 4
408                && count > Decimal::ZERO
409                && count.scale() <= 2,
410            "invalid exact Kalshi quantity or price"
411        );
412        let (stp, cancel_on_pause) = flags(params)?;
413
414        Ok(CreateOrderRequest {
415            ticker: crate::common::parse::parse_ticker(order.instrument_id())?,
416            side: if order.order_side() == OrderSide::Buy {
417                BookSide::Bid
418            } else {
419                BookSide::Ask
420            },
421            count: FixedPoint(count),
422            price: FixedPoint(price),
423            time_in_force: match order.time_in_force() {
424                TimeInForce::Ioc => VenueTimeInForce::ImmediateOrCancel,
425                TimeInForce::Fok => VenueTimeInForce::FillOrKill,
426                _ => VenueTimeInForce::GoodTillCanceled,
427            },
428            self_trade_prevention_type: stp,
429            subaccount,
430            exchange_index: shard,
431            client_order_id: Some(order.client_order_id().to_string()),
432            expiration_time,
433            post_only: Some(order.is_post_only()),
434            cancel_order_on_pause: Some(cancel_on_pause),
435            reduce_only: Some(order.is_reduce_only()),
436        })
437    })();
438
439    validated.map_err(|e| OrderDeniedReason::ValidationFailed {
440        detail: e.to_string(),
441    })
442}
443
444fn expiry(order: &OrderAny, now: UnixNanos) -> anyhow::Result<Option<i64>> {
445    if order.time_in_force() != TimeInForce::Gtd {
446        anyhow::ensure!(order.expire_time().is_none(), "Kalshi expiry requires GTD");
447        return Ok(None);
448    }
449
450    let expires = order.expire_time().context("Kalshi GTD expiry missing")?;
451    anyhow::ensure!(
452        expires.as_u64().is_multiple_of(1_000_000_000),
453        "Kalshi GTD expiry must use whole Unix seconds"
454    );
455    anyhow::ensure!(expires > now, "Kalshi GTD expiry must be in the future");
456    Ok(Some(i64::try_from(expires.as_u64() / 1_000_000_000)?))
457}
458
459fn flags(params: Option<&Params>) -> anyhow::Result<(SelfTradePrevention, bool)> {
460    let mut stp = SelfTradePrevention::TakerAtCross;
461    let mut cancel_on_pause = false;
462
463    if let Some(params) = params {
464        for (key, value) in params {
465            match key.as_str() {
466                "self_trade_prevention_type" => {
467                    stp = serde_json::from_value(value.clone())
468                        .context("unsupported Kalshi self-trade prevention")?;
469                }
470                "cancel_order_on_pause" => {
471                    cancel_on_pause = value.as_bool().context("invalid Kalshi cancel-on-pause")?;
472                }
473                _ => anyhow::bail!("unsupported Kalshi submission parameter"),
474            }
475        }
476    }
477
478    Ok((stp, cancel_on_pause))
479}
480
481pub(super) fn classify_failure(error: &KalshiHttpError) -> CommandFailure {
482    let reason = error.to_string();
483    if error.is_definitely_not_sent() {
484        CommandFailure::not_sent(reason)
485    } else if matches!(
486        venue_code(error),
487        Some((400 | 401 | 403, code)) if rejection_code(code).is_some()
488    ) {
489        CommandFailure::venue_rejected(reason)
490    } else {
491        CommandFailure::ambiguous(reason)
492    }
493}
494
495fn venue_code(error: &KalshiHttpError) -> Option<(u16, &str)> {
496    let KalshiHttpError::Venue { status, evidence } = error else {
497        return None;
498    };
499
500    let Field::Value(code) = &evidence.venue.as_ref()?.code else {
501        return None;
502    };
503
504    Some((*status, code))
505}
506
507// Recovery uses this reason to distinguish proven unsent submissions from venue rejections
508pub(super) const NOT_SENT_REASON: &str = "Order was not sent";
509
510fn post_only_rejection(error: &KalshiHttpError) -> bool {
511    let KalshiHttpError::Venue {
512        status: 400,
513        evidence,
514    } = error
515    else {
516        return false;
517    };
518
519    let Some(venue) = evidence.venue.as_ref() else {
520        return false;
521    };
522
523    post_only_error(venue)
524}
525
526pub(super) fn post_only_error(error: &VenueError) -> bool {
527    matches!(&error.code, Field::Value(code) if code == "post_only_cross")
528        || matches!(&error.code, Field::Value(code) if code == "invalid_order")
529            && matches!(&error.details, Field::Value(details) if details == "post only cross")
530}
531
532pub(super) fn rejection_reason(error: &KalshiHttpError) -> String {
533    if post_only_rejection(error) {
534        return "Post-only order would cross".into();
535    }
536
537    let Some((_, code)) = venue_code(error) else {
538        return NOT_SENT_REASON.into();
539    };
540
541    rejection_code(code).unwrap_or("Order rejected").into()
542}
543
544pub(super) fn rejection_code(code: &str) -> Option<&'static str> {
545    Some(match code {
546        "invalid_order" => "Invalid order",
547        "insufficient_balance" => "Insufficient balance",
548        "market_closed" => "Market closed",
549        "invalid_parameters" => "Invalid parameters",
550        "invalid_order_size" => "Invalid order size",
551        "invalid_order_price" => "Invalid order price",
552        "post_only_cross" => "Post-only order would cross",
553        "authentication_error" => "Authentication failed",
554        _ => return None,
555    })
556}
557
558#[cfg(test)]
559pub(super) mod tests {
560    use nautilus_common::messages::ExecutionEvent;
561    use nautilus_live::task::TaskGroup;
562    use nautilus_model::{
563        enums::AccountType,
564        events::OrderEventAny,
565        orders::builder::OrderTestBuilder,
566        types::{Currency, Price, Quantity},
567    };
568    use rstest::rstest;
569
570    use super::*;
571    use crate::http::error::ResponseEvidence;
572
573    #[allow(dead_code, reason = "shared key fixtures serve several suites")]
574    mod keys {
575        include!(concat!(
576            env!("CARGO_MANIFEST_DIR"),
577            "/tests/integration/keys.rs"
578        ));
579    }
580
581    pub(in crate::execution) fn pending() -> (
582        Submission,
583        tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
584    ) {
585        let fixtures: serde_json::Value =
586            serde_json::from_str(include_str!("../../test_data/instruments.json")).unwrap();
587        let market =
588            serde_json::from_value(fixtures["definitions"]["live"]["market"].clone()).unwrap();
589        let event =
590            serde_json::from_value(fixtures["definitions"]["live"]["event"].clone()).unwrap();
591        let definition =
592            crate::http::parse::parse_instrument(&market, &event, UnixNanos::from(1)).unwrap();
593        let order = OrderTestBuilder::new(OrderType::Limit)
594            .instrument_id(definition.id)
595            .client_order_id("drop-before-send".into())
596            .quantity(Quantity::from("1.25"))
597            .price(Price::from("0.600000"))
598            .time_in_force(TimeInForce::Gtc)
599            .build();
600        let request = request(&order, None, 3, 0).unwrap();
601
602        let transport = crate::config::KalshiDataClientConfig {
603            api_key_id: Some("drop-test".into()),
604            private_key: Some(keys::rsa_pkcs8().into()),
605            ..Default::default()
606        };
607
608        let http = KalshiHttpClient::new_authenticated(&transport).unwrap();
609        let (ws_client, _) = KalshiWebSocketClient::new(transport).unwrap();
610        let (sender, output) = tokio::sync::mpsc::unbounded_channel();
611
612        let mut emitter = ExecutionEventEmitter::new(
613            nautilus_core::time::get_atomic_clock_realtime(),
614            order.trader_id(),
615            "KALSHI-007".into(),
616            AccountType::Cash,
617            Some(Currency::USD()),
618        );
619
620        emitter.set_sender(sender);
621        let state = Arc::new(Mutex::new(PrivateState::new()));
622        let session = state.lock().unwrap().session.clone();
623        let (refresh, _) = tokio::sync::mpsc::unbounded_channel();
624
625        (
626            Submission {
627                order,
628                position_qty: None,
629                definition,
630                request,
631                http,
632                state,
633                emitter,
634                ready: Arc::new(AtomicBool::new(false)),
635                ws_client,
636                refresh,
637                session,
638                cancellation: CancellationToken::new(),
639            },
640            output,
641        )
642    }
643
644    #[rstest]
645    fn ambiguous_submission_invalidates_readiness_until_account_recovery() {
646        let (submission, mut output) = pending();
647        submission.ready.store(true, Ordering::Release);
648
649        let ticket = {
650            let mut state = submission.state.lock().unwrap();
651            state.epoch = Some((3, 4));
652            state.ledger.begin_refresh()
653        };
654
655        let resolved = submission.resolve(Err(KalshiHttpError::Status(503)));
656
657        let (epoch, refresh_valid) = {
658            let state = submission.state.lock().unwrap();
659            (state.epoch, state.ledger.check_refresh(ticket).is_ok())
660        };
661
662        assert!(!resolved);
663        assert!(!submission.ready.load(Ordering::Acquire));
664        assert_eq!(epoch, None);
665        assert!(!refresh_valid);
666        assert!(output.try_recv().is_err());
667    }
668
669    #[rstest]
670    #[cfg_attr(not(all(feature = "simulation", madsim)), tokio::test)]
671    #[cfg_attr(all(feature = "simulation", madsim), madsim::test)]
672    async fn pending_command_drop_delivers_one_denial(#[values(false, true)] forced: bool) {
673        let (submission, mut output) = pending();
674        let id = submission.order.client_order_id();
675        let state = Arc::clone(&submission.state);
676        let tasks = TaskGroup::new();
677
678        if forced {
679            let (started, ready) = tokio::sync::oneshot::channel();
680            tasks
681                .spawn(async move {
682                    started.send(()).unwrap();
683                    std::future::pending::<()>().await;
684                    submission.run().await;
685                })
686                .unwrap();
687
688            ready.await.unwrap();
689            tasks.abort();
690            tasks
691                .finish_shutdown(
692                    std::time::Duration::from_secs(1),
693                    std::time::Duration::from_secs(1),
694                )
695                .await
696                .unwrap();
697        } else {
698            tasks.begin_shutdown();
699            assert!(tasks.spawn(submission.run()).is_err());
700        }
701
702        let event = output.try_recv().unwrap();
703
704        let ExecutionEvent::Order(OrderEventAny::Denied(denied)) = event else {
705            panic!("expected Denied");
706        };
707
708        assert_eq!(denied.client_order_id, id);
709        assert_eq!(
710            denied.reason.as_str(),
711            "VALIDATION_FAILED: Kalshi submission canceled before dispatch"
712        );
713        assert!(output.try_recv().is_err());
714        assert_eq!(
715            state.lock().unwrap().orders[&id].order.status(),
716            OrderStatus::Denied
717        );
718    }
719
720    #[rstest]
721    #[case(400, "insufficient_balance", true)]
722    #[case(400, "post_only_cross", true)]
723    #[case(403, "authentication_error", true)]
724    #[case(400, "duplicate_client_order_id", false)]
725    #[case(409, "duplicate_client_order_id", false)]
726    #[case(400, "unrecognized_outcome", false)]
727    #[case(503, "invalid_order", false)]
728    fn failure_classification_requires_definitive_rejection(
729        #[case] status: u16,
730        #[case] code: &str,
731        #[case] rejected: bool,
732    ) {
733        let error = KalshiHttpError::Venue {
734            status,
735            evidence: Box::new(ResponseEvidence {
736                body: "redacted".into(),
737                venue: Some(VenueError {
738                    code: Field::Value(code.into()),
739                    message: Field::Missing,
740                    details: Field::Missing,
741                }),
742                retry_after: None,
743                request_id: None,
744            }),
745        };
746
747        let reason = error.to_string();
748        let expected = if rejected {
749            CommandFailure::venue_rejected(reason)
750        } else {
751            CommandFailure::ambiguous(reason)
752        };
753
754        assert_eq!(classify_failure(&error), expected);
755    }
756
757    #[rstest]
758    #[case(400, "post_only_cross", None, true)]
759    #[case(400, "invalid_order", Some("post only cross"), true)]
760    #[case(400, "invalid_order", Some("invalid quantity"), false)]
761    #[case(400, "invalid_order", None, false)]
762    #[case(400, "insufficient_balance", Some("post only cross"), false)]
763    #[case(503, "invalid_order", Some("post only cross"), false)]
764    #[case(503, "post_only_cross", None, false)]
765    fn post_only_rejection_requires_specific_venue_evidence(
766        #[case] status: u16,
767        #[case] code: &str,
768        #[case] details: Option<&str>,
769        #[case] expected: bool,
770    ) {
771        let error = KalshiHttpError::Venue {
772            status,
773            evidence: Box::new(ResponseEvidence {
774                body: "redacted".into(),
775                venue: Some(VenueError {
776                    code: Field::Value(code.into()),
777                    message: Field::Missing,
778                    details: details.map_or(Field::Missing, |value| Field::Value(value.into())),
779                }),
780                retry_after: None,
781                request_id: None,
782            }),
783        };
784
785        assert_eq!(post_only_rejection(&error), expected);
786
787        if expected {
788            assert_eq!(rejection_reason(&error), "Post-only order would cross");
789        }
790    }
791
792    #[rstest]
793    #[case(KalshiHttpError::Quota("local quota"), true)]
794    #[case(KalshiHttpError::Validation("local validation"), true)]
795    #[case(KalshiHttpError::Canceled { dispatched: false }, true)]
796    #[case(KalshiHttpError::Canceled { dispatched: true }, false)]
797    #[case(KalshiHttpError::Status(503), false)]
798    fn local_failure_classification_preserves_dispatch_evidence(
799        #[case] error: KalshiHttpError,
800        #[case] not_sent: bool,
801    ) {
802        let reason = error.to_string();
803        let expected = if not_sent {
804            CommandFailure::not_sent(reason)
805        } else {
806            CommandFailure::ambiguous(reason)
807        };
808
809        assert_eq!(classify_failure(&error), expected);
810    }
811
812    #[rstest]
813    #[case(TimeInForce::Gtc, "good_till_canceled", None)]
814    #[case(TimeInForce::Ioc, "immediate_or_cancel", None)]
815    #[case(TimeInForce::Fok, "fill_or_kill", None)]
816    #[case(TimeInForce::Gtd, "good_till_canceled", Some(4_102_444_800_i64))]
817    fn limit_matrix_encodes_exact_instructions(
818        #[case] tif: TimeInForce,
819        #[case] wire_tif: &str,
820        #[case] expires: Option<i64>,
821        #[values(OrderSide::Buy, OrderSide::Sell)] side: OrderSide,
822    ) {
823        let mut builder = OrderTestBuilder::new(OrderType::Limit);
824        builder
825            .instrument_id("EVENT-MARKET.KALSHI".into())
826            .client_order_id("matrix-order".into())
827            .quantity(Quantity::from("1.25"))
828            .price(Price::from("0.4321"))
829            .side(side)
830            .time_in_force(tif)
831            .post_only(tif == TimeInForce::Gtd)
832            .reduce_only(tif == TimeInForce::Ioc);
833
834        if let Some(expires) = expires {
835            builder.expire_time(UnixNanos::from(expires as u64 * 1_000_000_000));
836        }
837
838        let order = builder.build();
839        let wire = serde_json::to_value(request(&order, None, 3, 0).unwrap()).unwrap();
840
841        let mut expected = serde_json::from_str::<serde_json::Value>(include_str!(
842            "../../test_data/rest_requests.json"
843        ))
844        .unwrap()["limit_matrix"]
845            .clone();
846        expected["side"] = serde_json::json!(if side == OrderSide::Buy { "bid" } else { "ask" });
847        expected["time_in_force"] = serde_json::json!(wire_tif);
848        expected["post_only"] = serde_json::json!(tif == TimeInForce::Gtd);
849        expected["reduce_only"] = serde_json::json!(tif == TimeInForce::Ioc);
850        if let Some(expires) = expires {
851            expected["expiration_time"] = expires.into();
852        }
853
854        assert_eq!(wire, expected);
855    }
856
857    #[rstest]
858    #[case(1_000_000_000, 999_999_999, Ok(Some(1)))]
859    #[case(
860        1_000_000_000,
861        1_000_000_000,
862        Err("Kalshi GTD expiry must be in the future")
863    )]
864    #[case(
865        1_000_000_000,
866        1_000_000_001,
867        Err("Kalshi GTD expiry must be in the future")
868    )]
869    #[case(1_000_000_001, 0, Err("Kalshi GTD expiry must use whole Unix seconds"))]
870    fn gtd_expiry_is_exact_and_future(
871        #[case] expires: u64,
872        #[case] now: u64,
873        #[case] expected: Result<Option<i64>, &str>,
874    ) {
875        let order = OrderTestBuilder::new(OrderType::Limit)
876            .instrument_id("EVENT-MARKET.KALSHI".into())
877            .quantity(Quantity::from("1.25"))
878            .price(Price::from("0.4321"))
879            .time_in_force(TimeInForce::Gtd)
880            .expire_time(UnixNanos::from(expires))
881            .build();
882        assert_eq!(
883            expiry(&order, UnixNanos::from(now)).map_err(|e| e.to_string()),
884            expected.map_err(str::to_owned)
885        );
886    }
887}