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) -> Result<CreateOrderRequest, OrderDeniedReason> {
355    if order.order_type() != OrderType::Limit {
356        return Err(OrderDeniedReason::UnsupportedOrderType {
357            order_type: order.order_type(),
358        });
359    }
360
361    if !matches!(
362        order.time_in_force(),
363        TimeInForce::Gtc | TimeInForce::Ioc | TimeInForce::Fok | TimeInForce::Gtd
364    ) {
365        return Err(OrderDeniedReason::UnsupportedTimeInForce(
366            order.time_in_force(),
367        ));
368    }
369
370    if order.is_reduce_only() && order.time_in_force() != TimeInForce::Ioc {
371        return Err(OrderDeniedReason::UnsupportedReduceOnly);
372    }
373
374    if order.is_quote_quantity() {
375        return Err(OrderDeniedReason::unsupported_quote_quantity());
376    }
377
378    let validated = (|| -> anyhow::Result<_> {
379        anyhow::ensure!(
380            order.display_qty().is_none()
381                && !order.is_contingency()
382                && order.linked_order_ids().is_none()
383                && order.parent_order_id().is_none()
384                && !order.is_emulated()
385                && order.exec_algorithm_id().is_none(),
386            "unsupported Kalshi limit instruction combination"
387        );
388        anyhow::ensure!(
389            !order.is_post_only()
390                || matches!(order.time_in_force(), TimeInForce::Gtc | TimeInForce::Gtd),
391            "Kalshi post-only requires GTC or GTD"
392        );
393        let expiration_time = expiry(
394            order,
395            nautilus_core::time::get_atomic_clock_realtime().get_time_ns(),
396        )?;
397        let price = order
398            .price()
399            .context("Kalshi limit price missing")?
400            .as_decimal()
401            .normalize();
402        let count = order.quantity().as_decimal().normalize();
403        anyhow::ensure!(
404            price > Decimal::ZERO
405                && price < Decimal::ONE
406                && price.scale() <= 4
407                && count > Decimal::ZERO
408                && count.scale() <= 2,
409            "invalid exact Kalshi quantity or price"
410        );
411        let (stp, cancel_on_pause) = flags(params)?;
412
413        Ok(CreateOrderRequest {
414            ticker: crate::common::parse::parse_ticker(order.instrument_id())?,
415            side: if order.order_side() == OrderSide::Buy {
416                BookSide::Bid
417            } else {
418                BookSide::Ask
419            },
420            count: FixedPoint(count),
421            price: FixedPoint(price),
422            time_in_force: match order.time_in_force() {
423                TimeInForce::Ioc => VenueTimeInForce::ImmediateOrCancel,
424                TimeInForce::Fok => VenueTimeInForce::FillOrKill,
425                _ => VenueTimeInForce::GoodTillCanceled,
426            },
427            self_trade_prevention_type: stp,
428            subaccount: 0,
429            exchange_index: shard,
430            client_order_id: Some(order.client_order_id().to_string()),
431            expiration_time,
432            post_only: Some(order.is_post_only()),
433            cancel_order_on_pause: Some(cancel_on_pause),
434            reduce_only: Some(order.is_reduce_only()),
435        })
436    })();
437
438    validated.map_err(|e| OrderDeniedReason::ValidationFailed {
439        detail: e.to_string(),
440    })
441}
442
443fn expiry(order: &OrderAny, now: UnixNanos) -> anyhow::Result<Option<i64>> {
444    if order.time_in_force() != TimeInForce::Gtd {
445        anyhow::ensure!(order.expire_time().is_none(), "Kalshi expiry requires GTD");
446        return Ok(None);
447    }
448
449    let expires = order.expire_time().context("Kalshi GTD expiry missing")?;
450    anyhow::ensure!(
451        expires.as_u64().is_multiple_of(1_000_000_000),
452        "Kalshi GTD expiry must use whole Unix seconds"
453    );
454    anyhow::ensure!(expires > now, "Kalshi GTD expiry must be in the future");
455    Ok(Some(i64::try_from(expires.as_u64() / 1_000_000_000)?))
456}
457
458fn flags(params: Option<&Params>) -> anyhow::Result<(SelfTradePrevention, bool)> {
459    let mut stp = SelfTradePrevention::TakerAtCross;
460    let mut cancel_on_pause = false;
461
462    if let Some(params) = params {
463        for (key, value) in params {
464            match key.as_str() {
465                "self_trade_prevention_type" => {
466                    stp = serde_json::from_value(value.clone())
467                        .context("unsupported Kalshi self-trade prevention")?;
468                }
469                "cancel_order_on_pause" => {
470                    cancel_on_pause = value.as_bool().context("invalid Kalshi cancel-on-pause")?;
471                }
472                _ => anyhow::bail!("unsupported Kalshi submission parameter"),
473            }
474        }
475    }
476
477    Ok((stp, cancel_on_pause))
478}
479
480pub(super) fn classify_failure(error: &KalshiHttpError) -> CommandFailure {
481    let reason = error.to_string();
482    if error.is_definitely_not_sent() {
483        CommandFailure::not_sent(reason)
484    } else if matches!(
485        venue_code(error),
486        Some((400 | 401 | 403, code)) if rejection_code(code).is_some()
487    ) {
488        CommandFailure::venue_rejected(reason)
489    } else {
490        CommandFailure::ambiguous(reason)
491    }
492}
493
494fn venue_code(error: &KalshiHttpError) -> Option<(u16, &str)> {
495    let KalshiHttpError::Venue { status, evidence } = error else {
496        return None;
497    };
498
499    let Field::Value(code) = &evidence.venue.as_ref()?.code else {
500        return None;
501    };
502
503    Some((*status, code))
504}
505
506// Recovery uses this reason to distinguish proven unsent submissions from venue rejections
507pub(super) const NOT_SENT_REASON: &str = "Order was not sent";
508
509fn post_only_rejection(error: &KalshiHttpError) -> bool {
510    let KalshiHttpError::Venue {
511        status: 400,
512        evidence,
513    } = error
514    else {
515        return false;
516    };
517
518    let Some(venue) = evidence.venue.as_ref() else {
519        return false;
520    };
521
522    post_only_error(venue)
523}
524
525pub(super) fn post_only_error(error: &VenueError) -> bool {
526    matches!(&error.code, Field::Value(code) if code == "post_only_cross")
527        || matches!(&error.code, Field::Value(code) if code == "invalid_order")
528            && matches!(&error.details, Field::Value(details) if details == "post only cross")
529}
530
531pub(super) fn rejection_reason(error: &KalshiHttpError) -> String {
532    if post_only_rejection(error) {
533        return "Post-only order would cross".into();
534    }
535
536    let Some((_, code)) = venue_code(error) else {
537        return NOT_SENT_REASON.into();
538    };
539
540    rejection_code(code).unwrap_or("Order rejected").into()
541}
542
543pub(super) fn rejection_code(code: &str) -> Option<&'static str> {
544    Some(match code {
545        "invalid_order" => "Invalid order",
546        "insufficient_balance" => "Insufficient balance",
547        "market_closed" => "Market closed",
548        "invalid_parameters" => "Invalid parameters",
549        "invalid_order_size" => "Invalid order size",
550        "invalid_order_price" => "Invalid order price",
551        "post_only_cross" => "Post-only order would cross",
552        "authentication_error" => "Authentication failed",
553        _ => return None,
554    })
555}
556
557#[cfg(test)]
558pub(super) mod tests {
559    use nautilus_common::messages::ExecutionEvent;
560    use nautilus_live::task::TaskGroup;
561    use nautilus_model::{
562        enums::AccountType,
563        events::OrderEventAny,
564        orders::builder::OrderTestBuilder,
565        types::{Currency, Price, Quantity},
566    };
567    use rstest::rstest;
568
569    use super::*;
570    use crate::http::error::ResponseEvidence;
571
572    #[allow(dead_code, reason = "shared key fixtures serve several suites")]
573    mod keys {
574        include!(concat!(
575            env!("CARGO_MANIFEST_DIR"),
576            "/tests/integration/keys.rs"
577        ));
578    }
579
580    pub(in crate::execution) fn pending() -> (
581        Submission,
582        tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
583    ) {
584        let fixtures: serde_json::Value =
585            serde_json::from_str(include_str!("../../test_data/instruments.json")).unwrap();
586        let market =
587            serde_json::from_value(fixtures["definitions"]["live"]["market"].clone()).unwrap();
588        let event =
589            serde_json::from_value(fixtures["definitions"]["live"]["event"].clone()).unwrap();
590        let definition =
591            crate::http::parse::parse_instrument(&market, &event, UnixNanos::from(1)).unwrap();
592        let order = OrderTestBuilder::new(OrderType::Limit)
593            .instrument_id(definition.id)
594            .client_order_id("drop-before-send".into())
595            .quantity(Quantity::from("1.25"))
596            .price(Price::from("0.600000"))
597            .time_in_force(TimeInForce::Gtc)
598            .build();
599        let request = request(&order, None, 3).unwrap();
600
601        let transport = crate::config::KalshiDataClientConfig {
602            api_key_id: Some("drop-test".into()),
603            private_key: Some(keys::rsa_pkcs8().into()),
604            ..Default::default()
605        };
606
607        let http = KalshiHttpClient::new_authenticated(&transport).unwrap();
608        let (ws_client, _) = KalshiWebSocketClient::new(transport).unwrap();
609        let (sender, output) = tokio::sync::mpsc::unbounded_channel();
610
611        let mut emitter = ExecutionEventEmitter::new(
612            nautilus_core::time::get_atomic_clock_realtime(),
613            order.trader_id(),
614            "KALSHI-007".into(),
615            AccountType::Cash,
616            Some(Currency::USD()),
617        );
618
619        emitter.set_sender(sender);
620        let state = Arc::new(Mutex::new(PrivateState::new()));
621        let session = state.lock().unwrap().session.clone();
622        let (refresh, _) = tokio::sync::mpsc::unbounded_channel();
623
624        (
625            Submission {
626                order,
627                position_qty: None,
628                definition,
629                request,
630                http,
631                state,
632                emitter,
633                ready: Arc::new(AtomicBool::new(false)),
634                ws_client,
635                refresh,
636                session,
637                cancellation: CancellationToken::new(),
638            },
639            output,
640        )
641    }
642
643    #[rstest]
644    fn ambiguous_submission_invalidates_readiness_until_account_recovery() {
645        let (submission, mut output) = pending();
646        submission.ready.store(true, Ordering::Release);
647
648        let ticket = {
649            let mut state = submission.state.lock().unwrap();
650            state.epoch = Some((3, 4));
651            state.ledger.begin_refresh()
652        };
653
654        let resolved = submission.resolve(Err(KalshiHttpError::Status(503)));
655
656        let (epoch, refresh_valid) = {
657            let state = submission.state.lock().unwrap();
658            (state.epoch, state.ledger.check_refresh(ticket).is_ok())
659        };
660
661        assert!(!resolved);
662        assert!(!submission.ready.load(Ordering::Acquire));
663        assert_eq!(epoch, None);
664        assert!(!refresh_valid);
665        assert!(output.try_recv().is_err());
666    }
667
668    #[rstest]
669    #[cfg_attr(not(all(feature = "simulation", madsim)), tokio::test)]
670    #[cfg_attr(all(feature = "simulation", madsim), madsim::test)]
671    async fn pending_command_drop_delivers_one_denial(#[values(false, true)] forced: bool) {
672        let (submission, mut output) = pending();
673        let id = submission.order.client_order_id();
674        let state = Arc::clone(&submission.state);
675        let tasks = TaskGroup::new();
676
677        if forced {
678            let (started, ready) = tokio::sync::oneshot::channel();
679            tasks
680                .spawn(async move {
681                    started.send(()).unwrap();
682                    std::future::pending::<()>().await;
683                    submission.run().await;
684                })
685                .unwrap();
686
687            ready.await.unwrap();
688            tasks.abort();
689            tasks
690                .finish_shutdown(
691                    std::time::Duration::from_secs(1),
692                    std::time::Duration::from_secs(1),
693                )
694                .await
695                .unwrap();
696        } else {
697            tasks.begin_shutdown();
698            assert!(tasks.spawn(submission.run()).is_err());
699        }
700
701        let event = output.try_recv().unwrap();
702
703        let ExecutionEvent::Order(OrderEventAny::Denied(denied)) = event else {
704            panic!("expected Denied");
705        };
706
707        assert_eq!(denied.client_order_id, id);
708        assert_eq!(
709            denied.reason.as_str(),
710            "VALIDATION_FAILED: Kalshi submission canceled before dispatch"
711        );
712        assert!(output.try_recv().is_err());
713        assert_eq!(
714            state.lock().unwrap().orders[&id].order.status(),
715            OrderStatus::Denied
716        );
717    }
718
719    #[rstest]
720    #[case(400, "insufficient_balance", true)]
721    #[case(400, "post_only_cross", true)]
722    #[case(403, "authentication_error", true)]
723    #[case(400, "duplicate_client_order_id", false)]
724    #[case(409, "duplicate_client_order_id", false)]
725    #[case(400, "unrecognized_outcome", false)]
726    #[case(503, "invalid_order", false)]
727    fn failure_classification_requires_definitive_rejection(
728        #[case] status: u16,
729        #[case] code: &str,
730        #[case] rejected: bool,
731    ) {
732        let error = KalshiHttpError::Venue {
733            status,
734            evidence: Box::new(ResponseEvidence {
735                body: "redacted".into(),
736                venue: Some(VenueError {
737                    code: Field::Value(code.into()),
738                    message: Field::Missing,
739                    details: Field::Missing,
740                }),
741                retry_after: None,
742                request_id: None,
743            }),
744        };
745
746        let reason = error.to_string();
747        let expected = if rejected {
748            CommandFailure::venue_rejected(reason)
749        } else {
750            CommandFailure::ambiguous(reason)
751        };
752
753        assert_eq!(classify_failure(&error), expected);
754    }
755
756    #[rstest]
757    #[case(400, "post_only_cross", None, true)]
758    #[case(400, "invalid_order", Some("post only cross"), true)]
759    #[case(400, "invalid_order", Some("invalid quantity"), false)]
760    #[case(400, "invalid_order", None, false)]
761    #[case(400, "insufficient_balance", Some("post only cross"), false)]
762    #[case(503, "invalid_order", Some("post only cross"), false)]
763    #[case(503, "post_only_cross", None, false)]
764    fn post_only_rejection_requires_specific_venue_evidence(
765        #[case] status: u16,
766        #[case] code: &str,
767        #[case] details: Option<&str>,
768        #[case] expected: bool,
769    ) {
770        let error = KalshiHttpError::Venue {
771            status,
772            evidence: Box::new(ResponseEvidence {
773                body: "redacted".into(),
774                venue: Some(VenueError {
775                    code: Field::Value(code.into()),
776                    message: Field::Missing,
777                    details: details.map_or(Field::Missing, |value| Field::Value(value.into())),
778                }),
779                retry_after: None,
780                request_id: None,
781            }),
782        };
783
784        assert_eq!(post_only_rejection(&error), expected);
785
786        if expected {
787            assert_eq!(rejection_reason(&error), "Post-only order would cross");
788        }
789    }
790
791    #[rstest]
792    #[case(KalshiHttpError::Quota("local quota"), true)]
793    #[case(KalshiHttpError::Validation("local validation"), true)]
794    #[case(KalshiHttpError::Canceled { dispatched: false }, true)]
795    #[case(KalshiHttpError::Canceled { dispatched: true }, false)]
796    #[case(KalshiHttpError::Status(503), false)]
797    fn local_failure_classification_preserves_dispatch_evidence(
798        #[case] error: KalshiHttpError,
799        #[case] not_sent: bool,
800    ) {
801        let reason = error.to_string();
802        let expected = if not_sent {
803            CommandFailure::not_sent(reason)
804        } else {
805            CommandFailure::ambiguous(reason)
806        };
807
808        assert_eq!(classify_failure(&error), expected);
809    }
810
811    #[rstest]
812    #[case(TimeInForce::Gtc, "good_till_canceled", None)]
813    #[case(TimeInForce::Ioc, "immediate_or_cancel", None)]
814    #[case(TimeInForce::Fok, "fill_or_kill", None)]
815    #[case(TimeInForce::Gtd, "good_till_canceled", Some(4_102_444_800_i64))]
816    fn limit_matrix_encodes_exact_instructions(
817        #[case] tif: TimeInForce,
818        #[case] wire_tif: &str,
819        #[case] expires: Option<i64>,
820        #[values(OrderSide::Buy, OrderSide::Sell)] side: OrderSide,
821    ) {
822        let mut builder = OrderTestBuilder::new(OrderType::Limit);
823        builder
824            .instrument_id("EVENT-MARKET.KALSHI".into())
825            .client_order_id("matrix-order".into())
826            .quantity(Quantity::from("1.25"))
827            .price(Price::from("0.4321"))
828            .side(side)
829            .time_in_force(tif)
830            .post_only(tif == TimeInForce::Gtd)
831            .reduce_only(tif == TimeInForce::Ioc);
832
833        if let Some(expires) = expires {
834            builder.expire_time(UnixNanos::from(expires as u64 * 1_000_000_000));
835        }
836
837        let order = builder.build();
838        let wire = serde_json::to_value(request(&order, None, 3).unwrap()).unwrap();
839
840        let mut expected = serde_json::from_str::<serde_json::Value>(include_str!(
841            "../../test_data/rest_requests.json"
842        ))
843        .unwrap()["limit_matrix"]
844            .clone();
845        expected["side"] = serde_json::json!(if side == OrderSide::Buy { "bid" } else { "ask" });
846        expected["time_in_force"] = serde_json::json!(wire_tif);
847        expected["post_only"] = serde_json::json!(tif == TimeInForce::Gtd);
848        expected["reduce_only"] = serde_json::json!(tif == TimeInForce::Ioc);
849        if let Some(expires) = expires {
850            expected["expiration_time"] = expires.into();
851        }
852
853        assert_eq!(wire, expected);
854    }
855
856    #[rstest]
857    #[case(1_000_000_000, 999_999_999, Ok(Some(1)))]
858    #[case(
859        1_000_000_000,
860        1_000_000_000,
861        Err("Kalshi GTD expiry must be in the future")
862    )]
863    #[case(
864        1_000_000_000,
865        1_000_000_001,
866        Err("Kalshi GTD expiry must be in the future")
867    )]
868    #[case(1_000_000_001, 0, Err("Kalshi GTD expiry must use whole Unix seconds"))]
869    fn gtd_expiry_is_exact_and_future(
870        #[case] expires: u64,
871        #[case] now: u64,
872        #[case] expected: Result<Option<i64>, &str>,
873    ) {
874        let order = OrderTestBuilder::new(OrderType::Limit)
875            .instrument_id("EVENT-MARKET.KALSHI".into())
876            .quantity(Quantity::from("1.25"))
877            .price(Price::from("0.4321"))
878            .time_in_force(TimeInForce::Gtd)
879            .expire_time(UnixNanos::from(expires))
880            .build();
881        assert_eq!(
882            expiry(&order, UnixNanos::from(now)).map_err(|e| e.to_string()),
883            expected.map_err(str::to_owned)
884        );
885    }
886}