nautilus_kalshi/common/
parse.rs1use 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
34pub fn parse_instrument_id(ticker: &str) -> anyhow::Result<InstrumentId> {
42 validate_ticker(ticker)?;
43 Ok(InstrumentId::new(Symbol::new(ticker), *KALSHI_VENUE))
44}
45
46pub 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#[derive(Debug, Clone)]
67pub struct KalshiPriceGrid {
68 ranges: Vec<PriceRange>,
69 increment: Price,
70}
71
72impl KalshiPriceGrid {
73 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 #[must_use]
128 pub const fn increment(&self) -> Price {
129 self.increment
130 }
131
132 #[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 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 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}