// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
use crate::pro::*;
use crate::prediction_exchange_generated::PredictionBase;
use crate::prediction_exchange::PredictionRuntime;
pub struct KalshiCore {
pub exchange: crate::prediction_exchange::PredictionExchange,
}
impl KalshiCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::prediction_exchange::PredictionExchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = KalshiCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for KalshiCore {
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KalshiCore.
KalshiCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KalshiCore.
KalshiCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on KalshiCore.
KalshiCore::parse_balance(self, response)
}
fn parse_my_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KalshiCore.
KalshiCore::parse_my_trade(self, trade, &[market])
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KalshiCore.
KalshiCore::parse_prediction_trade(self, trade, &[market])
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KalshiCore.
KalshiCore::parse_prediction_order(self, order, &[market])
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KalshiCore.
KalshiCore::parse_prediction_position(self, position, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on KalshiCore.
KalshiCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on KalshiCore.
KalshiCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for KalshiCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"calculate_fee" => self.calculate_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]),
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_event" => self.fetch_event(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_events" => self.fetch_events(&args[..]).await,
"fetch_events_by_query" => self.fetch_events_by_query(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_outcome" => self.fetch_outcome(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_outcomes" => self.fetch_outcomes(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_raw_event_by_ticker" => self.fetch_raw_event_by_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_series_events" => self.fetch_series_events(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"fetch_settlements" => self.fetch_settlements(&args[..]).await,
"fetch_status" => self.fetch_status(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null),
args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_binary_market_to_outcomes" => self.parse_binary_market_to_outcomes(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_event" => self.parse_event(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_my_trade" => self.parse_my_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_open_interest" => self.parse_prediction_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_position" => self.parse_prediction_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_trade" => self.parse_prediction_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_settlement" => self.parse_settlement(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"resolve_event_series_tickers" => self.resolve_event_series_tickers(&args[..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"sorted_orders" => self.sorted_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null)),
// Prediction Core: fall through to prediction base methods (then Exchange base).
_ => self.call_dynamic_prediction_base(method, args).await,
}
})
}
}
impl crate::prediction_exchange_generated::PredictionBase for KalshiCore {
fn pred(&self) -> &crate::prediction_exchange::PredictionExchange { &self.exchange }
fn pred_mut(&mut self) -> &mut crate::prediction_exchange::PredictionExchange { &mut self.exchange }
}
impl std::ops::Deref for KalshiCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}
impl std::ops::DerefMut for KalshiCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.exchange) }
}
impl KalshiCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.super_describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("kalshi".into()));
m.insert("name".to_string(), Value::Str("Kalshi".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
m.insert("rateLimit".to_string(), Value::Int(200));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(false));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchEvent".to_string(), Value::Bool(true));
m.insert("fetchEvents".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchSettlements".to_string(), Value::Bool(true));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("prediction".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Int(1));
m.insert("1h".to_string(), Value::Int(60));
m.insert("1d".to_string(), Value::Int(1440));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/74fc2acb-58d0-4db0-b316-3124e7dc24db".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("kalshi".to_string(), Value::Str("https://external-api.kalshi.com/trade-api/v2".into()));
m.insert("elections".to_string(), Value::Str("https://api.elections.kalshi.com/v1".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("kalshi".to_string(), Value::Str("https://external-api.demo.kalshi.co/trade-api/v2".into()));
m.insert("elections".to_string(), Value::Str("https://api.elections.kalshi.com/v1".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://kalshi.com".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://trading-api.readme.io/reference/getting-started".into())]));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("kalshi".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("events".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/multivariate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/fee_changes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/{event_ticker}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/{event_ticker}/metadata".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series/fee_changes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series/{series_ticker}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series/{series_ticker}/markets/{ticker}/candlesticks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series/{series_ticker}/events/{ticker}/candlesticks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series/{series_ticker}/events/{ticker}/forecast_percentile_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/orderbooks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/candlesticks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{ticker}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{ticker}/orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("exchange/status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("exchange/schedule".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("exchange/announcements".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("exchange/user_data_timestamp".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("milestones".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("milestones/{milestone_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("structured_targets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("structured_targets/{structured_target_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("search/filters_by_sport".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("search/tags_by_categories".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("live_data/batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("live_data/milestone/{milestone_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("historical/markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("historical/markets/{ticker}/candlesticks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("historical/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("historical/cutoff_timestamps".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("multivariate_event_collections".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("multivariate_event_collections/{collection_ticker}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("multivariate_event_collections/{collection_ticker}/lookup".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("incentive_programs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("portfolio/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/orders/{order_id}/queue_position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/orders/queue_positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/settlements".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/deposits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/withdrawals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/order_groups".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/order_groups/{order_group_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/summary/total_resting_order_value".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/subaccounts/balances".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/subaccounts/netting".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/subaccounts/transfers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("historical/fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("historical/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("portfolio/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/events/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/orders/batched".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/orders/{order_id}/amend".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/orders/{order_id}/decrease".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/order_groups/create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/subaccounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/subaccounts/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("multivariate_event_collections/{collection_ticker}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("put".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("portfolio/order_groups/{order_group_id}/reset".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/order_groups/{order_group_id}/trigger".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/order_groups/{order_group_id}/limit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/subaccounts/netting".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("multivariate_event_collections/{collection_ticker}/lookup".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("portfolio/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/orders/batched".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/events/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/order_groups/{order_group_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("elections".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("search/series".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("privateKey".to_string(), Value::Bool(true));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("maker".to_string(), Value::Int(0));
m.insert("taker".to_string(), Value::Float(0.07));
m
}));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("not_found".to_string(), Value::Str("BadSymbol".into()));
m.insert("invalid_order".to_string(), Value::Str("InvalidOrder".into()));
m.insert("fill_or_kill_insufficient_resting_volume".to_string(), Value::Str("OrderNotFillable".into()));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultFetchEventsLimit".to_string(), Value::Int(200));
m.insert("maxFetchMarketsLimit".to_string(), Value::Int(1000));
m.insert("searchSeriesLimit".to_string(), Value::Int(25));
m.insert("maxFetchEventsResults".to_string(), Value::Int(100));
m.insert("maxEventPagesPerSeries".to_string(), Value::Int(20));
m.insert("defaultEventStatus".to_string(), Value::Str("open".into()));
m.insert("eventScopeParams".to_string(), Value::from(vec![Value::Str("category".into()), Value::Str("series_ticker".into())]));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name kalshi#fetchMarkets
* @description fetches kalshi markets; with a query it resolves the query via the events endpoint and returns the matched events' markets, otherwise it pages the markets listing
* @see https://trading-api.readme.io/reference/getmarkets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.query] a single search query; resolved against the events endpoint (event title/ticker), then the matched events' markets are returned
* @param {string[]} [params.queries] multiple search queries (alternative to query); markets from any matching event are returned
* @param {int} [params.limit] for an unscoped listing (no query), the max number of markets to collect (defaults to options.maxFetchMarketsLimit, 1000)
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut queries: Vec<Value> = self.parse_search_queries(&[params.clone()]).as_array().cloned().unwrap_or_default();
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
// kalshi's public markets endpoint has no free-text search, so a query would otherwise
// force a client-side scan of every open market (thousands, paged 1000 at a time, which
// hangs). Resolve the query against the events endpoint instead — it is bounded by
// maxPages, scoped server-side, supports multiple topics, and returns each event's parsed
// markets — then flatten those markets.
if queriesLength > ((0i64) as f64) {
let mut eventParams: Value = self.omit(params.clone(), Value::from(vec![Value::Str("limit".into())]), &[]);
let mut events: Value = self.fetch_events(&[eventParams]).await;
let mut eventsLength: f64 = ((events.len() as i64) as f64);
let mut queryMarkets: Vec<Value> = Vec::new();
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1261: bool = true;
while { if !__for_first_1261 { if let Value::Int(n) = &mut ei { *n += 1; } } __for_first_1261 = false; ei.as_f64().unwrap_or(f64::NAN) < eventsLength } {
let mut eventMarkets: Vec<Value> = self.safe_list(events.as_array().and_then(|__arr| match &ei { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), Value::Str("markets".into()), &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut eventMarketsLength: f64 = ((eventMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1260: bool = true;
while { if !__for_first_1260 { if let Value::Int(n) = &mut mi { *n += 1; } } __for_first_1260 = false; mi.as_f64().unwrap_or(f64::NAN) < eventMarketsLength } {
queryMarkets.push(eventMarkets.get(mi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
}
}
}
}
return Value::from(queryMarkets);
}
let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("query".into()), Value::Str("queries".into()), Value::Str("limit".into())]), &[]);
// no query: page the markets listing directly. Cap the total collected so an unscoped
// loadMarkets cannot run away through every kalshi market via the cursor.
let mut maxMarkets: Value = self.safe_integer_k(params, "limit", &[self.safe_integer(self.options.clone(), Value::Str("maxFetchMarketsLimit".into()), &[Value::Int(1000)])]);
let mut flatMarkets: Vec<Value> = Vec::new();
let mut eventsDict: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut cursor: Value = Value::Null;
// don't request a full 1000-market page (3+ MB) when the caller wants fewer
let mut pageLimit: Value = self.safe_integer_k(self.options.clone(), "marketsPageLimit", &[Value::Int(1000)]);
let mut limit: Value = pageLimit.clone();
if maxMarkets.as_f64().unwrap_or(f64::NAN) < pageLimit.as_f64().unwrap_or(f64::NAN) {
limit = maxMarkets.clone();
}
// default to tradeable (open) markets; kalshi has thousands of closed/settled markets and
// an unfiltered cursor pages through those, so loadMarkets would otherwise return mostly
// closed markets. Pass params.status (e.g. 'closed', 'settled', 'unopened') to override
let mut status: Value = self.safe_string_k(rest.clone(), "status", &[Value::Str("open".into())]);
loop {
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), limit.clone());
m.insert("status".to_string(), status.clone());
m
});
if (cursor != Value::Null) {
request.insert("cursor".into(), cursor.clone());
}
let __ws_arg_0 = self.extend(Value::Map(request), &[rest.clone()]);
let mut response: Value = self.kalshi_public_get_markets(&[__ws_arg_0]).await;
let mut rawMarkets: Vec<Value> = self.safe_list_k(response.clone(), "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut i: i64 = 0;
let mut __for_first_1263: bool = true;
while { if !__for_first_1263 { i += 1; } __for_first_1263 = false; i < (rawMarkets.len() as i64) } {
let mut raw: Value = rawMarkets.get(i as usize).cloned().unwrap_or(Value::Null);
let mut parsed: Vec<Value> = self.parse_binary_market_to_outcomes(raw.clone()).as_array().cloned().unwrap_or_default();
let mut eventTicker: Option<String> = self.safe_string_k_opt(raw.clone(), "event_ticker", &[]);
let mut eventTitle: Value = self.safe_string_k(raw, "title", &[eventTicker.clone().map(Value::from).unwrap_or(Value::Null)]);
{
let mut j: i64 = 0;
let mut __for_first_1262: bool = true;
while { if !__for_first_1262 { j += 1; } __for_first_1262 = false; j < (parsed.len() as i64) } {
let mut m: Value = parsed.get(j as usize).cloned().unwrap_or(Value::Null);
flatMarkets.push(m.clone());
if (eventTitle != Value::Null) && (eventTitle.as_str() != Some("")) {
let mut eventKey: Value = self.shorten_slug(eventTitle.clone());
if !(matches!((&eventsDict, &eventKey), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut eventsDict { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&eventKey), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), eventTicker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("slug".to_string(), eventTicker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("event".to_string(), eventKey.clone());
m.insert("title".to_string(), eventTitle.clone());
m.insert("markets".to_string(), Value::from(vec![]));
m
})); }
}
let mut eventEntry: Value = (if let (Some(__m), Some(__k)) = (eventsDict.as_map(), eventKey.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
// push through a local and write the slice back — the go transpiler's
// AppendToArray reassigns only a local copy of a map-stored array, so a
// direct push on eventEntry['markets'] loses the element in go
let mut entryMarkets: Value = crate::value::get_value_k(&eventEntry, "markets");
if let Value::Arr(__a) = &mut entryMarkets { std::sync::Arc::make_mut(__a).push(m); };
add_element_to_object(&mut eventEntry, &Value::Str("markets".into()), entryMarkets);
}
}
}
}
}
cursor = self.safe_string_k(response, "cursor", &[]);
let mut collectedLength: f64 = ((flatMarkets.len() as i64) as f64);
if ((cursor == Value::Null) || (cursor.as_str() == Some(""))) || rawMarketsLength < limit.as_f64().unwrap_or(f64::NAN) || collectedLength >= maxMarkets.as_f64().unwrap_or(f64::NAN) {
break;
}
}
self.exchange.events = eventsDict.clone();
let mut flatMarketsLength: f64 = ((flatMarkets.len() as i64) as f64);
if flatMarketsLength > maxMarkets.as_f64().unwrap_or(f64::NAN) {
return self.array_slice(Value::from(flatMarkets), Value::Int(0), &[maxMarkets]);
}
return Value::from(flatMarkets);
Value::Null
}
pub fn parse_binary_market_to_outcomes(&self, mut raw: Value) -> Value {
return Value::from(vec![self.parse_market(raw)]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#fetchOutcome
* @description resolves a single outcome on demand instead of bulk-loading. kalshi has tens of
* thousands of markets, so an id-form miss fetches just the requested market by ticker, and a
* handle-form miss resolves through the series-scoped events listing (a handle's first token is
* its series ticker); both merge into the cache so repeat lookups are free
* @param {string} outcomeSymbol an outcome id — a kalshi ticker, or a ticker with a '-NO' suffix — or a unified handle like KXBTCD_26JUL1417_53_000_ABOVE:YES
* @returns {object} the resolved outcome object
*/
pub async fn fetch_outcome(&mut self, mut outcomeSymbol: Value) -> Value {
// a kalshi ticker never contains ':', so only id-form inputs can be fetched by ticker —
// sending a unified handle (EVENT_MARKET:LABEL) as a ticker is a guaranteed 404.
// the indexOf comparison must stay INLINE and `< 0` — the php transpiler only rewrites the
// inline form to mb_strpos's `=== false`; assigned to a variable first, absence (false)
// never satisfies `< 0` and id-form inputs take the wrong branch
if !outcomeSymbol.as_str().unwrap_or("").contains(":") {
// endsWith + negative slice: no .length arithmetic (php count() / python slice traps)
let mut isNo: bool = outcomeSymbol.as_str().unwrap_or("").ends_with("-NO");
let mut baseTicker: Value = outcomeSymbol.clone();
if isNo {
baseTicker = outcomeSymbol.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = (__l - 3).max(0); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null);
}
let mut response: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
response = self.kalshi_public_get_markets_ticker(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), baseTicker);
m
})]).await;
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
// an unknown ticker returns 'not_found', which handleErrors maps to BadSymbol —
// fall through to the search-driven base resolution; let network failures propagate
if !(matches!(&e, Value::Str(__s) if __s.contains("[BadSymbol]"))) {
panic!("{}", e);
}
response = Value::Null;
}
if (response != Value::Null) {
let mut rawMarket: Value = self.safe_dict_k(response.clone(), "market", &[response.clone()]);
let mut parsed: Value = self.parse_market(rawMarket);
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
if (parsed == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOutcome() could not resolve parsed".into()))));
}
add_element_to_object(&mut self.markets, &parsed.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null), parsed.clone());
// index only the market just fetched, not a full O(markets x outcomes) rebuild of the
// whole cache — on-demand fetchOutcome (loadAllOutcomes false) is the hot path here
self.index_market_outcomes(parsed);
return self.outcome(outcomeSymbol.clone());
}
} else {
// handle-form: handles are shortenSlug(event_ticker) + '_' + <market slug> and kalshi
// series tickers are single alphanumeric segments, so the handle's first '_' token is
// its series ticker — fetch that series' open events (server-side filter, one page in
// the common case) and re-check the cache for the exact handle
let mut handleParts: Value = Value::Array(if let Some(__s) = outcomeSymbol.as_str() { __s.split(":").map(Value::from).collect() } else { Vec::new() });
let mut marketPart: Value = self.safe_string(handleParts, Value::Int(0), &[Value::Str("".into())]);
let mut parts: Value = Value::Array(if let Some(__s) = marketPart.as_str() { __s.split("_").map(Value::from).collect() } else { Vec::new() });
let mut seriesTicker: Option<String> = self.safe_string_opt(parts, Value::Int(0), &[]);
if (seriesTicker.is_some()) && (seriesTicker.as_deref() != Some("")) {
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
self.fetch_events(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("series_ticker".to_string(), seriesTicker.map(Value::from).unwrap_or(Value::Null));
m
})]).await;
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
// an unknown series is a plain miss — the free-text fallback below still runs;
// let network failures propagate
if !(matches!(&e, Value::Str(__s) if __s.contains("[BadSymbol]"))) {
panic!("{}", e);
}
}
if self.has_outcome(outcomeSymbol.clone()).as_bool() == Some(true) {
return self.safe_outcome(outcomeSymbol.clone(), &[]);
}
}
}
return self.super_fetch_outcome(outcomeSymbol).await;
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#fetchOutcomes
* @description resolves several uncached outcomes at once — ticker-shaped ids are batched through the markets listing's tickers filter (100 per request); anything left unresolved (handle-shaped symbols, unknown tickers) falls back to the single fetch and its guidance-rich BadSymbol
* @see https://docs.kalshi.com/api-reference/market/get-markets
* @param {string[]} outcomeSymbols kalshi tickers (optionally with a '-NO' suffix) or outcome handles
* @returns {object} the outcome cache
*/
pub async fn fetch_outcomes(&mut self, mut outcomeSymbols: Value) -> Value {
let __outcomeSymbols_empty = Vec::new();
let outcomeSymbols = outcomeSymbols.as_array().unwrap_or(&__outcomeSymbols_empty);
let mut tickers: Vec<Value> = Vec::new();
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomeSymbolsLength: f64 = ((outcomeSymbols.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1264: bool = true;
while { if !__for_first_1264 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1264 = false; i.as_f64().unwrap_or(f64::NAN) < outcomeSymbolsLength } {
let mut outcomeSymbol: Value = outcomeSymbols.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if outcomeSymbol.as_str().unwrap_or("").contains(":") {
continue;
}
let mut baseTicker: Value = outcomeSymbol.clone();
if (outcomeSymbol.as_str().unwrap_or("").ends_with("-NO")) {
baseTicker = outcomeSymbol.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = (__l - 3).max(0); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null);
}
if !(matches!((&seen, &baseTicker), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&baseTicker), Value::Bool(true)); }
tickers.push(baseTicker.clone());
}
}
}
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut chunkSize: Value = self.safe_integer_k(self.options.clone(), "fetchOutcomesBatchSize", &[Value::Int(100)]);
let mut tickersLength: Value = Value::Int(tickers.len() as i64);
let mut lastTickerIndex: Value = (match (&(tickersLength), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut chunk: Value = Value::from(vec![]);
{
let mut ti: Value = Value::Int(0);
let mut __for_first_1266: bool = true;
while { if !__for_first_1266 { if let Value::Int(n) = &mut ti { *n += 1; } } __for_first_1266 = false; ti.as_f64().unwrap_or(f64::NAN) < tickersLength.as_f64().unwrap_or(f64::NAN) } {
if let Value::Arr(__a) = &mut chunk { std::sync::Arc::make_mut(__a).push(tickers.get((ti).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)); }
let mut chunkLength: f64 = ((chunk.len() as i64) as f64);
if (chunkLength < chunkSize.as_f64().unwrap_or(f64::NAN)) && (ti.as_f64().unwrap_or(f64::NAN) < lastTickerIndex.as_f64().unwrap_or(f64::NAN)) {
continue;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tickers".to_string(), Value::Str(chunk.as_array().map(|__a| __a.iter().map(|__v| __v.to_string()).collect::<Vec<String>>().join(",")).unwrap_or_default().into()));
m.insert("limit".to_string(), chunkSize.clone());
m
});
chunk = Value::from(vec![]);
let mut response: Value = self.kalshi_public_get_markets(&[Value::Map(request)]).await;
let mut rawMarkets: Vec<Value> = self.safe_list_k(response, "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
{
let mut i: i64 = 0;
let mut __for_first_1265: bool = true;
while { if !__for_first_1265 { i += 1; } __for_first_1265 = false; i < (rawMarkets.len() as i64) } {
let mut parsed: Value = self.parse_market(rawMarkets.get(i as usize).cloned().unwrap_or(Value::Null));
if (parsed == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOutcomes() could not resolve parsed".into()))));
}
add_element_to_object(&mut self.markets, &parsed.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null), parsed.clone());
self.index_market_outcomes(parsed);
}
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1267: bool = true;
while { if !__for_first_1267 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1267 = false; i.as_f64().unwrap_or(f64::NAN) < outcomeSymbolsLength } {
if !(self.has_outcome(outcomeSymbols.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)).as_bool() == Some(true)) {
self.fetch_outcome(outcomeSymbols.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)).await;
}
}
}
return self.exchange.outcomes.clone();
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
// kalshi returns { "error": { "code": "...", ... } } with a 4xx; map known codes to ccxt
// errors (e.g. not_found -> BadSymbol) so callers can distinguish them from a transport
// outage (the base otherwise maps a bare 404 to the exchange-not-available error). unmapped codes fall
// through to the base http-status handling.
if (response == Value::Null) || (response == Value::Null) {
return Value::Null;
}
let mut error: Value = self.safe_dict_k(response, "error", &[]);
if (error != Value::Null) {
let mut errorCode: Option<String> = self.safe_string_k_opt(error, "code", &[]);
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorCode.clone().map(Value::from).unwrap_or(Value::Null), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorCode.map(Value::from).unwrap_or(Value::Null), feedback.clone());
}
// a 400 is a client-side bad request (bad params, invalid order), not a transport outage —
// throw BadRequest instead of letting the base map the bare 400 to a retryable network-unavailable error
if (code.as_f64() == Some(400.0)) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
panic!("{}", crate::exchange_errors::bad_request(feedback));
}
return Value::Null;
Value::Null
}
pub fn calculate_fee(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, mut price: Value, optional_args: &[Value]) -> Value {
let mut takerOrMaker = get_arg(optional_args, 0, Value::Str("taker".into()));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// kalshi's trading fee is NOT a flat 7% — it is 0.07 * contracts * price * (1 - price), which
// peaks at price 0.5 and vanishes near 0 or 1. the describe() `taker: 0.07` is only the
// coefficient; compute the real per-contract formula here so fee estimates are accurate
let mut priceStr: Value = self.number_to_string(price);
let mut amountStr: Value = self.number_to_string(amount);
let mut oneMinusP: Value = crate::precise::Precise::stringSub(&Value::Str("1".into()), &priceStr);
let mut feeCost: Value = crate::precise::Precise::stringMul(&Value::Str("0.07".into()), &amountStr);
feeCost = crate::precise::Precise::stringMul(&feeCost, &priceStr);
feeCost = crate::precise::Precise::stringMul(&feeCost, &oneMinusP);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), takerOrMaker);
m.insert("currency".to_string(), Value::Str("USD".into()));
m.insert("rate".to_string(), Value::Float(0.07));
m.insert("cost".to_string(), self.parse_number(feeCost, &[]));
m
});
Value::Null
}
pub fn parse_market(&self, mut raw: Value) -> Value {
// {
// "can_close_early":true,
// "close_time":"2029-07-01T14:00:00Z",
// "created_time":"0001-01-01T00:00:00Z",
// "early_close_condition":"This market will close and expire early if the event occurs.",
// "event_ticker":"KXBALANCE-29",
// "expected_expiration_time":"2029-07-01T14:00:00Z",
// "expiration_time":"2029-07-01T14:00:00Z",
// "expiration_value":"",
// "fractional_trading_enabled":false,
// "last_price_dollars":"0.1100",
// "latest_expiration_time":"2029-07-01T14:00:00Z",
// "liquidity_dollars":"0.0000",
// "market_type":"binary",
// "no_ask_dollars":"0.9000",
// "no_bid_dollars":"0.8900",
// "no_sub_title":"During Trump's term",
// "notional_value_dollars":"1.0000",
// "open_interest_fp":"16353.00",
// "open_time":"2025-01-03T15:00:00Z",
// "previous_price_dollars":"0.0000",
// "previous_yes_ask_dollars":"0.0000",
// "previous_yes_bid_dollars":"0.0000",
// "price_level_structure":"linear_cent",
// "price_ranges":[
// {
// "end":"1.0000",
// "start":"0.0000",
// "step":"0.0100"
// }
// ],
// "response_price_units":"usd_cent",
// "result":"",
// "rules_primary":"If there is not a budget deficit for any of fiscal years 2025, 2026, 2027, or 2028, then the market resolves to Yes.",
// "rules_secondary":"",
// "settlement_timer_seconds":"1800",
// "status":"active",
// "subtitle":"",
// "tick_size":"1",
// "ticker":"KXBALANCE-29",
// "title":"Will Trump balance the budget?",
// "updated_time":"0001-01-01T00:00:00Z",
// "volume_24h_fp":"85.00",
// "volume_fp":"40208.00",
// "yes_ask_dollars":"0.1100",
// "yes_ask_size_fp":"",
// "yes_bid_dollars":"0.1000",
// "yes_bid_size_fp":"",
// "yes_sub_title":"During Trump's term"
// }
let mut ticker: Option<String> = self.safe_string_k_opt(raw.clone(), "ticker", &[]);
let mut eventTicker: Option<String> = self.safe_string_k_opt(raw.clone(), "event_ticker", &[]);
let mut subtitle: Value = self.safe_string_k(raw.clone(), "subtitle", &[self.safe_string(raw.clone(), Value::Str("title".into()), &[])]);
// markets use status 'active' while events use 'open'
let mut status: Option<String> = self.safe_string_k(raw.clone(), "status", &[]).as_str().map(str::to_owned);
let mut active: Value = Value::Bool((status.as_deref() == Some("active")) || (status.as_deref() == Some("open")));
// resolution: kalshi sets `result` to 'yes'/'no' once the market settles (empty while trading)
let mut result: Option<String> = self.safe_string_lower_k_opt(raw.clone(), "result", &[]);
let mut resolved: bool = (status.as_deref() == Some("settled")) || ((result.is_some()) && (result.as_deref() != Some("")));
let mut endDate: Option<String> = self.safe_string2_opt(raw.clone(), Value::Str("latest_expiration_time".into()), Value::Str("expiration_time".into()), &[]);
let mut volume: Option<f64> = self.safe_number2_opt(raw.clone(), Value::Str("volume_fp".into()), Value::Str("volume".into()), &[]);
let mut liquidity: Option<f64> = self.safe_number2_opt(raw.clone(), Value::Str("liquidity_dollars".into()), Value::Str("liquidity".into()), &[]);
let mut openInt: Option<f64> = self.safe_number2_opt(raw.clone(), Value::Str("open_interest_fp".into()), Value::Str("open_interest".into()), &[]);
// Derive series ticker: drop last hyphen-segment from event_ticker
let mut seriesTicker: Value = eventTicker.clone().map(Value::from).unwrap_or(Value::Null);
if (eventTicker.is_some()) && (eventTicker.as_deref() != Some("")) {
let mut eventParts: Value = Value::Array(if let Some(__s) = eventTicker.as_deref() { __s.split("-").map(Value::from).collect() } else { Vec::new() });
let mut eventPartsLength: Value = Value::Int(eventParts.len() as i64);
if eventPartsLength.as_f64().unwrap_or(f64::NAN) > ((1i64) as f64) {
let mut seriesParts: Value = self.array_slice(eventParts, Value::Int(0), &[(match (&(eventPartsLength), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x),
Value::Float(y)) => Value::Float(x - y), _ => Value::Null })]);
seriesTicker = Value::str(seriesParts.as_array().cloned().unwrap_or_default().iter().filter_map(Value::as_str).collect::<Vec<_>>().join("-"));
}
}
// market symbol (no outcome suffix)
let mut subtitleOrTicker: Value = ticker.clone().map(Value::from).unwrap_or(Value::Null);
if (subtitle != Value::Null) {
subtitleOrTicker = subtitle.clone();
}
let mut marketSymbol: Value = self.slug_to_market_symbol(eventTicker.clone().map(Value::from).unwrap_or(Value::Null), subtitleOrTicker.clone());
// kalshi exposes the per-market price tick via price_ranges[].step (a dollar value,
// e.g. "0.0010" for deci-cent markets, "0.0100" for cent markets); older responses
// used tick_size (in cents). amount is a whole number of contracts
let mut priceRanges: Value = self.safe_list_k(raw.clone(), "price_ranges", &[Value::from(vec![])]);
let mut firstRange: Value = self.safe_dict(priceRanges, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut stepDollars: Option<String> = self.safe_string_k_opt(firstRange, "step", &[]);
let mut pricePrecision: Value = self.parse_number(crate::precise::Precise::stringDiv(&self.safe_string_k(raw.clone(), "tick_size", &[Value::Str("1".into())]), &Value::Str("100".into())), &[]);
if (stepDollars.is_some()) {
pricePrecision = self.parse_number(stepDollars.clone().map(Value::from).unwrap_or(Value::Null), &[]);
}
let mut precision: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Int(1));
m.insert("price".to_string(), pricePrecision);
m
});
// Build outcomes
let mut outcomeLabels: Value = Value::from(vec![Value::Str("YES".into()), Value::Str("NO".into())]);
let mut outcomeIds: Value = Value::from(vec![ticker.clone().map(Value::from).unwrap_or(Value::Null), Value::Str(format!("{}{}", ticker.clone().map(Value::from).unwrap_or(Value::Null), Value::Str("-NO".into())).into())]);
let mut outcomes: Vec<Value> = Vec::new();
let mut resolvedOutcome: Value = Value::Null;
{
let mut oi: i64 = 0;
let mut __for_first_1268: bool = true;
while { if !__for_first_1268 { oi += 1; } __for_first_1268 = false; oi < (outcomeLabels.len() as i64) } {
let mut label: Value = outcomeLabels.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null);
let mut outcomeHandle: Value = self.slug_to_outcome_symbol(eventTicker.clone().map(Value::from).unwrap_or(Value::Null), subtitleOrTicker.clone(), label.clone());
let mut winnerRaw: Value = Value::Null;
let mut settleFractionRaw: Value = Value::Null;
if resolved && (result.is_some()) && (result.as_deref() != Some("")) {
winnerRaw = (Value::Bool((if let Some(__s) = label.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null }).as_str() == result.as_deref()));
settleFractionRaw = (if (winnerRaw).as_bool() == Some(true) { Value::Int(1) } else { Value::Int(0) });
if winnerRaw.as_bool() == Some(true) {
resolvedOutcome = outcomeHandle.clone();
}
}
// effectively-final copies for the object literal below (Java cannot capture a
// reassigned local into the anonymous inner class it emits for a map literal)
let mut winner: Value = winnerRaw;
let mut settleFraction: Value = settleFractionRaw;
outcomes.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), outcomeIds.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), outcomeIds.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null));
m.insert("outcome".to_string(), outcomeHandle);
m.insert("market".to_string(), marketSymbol.clone());
m.insert("label".to_string(), label.clone());
m.insert("active".to_string(), active.clone());
m.insert("winner".to_string(), winner);
m.insert("settleFraction".to_string(), settleFraction);
m.insert("precision".to_string(), Value::Map(precision.clone()));
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("eventTicker".to_string(), eventTicker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("seriesTicker".to_string(), seriesTicker.clone());
m.insert("subtitle".to_string(), subtitle.clone());
m.insert("outcomeLabel".to_string(), label);
m.insert("volume".to_string(), Value::from(volume));
m.insert("liquidity".to_string(), Value::from(liquidity));
m.insert("openInterest".to_string(), Value::from(openInt));
m
}));
m
}));
}
}
// effectively-final copy for the market object literal below (reassigned in the loop)
let mut marketResolvedOutcome: Value = resolvedOutcome;
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), ticker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("market".to_string(), marketSymbol);
m.insert("base".to_string(), Value::Str("USD".into()));
m.insert("quote".to_string(), Value::Str("USD".into()));
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), ticker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("quoteId".to_string(), Value::Str("USD".into()));
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("prediction".into()));
m.insert("marketType".to_string(), Value::Str("binary".into()));
m.insert("executionModel".to_string(), Value::Str("clob".into()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("active".to_string(), active);
m.insert("resolved".to_string(), Value::Bool(resolved));
m.insert("resolvedOutcome".to_string(), marketResolvedOutcome);
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), (if ((endDate.is_some()) && (endDate.as_deref() != Some(""))) { self.parse8601(endDate.clone().map(Value::from).unwrap_or(Value::Null)) } else { Value::Null }));
m.insert("expiryDatetime".to_string(), endDate.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("taker".to_string(), Value::Float(0.07));
m.insert("maker".to_string(), Value::Int(0));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("feeSide".to_string(), Value::Str("get".into()));
m.insert("precision".to_string(), Value::Map(precision));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(1));
m.insert("max".to_string(), Value::Int(1));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(1));
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Float(0.01));
m.insert("max".to_string(), Value::Float(0.99));
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("outcomes".to_string(), Value::from(outcomes));
m.insert("info".to_string(), self.extend(raw, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("eventTicker".to_string(), eventTicker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("seriesTicker".to_string(), seriesTicker);
m.insert("subtitle".to_string(), subtitle);
m.insert("volume".to_string(), Value::from(volume));
m.insert("liquidity".to_string(), Value::from(liquidity));
m.insert("openInterest".to_string(), Value::from(openInt));
m
})]));
m.insert("created".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name kalshi#fetchTicker
* @description fetches the current market price and bid/ask for a single kalshi outcome
* @see https://docs.kalshi.com/api-reference/market/get-market
* @param {string} outcome the unified outcome like TRUMP_BRING_BACK_MANUFACTURING:YES or outcomeId like KXGDPSHAREMANU-29
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub async fn fetch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut ticker: Option<String> = self.safe_string_opt(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_1 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_public_get_markets_ticker(&[__ws_arg_1]).await;
//
// {
// "market": {
// "can_close_early": true,
// "close_time": "2029-06-30T03:59:00Z",
// "created_time": "2025-06-05T17:55:43.779104Z",
// "early_close_condition": "This market will close and expire early if the event occurs.",
// "event_ticker": "KXGDPSHAREMANU-29",
// "expected_expiration_time": "2029-06-30T14:00:00Z",
// "expiration_time": "2029-07-07T14:00:00Z",
// "expiration_value": "",
// "floor_strike": "13.1",
// "fractional_trading_enabled": true,
// "last_price_dollars": "0.1980",
// "latest_expiration_time": "2029-07-07T14:00:00Z",
// "liquidity_dollars": "0.0000",
// "market_type": "binary",
// "no_ask_dollars": "0.8890",
// "no_bid_dollars": "0.8030",
// "no_sub_title": "Before 2029",
// "notional_value_dollars": "1.0000",
// "open_interest_fp": "11077.21",
// "open_time": "2025-06-05T18:00:00Z",
// "previous_price_dollars": "0.1980",
// "previous_yes_ask_dollars": "0.1970",
// "previous_yes_bid_dollars": "0.1110",
// "price_level_structure": "deci_cent",
// "price_ranges": [
// {
// "start": "0.55",
// "end": "0.56",
// "step": "0.01"
// }
// ],
// "response_price_units": "usd_cent",
// "result": "",
// "rules_primary": "If the value added by Manufacturing to GDP in Q4 2028 is at least 13.1% (the value it was in Q1 2005), then the market resolves to Yes.",
// "rules_secondary": "",
// "settlement_timer_seconds": "1800",
// "status": "active",
// "strike_type": "greater_or_equal",
// "tick_size": "1",
// "ticker": "KXGDPSHAREMANU-29",
// "title": "Will Trump bring back manufacturing?",
// "updated_time": "2026-04-09T10:32:47.890506Z",
// "volume_24h_fp": "0.00",
// "volume_fp": "19617.68",
// "yes_ask_dollars": "0.1970",
// "yes_ask_size_fp": "2750.00",
// "yes_bid_dollars": "0.1110",
// "yes_bid_size_fp": "2505.61",
// "yes_sub_title": "Before 2029"
// }
// }
//
let mut raw: Value = self.safe_dict_k(response.clone(), "market", &[response.clone()]);
return self.parse_prediction_ticker(raw, &[outcomeObj]);
Value::Null
}
/*
* @method
* @name kalshi#fetchStatus
* @description fetches the kalshi exchange status
* @see https://docs.kalshi.com/api-reference/exchange/get-exchange-status
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure](https://docs.ccxt.com/#/?id=exchange-status-structure)
*/
pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.kalshi_public_get_exchange_status(&[params]).await;
//
// { "exchange_active": true, "trading_active": true }
//
let mut tradingActive: bool = self.safe_bool_k_opt(response.clone(), "trading_active", &[Value::Bool(false)]).unwrap_or(false);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if tradingActive { Value::Str("ok".into()) } else { Value::Str("maintenance".into()) }));
m.insert("updated".to_string(), Value::Null);
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
/*
* @method
* @name kalshi#fetchOpenInterest
* @description fetches the open interest of a prediction market outcome
* @see https://docs.kalshi.com/api-reference/market/get-market
* @param {string} outcome unified outcome or outcome id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [open interest structure](https://docs.ccxt.com/#/?id=open-interest-structure)
*/
pub async fn fetch_open_interest(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut ticker: Option<String> = self.safe_string_opt(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_2 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_public_get_markets_ticker(&[__ws_arg_2]).await;
let mut raw: Value = self.safe_dict_k(response.clone(), "market", &[response.clone()]);
return self.parse_prediction_open_interest(raw, &[outcomeObj]);
Value::Null
}
pub fn parse_prediction_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// { "ticker": "...", "open_interest_fp": "60802.01", "updated_time": "2026-04-09T10:32:47.890506Z", ... } // the market object of GET /markets/{ticker}, open interest in contracts
//
let mut timestamp: Value = self.parse8601(self.safe_string_k(interest.clone(), "updated_time", &[]));
let mut openInterest: Value = self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("openInterestAmount".to_string(), self.safe_number2(interest.clone(), Value::Str("open_interest_fp".into()), Value::Str("open_interest".into()), &[]));
m.insert("openInterestValue".to_string(), Value::Null);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("info".to_string(), interest);
m
}), &[market.clone()]);
add_element_to_object(&mut openInterest, &Value::Str("outcome".into()), self.safe_outcome_symbol(Value::Null, &[market.clone()]));
add_element_to_object(&mut openInterest, &Value::Str("outcomeId".into()), self.safe_string_k(market, "outcomeId", &[]));
remove(&mut openInterest, &Value::Str("symbol".into()));
return openInterest;
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parsePredictionTicker
* @description parses a raw kalshi market object into a unified ticker object
* @param {object} raw the raw market object
* @param {object} [market] the outcome object the ticker belongs to
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub fn parse_prediction_ticker(&self, mut raw: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "market": {
// "can_close_early": true,
// "close_time": "2029-06-30T03:59:00Z",
// "created_time": "2025-06-05T17:55:43.779104Z",
// "early_close_condition": "This market will close and expire early if the event occurs.",
// "event_ticker": "KXGDPSHAREMANU-29",
// "expected_expiration_time": "2029-06-30T14:00:00Z",
// "expiration_time": "2029-07-07T14:00:00Z",
// "expiration_value": "",
// "floor_strike": "13.1",
// "fractional_trading_enabled": true,
// "last_price_dollars": "0.1980",
// "latest_expiration_time": "2029-07-07T14:00:00Z",
// "liquidity_dollars": "0.0000",
// "market_type": "binary",
// "no_ask_dollars": "0.8890",
// "no_bid_dollars": "0.8030",
// "no_sub_title": "Before 2029",
// "notional_value_dollars": "1.0000",
// "open_interest_fp": "11077.21",
// "open_time": "2025-06-05T18:00:00Z",
// "previous_price_dollars": "0.1980",
// "previous_yes_ask_dollars": "0.1970",
// "previous_yes_bid_dollars": "0.1110",
// "price_level_structure": "deci_cent",
// "price_ranges": [
// {
// "start": "0.55",
// "end": "0.56",
// "step": "0.01"
// }
// ],
// "response_price_units": "usd_cent",
// "result": "",
// "rules_primary": "If the value added by Manufacturing to GDP in Q4 2028 is at least 13.1% (the value it was in Q1 2005), then the market resolves to Yes.",
// "rules_secondary": "",
// "settlement_timer_seconds": "1800",
// "status": "active",
// "strike_type": "greater_or_equal",
// "tick_size": "1",
// "ticker": "KXGDPSHAREMANU-29",
// "title": "Will Trump bring back manufacturing?",
// "updated_time": "2026-04-09T10:32:47.890506Z",
// "volume_24h_fp": "0.00",
// "volume_fp": "19617.68",
// "yes_ask_dollars": "0.1970",
// "yes_ask_size_fp": "2750.00",
// "yes_bid_dollars": "0.1110",
// "yes_bid_size_fp": "2505.61",
// "yes_sub_title": "Before 2029"
// }
// }
//
let mut marketAny: Value = market.clone();
let mut outcomeObj: Value = self.safe_outcome(self.safe_string_k(marketAny.clone(), "outcome", &[]), &[marketAny]);
let mut outcomeLabel: Value = (if ((market != Value::Null) && (market != Value::Null)) { self.safe_string_upper_k(market.clone(), "label", &[self.safe_string_upper(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("outcomeLabel".into()), &[Value::Str("YES".into())])]) } else { Value::Str("YES".into()) });
let mut isNo: bool = outcomeLabel.as_str() == Some("NO");
let mut timestamp: Value = self.parse8601(self.safe_string_k(raw.clone(), "updated_time", &[]));
let mut outcome: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcome", &[]);
let mut yesAsk: Value = self.safe_number_k(raw.clone(), "yes_ask_dollars", &[]);
let mut yesBid: Value = self.safe_number_k(raw.clone(), "yes_bid_dollars", &[]);
let mut noAsk: Value = self.safe_number_k(raw.clone(), "no_ask_dollars", &[]);
let mut noBid: Value = self.safe_number_k(raw.clone(), "no_bid_dollars", &[]);
let mut last: Value = self.safe_number_k(raw.clone(), "last_price_dollars", &[]);
let mut bid: Value = Value::Null;
let mut ask: Value = Value::Null;
let mut close: Value = Value::Null;
if isNo {
bid = noBid;
ask = noAsk;
close = (if (last != Value::Null) { self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &self.number_to_string(last.clone())), &[]) } else { Value::Null });
} else {
bid = yesBid;
ask = yesAsk;
close = last;
}
// the book is quoted in the yes token, the no side mirrors with sizes swapped
let mut bidSizeString: Value = Value::Null;
if isNo {
bidSizeString = self.safe_string_k(raw.clone(), "yes_ask_size_fp", &[]);
} else {
bidSizeString = self.safe_string_k(raw.clone(), "yes_bid_size_fp", &[]);
}
let mut askSizeString: Value = Value::Null;
if isNo {
askSizeString = self.safe_string_k(raw.clone(), "yes_bid_size_fp", &[]);
} else {
askSizeString = self.safe_string_k(raw.clone(), "yes_ask_size_fp", &[]);
}
// kalshi occasionally reports a negative size for settling/closed markets; a size
// can't be negative, so drop it rather than emit an invalid volume
let mut bidVolume: Value = Value::Null;
if (bidSizeString != Value::Null) && crate::precise::Precise::stringGe(&bidSizeString, &Value::Str("0".into())).as_bool() == Some(true) {
bidVolume = self.parse_number(bidSizeString.clone(), &[]);
}
let mut askVolume: Value = Value::Null;
if (askSizeString != Value::Null) && crate::precise::Precise::stringGe(&askSizeString, &Value::Str("0".into())).as_bool() == Some(true) {
askVolume = self.parse_number(askSizeString.clone(), &[]);
}
let mut average: Value = Value::Null;
if (bid != Value::Null) && (ask != Value::Null) {
average = self.parse_number(crate::precise::Precise::stringDiv(&crate::precise::Precise::stringAdd(&self.number_to_string(bid.clone()), &self.number_to_string(ask.clone())), &Value::Str("2".into())), &[]);
}
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcome.map(Value::from).unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(outcomeObj, Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), bid);
m.insert("bidVolume".to_string(), bidVolume);
m.insert("ask".to_string(), ask);
m.insert("askVolume".to_string(), askVolume);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), close.clone());
m.insert("last".to_string(), close);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), average);
m.insert("baseVolume".to_string(), self.safe_number_n(raw.clone(), Value::from(vec![Value::Str("volume_24h_fp".into()), Value::Str("volume_24h".into()), Value::Str("volume".into())]), &[]));
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("info".to_string(), raw);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name kalshi#fetchTickers
* @description fetches tickers for multiple outcomes at once, batching their market tickers through the markets endpoint (100 per request)
* @see https://docs.kalshi.com/api-reference/market/get-markets
* @param {string[]} outcomes unified outcomes — required: kalshi has tens of thousands of markets and no endpoint returning all tickers at once, so an unscoped call is not supported
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [prediction ticker structures](https://docs.ccxt.com/#/?id=prediction-ticker-structure) indexed by outcome
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcomes == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles to fetch (discover them via fetchEvents ())".into()))));
}
// batch-resolve the uncached outcomes (one markets request per 100 tickers)
self.load_outcomes(&[outcomes.clone()]).await;
// group requested outcomes by their market ticker, yes and no outcomes share one market
let mut outcomesByTicker: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut tickers: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1269: bool = true;
while { if !__for_first_1269 { i += 1; } __for_first_1269 = false; i < (outcomes.len() as i64) } {
let mut outcomeObj: Value = self.outcome(outcomes.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null));
let mut ticker: Option<String> = self.safe_string_opt(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
if (ticker.is_none()) {
continue;
}
if !(matches!((&outcomesByTicker, &ticker.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut outcomesByTicker { std::sync::Arc::make_mut(__d).insert(ticker.as_deref().unwrap_or("null").to_string(), Value::from(vec![])); }
tickers.push(ticker.clone().map(Value::from).unwrap_or(Value::Null));
}
// reassign after push, plain mutation through a local is lost in transpiled php (arrays are value types there)
let mut grouped: Value = self.safe_list(outcomesByTicker.clone(), ticker.clone().map(Value::from).unwrap_or(Value::Null), &[Value::from(vec![])]);
if let Value::Arr(__a) = &mut grouped { std::sync::Arc::make_mut(__a).push(outcomeObj); }
if let Value::Dict(__d) = &mut outcomesByTicker { std::sync::Arc::make_mut(__d).insert(ticker.as_deref().unwrap_or("null").to_string(), grouped.clone()); }
}
}
let mut chunkSize: Value = self.safe_integer_k(self.options.clone(), "fetchTickersBatchSize", &[Value::Int(100)]);
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut tickersLength: Value = Value::Int(tickers.len() as i64);
let mut lastTickerIndex: Value = (match (&(tickersLength), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut chunk: Value = Value::from(vec![]);
{
let mut ti: Value = Value::Int(0);
let mut __for_first_1272: bool = true;
while { if !__for_first_1272 { if let Value::Int(n) = &mut ti { *n += 1; } } __for_first_1272 = false; ti.as_f64().unwrap_or(f64::NAN) < tickersLength.as_f64().unwrap_or(f64::NAN) } {
if let Value::Arr(__a) = &mut chunk { std::sync::Arc::make_mut(__a).push(tickers.get((ti).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)); }
let mut chunkLength: f64 = ((chunk.len() as i64) as f64);
if (chunkLength < chunkSize.as_f64().unwrap_or(f64::NAN)) && (ti.as_f64().unwrap_or(f64::NAN) < lastTickerIndex.as_f64().unwrap_or(f64::NAN)) {
continue;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tickers".to_string(), Value::Str(chunk.as_array().map(|__a| __a.iter().map(|__v| __v.to_string()).collect::<Vec<String>>().join(",")).unwrap_or_default().into()));
m.insert("limit".to_string(), chunkSize.clone());
m
});
chunk = Value::from(vec![]);
let __ws_arg_3 = self.extend(Value::Map(request), &[params.clone()]);
let mut response: Value = self.kalshi_public_get_markets(&[__ws_arg_3]).await;
let mut rawMarkets: Vec<Value> = self.safe_list_k(response, "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
{
let mut i: i64 = 0;
let mut __for_first_1271: bool = true;
while { if !__for_first_1271 { i += 1; } __for_first_1271 = false; i < (rawMarkets.len() as i64) } {
let mut raw: Value = rawMarkets.get(i as usize).cloned().unwrap_or(Value::Null);
let mut marketTicker: Option<String> = self.safe_string_k_opt(raw.clone(), "ticker", &[]);
if (marketTicker.is_none()) || !(matches!((&outcomesByTicker, &marketTicker.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
continue;
}
let mut grouped: Value = (if let (Some(__m), Some(__k)) = (outcomesByTicker.as_map(), marketTicker.as_deref()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
{
let mut j: Value = Value::Int(0);
let mut __for_first_1270: bool = true;
while { if !__for_first_1270 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_1270 = false; j.as_f64().unwrap_or(f64::NAN) < get_array_length(&grouped).as_f64().unwrap_or(f64::NAN) } {
let mut ticker: Value = self.parse_prediction_ticker(raw.clone(), &[get_value(&grouped, &j)]);
let mut symbolKey: Option<String> = self.safe_string_k_opt(ticker.clone(), "outcome", &[]);
if (symbolKey.is_some()) {
result.insert(symbolKey.as_deref().unwrap_or("null").to_string(), ticker);
}
}
}
}
}
}
}
return Value::Map(result);
Value::Null
}
/*
* @method
* @name kalshi#fetchOrderBook
* @description fetches the order book for a single kalshi outcome
* @see https://docs.kalshi.com/api-reference/market/get-market-orderbook
* @param {string} outcome unified outcome or outcome id
* @param {int} [limit] the maximum number of bids/asks to return (not enforced by kalshis API, reserved for future client-side trimming)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
*/
pub async fn fetch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut ticker: Option<String> = self.safe_string_opt(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
let mut isNo: bool = self.safe_string_k(outcomeObj.clone(), "label", &[]).as_str() == Some("NO");
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone().map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_4 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_public_get_markets_ticker_orderbook(&[__ws_arg_4]).await;
//
// {
// "orderbook_fp": {
// "no_dollars": [
// [ "0.1500", "100.00" ], [ "0.1600", "101.00" ]
// ],
// "yes_dollars": [
// [ "0.1500", "100.00" ], [ "0.1600", "101.00" ]
// ]
// }
// }
//
let mut book: Value = self.safe_dict_k(response.clone(), "orderbook_fp", &[response.clone()]);
// Kalshi uses YES-side perspective: `yes` = bids, `no` = asks (inverted)
let mut rawYes: Vec<Value> = self.safe_list_k(book.clone(), "yes_dollars", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rawNo: Vec<Value> = self.safe_list_k(book, "no_dollars", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
// Convert [price_cents, size] → [price, size]
let mut bids: Vec<Value> = Vec::new();
let mut asks: Vec<Value> = Vec::new();
if isNo {
{
let mut bi: i64 = 0;
let mut __for_first_1273: bool = true;
while { if !__for_first_1273 { bi += 1; } __for_first_1273 = false; bi < (rawNo.len() as i64) } {
let mut price: Value = self.safe_number(rawNo.get(bi as usize).cloned().unwrap_or(Value::Null), Value::Int(0), &[]);
bids.push(Value::from(vec![price.clone(), self.safe_number(rawNo.get(bi as usize).cloned().unwrap_or(Value::Null), Value::Int(1), &[])]));
}
}
{
let mut ai: i64 = 0;
let mut __for_first_1274: bool = true;
while { if !__for_first_1274 { ai += 1; } __for_first_1274 = false; ai < (rawYes.len() as i64) } {
let mut yesPrice: Value = self.safe_number(rawYes.get(ai as usize).cloned().unwrap_or(Value::Null), Value::Int(0), &[]);
let mut price: Value = (if (yesPrice != Value::Null) { self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &self.number_to_string(yesPrice)), &[]) } else { Value::Null });
asks.push(Value::from(vec![price.clone(), self.safe_number(rawYes.get(ai as usize).cloned().unwrap_or(Value::Null), Value::Int(1), &[])]));
}
}
} else {
{
let mut bi: i64 = 0;
let mut __for_first_1275: bool = true;
while { if !__for_first_1275 { bi += 1; } __for_first_1275 = false; bi < (rawYes.len() as i64) } {
let mut price: Value = self.safe_number(rawYes.get(bi as usize).cloned().unwrap_or(Value::Null), Value::Int(0), &[]);
bids.push(Value::from(vec![price.clone(), self.safe_number(rawYes.get(bi as usize).cloned().unwrap_or(Value::Null), Value::Int(1), &[])]));
}
}
{
let mut ai: i64 = 0;
let mut __for_first_1276: bool = true;
while { if !__for_first_1276 { ai += 1; } __for_first_1276 = false; ai < (rawNo.len() as i64) } {
let mut noPrice: Value = self.safe_number(rawNo.get(ai as usize).cloned().unwrap_or(Value::Null), Value::Int(0), &[]);
let mut price: Value = (if (noPrice != Value::Null) { self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &self.number_to_string(noPrice)), &[]) } else { Value::Null });
asks.push(Value::from(vec![price, self.safe_number(rawNo.get(ai as usize).cloned().unwrap_or(Value::Null), Value::Int(1), &[])]));
}
}
}
return self.safe_prediction_order_book(self.sorted_orders(self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome]), Value::Null, Value::from(bids), Value::from(asks)), &[outcomeObj]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#sortedOrders
* @description sorts bids descending and asks ascending, then returns a CCXT-shaped order book object
* @param {string} outcome unified outcome
* @param {int} timestamp timestamp in ms
* @param {object[]} bids array of [price, size] bid levels
* @param {object[]} asks array of [price, size] ask levels
* @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
*/
pub fn sorted_orders(&self, mut outcome: Value, mut timestamp: Value, mut bids: Value, mut asks: Value) -> Value {
// Sort bids descending, asks ascending, match CCXT OrderBook shape
let mut bidsValue: Value = self.sort_by(bids, Value::Int(0), &[Value::Bool(true)]);
let mut asksValue: Value = self.sort_by(asks, Value::Int(0), &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcome);
m.insert("bids".to_string(), bidsValue);
m.insert("asks".to_string(), asksValue);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("nonce".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name kalshi#fetchOHLCV
* @description fetches OHLCV candlesticks for a single kalshi outcome from the candlesticks endpoint
* @see https://docs.kalshi.com/api-reference/market/get-market-candlesticks
* @param {string} outcome unified outcome
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum number of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} a list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut ticker: Option<String> = self.safe_string_opt(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
let mut seriesTicker: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("seriesTicker".into()), &[ticker.clone().map(Value::from).unwrap_or(Value::Null)]);
let mut periodMin: Option<i64> = self.safe_integer(self.timeframes.clone(), timeframe.clone(), &[]).as_i64();
if (periodMin.is_none()) {
// reject an unsupported timeframe locally instead of silently returning 1-minute candles.
// hoist Object.keys(...).join(...) to a local — inline in a throw mangles in PHP
let mut tfKeys: Value = Value::Array(self.timeframes.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default());
let mut supported: Value = Value::Str(tfKeys.as_array().map(|__a| __a.iter().map(|__v| __v.to_string()).collect::<Vec<String>>().join(", ")).unwrap_or_default().into());
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() does not support the ".into())).into()), timeframe).into()), Value::Str(" timeframe (supported: ".into())).into()), supported).into()), Value::Str(")".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("series_ticker".to_string(), seriesTicker);
m.insert("ticker".to_string(), ticker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("period_interval".to_string(), Value::from(periodMin));
m
});
let mut now: Value = self.seconds();
let mut tf: Value = self.parse_timeframe(timeframe.clone());
if (since != Value::Null) {
let mut sinceS: Value = self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
request.insert("start_ts".into(), sinceS.clone());
if (limit != Value::Null) {
let mut end: Value = self.sum(&[sinceS, (match (&(limit), &(tf)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
request.insert("end_ts".into(), (if (end.as_f64().unwrap_or(f64::NAN) < now.as_f64().unwrap_or(f64::NAN)) { end } else { now.clone() }));
} else {
// the candlesticks endpoint requires end_ts - default to now
request.insert("end_ts".into(), now.clone());
}
} else {
let mut defaultLimit: Value = self.safe_integer_k(self.options.clone(), "defaultFetchOHLCVLimit", &[Value::Int(200)]);
let mut candlesCount: Value = defaultLimit;
if (limit != Value::Null) {
candlesCount = limit.clone();
}
request.insert("end_ts".into(), now.clone());
request.insert("start_ts".into(), (match (&(now), &(((match (&(candlesCount), &(tf)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y),
_ => Value::Null })))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }));
}
let __ws_arg_5 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_public_get_series_series_ticker_markets_ticker_candlesticks(&[__ws_arg_5]).await;
//
// {
// "candlesticks": [
// {
// "end_period_ts": 1776109260,
// "open_interest_fp": "10869.00",
// "price": {
// "open_dollars": "0.5600",
// "low_dollars": "0.5600",
// "high_dollars": "0.5600",
// "close_dollars": "0.5600",
// "mean_dollars": "0.5600",
// "previous_dollars": "0.5600",
// "min_dollars": "0.5600",
// "max_dollars": "0.5600"
// },
// "volume_fp": "0.00",
// "yes_ask": {
// "close_dollars": "0.1630",
// "high_dollars": "0.1630",
// "low_dollars": "0.1500",
// "open_dollars": "0.1630"
// },
// "yes_bid": {
// "close_dollars": "0.0800",
// "high_dollars": "0.0800",
// "low_dollars": "0.0700",
// "open_dollars": "0.0800"
// }
// },
// ],
// "ticker": "KXGDPSHAREMANU-29"
// }
//
let mut candles: Vec<Value> = self.safe_list_k(response, "candlesticks", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut usableCandles: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1277: bool = true;
while { if !__for_first_1277 { i += 1; } __for_first_1277 = false; i < (candles.len() as i64) } {
let mut candle: Value = candles.get(i as usize).cloned().unwrap_or(Value::Null);
let mut priceObj: Value = self.safe_dict_k(candle.clone(), "price", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut openPrice: Option<f64> = self.safe_number_k(priceObj.clone(), "open_dollars", &[]).as_f64();
let mut previousPrice: Option<f64> = self.safe_number_k(priceObj, "previous_dollars", &[]).as_f64();
if (openPrice.is_some()) || (previousPrice.is_some()) {
usableCandles.push(candle);
}
}
}
// kalshi candles carry only the period-END timestamp; thread the candle duration through so
// parseOHLCV can stamp each candle at its OPEN (the CCXT convention)
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("ohlcvCandleDurationSeconds".into(), tf); }
return self.parse_ohlc_vs(Value::from(usableCandles), &[outcomeObj, timeframe, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parseOHLCV
* @description parses a single kalshi candlestick object into a CCXT OHLCV tuple, converting cent prices to decimals
* @param {object} ohlcv the raw candlestick object
* @param {object} [market] the outcome object the candle belongs to
* @returns {int[]} a candle ordered as timestamp, open, high, low, close, volume
*/
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "end_period_ts": 1776109260,
// "open_interest_fp": "10869.00",
// "price": {
// "open_dollars": "0.5600",
// "low_dollars": "0.5600",
// "high_dollars": "0.5600",
// "close_dollars": "0.5600",
// "mean_dollars": "0.5600",
// "previous_dollars": "0.5600",
// "min_dollars": "0.5600",
// "max_dollars": "0.5600"
// },
// "volume_fp": "0.00",
// "yes_ask": {
// "close_dollars": "0.1630",
// "high_dollars": "0.1630",
// "low_dollars": "0.1500",
// "open_dollars": "0.1630"
// },
// "yes_bid": {
// "close_dollars": "0.0800",
// "high_dollars": "0.0800",
// "low_dollars": "0.0700",
// "open_dollars": "0.0800"
// }
// }
//
let mut price: Value = self.safe_dict_k(ohlcv.clone(), "price", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// no-trade periods carry only previous_dollars (last trade price) → flat candle
let mut previous: Value = self.safe_number_k(price.clone(), "previous_dollars", &[]);
// the raw candle exposes only the period END (`end_period_ts`); subtract the candle duration
// threaded in from fetchOHLCV to stamp the candle at its OPEN (CCXT convention)
let mut endTimestamp: Value = self.safe_timestamp_k(ohlcv.clone(), "end_period_ts", &[]);
let mut durationSeconds: Value = self.safe_integer_k(self.options.clone(), "ohlcvCandleDurationSeconds", &[Value::Int(0)]);
let mut timestamp: Value = endTimestamp.clone();
if (endTimestamp != Value::Null) {
timestamp = (match (&(endTimestamp), &((match (&(durationSeconds), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y),
_ => Value::Null }))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
}
return Value::from(vec![timestamp, self.safe_number_k(price.clone(), "open_dollars", &[previous.clone()]), self.safe_number_k(price.clone(), "high_dollars", &[previous.clone()]), self.safe_number_k(price.clone(), "low_dollars", &[previous.clone()]), self.safe_number_k(price, "close_dollars", &[previous]), self.safe_number_k(ohlcv, "volume_fp", &[Value::Int(0)])]);
Value::Null
}
/*
* @method
* @name kalshi#fetchTrades
* @description fetches public trade history for a single kalshi market ticker
* @see https://docs.kalshi.com/api-reference/market/get-trades
* @param {string} outcome unified outcome
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum number of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_trades(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut ticker: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone());
m
});
if (limit != Value::Null) {
request.insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(1000)));
}
let __ws_arg_6 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_public_get_markets_trades(&[__ws_arg_6]).await;
let mut trades: Vec<Value> = self.safe_list_k(response, "trades", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut filteredTrades: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1278: bool = true;
while { if !__for_first_1278 { i += 1; } __for_first_1278 = false; i < (trades.len() as i64) } {
let mut trade: Value = trades.get(i as usize).cloned().unwrap_or(Value::Null);
let mut tradeTicker: Value = self.safe_string2(trade.clone(), Value::Str("ticker".into()), Value::Str("market_ticker".into()), &[]);
if (tradeTicker == Value::Null) || (tradeTicker == ticker) {
filteredTrades.push(trade);
}
}
}
return self.parse_prediction_trades(Value::from(filteredTrades), &[outcomeObj, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parsePredictionTrade
* @description parses a raw kalshi trade object into a unified trade object
* @param {object} trade the raw trade object
* @param {object} [market] the outcome object the trade belongs to
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut id: Option<String> = self.safe_string_k_opt(trade.clone(), "trade_id", &[]);
let mut ts: Value = self.parse8601(self.safe_string_k(trade.clone(), "created_time", &[]));
let mut priceCents: Value = self.safe_number2(trade.clone(), Value::Str("yes_price".into()), Value::Str("price".into()), &[]);
let mut centsPrice: Value = Value::Null;
if (priceCents != Value::Null) {
centsPrice = (match ((priceCents).as_f64(), (Value::Int(100)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
let mut price: Value = self.safe_number2(trade.clone(), Value::Str("yes_price_dollars".into()), Value::Str("price_dollars".into()), &[centsPrice]);
let mut amountFp: Value = self.safe_number2(trade.clone(), Value::Str("count_fp".into()), Value::Str("size_fp".into()), &[]);
let mut amount: Value = self.safe_number_k(trade.clone(), "count", &[amountFp]);
let mut rawSide: Option<String> = self.safe_string_lower_k_opt(trade.clone(), "taker_side", &[]);
let mut marketAny: Value = market.clone();
let mut outcomeObj: Value = self.safe_outcome(self.safe_string_k(marketAny.clone(), "outcome", &[]), &[marketAny]);
let mut marketInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut requestedOutcomeLabel: Value = self.safe_string_lower_k(outcomeObj.clone(), "label", &[self.safe_string_lower(marketInfo, Value::Str("outcomeLabel".into()), &[])]);
let mut outcomeSymbol: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcome", &[]);
let mut outcomeId: Option<String> = self.safe_string2_opt(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]);
let mut side: Value = Value::Null;
if (rawSide.as_deref() == Some("yes")) || (rawSide.as_deref() == Some("no")) {
if (requestedOutcomeLabel.as_str() == Some("yes")) || (requestedOutcomeLabel.as_str() == Some("no")) {
side = (if (rawSide.as_deref() == requestedOutcomeLabel.as_str()) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
} else {
side = (if (rawSide.as_deref() == Some("yes")) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
}
}
let mut cost: Value = Value::Null;
if (price != Value::Null) && (amount != Value::Null) {
cost = (match (&(price), &(amount)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
}
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts));
m.insert("outcome".to_string(), outcomeSymbol.map(Value::from).unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), outcomeId.map(Value::from).unwrap_or(Value::Null));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(outcomeObj, Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), Value::Str("taker".into()));
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), cost);
m.insert("fee".to_string(), Value::Null);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name kalshi#fetchMyTrades
* @description fetch the fills (executed trades) of the authenticated kalshi user
* @see https://trading-api.readme.io/reference/getfills
* @param {string} [outcome] filter to a single unified outcome
* @param {int} [since] the earliest fill timestamp (ms) to fetch
* @param {int} [limit] the maximum number of fills to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
// the ticker filter narrows to the market; a market has both legs, so the
// wanted-leg filter below still drops the opposite-leg fills
outcomeObj = self.outcome(outcome.clone());
if (outcomeObj == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a valid outcome".into()))));
}
request.insert("ticker".into(), self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]));
}
if (limit != Value::Null) {
request.insert("limit".into(), limit.clone());
}
let __ws_arg_7 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_private_get_portfolio_fills(&[__ws_arg_7]).await;
let mut fills: Vec<Value> = self.safe_list_k(response, "fills", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut fillsLength: f64 = ((fills.len() as i64) as f64);
let mut trades: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1279: bool = true;
while { if !__for_first_1279 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1279 = false; i.as_f64().unwrap_or(f64::NAN) < fillsLength } {
trades.push(self.parse_my_trade(fills.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[outcomeObj.clone()]));
}
}
let mut wantedOutcomeObj: Value = (if (outcome != Value::Null) { self.outcome(outcome.clone()) } else { Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut wantedOutcome: Option<String> = self.safe_string_k_opt(wantedOutcomeObj, "outcome", &[]);
let mut result: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1280: bool = true;
while { if !__for_first_1280 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1280 = false; i.as_f64().unwrap_or(f64::NAN) < ((trades.len() as i64) as f64) } {
let mut trade: Value = trades.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if (wantedOutcome.is_none()) || (self.safe_string_k(trade.clone(), "outcome", &[]).as_str() == wantedOutcome.as_deref()) {
result.push(trade);
}
}
}
return self.filter_by_since_limit(Value::from(result), &[since, limit, Value::Str("timestamp".into())]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parseMyTrade
* @description parses one raw kalshi fill into the unified trade shape
* @param {object} fill the raw kalshi fill
* @param {object} [market] a resolved outcome/market hint
* @returns {object} a unified trade structure
*/
pub fn parse_my_trade(&self, mut fill: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut id: Option<String> = self.safe_string2_opt(fill.clone(), Value::Str("fill_id".into()), Value::Str("trade_id".into()), &[]);
let mut orderId: Option<String> = self.safe_string_k_opt(fill.clone(), "order_id", &[]);
let mut ticker: Option<String> = self.safe_string2_opt(fill.clone(), Value::Str("ticker".into()), Value::Str("market_ticker".into()), &[]);
// the leg the fill executed on ('yes' | 'no'); NO is addressed as <ticker>-NO
let mut sideLeg: Option<String> = self.safe_string_lower_k(fill.clone(), "side", &[]).as_str().map(str::to_owned);
let mut outcomeKey: Value = ticker.clone().map(Value::from).unwrap_or(Value::Null);
if (sideLeg.as_deref() == Some("no")) && (ticker.is_some()) {
outcomeKey = Value::Str(format!("{}{}", ticker.map(Value::from).unwrap_or(Value::Null), Value::Str("-NO".into())).into());
}
let mut mkt: Value = self.safe_outcome(outcomeKey.clone(), &[market.clone()]);
let mut ts: Value = self.parse8601(self.safe_string_k(fill.clone(), "created_time", &[]));
// action is the order side (buy/sell) of the held leg
let mut action: Option<String> = self.safe_string_lower_k(fill.clone(), "action", &[]).as_str().map(str::to_owned);
let mut side: String = "buy".to_string();
if (action.as_deref() == Some("sell")) {
side = "sell".to_string();
}
// price is the price of the leg held; kalshi reports dollars in V2, cents otherwise
let mut centsKey: String = "yes_price".to_string();
let mut dollarsKey: String = "yes_price_dollars".to_string();
if (sideLeg.as_deref() == Some("no")) {
centsKey = "no_price".to_string();
dollarsKey = "no_price_dollars".to_string();
}
let mut legCents: Value = self.safe_number(fill.clone(), Value::from(centsKey), &[]);
let mut centsPrice: Value = Value::Null;
if (legCents != Value::Null) {
centsPrice = (match ((legCents).as_f64(), (Value::Int(100)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
let mut price: Value = self.safe_number(fill.clone(), Value::from(dollarsKey), &[centsPrice]);
let mut amount: Value = self.safe_number2(fill.clone(), Value::Str("count_fp".into()), Value::Str("count".into()), &[]);
let mut cost: Value = Value::Null;
if (price != Value::Null) && (amount != Value::Null) {
cost = (match (&(price), &(amount)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
}
let mut isTaker: bool = self.safe_bool_k_opt(fill.clone(), "is_taker", &[Value::Bool(true)]).unwrap_or(true);
let mut takerOrMaker: String = "maker".to_string();
if isTaker {
takerOrMaker = "taker".to_string();
}
let mut feeCost: Value = self.safe_number_k(fill.clone(), "fee_cost", &[]);
let mut fee: Value = Value::Null;
if (feeCost != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("currency".to_string(), Value::Str("USD".into()));
m
});
}
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
m.insert("info".to_string(), fill);
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts));
m.insert("outcome".to_string(), self.safe_string_k(mkt.clone(), "outcome", &[outcomeKey]));
m.insert("outcomeId".to_string(), self.safe_string2(mkt.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("label".to_string(), self.safe_string_k(mkt.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(mkt, Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m.insert("order".to_string(), orderId.map(Value::from).unwrap_or(Value::Null));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), Value::from(side));
m.insert("takerOrMaker".to_string(), Value::from(takerOrMaker));
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), cost);
m.insert("fee".to_string(), fee);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name kalshi#fetchBalance
* @description fetches the authenticated user's USD portfolio balance from kalshi
* @see https://trading-api.readme.io/reference/getbalance
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.kalshi_private_get_portfolio_balance(&[params]).await;
return self.parse_balance(response);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parseBalance
* @description parses a kalshi balance response (cents) into a unified balances object with a USD entry
* @param {object} response the raw balance response
* @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
*/
pub fn parse_balance(&self, mut response: Value) -> Value {
// Kalshi balance in cents → divide by 100
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut balanceCents: Value = self.safe_number_k(response, "balance", &[]);
let mut total: Value = Value::Null;
if (balanceCents != Value::Null) {
total = (match ((balanceCents).as_f64(), (Value::Int(100)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
result.insert("USD".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("free".to_string(), total.clone());
m.insert("used".to_string(), Value::Int(0));
m.insert("total".to_string(), total);
m
}));
return self.safe_balance(Value::Map(result));
Value::Null
}
/*
* @method
* @name kalshi#fetchPositions
* @description fetches open market positions for the authenticated kalshi user
* @see https://trading-api.readme.io/reference/getportfoliopositions
* @param {string[]} [outcomes] filter by outcome ids or outcomes
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction position structures](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomesLength: i64 = 0;
if (outcomes != Value::Null) {
outcomesLength = outcomes.len() as i64;
}
if (outcomesLength as f64) > ((0i64) as f64) {
self.load_outcomes(&[outcomes.clone()]).await;
}
// no bulk warm-up on the unfiltered path: the portfolio request is self-contained and
// labels resolve cache-only via safeOutcome (raw tickers when the cache is cold)
let mut response: Value = self.kalshi_private_get_portfolio_positions(&[params]).await;
let mut positions: Value = self.safe_list_k(response, "market_positions", &[Value::from(vec![])]);
// filter by the requested outcomes' market tickers — a kalshi position is per market
// ticker and covers both the YES and the NO leg
if (((outcomesLength as f64) == 0.0)) {
return self.parse_prediction_positions(positions.clone(), &[]);
}
let mut parsed: Vec<Value> = self.parse_prediction_positions(positions, &[]).as_array().cloned().unwrap_or_default();
let mut wantedTickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (outcomes == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() missing outcomes".into()))));
}
{
let mut i: i64 = 0;
let mut __for_first_1281: bool = true;
while { if !__for_first_1281 { i += 1; } __for_first_1281 = false; i < (outcomes.len() as i64) } {
let mut outcomeObj: Value = self.outcome(outcomes.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null));
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketTicker: Option<String> = self.safe_string_k_opt(outcomeInfo, "ticker", &[]);
if (marketTicker.is_some()) {
if let Value::Dict(__d) = &mut wantedTickers { std::sync::Arc::make_mut(__d).insert(marketTicker.as_deref().unwrap_or("null").to_string(), Value::Bool(true)); }
}
}
}
let mut result: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_1282: bool = true;
while { if !__for_first_1282 { i += 1; } __for_first_1282 = false; i < (parsed.len() as i64) } {
let mut position: Value = parsed.get(i as usize).cloned().unwrap_or(Value::Null);
let mut positionInfo: Value = self.safe_dict_k(position.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positionTicker: Option<String> = self.safe_string_k_opt(positionInfo, "ticker", &[]);
if (positionTicker.is_some()) && (matches!((&wantedTickers, &positionTicker.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Arr(__a) = &mut result { std::sync::Arc::make_mut(__a).push(position); }
}
}
}
return result;
Value::Null
}
/*
* @method
* @name kalshi#fetchSettlements
* @description fetches the user's settled (resolved) positions, with the collateral paid out and realized pnl
* @see https://trading-api.readme.io/reference/getportfoliosettlements
* @param {string} [outcome] filter to a single unified outcome
* @param {int} [since] timestamp in ms of the earliest settlement to fetch
* @param {int} [limit] the maximum number of settlements to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of prediction settlement structures
*/
pub async fn fetch_settlements(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
request.insert("limit".into(), limit.clone());
}
let __ws_arg_8 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_private_get_portfolio_settlements(&[__ws_arg_8]).await;
let mut rawSettlements: Vec<Value> = self.safe_list_k(response, "settlements", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rawSettlementsLength: f64 = ((rawSettlements.len() as i64) as f64);
let mut parsed: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1283: bool = true;
while { if !__for_first_1283 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1283 = false; i.as_f64().unwrap_or(f64::NAN) < rawSettlementsLength } {
parsed.push(self.parse_settlement(rawSettlements.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[]));
}
}
let mut wantedOutcomeObj: Value = (if (outcome != Value::Null) { self.outcome(outcome.clone()) } else { Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut wantedOutcome: Option<String> = self.safe_string_k_opt(wantedOutcomeObj, "outcome", &[]);
let mut result: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1284: bool = true;
while { if !__for_first_1284 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1284 = false; i.as_f64().unwrap_or(f64::NAN) < ((parsed.len() as i64) as f64) } {
let mut settlement: Value = parsed.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if (wantedOutcome.is_none()) || (self.safe_string_k(settlement.clone(), "outcome", &[]).as_str() == wantedOutcome.as_deref()) {
result.push(settlement);
}
}
}
return self.filter_by_since_limit(Value::from(result), &[since, limit, Value::Str("timestamp".into())]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parseSettlement
* @description parses one raw kalshi settlement into the unified prediction settlement shape
* @param {object} settlement the raw kalshi settlement
* @param {object} [market] a resolved outcome/market hint
* @returns {object} a prediction settlement structure
*/
pub fn parse_settlement(&self, mut settlement: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut ticker: Option<String> = self.safe_string_k_opt(settlement.clone(), "ticker", &[]);
// the leg the user actually held (kalshi reports separate yes/no counts + costs)
let mut yesCount: Value = self.safe_number2(settlement.clone(), Value::Str("yes_count_fp".into()), Value::Str("yes_count".into()), &[Value::Int(0)]);
let mut noCount: Value = self.safe_number2(settlement.clone(), Value::Str("no_count_fp".into()), Value::Str("no_count".into()), &[Value::Int(0)]);
let mut heldYes: Value = Value::Bool(!(noCount.as_f64().unwrap_or(f64::NAN) > yesCount.as_f64().unwrap_or(f64::NAN)));
let mut heldLabel: String = "NO".to_string();
if matches!(&heldYes, Value::Bool(true)) {
heldLabel = "YES".to_string();
}
let mut tickerMissing: bool = ticker.is_none();
let mut useHeldYesTicker: bool = matches!(&heldYes, Value::Bool(true)) || tickerMissing;
let mut heldTicker: Value = Value::Null;
if useHeldYesTicker {
heldTicker = ticker.clone().map(Value::from).unwrap_or(Value::Null);
} else {
heldTicker = (Value::Str(format!("{}{}", ticker.clone().map(Value::from).unwrap_or(Value::Null), Value::Str("-NO".into())).into()));
}
let mut mkt: Value = self.safe_outcome(heldTicker.clone(), &[market]);
// which leg won; market_result is yes or no
let mut marketResult: Option<String> = self.safe_string_upper_k_opt(settlement.clone(), "market_result", &[]);
let mut won: Value = (Value::Bool(marketResult.as_deref() == Some(heldLabel.as_str())));
// kalshi reports money as dollar keys on V2, else cents
let mut revenueCents: Value = self.safe_number_k(settlement.clone(), "revenue", &[]);
let mut centsPayout: Value = Value::Null;
if (revenueCents != Value::Null) {
centsPayout = (match ((revenueCents).as_f64(), (Value::Int(100)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
let mut payout: Value = self.safe_number_k(settlement.clone(), "revenue_dollars", &[centsPayout]);
let mut costKey: String = "no_total_cost".to_string();
if matches!(&heldYes, Value::Bool(true)) {
costKey = "yes_total_cost".to_string();
}
let mut costDollarsKey: String = "no_total_cost_dollars".to_string();
if matches!(&heldYes, Value::Bool(true)) {
costDollarsKey = "yes_total_cost_dollars".to_string();
}
let mut costCents: Value = self.safe_number(settlement.clone(), Value::from(costKey), &[]);
let mut centsCost: Value = Value::Null;
if (costCents != Value::Null) {
centsCost = (match ((costCents).as_f64(), (Value::Int(100)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
let mut cost: Value = self.safe_number(settlement.clone(), Value::from(costDollarsKey), &[centsCost]);
let mut pnl: Value = Value::Null;
if (payout != Value::Null) && (cost != Value::Null) {
pnl = (match (&(payout), &(cost)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
}
let mut ts: Value = self.parse8601(self.safe_string_k(settlement.clone(), "settled_time", &[]));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), settlement);
m.insert("id".to_string(), ticker.map(Value::from).unwrap_or(Value::Null));
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts));
m.insert("outcome".to_string(), self.safe_string_k(mkt.clone(), "outcome", &[heldTicker.clone()]));
m.insert("outcomeId".to_string(), self.safe_string2(mkt.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[heldTicker]));
m.insert("market".to_string(), self.safe_string2(mkt, Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m.insert("event".to_string(), Value::Null);
m.insert("result".to_string(), marketResult.map(Value::from).unwrap_or(Value::Null));
m.insert("won".to_string(), won.clone());
m.insert("amount".to_string(), (if (heldYes).as_bool() == Some(true) { yesCount } else { noCount }));
m.insert("price".to_string(), (if (won).as_bool() == Some(true) { Value::Int(1) } else { Value::Int(0) }));
m.insert("cost".to_string(), cost);
m.insert("payout".to_string(), payout);
m.insert("pnl".to_string(), pnl);
m
});
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parsePredictionPosition
* @description parses a raw kalshi portfolio position into a unified position object
* @param {object} position the raw position object
* @param {object} [market] the outcome object the position belongs to
* @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub fn parse_prediction_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut ticker: Option<String> = self.safe_string_k_opt(position.clone(), "ticker", &[]);
let mut outcomeObj: Value = self.safe_outcome(ticker.clone().map(Value::from).unwrap_or(Value::Null), &[market]);
let mut yesContracts: Value = self.safe_number_k(position.clone(), "position", &[]); // positive = long YES
let mut positionSide: Value = Value::Null;
let mut contractsValue: Value = Value::Null;
if (yesContracts != Value::Null) {
positionSide = (if (yesContracts.as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) { Value::Str("long".into()) } else { Value::Str("short".into()) });
contractsValue = self.parse_number(crate::precise::Precise::stringAbs(&self.number_to_string(yesContracts)), &[]);
}
return self.safe_prediction_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Null);
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[ticker.map(Value::from).unwrap_or(Value::Null)]));
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(outcomeObj, Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("contracts".to_string(), contractsValue);
m.insert("contractSize".to_string(), Value::Int(1));
m.insert("side".to_string(), positionSide);
m.insert("notional".to_string(), Value::Null);
m.insert("leverage".to_string(), Value::Int(1));
m.insert("unrealizedPnl".to_string(), Value::Null);
m.insert("realizedPnl".to_string(), Value::Null);
m.insert("collateral".to_string(), Value::Null);
m.insert("entryPrice".to_string(), Value::Null);
m.insert("markPrice".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Str("cross".into()));
m.insert("marginType".to_string(), Value::Str("cross".into()));
m.insert("percentage".to_string(), Value::Null);
m.insert("info".to_string(), position);
m
}));
Value::Null
}
/*
* @method
* @name kalshi#fetchOpenOrders
* @description fetches resting (open) orders for the authenticated kalshi user, optionally filtered by ticker
* @see https://trading-api.readme.io/reference/getorders
* @param {string} [outcome] filter by unified outcome
* @param {int} [since] timestamp in ms of the earliest order to fetch
* @param {int} [limit] the maximum number of orders to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("resting".into()));
m
});
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
outcomeObj = self.outcome(outcome.clone());
if (outcomeObj == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a valid outcome".into()))));
}
request.insert("ticker".into(), self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]));
}
let __ws_arg_9 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_private_get_portfolio_orders(&[__ws_arg_9]).await;
let mut orders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
return self.parse_prediction_orders(orders, &[outcomeObj, since, limit]);
Value::Null
}
/*
* @method
* @name kalshi#fetchOrders
* @description fetches all orders (resting, executed and canceled) for the authenticated kalshi user
* @see https://trading-api.readme.io/reference/getorders
* @param {string} [outcome] filter by unified outcome
* @param {int} [since] timestamp in ms of the earliest order to fetch
* @param {int} [limit] the maximum number of orders to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
}
// no status filter — the endpoint returns every order; pass params.status to narrow
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
outcomeObj = self.outcome(outcome.clone());
if (outcomeObj == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a valid outcome".into()))));
}
request.insert("ticker".into(), self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]));
}
let __ws_arg_10 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_private_get_portfolio_orders(&[__ws_arg_10]).await;
let mut orders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
return self.parse_prediction_orders(orders, &[outcomeObj, since, limit]);
Value::Null
}
/*
* @method
* @name kalshi#fetchClosedOrders
* @description fetches the closed (executed or canceled) orders for the authenticated kalshi user
* @see https://trading-api.readme.io/reference/getorders
* @param {string} [outcome] filter by unified outcome
* @param {int} [since] timestamp in ms of the earliest order to fetch
* @param {int} [limit] the maximum number of orders to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// kalshi's status filter takes a single value (resting|executed|canceled); "closed" spans
// both executed and canceled, so fetch every order and keep the non-open ones client-side
let mut orders: Value = self.fetch_orders(&[outcome, Value::Null, Value::Null, params]).await;
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1285: bool = true;
while { if !__for_first_1285 { i += 1; } __for_first_1285 = false; i < (orders.len() as i64) } {
let mut order: Value = orders.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut status: Option<String> = self.safe_string_k(order.clone(), "status", &[]).as_str().map(str::to_owned);
if (status.as_deref() == Some("closed")) || (status.as_deref() == Some("canceled")) {
result.push(order);
}
}
}
return self.filter_by_since_limit(Value::from(result), &[since, limit, Value::Str("timestamp".into())]);
Value::Null
}
/*
* @method
* @name kalshi#fetchOrder
* @description fetches a single order by id from the kalshi portfolio endpoint
* @see https://trading-api.readme.io/reference/getorder
* @param {string} id order id
* @param {string} [outcome] unified outcome
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// outcome is only a labelling hint here — the request needs just the id, and
// parsePredictionOrder resolves identity cache-only, so don't force a full market scan
if (outcome != Value::Null) {
self.load_outcome(outcome, &[]).await;
}
let __ws_arg_11 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
}), &[params]);
let mut response: Value = self.kalshi_private_get_portfolio_orders_order_id(&[__ws_arg_11]).await;
return self.parse_prediction_order(self.safe_dict_k(response.clone(), "order", &[response.clone()]), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parsePredictionOrder
* @description parses a raw kalshi order object into a unified order object
* @param {object} order the raw order object
* @param {object} [market] the outcome object the order belongs to
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub fn parse_prediction_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut id: Option<String> = self.safe_string_k_opt(order.clone(), "order_id", &[]);
let mut ticker: Option<String> = self.safe_string_k_opt(order.clone(), "ticker", &[]);
// a kalshi order is leg-specific: the raw `side` field says which leg ('yes'|'no');
// the bare ticker is the YES outcome's id, the NO leg is addressed as `<ticker>-NO`
let mut sideLeg: Option<String> = self.safe_string_lower_k(order.clone(), "side", &[]).as_str().map(str::to_owned);
let mut outcomeKey: Value = ticker.clone().map(Value::from).unwrap_or(Value::Null);
if (sideLeg.as_deref() == Some("no")) && (ticker.is_some()) {
outcomeKey = Value::Str(format!("{}{}", ticker.map(Value::from).unwrap_or(Value::Null), Value::Str("-NO".into())).into());
}
let mut mkt: Value = self.safe_outcome(outcomeKey, &[market]);
let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "status", &[])).map(Value::from).unwrap_or(Value::Null);
// never invent a side: a minimal response (e.g. a DELETE/cancel body) omits `action`,
// and defaulting to 'sell' misreports a canceled buy. leave it undefined when absent.
let mut action: Option<String> = self.safe_string_lower_k(order.clone(), "action", &[]).as_str().map(str::to_owned);
let mut side: Value = Value::Null;
if (action.as_deref() == Some("buy")) {
side = Value::Str("buy".into());
} else if (action.as_deref() == Some("sell")) {
side = Value::Str("sell".into());
}
// price in the outcome's own leg: V2 returns *_price_dollars (already dollars),
// legacy returned yes_price/no_price in cents
let mut labelIsNo: bool = self.safe_string_upper_k(mkt.clone(), "label", &[]).as_str() == Some("NO");
let mut dollarsKey: String = "yes_price_dollars".to_string();
if labelIsNo {
dollarsKey = "no_price_dollars".to_string();
}
let mut centsKey: String = "yes_price".to_string();
if labelIsNo {
centsKey = "no_price".to_string();
}
let mut price: Value = self.safe_number(order.clone(), Value::from(dollarsKey), &[]);
if (price == Value::Null) {
let mut priceCents: Value = self.safe_number(order.clone(), Value::from(centsKey), &[]);
if (priceCents != Value::Null) {
price = (match ((priceCents).as_f64(), (Value::Int(100)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
}
// V2 counts are fixed-point (*_count_fp); legacy used count / filled_count
let mut amount: Value = self.safe_number2(order.clone(), Value::Str("initial_count_fp".into()), Value::Str("count".into()), &[]);
let mut filled: Value = self.safe_number2(order.clone(), Value::Str("fill_count_fp".into()), Value::Str("filled_count".into()), &[Value::Int(0)]);
let mut remaining: Value = self.safe_number_k(order.clone(), "remaining_count_fp", &[]);
if (remaining == Value::Null) && (amount != Value::Null) && (filled != Value::Null) {
remaining = (match (&(amount), &(filled)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
}
let mut ts: Value = self.parse8601(self.safe_string_k(order.clone(), "created_time", &[]));
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
m.insert("clientOrderId".to_string(), self.safe_string_k(order.clone(), "client_order_id", &[]));
m.insert("info".to_string(), order.clone());
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("outcome".to_string(), self.safe_string_k(mkt.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string2(mkt.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("label".to_string(), self.safe_string_k(mkt.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(mkt.clone(), Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m.insert("type".to_string(), self.safe_string_lower_k(order, "type", &[Value::Str("limit".into())]));
m.insert("timeInForce".to_string(), Value::Str("GTC".into()));
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("stopPrice".to_string(), Value::Null);
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), remaining);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m
}), &[mkt]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parseOrderStatus
* @description maps a kalshi order status string to the CCXT unified status vocabulary
* @param {string} status the raw kalshi order status
* @returns {string} the unified order status
*/
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("resting".to_string(), Value::Str("open".into()));
m.insert("executed".to_string(), Value::Str("closed".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("pending".to_string(), Value::Str("open".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name kalshi#createOrder
* @description places a limit or market order on kalshi for the given outcome token
* @see https://trading-api.readme.io/reference/createorder
* @param {string} outcome unified outcome
* @param {string} type 'limit' or 'market'
* @param {string} side 'buy' or 'sell'
* @param {float} amount number of contracts
* @param {float} [price] limit price in dollars (0–1 range)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_order(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// kalshi has no market orders — every order is a limit order and the price is required
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price - kalshi has only limit orders (no market orders). For immediate execution pass an aggressive price with params { 'time_in_force': 'immediate_or_cancel' }".into()))));
}
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut ticker: Option<String> = self.safe_string_opt(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
let mut isNo: bool = self.safe_string_k(outcomeObj.clone(), "label", &[]).as_str() == Some("NO");
let mut isBuy: bool = side.as_str() == Some("buy");
// kalshi V2 (/portfolio/events/orders) quotes the YES leg only: side 'bid' = buy YES,
// 'ask' = sell YES, price in dollars. a NO order maps to the complementary YES order
// buy NO @ q == sell YES @ 1-q - flip the book side and the price
let mut bookSide: Value = Value::Str("ask".into());
if isBuy {
bookSide = Value::Str("bid".into());
}
if isNo {
bookSide = (if (isBuy) { Value::Str("ask".into()) } else { Value::Str("bid".into()) });
}
let mut yesPrice: Value = (if (isNo && (price != Value::Null)) { self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &self.number_to_string(price.clone())), &[]) } else { price.clone() });
let mut isMarket: bool = type_var.as_str() == Some("market");
// accept the unified `timeInForce` and map it onto kalshi's vocabulary; the native
// `time_in_force` param (handled below) still overrides
let mut unifiedTif: Option<String> = self.safe_string_upper_k(params.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
let mut paramsOmitted: Value = self.omit(params, Value::Str("timeInForce".into()), &[]);
let mut defaultTif: String = "good_till_canceled".to_string();
if isMarket {
defaultTif = "immediate_or_cancel".to_string();
}
// kalshi has BOTH immediate_or_cancel (partial ok) and fill_or_kill (all-or-nothing);
// map the unified tokens to the matching primitive rather than collapsing FOK into IOC
if (unifiedTif.as_deref() == Some("IOC")) {
defaultTif = "immediate_or_cancel".to_string();
} else if (unifiedTif.as_deref() == Some("FOK")) {
defaultTif = "fill_or_kill".to_string();
} else if (unifiedTif.as_deref() == Some("GTC")) {
defaultTif = "good_till_canceled".to_string();
}
let timeInForceparamsTimeInForceVariable: Vec<Value> = self.handle_option_string_and_params(paramsOmitted, Value::Str("createOrder".into()), Value::Str("time_in_force".into()), &[Value::from(defaultTif)]).as_array().cloned().unwrap_or_default();
let mut timeInForce: Value = timeInForceparamsTimeInForceVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsTimeInForce: Value = timeInForceparamsTimeInForceVariable.get(1).cloned().unwrap_or(Value::Null);
let stpparamsSelfTradePreventionTypeVariable: Vec<Value> = self.handle_option_string_and_params(paramsTimeInForce, Value::Str("createOrder".into()), Value::Str("self_trade_prevention_type".into()), &[Value::Str("taker_at_cross".into())]).as_array().cloned().unwrap_or_default();
let mut stp: Value = stpparamsSelfTradePreventionTypeVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsSelfTradePreventionType: Value = stpparamsSelfTradePreventionTypeVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.map(Value::from).unwrap_or(Value::Null));
m.insert("side".to_string(), bookSide);
m.insert("count".to_string(), self.number_to_string(amount.clone()));
m.insert("time_in_force".to_string(), timeInForce);
m.insert("self_trade_prevention_type".to_string(), stp);
m
});
if (yesPrice != Value::Null) {
request.insert("price".into(), self.number_to_string(yesPrice));
}
let __ws_arg_12 = self.extend(Value::Map(request), &[paramsSelfTradePreventionType]);
let mut response: Value = self.kalshi_private_post_portfolio_events_orders(&[__ws_arg_12]).await;
// the V2 create response is minimal (order_id, fill_count, remaining_count), so backfill
// the known order details and resolve the status from the remaining count
let mut order: Value = self.parse_prediction_order(response.clone(), &[outcomeObj]);
if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("side".to_string(), side); }
if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("amount".to_string(), amount.clone()); }
if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("price".to_string(), price); }
// the minimal create response reports fills as fill_count/remaining_count (not the *_fp keys
// parsePredictionOrder reads on the fetch path), so backfill filled/remaining from them here —
// otherwise a fully-filled order would return status 'closed' with filled 0
let mut remainingCount: Value = self.safe_number_k(response.clone(), "remaining_count", &[]);
let mut filledCount: Value = self.safe_number_k(response, "fill_count", &[]);
if (filledCount != Value::Null) {
if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("filled".to_string(), filledCount); }
} else if (remainingCount != Value::Null) {
add_element_to_object(&mut order, &Value::Str("filled".into()), (match (&(amount), &(remainingCount)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }));
}
if (remainingCount != Value::Null) {
if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("remaining".to_string(), remainingCount.clone()); }
}
if (self.safe_string_k(order.clone(), "status", &[]) == Value::Null) {
let mut resolvedStatus: String = "open".to_string();
if (remainingCount != Value::Null) && (remainingCount.as_f64() == Some(0.0)) {
resolvedStatus = "closed".to_string();
}
if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("status".to_string(), Value::from(resolvedStatus)); }
}
return order;
Value::Null
}
/*
* @method
* @name kalshi#editOrder
* @description edits a resting order by cancelling it and placing a new one with the updated terms
* @see https://trading-api.readme.io/reference/createorder
* @param {string} id the id of the order to edit
* @param {string} outcome unified outcome
* @param {string} type 'limit' (kalshi has only limit orders)
* @param {string} side 'buy' or 'sell'
* @param {float} [amount] the new number of contracts
* @param {float} [price] the new price (0..1)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn edit_order(&mut self, mut id: Value, mut outcome: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// kalshi has no live amend endpoint (the V1 /amend path is 410 Gone with no V2 replacement),
// so edit = cancel the resting order then place a fresh one with the new terms. validate the
// new order's required inputs BEFORE cancelling so a bad edit doesn't leave the user with the
// order cancelled and nothing to replace it (kalshi is limit-only, so price + amount are required)
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires a price - kalshi has only limit orders".into()))));
}
if (amount == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires an amount".into()))));
}
self.load_outcome(outcome.clone(), &[]).await;
self.cancel_order(id, &[outcome.clone()]).await;
return self.create_order(outcome, type_var, side, amount, &[price, params]).await;
Value::Null
}
/*
* @method
* @name kalshi#cancelOrder
* @description cancels a single open order by id on kalshi
* @see https://trading-api.readme.io/reference/cancelorder
* @param {string} id order id
* @param {string} [outcome] unified outcome
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
outcomeObj = self.load_outcome(outcome, &[]).await;
}
// v2 cancel: DELETE /portfolio/events/orders/{order_id} (the /portfolio/orders/{id}
// and /portfolio/orders/batched paths are deprecated v1 endpoints returning 410 Gone)
let __ws_arg_13 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id.clone());
m
}), &[params]);
let mut response: Value = self.kalshi_private_delete_portfolio_events_orders_order_id(&[__ws_arg_13]).await;
// the delete response is minimal (no ticker/action/id/status): pass the resolved outcome so
// the parser can fill outcome/outcomeId/market/label, then backfill the id and canceled status
let mut order: Value = self.parse_prediction_order(self.safe_dict_k(response.clone(), "order", &[response.clone()]), &[outcomeObj]);
if (self.safe_string_k(order.clone(), "id", &[]) == Value::Null) {
if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("id".to_string(), id); }
}
if (self.safe_string_k(order.clone(), "status", &[]) == Value::Null) {
if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("status".to_string(), Value::Str("canceled".into())); }
}
return order;
Value::Null
}
/*
* @method
* @name kalshi#cancelAllOrders
* @description cancels all open orders on kalshi, optionally scoped to one outcome ticker
* @see https://trading-api.readme.io/reference/cancelorders
* @param {string} [outcome] unified outcome to scope the cancellation to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
}
// kalshi has no "cancel all" / batch-cancel endpoint (the v1 DELETE /portfolio/orders
// and /portfolio/orders/batched paths are 410 Gone) — fetch the resting orders and
// cancel them one by one via the v2 DELETE /portfolio/events/orders/{order_id}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("resting".into()));
m
});
if (outcome != Value::Null) {
let mut outcomeObj: Value = self.outcome(outcome.clone());
request.insert("ticker".into(), self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]));
}
let mut restingResponse: Value = self.kalshi_private_get_portfolio_orders(&[Value::Map(request)]).await;
let mut restingOrders: Vec<Value> = self.safe_list_k(restingResponse, "orders", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut restingOrdersLength: f64 = ((restingOrders.len() as i64) as f64);
let mut canceledOrders: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1286: bool = true;
while { if !__for_first_1286 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1286 = false; i.as_f64().unwrap_or(f64::NAN) < restingOrdersLength } {
let mut restingOrder: Value = restingOrders.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut orderId: Option<String> = self.safe_string_k_opt(restingOrder.clone(), "order_id", &[]);
if (orderId.is_some()) {
let __ws_arg_14 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), orderId.map(Value::from).unwrap_or(Value::Null));
m
}), &[params.clone()]);
self.kalshi_private_delete_portfolio_events_orders_order_id(&[__ws_arg_14]).await;
// the DELETE body is minimal — parse the already-fetched resting order instead, which
// carries the true side/outcome/price/count, then mark it canceled
let mut parsed: Value = self.parse_prediction_order(restingOrder, &[]);
if let Value::Dict(__rda) = &mut parsed { std::sync::Arc::make_mut(__rda).insert("status".to_string(), Value::Str("canceled".into())); }
canceledOrders.push(parsed);
}
}
}
return Value::from(canceledOrders);
Value::Null
}
/*
* @method
* @name kalshi#fetchEvents
* @description fetches kalshi events scoped by a search query, tag, category or series ticker — always live from the API, never from the local cache (it POPULATES the cache for later event()/outcome lookups). the scope decides the endpoint: a free-text `query` hits kalshi's ranked search endpoint and the top `limit` matches are fetched canonically; `tags`/`category` resolve to series via the /series listing then fetch their events; `series_ticker` is used verbatim. `limit` bounds how many events are actually fetched (broad scopes stop early), and any other param is forwarded straight to the /events endpoint.
* @see https://docs.kalshi.com/api-reference/events/get-events
* @param {object} [params] extra parameters specific to the exchange API endpoint (unrecognised keys are forwarded to GET /events)
* @param {string} [params.query] free-text search resolved server-side via kalshi's series search endpoint
* @param {string[]} [params.queries] multiple free-text searches (alternative to query, unioned)
* @param {string} [params.series_ticker] one or more comma-separated kalshi series tickers (e.g. 'KXBTC') — used verbatim, no search
* @param {string[]} [params.tags] kalshi series tags (e.g. ['BTC']) — resolved to series via the /series listing
* @param {string} [params.category] a kalshi series category (e.g. 'Crypto') — resolved to series via the /series listing
* @param {string} [params.status] 'active' | 'inactive' | 'closed', defaults to options.defaultEventStatus
* @param {int} [params.limit] max number of events to return
* @returns {object[]} an array of event structures
*/
pub async fn fetch_events(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
if (queries == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchEvents() missing queries".into()))));
}
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("query".into()), Value::Str("queries".into())]), &[]);
let mut userLimit: Value = self.safe_integer_k(paramsOmitted.clone(), "limit", &[]);
// bound how many events are actually FETCHED (not just returned) so a broad scope like
// category='Crypto' (hundreds of series) doesn't page every one of them
let mut fetchCap: Value = self.safe_integer_k(self.options.clone(), "maxFetchEventsResults", &[Value::Int(100)]);
if (userLimit != Value::Null) {
fetchCap = userLimit;
}
// map the unified status onto the kalshi event status pushed server-side. 'settled'/'resolved'
// map to kalshi's 'settled' (so resolved events ARE discoverable — previously they were
// silently rewritten to 'open'); 'all' sends no filter
let mut requestedStatus: Option<String> = self.safe_string_k(paramsOmitted.clone(), "status", &[self.safe_string(self.options.clone(), Value::Str("defaultEventStatus".into()), &[Value::Str("open".into())])]).as_str().map(str::to_owned);
let mut status: Value = Value::Null;
if (requestedStatus.as_deref() == Some("active")) || (requestedStatus.as_deref() == Some("open")) {
status = Value::Str("open".into());
} else if (requestedStatus.as_deref() == Some("closed")) || (requestedStatus.as_deref() == Some("inactive")) {
status = Value::Str("closed".into());
} else if (requestedStatus.as_deref() == Some("settled")) || (requestedStatus.as_deref() == Some("resolved")) {
status = Value::Str("settled".into());
}
// anything beyond the unified keys is forwarded verbatim to the events endpoint (kalshi filters)
let mut rest: Value = self.omit(paramsOmitted.clone(), Value::from(vec![Value::Str("status".into()), Value::Str("limit".into()), Value::Str("maxPages".into()), Value::Str("sort".into()), Value::Str("searchIn".into()), Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("tags".into()), Value::Str("category".into()), Value::Str("series_ticker".into())]), &[]);
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut eventId: Option<String> = self.safe_string2_opt(paramsOmitted.clone(), Value::Str("eventId".into()), Value::Str("slug".into()), &[]);
let mut rawEvents: Value = Value::from(vec![]);
if queriesLength > ((0i64) as f64) {
// free-text search: ranked events from the search endpoint, top `fetchCap` fetched canonically
rawEvents = self.fetch_events_by_query(queries, fetchCap.clone(), &[rest.clone()]).await;
} else if (eventId.is_some()) {
// kalshi's event id (and slug) is the event_ticker — fetch it directly
let mut fullEvent: Value = self.fetch_raw_event_by_ticker(eventId.clone().map(Value::from).unwrap_or(Value::Null), &[rest.clone()]).await;
rawEvents = Value::from(vec![fullEvent]);
} else {
// tags / category / series_ticker resolve to a set of series; fetch their events, capped
let mut seriesTickers: Value = self.resolve_event_series_tickers(&[paramsOmitted.clone()]).await;
let mut seriesTickersLength: f64 = ((seriesTickers.len() as i64) as f64);
if (seriesTickersLength == 0.0) {
self.require_event_query(&[paramsOmitted.clone()]);
}
rawEvents = self.fetch_series_events(seriesTickers, status, fetchCap, &[rest]).await;
}
let mut rawEventsLength: f64 = ((rawEvents.len() as i64) as f64);
let mut result: Vec<Value> = Vec::new();
{
let mut di: Value = Value::Int(0);
let mut __for_first_1288: bool = true;
while { if !__for_first_1288 { if let Value::Int(n) = &mut di { *n += 1; } } __for_first_1288 = false; di.as_f64().unwrap_or(f64::NAN) < rawEventsLength } {
let mut parsedEvent: indexmap::IndexMap<String, Value> = self.parse_event(rawEvents.as_array().and_then(|__arr| match &di { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)).as_map().cloned().unwrap_or_default();
result.push(Value::Map(parsedEvent.clone()));
// register the parsed markets so populateOutcomes can index their outcomes
let mut parsedMarkets: Value = parsedEvent.get("markets").cloned().unwrap_or(Value::Null);
let mut parsedMarketsLength: f64 = ((parsedMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1287: bool = true;
while { if !__for_first_1287 { if let Value::Int(n) = &mut mi { *n += 1; } } __for_first_1287 = false; mi.as_f64().unwrap_or(f64::NAN) < parsedMarketsLength } {
let mut m: Value = parsedMarkets.as_array().and_then(|__arr| match &mi { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
add_element_to_object(&mut self.markets, &m.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null), m.clone());
}
}
}
}
self.populate_outcomes();
// scoping already happened server-side, so strip the resolved scopes before the client-side
// pass: applyEventFetchParams' tag filter needs an event-level `tags` field kalshi events lack,
// and its query filter would drop a "bitcoin"-searched event whose title only says "BTC"
let mut postParams: Value = self.omit(paramsOmitted, Value::from(vec![Value::Str("tags".into()), Value::Str("category".into()), Value::Str("series_ticker".into())]), &[]);
return self.apply_event_fetch_params(Value::from(result), &[postParams, Value::from(vec![])]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#fetchEventsByQuery
* @description resolves free-text queries to ranked event tickers via kalshi's search endpoint, then fetches the top `limit` events canonically (with nested markets)
* @param {string[]} queries free-text search strings
* @param {int} [limit] max number of events to fetch
* @param {object} [rest] extra params forwarded verbatim to the events endpoint
* @returns {object[]} raw kalshi event objects with nested markets
*/
pub async fn fetch_events_by_query(&mut self, mut queries: Value, mut limit: Value, optional_args: &[Value]) -> Value {
let mut rest = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __queries_empty = Vec::new();
let queries = queries.as_array().unwrap_or(&__queries_empty);
let mut pageSize: Value = (if (limit != Value::Null) { limit.clone() } else { self.safe_integer_k(self.options.clone(), "searchSeriesLimit", &[Value::Int(25)]) });
// free-text query -> kalshi's series search endpoint (elections web host, ranked server-side)
let mut seen: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut eventTickers: Vec<Value> = Vec::new();
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
{
let mut qi: Value = Value::Int(0);
let mut __for_first_1290: bool = true;
while { if !__for_first_1290 { if let Value::Int(n) = &mut qi { *n += 1; } } __for_first_1290 = false; qi.as_f64().unwrap_or(f64::NAN) < queriesLength } {
let mut searchResponse: Value = self.elections_public_get_search_series(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("query".to_string(), queries.get((qi).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
m.insert("order_by".to_string(), Value::Str("querymatch".into()));
m.insert("page_size".to_string(), pageSize.clone());
m
})]).await;
let mut page: Vec<Value> = self.safe_list_k(searchResponse, "current_page", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut pageLength: f64 = ((page.len() as i64) as f64);
{
let mut pi: Value = Value::Int(0);
let mut __for_first_1289: bool = true;
while { if !__for_first_1289 { if let Value::Int(n) = &mut pi { *n += 1; } } __for_first_1289 = false; pi.as_f64().unwrap_or(f64::NAN) < pageLength } {
let mut et: Option<String> = self.safe_string_opt(page.get(pi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), Value::Str("event_ticker".into()), &[]);
if (et.is_some()) {
let mut already: Option<String> = self.safe_string(Value::Map(seen.clone()), et.clone().map(Value::from).unwrap_or(Value::Null), &[]).as_str().map(str::to_owned);
if (already.is_none()) {
seen.insert(et.as_deref().unwrap_or("null").to_string(), et.clone().map(Value::from).unwrap_or(Value::Null));
eventTickers.push(et.map(Value::from).unwrap_or(Value::Null));
}
}
}
}
}
}
let mut rawEvents: Vec<Value> = Vec::new();
let mut eventTickersLength: f64 = ((eventTickers.len() as i64) as f64);
let mut hasLimit: bool = limit != Value::Null;
let mut limitOrZero: Value = (if hasLimit { limit } else { Value::Int(0) });
let mut limitValue: Value = self.parse_to_int(limitOrZero);
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1291: bool = true;
while { if !__for_first_1291 { if let Value::Int(n) = &mut ei { *n += 1; } } __for_first_1291 = false; ei.as_f64().unwrap_or(f64::NAN) < eventTickersLength } {
let mut collectedLength: f64 = ((rawEvents.len() as i64) as f64);
if hasLimit && (collectedLength >= limitValue.as_f64().unwrap_or(f64::NAN)) {
break;
}
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut fullEvent: Value = self.fetch_raw_event_by_ticker(eventTickers.get((ei).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[rest.clone()]).await;
rawEvents.push(fullEvent);
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if !(matches!(&e, Value::Str(__s) if __s.contains("[BadSymbol]"))) {
panic!("{}", e);
}
}
}
}
return Value::from(rawEvents);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#fetchRawEventByTicker
* @description fetches a single raw kalshi event object (with nested markets) by its event ticker
* @param {string} ticker the kalshi event ticker
* @param {object} [params] extra params forwarded verbatim to the events endpoint
* @returns {object} the raw kalshi event object with nested markets
*/
pub async fn fetch_raw_event_by_ticker(&mut self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("event_ticker".to_string(), ticker);
m.insert("with_nested_markets".to_string(), Value::Bool(true));
m
});
let __ws_arg_15 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.kalshi_public_get_events_event_ticker(&[__ws_arg_15]).await;
// a typed copy of the event row: the caller-facing dict is never the raw response
let __ws_arg_16 = self.safe_dict_k(response.clone(), "event", &[response.clone()]);
let mut fullEvent: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[__ws_arg_16]);
let mut nestedMarkets: Value = self.safe_list_k(fullEvent.clone(), "markets", &[]);
if (nestedMarkets == Value::Null) {
add_element_to_object(&mut fullEvent, &Value::Str("markets".into()), self.safe_list_k(response, "markets", &[Value::from(vec![])]));
}
return fullEvent;
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#resolveEventSeriesTickers
* @description resolves a fetchEvents scope (tags, category or series_ticker) to a deduplicated list of kalshi series tickers, preserving discovery order
* @param {object} [params] the fetchEvents params carrying tags / category / series_ticker
* @returns {string[]} deduplicated series tickers
*/
pub async fn resolve_event_series_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __params_empty = indexmap::IndexMap::new();
let params = params.as_map().unwrap_or(&__params_empty);
let mut collected: Value = Value::from(vec![]);
// tags / category -> documented /series listing
let mut tags: Vec<Value> = (match params.get("tags") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) }).as_array().cloned().unwrap_or_default();
let mut tagsLength: f64 = ((tags.len() as i64) as f64);
{
let mut ti: Value = Value::Int(0);
let mut __for_first_1293: bool = true;
while { if !__for_first_1293 { if let Value::Int(n) = &mut ti { *n += 1; } } __for_first_1293 = false; ti.as_f64().unwrap_or(f64::NAN) < tagsLength } {
let mut seriesResponse: Value = self.kalshi_public_get_series(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tags".to_string(), tags.get(ti.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
m
})]).await;
let mut seriesList: Value = self.safe_list_k(seriesResponse.clone(), "series", &[Value::from(vec![])]);
let mut seriesListLength: f64 = ((seriesList.len() as i64) as f64);
{
let mut si: Value = Value::Int(0);
let mut __for_first_1292: bool = true;
while { if !__for_first_1292 { if let Value::Int(n) = &mut si { *n += 1; } } __for_first_1292 = false; si.as_f64().unwrap_or(f64::NAN) < seriesListLength } {
let mut st: Option<String> = self.safe_string_opt(seriesList.as_array().and_then(|__arr| match &si { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
if (st.is_some()) {
if let Value::Arr(__a) = &mut collected { std::sync::Arc::make_mut(__a).push(st.map(Value::from).unwrap_or(Value::Null)); }
}
}
}
}
}
let mut category: Value = (match params.get("category") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (category != Value::Null) {
let mut seriesResponse: Value = self.kalshi_public_get_series(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("category".to_string(), category);
m
})]).await;
let mut seriesList: Value = self.safe_list_k(seriesResponse, "series", &[Value::from(vec![])]);
let mut seriesListLength: f64 = ((seriesList.len() as i64) as f64);
{
let mut si: Value = Value::Int(0);
let mut __for_first_1294: bool = true;
while { if !__for_first_1294 { if let Value::Int(n) = &mut si { *n += 1; } } __for_first_1294 = false; si.as_f64().unwrap_or(f64::NAN) < seriesListLength } {
let mut st: Option<String> = self.safe_string_opt(seriesList.as_array().and_then(|__arr| match &si { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
if (st.is_some()) {
if let Value::Arr(__a) = &mut collected { std::sync::Arc::make_mut(__a).push(st.map(Value::from).unwrap_or(Value::Null)); }
}
}
}
}
// explicit series_ticker(s) — comma-separated accepted, used verbatim
let mut seriesParam: Value = (match params.get("series_ticker") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (seriesParam != Value::Null) {
let mut parts: Vec<Value> = Value::Array(if let Some(__s) = seriesParam.as_str() { __s.split(",").map(Value::from).collect() } else { Vec::new() }).as_array().cloned().unwrap_or_default();
let mut partsLength: f64 = ((parts.len() as i64) as f64);
{
let mut pi: Value = Value::Int(0);
let mut __for_first_1295: bool = true;
while { if !__for_first_1295 { if let Value::Int(n) = &mut pi { *n += 1; } } __for_first_1295 = false; pi.as_f64().unwrap_or(f64::NAN) < partsLength } {
if let Value::Arr(__a) = &mut collected { std::sync::Arc::make_mut(__a).push(parts.get(pi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)); }
}
}
}
// deduplicate preserving order
let mut seen: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut ordered: Vec<Value> = Vec::new();
let mut collectedLength: f64 = ((collected.len() as i64) as f64);
{
let mut ci: Value = Value::Int(0);
let mut __for_first_1296: bool = true;
while { if !__for_first_1296 { if let Value::Int(n) = &mut ci { *n += 1; } } __for_first_1296 = false; ci.as_f64().unwrap_or(f64::NAN) < collectedLength } {
let mut st: Option<String> = self.safe_string_opt(collected.clone(), ci.clone(), &[]);
let mut already: Option<String> = self.safe_string(Value::Map(seen.clone()), st.clone().map(Value::from).unwrap_or(Value::Null), &[]).as_str().map(str::to_owned);
if (st.is_some()) && (st.as_deref() != Some("")) && (already.is_none()) {
seen.insert(st.as_deref().unwrap_or("null").to_string(), st.clone().map(Value::from).unwrap_or(Value::Null));
ordered.push(st.map(Value::from).unwrap_or(Value::Null));
}
}
}
return Value::from(ordered);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#fetchSeriesEvents
* @description fetches the canonical events (with nested markets) of the given kalshi series, cursor-paginated per series and stopping once `limit` events are gathered
* @param {string[]} seriesTickers the series to fetch events for
* @param {string} status the kalshi event status ('open' | 'closed')
* @param {int} [limit] stop fetching once this many events are gathered
* @param {object} [rest] extra params forwarded verbatim to the events endpoint
* @returns {object[]} raw kalshi event objects with nested markets
*/
pub async fn fetch_series_events(&mut self, mut seriesTickers: Value, mut status: Value, mut limit: Value, optional_args: &[Value]) -> Value {
let mut rest = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __seriesTickers_empty = Vec::new();
let seriesTickers = seriesTickers.as_array().unwrap_or(&__seriesTickers_empty);
let mut rawEvents: Vec<Value> = Vec::new();
let mut seriesTickersLength: f64 = ((seriesTickers.len() as i64) as f64);
let mut pageLimit: Value = self.parse_to_int(self.safe_integer_k(self.options.clone(), "defaultFetchEventsLimit", &[Value::Int(200)]));
let mut maxPages: Value = self.safe_integer_k(self.options.clone(), "maxEventPagesPerSeries", &[Value::Int(20)]);
let mut hasLimit: bool = limit != Value::Null;
let mut limitOrZero: Value = (if hasLimit { limit } else { Value::Int(0) });
let mut limitValue: Value = self.parse_to_int(limitOrZero);
{
let mut si: Value = Value::Int(0);
let mut __for_first_1299: bool = true;
while { if !__for_first_1299 { if let Value::Int(n) = &mut si { *n += 1; } } __for_first_1299 = false; si.as_f64().unwrap_or(f64::NAN) < seriesTickersLength } {
let mut collectedLength: f64 = ((rawEvents.len() as i64) as f64);
if hasLimit && (collectedLength >= limitValue.as_f64().unwrap_or(f64::NAN)) {
break;
}
let mut cursor: Value = Value::Null;
{
let mut page: Value = Value::Int(0);
let mut __for_first_1298: bool = true;
while { if !__for_first_1298 { if let Value::Int(n) = &mut page { *n += 1; } } __for_first_1298 = false; page.as_f64().unwrap_or(f64::NAN) < maxPages.as_f64().unwrap_or(f64::NAN) } {
let mut reqLimit: Value = pageLimit.clone();
if hasLimit && (limitValue != Value::Null) {
let mut collectedSoFar: Value = Value::Int(rawEvents.len() as i64);
let mut remaining: Value = self.parse_to_int((match (&(limitValue), &(collectedSoFar)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }));
if remaining.as_f64().unwrap_or(f64::NAN) < reqLimit.as_f64().unwrap_or(f64::NAN) {
reqLimit = remaining;
}
if reqLimit.as_f64().unwrap_or(f64::NAN) <= ((0i64) as f64) {
break;
}
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("series_ticker".to_string(), seriesTickers.get((si).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
m.insert("status".to_string(), status.clone());
m.insert("with_nested_markets".to_string(), Value::Bool(true));
m.insert("limit".to_string(), reqLimit.clone());
m
});
if (cursor != Value::Null) {
request.insert("cursor".into(), cursor.clone());
}
let __ws_arg_17 = self.extend(Value::Map(request), &[rest.clone()]);
let mut response: Value = self.kalshi_public_get_events(&[__ws_arg_17]).await;
let mut pageEvents: Vec<Value> = self.safe_list_k(response.clone(), "events", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut pageEventsLength: f64 = ((pageEvents.len() as i64) as f64);
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1297: bool = true;
while { if !__for_first_1297 { if let Value::Int(n) = &mut ei { *n += 1; } } __for_first_1297 = false; ei.as_f64().unwrap_or(f64::NAN) < pageEventsLength } {
rawEvents.push(pageEvents.get(ei.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
}
}
cursor = self.safe_string_k(response, "cursor", &[]);
let mut collectedAfterPage: f64 = ((rawEvents.len() as i64) as f64);
if hasLimit && (collectedAfterPage >= limitValue.as_f64().unwrap_or(f64::NAN)) {
break;
}
if (cursor == Value::Null) || (cursor.as_str() == Some("")) || (pageEventsLength < reqLimit.as_f64().unwrap_or(f64::NAN)) {
break;
}
}
}
}
}
return Value::from(rawEvents);
Value::Null
}
/*
* @method
* @name kalshi#fetchEvent
* @description fetches a single prediction-market event by its event ticker
* @see https://trading-api.readme.io/reference/getevent
* @param {string} id the event ticker
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction event structure](https://docs.ccxt.com/#/?id=prediction-event-structure)
*/
pub async fn fetch_event(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut fullEvent: Value = self.fetch_raw_event_by_ticker(id, &[params]).await;
let mut event: Value = self.parse_event(fullEvent);
self.index_event_outcomes(event.clone());
return event;
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#parseEvent
* @description parses a raw kalshi event object (with nested markets) into the unified CCXT event shape
* @param {object} rawEvent the raw event object
* @returns {object} an event structure
*/
pub fn parse_event(&self, mut rawEvent: Value) -> Value {
// {
// "available_on_brokers": true,
// "category": "Politics",
// "collateral_return_type": "",
// "event_ticker": "KXBALANCE-29",
// "last_updated_ts": "0001-01-01T00:00:00Z",
// "markets": [
// {
// "can_close_early": true,
// "close_time": "2029-07-01T14:00:00Z",
// "created_time": "0001-01-01T00:00:00Z",
// "early_close_condition": "This market will close and expire early if the event occurs.",
// "event_ticker": "KXBALANCE-29",
// "expected_expiration_time": "2029-07-01T14:00:00Z",
// "expiration_time": "2029-07-01T14:00:00Z",
// "expiration_value": "",
// "fractional_trading_enabled": false,
// "last_price_dollars": "0.1000",
// "latest_expiration_time": "2029-07-01T14:00:00Z",
// "liquidity_dollars": "0.0000",
// "market_type": "binary",
// "no_ask_dollars": "0.9000",
// "no_bid_dollars": "0.8900",
// "no_sub_title": "During Trump's term",
// "notional_value_dollars": "1.0000",
// "open_interest_fp": "16268.00",
// "open_time": "2025-01-03T15:00:00Z",
// "previous_price_dollars": "0.0000",
// "previous_yes_ask_dollars": "0.0000",
// "previous_yes_bid_dollars": "0.0000",
// "price_level_structure": "linear_cent",
// "price_ranges": [
// {
// "end": "1.0000",
// "start": "0.0000",
// "step": "0.0100"
// }
// ],
// "response_price_units": "usd_cent",
// "result": "",
// "rules_primary": "If there is not a budget deficit for any of fiscal years 2025, 2026, 2027, or 2028, then the market resolves to Yes.",
// "rules_secondary": "",
// "settlement_timer_seconds": "1800",
// "status": "active",
// "subtitle": "",
// "tick_size": "1",
// "ticker": "KXBALANCE-29",
// "title": "Will Trump balance the budget?",
// "updated_time": "0001-01-01T00:00:00Z",
// "volume_24h_fp": "28.00",
// "volume_fp": "40111.00",
// "yes_ask_dollars": "0.1100",
// "yes_ask_size_fp": "",
// "yes_bid_dollars": "0.1000",
// "yes_bid_size_fp": "",
// "yes_sub_title": "During Trump's term"
// }
// ],
// "mutually_exclusive": false,
// "series_ticker": "KXBALANCE",
// "strike_period": "",
// "sub_title": "During Trump's term",
// "title": "Will Trump balance the budget?"
// }
let mut rawMarkets: Value = self.safe_list_k(rawEvent.clone(), "markets", &[Value::from(vec![])]);
let mut marketsList: Vec<Value> = Vec::new();
// aggregate volume/liquidity from the markets and derive the creation time so sort works;
// kalshi event payloads carry no status/end_date_iso/resolved of their own, so active,
// resolved and the resolution deadline are aggregated from the child markets too
let mut totalVolume: Value = Value::Int(0);
let mut totalLiquidity: Value = Value::Int(0);
// seeded from the first market, which the loop re-reads, so the min/max stays the same
let mut firstMarket: Value = self.safe_dict(rawMarkets.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut earliestCreated: Value = self.parse8601(self.safe_string_k(firstMarket.clone(), "open_time", &[]));
let mut anyActive: Value = Value::Bool(false);
let mut allResolved: Value = Value::Bool(true);
let mut latestClose: Value = self.parse8601(self.safe_string_k(firstMarket, "close_time", &[]));
{
let mut i: i64 = 0;
let mut __for_first_1300: bool = true;
while { if !__for_first_1300 { i += 1; } __for_first_1300 = false; i < (rawMarkets.len() as i64) } {
let mut rawMarket: Value = rawMarkets.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut parsed: Value = self.parse_market(rawMarket.clone());
marketsList.push(parsed);
totalVolume = self.sum(&[totalVolume.clone(), self.safe_number2(rawMarket.clone(), Value::Str("volume_fp".into()), Value::Str("volume".into()), &[Value::Int(0)])]);
totalLiquidity = self.sum(&[totalLiquidity.clone(), self.safe_number2(rawMarket.clone(), Value::Str("liquidity_dollars".into()), Value::Str("liquidity".into()), &[Value::Int(0)])]);
let mut marketCreated: Value = self.parse8601(self.safe_string_k(rawMarket.clone(), "open_time", &[]));
if (marketCreated != Value::Null) && ((earliestCreated == Value::Null) || (marketCreated.as_f64().unwrap_or(f64::NAN) < earliestCreated.as_f64().unwrap_or(f64::NAN))) {
earliestCreated = marketCreated;
}
let mut marketStatus: Option<String> = self.safe_string_k(rawMarket.clone(), "status", &[]).as_str().map(str::to_owned);
if (marketStatus.as_deref() == Some("active")) {
anyActive = Value::Bool(true);
}
let mut marketResult: Option<String> = self.safe_string_k(rawMarket.clone(), "result", &[]).as_str().map(str::to_owned);
let mut marketResolved: bool = (marketStatus.as_deref() == Some("settled")) || ((marketResult.is_some()) && (marketResult.as_deref() != Some("")));
if !marketResolved {
allResolved = Value::Bool(false);
}
let mut marketClose: Value = self.parse8601(self.safe_string_k(rawMarket, "close_time", &[]));
if (marketClose != Value::Null) && ((latestClose == Value::Null) || (marketClose.as_f64().unwrap_or(f64::NAN) > latestClose.as_f64().unwrap_or(f64::NAN))) {
latestClose = marketClose;
}
}
}
// the aggregates only mean something when the payload nested any markets at all
let mut marketsCount: f64 = ((marketsList.len() as i64) as f64);
let mut active: Value = Value::Null;
if marketsCount > ((0i64) as f64) {
active = anyActive;
}
let mut resolved: Value = self.safe_bool_k(rawEvent.clone(), "resolved", &[]);
if (resolved == Value::Null) && (marketsCount > ((0i64) as f64)) {
resolved = allResolved;
}
let mut end: Value = self.parse8601(self.safe_string_k(rawEvent.clone(), "end_date_iso", &[]));
if (end == Value::Null) {
end = latestClose;
}
let mut ticker: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "event_ticker", &[]);
let mut title: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "title", &[]);
let mut hasTitle: bool = (title.is_some()) && (title.as_deref() != Some(""));
let mut eventSlug: Value = Value::Null;
if hasTitle {
eventSlug = self.shorten_slug(title.clone().map(Value::from).unwrap_or(Value::Null));
}
let mut created: Value = self.parse8601(self.safe_string_k(rawEvent.clone(), "created_date_iso", &[]));
if (created == Value::Null) {
created = earliestCreated;
}
let __ws_arg_18 = self.safe_string_k(rawEvent.clone(), "url", &[]);
let __ws_arg_19 = self.safe_string_k(rawEvent.clone(), "image_url", &[]);
let __ws_arg_20 = self.safe_string_k(rawEvent.clone(), "created_date_iso", &[]);
let __ws_arg_21 = self.iso8601(end.clone());
let __ws_arg_22 = self.safe_string_k(rawEvent.clone(), "category", &[]);
let __ws_arg_23 = self.parse8601(self.safe_string_k(rawEvent.clone(), "last_updated_date_iso", &[]));
let __ws_arg_24 = self.safe_string_k(rawEvent.clone(), "last_updated_date_iso", &[]);
let __ws_arg_25 = self.safe_string_k(rawEvent.clone(), "resolution_source", &[]);
return self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), ticker.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("slug".to_string(), ticker.map(Value::from).unwrap_or(Value::Null));
m.insert("event".to_string(), eventSlug);
m.insert("title".to_string(), title.map(Value::from).unwrap_or(Value::Null));
m.insert("markets".to_string(), Value::from(marketsList));
m.insert("volume".to_string(), totalVolume);
m.insert("liquidity".to_string(), totalLiquidity);
m.insert("url".to_string(), __ws_arg_18);
m.insert("image".to_string(), __ws_arg_19);
m.insert("created".to_string(), created);
m.insert("createdDatetime".to_string(), __ws_arg_20);
m.insert("end".to_string(), end);
m.insert("endDatetime".to_string(), __ws_arg_21);
m.insert("category".to_string(), __ws_arg_22);
m.insert("lastUpdatedAt".to_string(), __ws_arg_23);
m.insert("lastUpdatedAtDatetime".to_string(), __ws_arg_24);
m.insert("resolutionSource".to_string(), __ws_arg_25);
m.insert("active".to_string(), active);
m.insert("resolved".to_string(), resolved);
m.insert("info".to_string(), rawEvent);
m
}), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name kalshi#sign
* @description builds the request URL and attaches RSA-PSS SHA-256 authentication headers for private endpoints
* @param {string} path the endpoint path
* @param {string|string[]} [api] the api group and access level
* @param {string} [method] HTTP method
* @param {object} [params] request parameters
* @returns {object} a dictionary with url, method, body and headers
*/
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("kalshi".into())]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiGroup: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut access: Option<String> = api.get(1).and_then(Value::as_str).map(str::to_owned);
let mut baseUrls: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null);
let mut baseUrl: Value = self.safe_string(baseUrls.clone(), apiGroup, &[self.safe_string_k(baseUrls.clone(), "kalshi", &[Value::Str("".into())])]);
let mut implodedPath: Value = self.implode_params(path.clone(), params.clone());
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseUrl, Value::Str("/".into())).into()), implodedPath).into());
let mut query: Value = self.omit(params, self.extract_params(path), &[]);
let mut querystring: Value = self.urlencode(query.clone(), &[]);
if (method.as_str() == Some("GET")) && (querystring.as_str() != Some("")) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), querystring).into())).into());
}
let mut existingHeaders: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut headersValue: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Accept".to_string(), Value::Str("application/json".into()));
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m
}), &[Value::Map(existingHeaders)]);
let mut bodyValue: Value = Value::Null;
if (access.as_deref() == Some("private")) {
self.check_required_credentials(&[]);
let mut timestamp: Value = Value::Str(format!("{}", self.milliseconds()).into());
// Signing payload: {timestamp}{METHOD}{path}, where path is the full request path
// INCLUDING the /trade-api/v2 prefix and any path params substituted in, but NOT
// the query string (e.g. /trade-api/v2/portfolio/orders/{order_id})
let mut tradeApiIndex: Value = Value::Int(baseUrl.as_str().and_then(|__s| __s.find("/trade-api")).map(|__i| __i as i64).unwrap_or(-1));
let mut versionPrefix: Value = (match (&(baseUrl), (match &(tradeApiIndex) { Value::Int(__n) => Some(*__n), Value::Float(__f) => Some(*__f as i64), Value::Str(__s) => __s.parse::<i64>().ok(), Value::Bool(__b) => Some(if *__b { 1 } else { 0 }), _ => None }).unwrap_or(0), (match &(Value::Null) { Value::Int(__n) => Some(*__n),
Value::Float(__f) => Some(*__f as i64), Value::Str(__s) => __s.parse::<i64>().ok(), Value::Bool(__b) => Some(if *__b { 1 } else { 0 }), _ => None })) { (Value::Str(__sv), __b, __e) => match (__sv.chars().count() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l,
Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i, __j) => if __i <= __j { Value::Str(__sv.chars().skip(__i as usize).take((__j - __i) as usize).collect::<String>().into()) } else { Value::Str(String::new().into()) } } }, (Value::Arr(__a), __b,
__e) => match (__a.len() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l, Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i, __j) => if __i <= __j { Value::Array(__a[__i as usize..__j as usize].to_vec()) } else { Value::Array(vec![]) } } }, _ => Value::Null });
let mut pathForSigning: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", versionPrefix, Value::Str("/".into())).into()), implodedPath).into());
let mut payload: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", timestamp, method).into()), pathForSigning).into());
// RSA-PSS SHA-256 signature with the private key PEM
let mut keyParts: Value = Value::Array(if let Some(__s) = self.privateKey.as_str() { __s.split("\\n").map(Value::from).collect() } else { Vec::new() });
let mut cleanPrivateKey: Value = Value::Str(keyParts.as_array().map(|__a| __a.iter().map(|__v| __v.to_string()).collect::<Vec<String>>().join("\n")).unwrap_or_default().into());
let mut signature: Value = rsa(payload, cleanPrivateKey, Value::Str("sha256".into()));
headersValue = self.extend(headersValue.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("KALSHI-ACCESS-KEY".to_string(), self.apiKey.clone());
m.insert("KALSHI-ACCESS-SIGNATURE".to_string(), signature);
m.insert("KALSHI-ACCESS-TIMESTAMP".to_string(), timestamp);
m
})]);
if (method.as_str() != Some("GET")) && (querystring.as_str() != Some("")) {
// kalshi expects a JSON body; the signature covers only timestamp+method+path
bodyValue = json_stringify(&query);
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), bodyValue);
m.insert("headers".to_string(), headersValue);
m
});
Value::Null
}
}