Skip to main content

nautilus_kalshi/common/
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 instrument identity and exact price grids.
17
18use anyhow::Context;
19use nautilus_model::{
20    identifiers::{InstrumentId, Symbol},
21    instruments::tick_scheme::{
22        TickScheme, TieredTickScheme, get_tick_scheme, register_tick_scheme,
23    },
24    types::Price,
25};
26use rust_decimal::{Decimal, prelude::ToPrimitive};
27use ustr::Ustr;
28
29use crate::{
30    common::consts::{KALSHI_VENUE, PRICE_PRECISION},
31    http::models::PriceRange,
32};
33
34/// Converts a native, case-sensitive ticker to its canonical instrument ID.
35///
36/// Accepts ASCII letters, digits, hyphens, and decimal points between digits.
37///
38/// # Errors
39///
40/// Returns an error if the ticker is empty or contains unsupported characters.
41pub fn parse_instrument_id(ticker: &str) -> anyhow::Result<InstrumentId> {
42    validate_ticker(ticker)?;
43    Ok(InstrumentId::new(Symbol::new(ticker), *KALSHI_VENUE))
44}
45
46/// Returns a canonical instrument's native ticker without changing its case.
47///
48/// # Errors
49///
50/// Returns an error if the venue is not KALSHI or the market ticker is invalid.
51pub fn parse_ticker(instrument_id: InstrumentId) -> anyhow::Result<String> {
52    anyhow::ensure!(
53        instrument_id.venue == *KALSHI_VENUE,
54        "instrument venue must be KALSHI"
55    );
56    let ticker = instrument_id.symbol.as_str();
57    validate_ticker(ticker)?;
58    Ok(ticker.to_owned())
59}
60
61/// Exact market bands used for admission and explicit price validation.
62///
63/// Native limit submission enforces the lattice through `contains`; simulation does not.
64///
65/// Storage uses six decimal places independently of the current venue grid.
66#[derive(Debug, Clone)]
67pub struct KalshiPriceGrid {
68    ranges: Vec<PriceRange>,
69    increment: Price,
70}
71
72impl KalshiPriceGrid {
73    /// Validates ordered, non-overlapping bands within the binary payout interval.
74    ///
75    /// # Errors
76    ///
77    /// Returns an error if bands are missing, bounds or steps are invalid, or precision exceeds six places.
78    pub fn new(ranges: &[PriceRange]) -> anyhow::Result<Self> {
79        anyhow::ensure!(!ranges.is_empty(), "missing price ranges");
80        let mut quantum = 0;
81        let mut previous_end = Decimal::ZERO;
82
83        for range in ranges {
84            let start = range.start.0;
85            let end = range.end.0;
86            let step = range.step.0;
87            anyhow::ensure!(
88                start >= previous_end
89                    && start >= Decimal::ZERO
90                    && start < end
91                    && end <= Decimal::ONE,
92                "invalid or overlapping price range"
93            );
94            anyhow::ensure!(
95                step > Decimal::ZERO && step < end - start,
96                "invalid price range step"
97            );
98
99            for value in [start, end, step] {
100                anyhow::ensure!(
101                    value.normalize().scale() <= u32::from(PRICE_PRECISION),
102                    "price range exceeds six decimal places"
103                );
104            }
105
106            for value in [start, step] {
107                let scaled = (value * Decimal::from(10_i64.pow(u32::from(PRICE_PRECISION))))
108                    .to_i64()
109                    .context("invalid price quantum")?;
110                quantum = gcd(quantum, scaled);
111            }
112
113            previous_end = end;
114        }
115
116        let increment = Price::from_decimal_dp(
117            Decimal::new(quantum, u32::from(PRICE_PRECISION)),
118            PRICE_PRECISION,
119        )?;
120        Ok(Self {
121            ranges: ranges.to_vec(),
122            increment,
123        })
124    }
125
126    /// Returns the base quantum; full band validation remains required.
127    #[must_use]
128    pub const fn increment(&self) -> Price {
129        self.increment
130    }
131
132    /// Tests a strict interior binary price against its exact band lattice.
133    #[must_use]
134    pub fn contains(&self, price: Decimal) -> bool {
135        price > Decimal::ZERO
136            && price < Decimal::ONE
137            && self.ranges.iter().any(|range| {
138                price >= range.start.0
139                    && price < range.end.0
140                    && (price - range.start.0) % range.step.0 == Decimal::ZERO
141            })
142    }
143
144    /// Registers or reuses a content-named navigation scheme after exact tick verification.
145    ///
146    /// Call this again after loading a persisted instrument's bands on restart.
147    ///
148    /// # Errors
149    ///
150    /// Returns an error if the shared scheme cannot reproduce the decimal lattice exactly.
151    pub fn register(&self) -> anyhow::Result<Ustr> {
152        let mut name = String::from("KALSHI");
153        let mut tiers = Vec::with_capacity(self.ranges.len());
154        let mut expected = Vec::new();
155
156        for range in &self.ranges {
157            let [start, end, step] = [range.start.0, range.end.0, range.step.0];
158            name.push_str(&format!(
159                "_{}_{}_{}",
160                start.normalize(),
161                end.normalize(),
162                step.normalize()
163            ));
164
165            let start = if start.is_zero() { step } else { start };
166            // Exclude a rounded-up end tick from the shared floating-point constructor
167            tiers.push((
168                start.to_f64().context("invalid band start")?,
169                (end - Decimal::new(5, u32::from(PRICE_PRECISION) + 1))
170                    .to_f64()
171                    .context("invalid band end")?,
172                step.to_f64().context("invalid band step")?,
173            ));
174            let mut value = start;
175            while value < end {
176                expected.push(Price::from_decimal_dp(value, PRICE_PRECISION)?);
177                value += step;
178            }
179        }
180
181        let scheme = TieredTickScheme::new(
182            &tiers,
183            PRICE_PRECISION,
184            10_usize.pow(u32::from(PRICE_PRECISION)) + 1,
185        )?;
186
187        anyhow::ensure!(
188            scheme.ticks() == expected,
189            "navigation scheme differs from exact price grid"
190        );
191        let scheme = TickScheme::Tiered(scheme);
192        if let Err(e) = register_tick_scheme(&name, scheme.clone()) {
193            anyhow::ensure!(
194                get_tick_scheme(&name) == Some(scheme),
195                "inconsistent registered price grid: {e}"
196            );
197        }
198
199        Ok(Ustr::from(&name))
200    }
201}
202
203fn validate_ticker(ticker: &str) -> anyhow::Result<()> {
204    let bytes = ticker.as_bytes();
205    anyhow::ensure!(
206        !ticker.is_empty()
207            && bytes.iter().enumerate().all(|(index, c)| {
208                c.is_ascii_alphanumeric()
209                    || *c == b'-'
210                    || (*c == b'.'
211                        && index > 0
212                        && bytes[index - 1].is_ascii_digit()
213                        && bytes.get(index + 1).is_some_and(u8::is_ascii_digit))
214            }),
215        "invalid Kalshi ticker"
216    );
217    Ok(())
218}
219
220fn gcd(mut a: i64, mut b: i64) -> i64 {
221    while b != 0 {
222        (a, b) = (b, a % b);
223    }
224
225    a
226}