Skip to main content

nautilus_kalshi/http/
parse.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
16//! Kalshi REST response decoding and pagination controls.
17
18use std::collections::HashSet;
19
20use nautilus_core::{
21    UnixNanos, datetime::try_datetime_to_unix_nanos, params::Params, string::secret::SecretString,
22};
23use nautilus_model::{
24    data::InstrumentClose,
25    enums::{AssetClass, InstrumentCloseType},
26    identifiers::Symbol,
27    instruments::BinaryOption,
28    types::{Currency, Price, Quantity},
29};
30use nautilus_network::http::HttpResponse;
31use rust_decimal::Decimal;
32use serde::de::DeserializeOwned;
33use ustr::Ustr;
34
35use super::{
36    error::{KalshiHttpError, ResponseEvidence},
37    models::{Event, Field, Market, VenueError},
38};
39use crate::common::{
40    consts::{PRICE_PRECISION, SIZE_PRECISION},
41    enums::{CollateralReturnType, MarketStatus, MarketType, SettlementBoundsType},
42    parse::{KalshiPriceGrid, parse_instrument_id},
43};
44
45/// Decodes a successful envelope or retains typed HTTP and venue failure evidence.
46///
47/// # Errors
48///
49/// Returns an error if the status is not successful or the success body is malformed.
50pub fn decode_response<T: DeserializeOwned>(response: HttpResponse) -> Result<T, KalshiHttpError> {
51    let status = response.status.as_u16();
52    if (200..300).contains(&status) {
53        return decode_body(response);
54    }
55
56    let evidence = response_evidence(response);
57    if evidence.venue.is_some() {
58        Err(KalshiHttpError::Venue { status, evidence })
59    } else {
60        Err(KalshiHttpError::Http { status, evidence })
61    }
62}
63
64pub(super) fn decode_body<T: DeserializeOwned>(
65    response: HttpResponse,
66) -> Result<T, KalshiHttpError> {
67    serde_json::from_slice(&response.body).map_err(|e| KalshiHttpError::Decode {
68        status: response.status.as_u16(),
69        line: e.line(),
70        column: e.column(),
71        evidence: response_evidence(response),
72    })
73}
74
75pub(super) fn unexpected_response(response: HttpResponse, reason: &'static str) -> KalshiHttpError {
76    KalshiHttpError::Response {
77        status: response.status.as_u16(),
78        reason,
79        evidence: response_evidence(response),
80    }
81}
82
83fn response_evidence(response: HttpResponse) -> Box<ResponseEvidence> {
84    let body = SecretString::from(String::from_utf8_lossy(&response.body).into_owned());
85    let mut venue = serde_json::from_slice::<VenueError>(&response.body)
86        .ok()
87        .filter(|e| !e.code.is_missing() || !e.message.is_missing() || !e.details.is_missing());
88
89    if venue.is_none() {
90        #[derive(serde::Deserialize)]
91        struct ErrorEnvelope {
92            error: VenueError,
93        }
94        venue = serde_json::from_slice::<ErrorEnvelope>(&response.body)
95            .ok()
96            .map(|e| e.error);
97    }
98
99    let mut headers = response.headers;
100
101    Box::new(ResponseEvidence {
102        body,
103        venue,
104        retry_after: headers.remove("retry-after"),
105        request_id: headers.remove("x-request-id"),
106    })
107}
108
109/// A finite pagination result. A page budget never masquerades as exhaustion.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct Pages<T> {
112    /// Records collected within the page budget, deduplicated by source identity.
113    pub records: Vec<T>,
114    /// Whether the source was exhausted within the page budget.
115    pub complete: bool,
116    /// Continuation cursor for the next page, or `None` when the source is exhausted.
117    pub next_cursor: Option<String>,
118}
119
120pub(crate) struct Pagination {
121    cursors: HashSet<String>,
122    identities: HashSet<String>,
123}
124
125impl Pagination {
126    pub(crate) fn new(cursor: Option<&str>) -> Self {
127        Self {
128            cursors: cursor.into_iter().map(str::to_owned).collect(),
129            identities: HashSet::new(),
130        }
131    }
132
133    pub(super) fn retain(&mut self, identity: String) -> bool {
134        self.identities.insert(identity)
135    }
136
137    pub(crate) fn advance(
138        &mut self,
139        cursor: Field<String>,
140        empty: bool,
141    ) -> Result<Option<String>, KalshiHttpError> {
142        match cursor {
143            Field::Missing | Field::Null => Ok(None),
144            Field::Value(cursor) if cursor.is_empty() => Ok(None),
145            Field::Value(cursor) => {
146                if !self.cursors.insert(cursor.clone()) {
147                    return Err(KalshiHttpError::Pagination("repeated cursor"));
148                }
149
150                if empty {
151                    return Err(KalshiHttpError::Pagination(
152                        "empty page with a continuation cursor",
153                    ));
154                }
155
156                Ok(Some(cursor))
157            }
158        }
159    }
160}
161
162/// Maps an admitted ordinary market to the canonical YES-priced instrument.
163///
164/// The retained market and event metadata restore grid and shard context on restart.
165///
166/// # Errors
167///
168/// Returns an error if economics are unsupported, identity or shard is inconsistent, or metadata is invalid.
169pub fn parse_instrument(
170    market: &Market,
171    event: &Event,
172    ts_init: UnixNanos,
173) -> anyhow::Result<BinaryOption> {
174    anyhow::ensure!(
175        supported_market(market, event),
176        "unsupported market economics or family"
177    );
178    anyhow::ensure!(
179        market.event_ticker == event.event_ticker,
180        "market and event identity mismatch"
181    );
182    parse_instrument_id(&event.event_ticker)?;
183    parse_instrument_id(&event.series_ticker)?;
184
185    let exchange_index = match market.exchange_index {
186        Field::Value(v) if v >= 0 => v,
187        _ => anyhow::bail!("missing or invalid market exchange index"),
188    };
189
190    anyhow::ensure!(
191        matches!(event.exchange_index, Field::Missing | Field::Null)
192            || event.exchange_index == Field::Value(exchange_index),
193        "market and event shard mismatch"
194    );
195    let id = parse_instrument_id(&market.ticker)?;
196    let grid = KalshiPriceGrid::new(&market.price_ranges)?;
197    let tick_scheme = grid.register()?;
198    let activation_ns = try_datetime_to_unix_nanos(market.open_time)?;
199    let expiration_ns = try_datetime_to_unix_nanos(market.latest_expiration_time)?;
200    anyhow::ensure!(
201        activation_ns < expiration_ns,
202        "invalid instrument lifecycle interval"
203    );
204
205    let ts_event = match market.updated_time {
206        Field::Value(value) => try_datetime_to_unix_nanos(value)?,
207        _ => ts_init,
208    };
209
210    let mut event_metadata = event.clone();
211    event_metadata.markets = Field::Missing;
212
213    let mut event_info = serde_json::to_value(&event_metadata)?;
214    if let Field::Value(multiplier) = event_metadata.fee_multiplier_override {
215        event_info["fee_multiplier_override"] = multiplier.0.to_string().into();
216    }
217
218    let info = Params::new(
219        [
220            ("market".into(), serde_json::to_value(market)?),
221            ("event".into(), event_info),
222        ]
223        .into(),
224    );
225
226    let size_increment =
227        Quantity::from_decimal_dp(Decimal::new(1, u32::from(SIZE_PRECISION)), SIZE_PRECISION)?;
228    let instrument = BinaryOption::builder()
229        .instrument_id(id)
230        .raw_symbol(Symbol::new(&market.ticker))
231        .asset_class(AssetClass::Alternative)
232        .currency(Currency::USD())
233        .activation_ns(activation_ns)
234        .expiration_ns(expiration_ns)
235        .price_precision(PRICE_PRECISION)
236        .size_precision(SIZE_PRECISION)
237        .price_increment(grid.increment())
238        .size_increment(size_increment)
239        .min_quantity(size_increment)
240        .event_id(Ustr::from(&market.event_ticker))
241        .outcome(Ustr::from("YES"))
242        .description(Ustr::from(&market.yes_sub_title))
243        .tick_scheme(tick_scheme)
244        .info(info)
245        .ts_event(ts_event)
246        .ts_init(ts_init)
247        .build()?;
248    Ok(instrument)
249}
250
251pub(crate) fn supported_market(market: &Market, event: &Event) -> bool {
252    market.market_type == MarketType::Binary
253        && market.notional_value_dollars.0 == Decimal::ONE
254        && market.settlement_bounds_type == SettlementBoundsType::Default
255        && event.collateral_return_type == CollateralReturnType::None
256        && !matches!(&market.settlement_floor_dollars, Field::Value(v) if v.0 != Decimal::ZERO)
257        && !matches!(&market.mve_collection_ticker, Field::Value(v) if !v.is_empty())
258        && !matches!(&market.mve_selected_legs, Field::Value(v) if !v.is_empty())
259}
260
261/// Returns authoritative final YES payout evidence for an admitted ordinary binary market.
262///
263/// Returns `None` for non-finalized markets, including determined, disputed, and amended states.
264/// This is market evidence, not a credited account amount. Account consumers must reconcile all
265/// fills through the settlement timestamp before applying it and reconcile actual cash separately.
266///
267/// # Errors
268///
269/// Returns an error if a finalized definition has unsupported economics, invalid identity,
270/// missing final evidence, an invalid settlement timestamp, or a payout outside `[0, 1]`
271/// or beyond six decimal places.
272pub fn parse_instrument_close(
273    market: &Market,
274    event: &Event,
275    ts_init: UnixNanos,
276) -> anyhow::Result<Option<InstrumentClose>> {
277    if market.status != MarketStatus::Finalized {
278        return Ok(None);
279    }
280
281    let instrument = parse_instrument(market, event, ts_init)?;
282
283    let Field::Value(value) = &market.settlement_value_dollars else {
284        anyhow::bail!("finalized market has no settlement value");
285    };
286
287    let Field::Value(timestamp) = market.settlement_ts else {
288        anyhow::bail!("finalized market has no settlement timestamp");
289    };
290
291    anyhow::ensure!(
292        (Decimal::ZERO..=Decimal::ONE).contains(&value.0)
293            && value.0.normalize().scale() <= u32::from(PRICE_PRECISION),
294        "invalid final settlement value"
295    );
296    let price = Price::from_decimal_dp(value.0, PRICE_PRECISION)?;
297    let ts_event = try_datetime_to_unix_nanos(timestamp)?;
298    anyhow::ensure!(
299        ts_event > UnixNanos::default(),
300        "invalid settlement timestamp"
301    );
302    Ok(Some(InstrumentClose::new(
303        instrument.id,
304        price,
305        InstrumentCloseType::ContractExpired,
306        ts_event,
307        ts_init,
308    )))
309}