// 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()).clone());
m.insert("invalid_order".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("fill_or_kill_insufficient_resting_volume".to_string(), Value::Str("OrderNotFillable".into()).clone());
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: Value = self.parse_search_queries(&[params.clone()]);
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: Value = Value::from(vec![]);
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1232: bool = true;
while { if !__for_first_1232 { ei = (match (&(ei), &(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 }); } __for_first_1232 = false; ei.as_f64().unwrap_or(f64::NAN) < eventsLength } {
let mut eventMarkets: 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![])]);
let mut eventMarketsLength: f64 = ((eventMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1231: bool = true;
while { if !__for_first_1231 { mi = (match (&(mi), &(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 }); } __for_first_1231 = false; mi.as_f64().unwrap_or(f64::NAN) < eventMarketsLength } {
append_to_array(&mut queryMarkets, eventMarkets.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));
}
}
}
}
return 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: Value = Value::from(vec![]);
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 = crate::runtime::Math::min(&maxMarkets, &pageLimit);
// 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: Value = Value::Map({
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) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("cursor".into(), cursor.clone()); }
}
let __ws_arg_0 = self.extend(request, &[rest.clone()]);
let mut response: Value = self.kalshi_public_get_markets(&[__ws_arg_0]).await;
let mut rawMarkets: Value = self.safe_list_k(response.clone(), "markets", &[Value::from(vec![])]);
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1234: bool = true;
while { if !__for_first_1234 { i = (match (&(i), &(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 }); } __for_first_1234 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawMarkets.len() as i64) as f64) } {
let mut raw: Value = rawMarkets.as_array().and_then(|__arr| match &i { 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);
let mut parsed: Value = self.parse_binary_market_to_outcomes(raw.clone());
let mut eventTicker: Value = self.safe_string_k(raw.clone(), "event_ticker", &[]);
let mut eventTitle: Value = self.safe_string_k(raw, "title", &[eventTicker.clone()]);
let mut eventKey: Value = Value::Null;
if (eventTitle != Value::Null) && (eventTitle.as_str() != Some("")) {
eventKey = self.shorten_slug(eventTitle.clone());
}
{
let mut j: Value = Value::Int(0);
let mut __for_first_1233: bool = true;
while { if !__for_first_1233 { j = (match (&(j), &(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 }); } __for_first_1233 = false; j.as_f64().unwrap_or(f64::NAN) < ((parsed.len() as i64) as f64) } {
let mut m: Value = parsed.as_array().and_then(|__arr| match &j { 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);
append_to_array(&mut flatMarkets, m.clone());
if (eventKey != Value::Null) && (eventKey.as_str() != Some("")) {
if !(in_op(&eventsDict, &eventKey)) {
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());
m.insert("slug".to_string(), eventTicker.clone());
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 = eventsDict.as_map().and_then(|__m| eventKey.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(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");
append_to_array(&mut entryMarkets, 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(flatMarkets.clone(), Value::Int(0), &[maxMarkets]);
}
return 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 Value::Int(outcomeSymbol.as_str().and_then(|__s| __s.find(":")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
// parseToInt-wrapped .length: the bare `const n = str.length;` statement is the php
// transpiler's ARRAY hint (count()), and `.length` inline inside slice() args breaks
// the python transpiler — this form emits strlen()/len() correctly in both
let mut symbolLength: Value = self.parse_to_int(Value::Int(outcomeSymbol.len() as i64));
let mut suffix: Value = slice(&outcomeSymbol, &(match (&(symbolLength), &(Value::Int(3))) { (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::Null);
let mut isNo: bool = suffix.as_str() == Some("-NO");
let mut baseTicker: Value = outcomeSymbol.clone();
if isNo {
baseTicker = slice(&outcomeSymbol, &Value::Int(0), &(match (&(symbolLength), &(Value::Int(3))) { (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 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 = split(&outcomeSymbol, &Value::Str(":".into()));
let mut marketPart: Value = self.safe_string(handleParts, Value::Int(0), &[Value::Str("".into())]);
let mut parts: Value = split(&marketPart, &Value::Str("_".into()));
let mut seriesTicker: Value = self.safe_string(parts, Value::Int(0), &[]);
if (seriesTicker != Value::Null) && (seriesTicker.as_str() != 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);
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 is_true(&self.has_outcome(outcomeSymbol.clone())) {
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 mut tickers: Value = Value::from(vec![]);
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1235: bool = true;
while { if !__for_first_1235 { i = (match (&(i), &(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 }); } __for_first_1235 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomeSymbols.len() as i64) as f64) } {
let mut outcomeSymbol: Value = outcomeSymbols.as_array().and_then(|__arr| match &i { 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);
if Value::Int(outcomeSymbol.as_str().and_then(|__s| __s.find(":")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
continue;
}
// parseToInt-wrapped .length — see the fetchOutcome comment (php count()/python slice traps)
let mut symbolLength: Value = self.parse_to_int(Value::Int(outcomeSymbol.len() as i64));
let mut suffix: Value = slice(&outcomeSymbol, &(match (&(symbolLength), &(Value::Int(3))) { (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::Null);
let mut baseTicker: Value = outcomeSymbol.clone();
if (suffix.as_str() == Some("-NO")) {
baseTicker = slice(&outcomeSymbol, &Value::Int(0), &(match (&(symbolLength), &(Value::Int(3))) { (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 !(in_op(&seen, &baseTicker)) {
if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&baseTicker), Value::Bool(true)); }
append_to_array(&mut tickers, 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 startIndex: Value = Value::Int(0);
while startIndex.as_f64().unwrap_or(f64::NAN) < tickersLength.as_f64().unwrap_or(f64::NAN) {
let mut endIndex: Value = self.sum(&[startIndex.clone(), chunkSize.clone()]);
if endIndex.as_f64().unwrap_or(f64::NAN) > tickersLength.as_f64().unwrap_or(f64::NAN) {
endIndex = tickersLength.clone();
}
let mut chunk: Value = Value::from(vec![]);
{
let mut i: Value = startIndex.clone();
let mut __for_first_1236: bool = true;
while { if !__for_first_1236 { i = (match (&(i), &(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 }); } __for_first_1236 = false; i.as_f64().unwrap_or(f64::NAN) < endIndex.as_f64().unwrap_or(f64::NAN) } {
append_to_array(&mut chunk, get_value(&tickers, &i));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tickers".to_string(), join(&chunk, &Value::Str(",".into())));
m.insert("limit".to_string(), chunkSize.clone());
m
});
let mut response: Value = self.kalshi_public_get_markets(&[request]).await;
let mut rawMarkets: Value = self.safe_list_k(response, "markets", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1237: bool = true;
while { if !__for_first_1237 { i = (match (&(i), &(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 }); } __for_first_1237 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawMarkets.len() as i64) as f64) } {
let mut parsed: Value = self.parse_market(rawMarkets.as_array().and_then(|__arr| match &i { 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));
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);
}
}
startIndex = self.sum(&[startIndex.clone(), chunkSize.clone()]);
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1238: bool = true;
while { if !__for_first_1238 { i = (match (&(i), &(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 }); } __for_first_1238 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomeSymbols.len() as i64) as f64) } {
if !is_true(&self.has_outcome(outcomeSymbols.as_array().and_then(|__arr| match &i { 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))) {
self.fetch_outcome(outcomeSymbols.as_array().and_then(|__arr| match &i { 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)).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: Value = self.safe_string_k(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(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorCode, 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: Value = self.safe_string_k(raw.clone(), "ticker", &[]);
let mut eventTicker: Value = self.safe_string_k(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: Value = self.safe_string_lower_k(raw.clone(), "result", &[]);
let mut resolved: Value = Value::Bool((status.as_deref() == Some("settled")) || ((result != Value::Null) && (result.as_str() != Some(""))));
let mut endDate: Value = self.safe_string_k(raw.clone(), "expiration_time", &[]);
let mut volume: Value = self.safe_number2(raw.clone(), Value::Str("volume_fp".into()), Value::Str("volume".into()), &[]);
let mut liquidity: Value = self.safe_number2(raw.clone(), Value::Str("liquidity_dollars".into()), Value::Str("liquidity".into()), &[]);
let mut openInt: Value = self.safe_number2(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 eventParts: Value = Value::from(vec![]);
if (eventTicker != Value::Null) && (eventTicker.as_str() != Some("")) {
eventParts = split(&eventTicker, &Value::Str("-".into()));
}
let mut seriesTicker: Value = eventTicker.clone();
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 = join(&seriesParts, &Value::Str("-".into()));
}
// market symbol (no outcome suffix)
let mut subtitleOrTicker: Value = ticker.clone();
if (subtitle != Value::Null) {
subtitleOrTicker = subtitle.clone();
}
let mut marketSymbol: Value = self.slug_to_market_symbol(eventTicker.clone(), 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: Value = self.safe_string_k(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 != Value::Null) {
pricePrecision = self.parse_number(stepDollars, &[]);
}
let mut precision: Value = Value::Map({
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(), Value::Str(format!("{}{}", ticker, Value::Str("-NO".into())).into())]);
let mut outcomes: Value = Value::from(vec![]);
let mut resolvedOutcome: Value = Value::Null;
{
let mut oi: Value = Value::Int(0);
let mut __for_first_1239: bool = true;
while { if !__for_first_1239 { oi = (match (&(oi), &(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 }); } __for_first_1239 = false; oi.as_f64().unwrap_or(f64::NAN) < ((outcomeLabels.len() as i64) as f64) } {
let mut label: Value = outcomeLabels.as_array().and_then(|__arr| match &oi { 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);
let mut outcomeHandle: Value = self.slug_to_outcome_symbol(eventTicker.clone(), subtitleOrTicker.clone(), label.clone());
let mut winnerRaw: Value = Value::Null;
let mut settleFractionRaw: Value = Value::Null;
if matches!(&resolved, Value::Bool(true)) && (result != Value::Null) && (result.as_str() != Some("")) {
winnerRaw = (Value::Bool(to_lower(&label).as_str() == result.as_str()));
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;
append_to_array(&mut outcomes, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), outcomeIds.as_array().and_then(|__arr| match &oi { 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));
m.insert("outcomeId".to_string(), outcomeIds.as_array().and_then(|__arr| match &oi { 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));
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(), precision.clone());
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone());
m.insert("eventTicker".to_string(), eventTicker.clone());
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(), volume.clone());
m.insert("liquidity".to_string(), liquidity.clone());
m.insert("openInterest".to_string(), openInt.clone());
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());
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());
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(), 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 != Value::Null) && (endDate.as_str() != Some(""))) { self.parse8601(endDate.clone()) } else { Value::Null }));
m.insert("expiryDatetime".to_string(), endDate);
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(), 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(), outcomes);
m.insert("info".to_string(), self.extend(raw, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker);
m.insert("eventTicker".to_string(), eventTicker);
m.insert("seriesTicker".to_string(), seriesTicker);
m.insert("subtitle".to_string(), subtitle);
m.insert("volume".to_string(), volume);
m.insert("liquidity".to_string(), liquidity);
m.insert("openInterest".to_string(), 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: 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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker);
m
});
let __ws_arg_1 = self.extend(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_value_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: Value = self.safe_bool_k(response.clone(), "trading_active", &[Value::Bool(false)]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if (tradingActive.as_bool() == Some(true)) { 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: 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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker);
m
});
let __ws_arg_2 = self.extend(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_k(market.clone(), "label", &[self.safe_string(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 = to_upper(&outcomeLabel).as_str() == Some("NO");
let mut timestamp: Value = self.parse8601(self.safe_string_k(raw.clone(), "updated_time", &[]));
let mut outcome: Value = self.safe_string_k(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) && is_true(&crate::precise::Precise::stringGe(&bidSizeString, &Value::Str("0".into()))) {
bidVolume = self.parse_number(bidSizeString.clone(), &[]);
}
let mut askVolume: Value = Value::Null;
if (askSizeString != Value::Null) && is_true(&crate::precise::Precise::stringGe(&askSizeString, &Value::Str("0".into()))) {
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);
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;
let mut targets: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1240: bool = true;
while { if !__for_first_1240 { i = (match (&(i), &(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 }); } __for_first_1240 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomes.len() as i64) as f64) } {
append_to_array(&mut targets, outcomes.as_array().and_then(|__arr| match &i { 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));
}
}
// 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: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1241: bool = true;
while { if !__for_first_1241 { i = (match (&(i), &(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 }); } __for_first_1241 = false; i.as_f64().unwrap_or(f64::NAN) < ((targets.len() as i64) as f64) } {
let mut outcomeObj: Value = self.outcome(targets.as_array().and_then(|__arr| match &i { 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));
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()), &[]);
if (ticker == Value::Null) {
continue;
}
if !(in_op(&outcomesByTicker, &ticker)) {
if let Value::Dict(__d) = &mut outcomesByTicker { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&ticker), Value::from(vec![])); }
append_to_array(&mut tickers, ticker.clone());
}
// reassign after push, plain mutation through a local is lost in transpiled php (arrays are value types there)
let mut grouped: Value = get_value(&outcomesByTicker, &ticker);
append_to_array(&mut grouped, outcomeObj);
crate::set_value(&mut outcomesByTicker, &ticker, grouped.clone());
if let Value::Dict(__d) = &mut outcomesByTicker { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&ticker), grouped.clone()); }
}
}
let mut chunkSize: Value = self.safe_integer_k(self.options.clone(), "fetchTickersBatchSize", &[Value::Int(100)]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut tickersLength: Value = Value::Int(tickers.len() as i64);
let mut startIndex: Value = Value::Int(0);
while startIndex.as_f64().unwrap_or(f64::NAN) < tickersLength.as_f64().unwrap_or(f64::NAN) {
let mut endIndex: Value = self.sum(&[startIndex.clone(), chunkSize.clone()]);
if endIndex.as_f64().unwrap_or(f64::NAN) > tickersLength.as_f64().unwrap_or(f64::NAN) {
endIndex = tickersLength.clone();
}
let mut chunk: Value = Value::from(vec![]);
{
let mut i: Value = startIndex.clone();
let mut __for_first_1242: bool = true;
while { if !__for_first_1242 { i = (match (&(i), &(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 }); } __for_first_1242 = false; i.as_f64().unwrap_or(f64::NAN) < endIndex.as_f64().unwrap_or(f64::NAN) } {
append_to_array(&mut chunk, get_value(&tickers, &i));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tickers".to_string(), join(&chunk, &Value::Str(",".into())));
m.insert("limit".to_string(), chunkSize.clone());
m
});
let __ws_arg_3 = self.extend(request, &[params.clone()]);
let mut response: Value = self.kalshi_public_get_markets(&[__ws_arg_3]).await;
let mut rawMarkets: Value = self.safe_list_k(response, "markets", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1244: bool = true;
while { if !__for_first_1244 { i = (match (&(i), &(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 }); } __for_first_1244 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawMarkets.len() as i64) as f64) } {
let mut raw: Value = rawMarkets.as_array().and_then(|__arr| match &i { 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);
let mut marketTicker: Value = self.safe_string_k(raw.clone(), "ticker", &[]);
if (marketTicker == Value::Null) || !(in_op(&outcomesByTicker, &marketTicker)) {
continue;
}
let mut grouped: Value = outcomesByTicker.as_map().and_then(|__m| marketTicker.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1243: bool = true;
while { if !__for_first_1243 { j = (match (&(j), &(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 }); } __for_first_1243 = 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: Value = self.safe_string_k(ticker.clone(), "outcome", &[]);
if (symbolKey != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbolKey), ticker); }
}
}
}
}
}
startIndex = self.sum(&[startIndex.clone(), chunkSize.clone()]);
}
return 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: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
let mut isNo: bool = outcomeObj.as_map().and_then(|__m| __m.get("label")).cloned().unwrap_or(Value::Null).as_str() == Some("NO");
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker);
m
});
let __ws_arg_4 = self.extend(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_value_k(response.clone(), "orderbook_fp", &[response.clone()]);
// Kalshi uses YES-side perspective: `yes` = bids, `no` = asks (inverted)
let mut rawYes: Value = self.safe_list_k(book.clone(), "yes_dollars", &[Value::from(vec![])]);
let mut rawNo: Value = self.safe_list_k(book, "no_dollars", &[Value::from(vec![])]);
// Convert [price_cents, size] → [price, size]
let mut bids: Value = Value::from(vec![]);
let mut asks: Value = Value::from(vec![]);
if isNo {
{
let mut bi: Value = Value::Int(0);
let mut __for_first_1245: bool = true;
while { if !__for_first_1245 { bi = (match (&(bi), &(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 }); } __for_first_1245 = false; bi.as_f64().unwrap_or(f64::NAN) < ((rawNo.len() as i64) as f64) } {
let mut price: Value = self.safe_number(rawNo.as_array().and_then(|__arr| match &bi { 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::Int(0), &[]);
append_to_array(&mut bids, Value::from(vec![price.clone(), self.safe_number(rawNo.as_array().and_then(|__arr| match &bi { 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::Int(1), &[])]));
}
}
{
let mut ai: Value = Value::Int(0);
let mut __for_first_1246: bool = true;
while { if !__for_first_1246 { ai = (match (&(ai), &(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 }); } __for_first_1246 = false; ai.as_f64().unwrap_or(f64::NAN) < ((rawYes.len() as i64) as f64) } {
let mut yesPrice: Value = self.safe_number(rawYes.as_array().and_then(|__arr| match &ai { 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::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 });
append_to_array(&mut asks, Value::from(vec![price.clone(), self.safe_number(rawYes.as_array().and_then(|__arr| match &ai { 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::Int(1), &[])]));
}
}
} else {
{
let mut bi: Value = Value::Int(0);
let mut __for_first_1247: bool = true;
while { if !__for_first_1247 { bi = (match (&(bi), &(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 }); } __for_first_1247 = false; bi.as_f64().unwrap_or(f64::NAN) < ((rawYes.len() as i64) as f64) } {
let mut price: Value = self.safe_number(rawYes.as_array().and_then(|__arr| match &bi { 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::Int(0), &[]);
append_to_array(&mut bids, Value::from(vec![price.clone(), self.safe_number(rawYes.as_array().and_then(|__arr| match &bi { 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::Int(1), &[])]));
}
}
{
let mut ai: Value = Value::Int(0);
let mut __for_first_1248: bool = true;
while { if !__for_first_1248 { ai = (match (&(ai), &(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 }); } __for_first_1248 = false; ai.as_f64().unwrap_or(f64::NAN) < ((rawNo.len() as i64) as f64) } {
let mut noPrice: Value = self.safe_number(rawNo.as_array().and_then(|__arr| match &ai { 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::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 });
append_to_array(&mut asks, Value::from(vec![price, self.safe_number(rawNo.as_array().and_then(|__arr| match &ai { 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::Int(1), &[])]));
}
}
}
return self.safe_prediction_order_book(self.sorted_orders(self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome]), Value::Null, bids, 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: Value = self.safe_string(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()]);
let mut periodMin: Value = self.safe_integer(self.timeframes.clone(), timeframe.clone(), &[]);
if (periodMin == Value::Null) {
// 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 = object_keys(&self.timeframes);
let mut supported: Value = join(&tfKeys, &Value::Str(", ".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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("series_ticker".to_string(), seriesTicker);
m.insert("ticker".to_string(), ticker);
m.insert("period_interval".to_string(), 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 }));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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 })]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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 = (if (limit != Value::Null) { limit.clone() } else { defaultLimit });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end_ts".into(), now.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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(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: Value = self.safe_list_k(response, "candlesticks", &[Value::from(vec![])]);
let mut usableCandles: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1249: bool = true;
while { if !__for_first_1249 { i = (match (&(i), &(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 }); } __for_first_1249 = false; i.as_f64().unwrap_or(f64::NAN) < ((candles.len() as i64) as f64) } {
let mut candle: Value = candles.as_array().and_then(|__arr| match &i { 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);
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()) {
append_to_array(&mut usableCandles, 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(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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone());
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(1000))); }
}
let __ws_arg_6 = self.extend(request, &[params]);
let mut response: Value = self.kalshi_public_get_markets_trades(&[__ws_arg_6]).await;
let mut trades: Value = self.safe_list_k(response, "trades", &[Value::from(vec![])]);
let mut filteredTrades: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1250: bool = true;
while { if !__for_first_1250 { i = (match (&(i), &(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 }); } __for_first_1250 = false; i.as_f64().unwrap_or(f64::NAN) < ((trades.len() as i64) as f64) } {
let mut trade: Value = trades.as_array().and_then(|__arr| match &i { 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);
let mut tradeTicker: Value = self.safe_string2(trade.clone(), Value::Str("ticker".into()), Value::Str("market_ticker".into()), &[]);
if (tradeTicker == Value::Null) || (tradeTicker.as_str() == ticker.as_str()) {
append_to_array(&mut filteredTrades, trade);
}
}
}
return self.parse_prediction_trades(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: Value = self.safe_string_k(trade.clone(), "trade_id", &[]);
let mut ts: Value = self.parse8601(self.safe_string_k(trade.clone(), "created_time", &[]));
let mut priceDollars: Value = self.safe_number2(trade.clone(), Value::Str("yes_price_dollars".into()), Value::Str("price_dollars".into()), &[]);
let mut priceCents: Value = self.safe_number2(trade.clone(), Value::Str("yes_price".into()), Value::Str("price".into()), &[]);
let mut price: Value = Value::Null;
if (priceDollars != Value::Null) {
price = priceDollars;
} else 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 });
}
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: Value = self.safe_string_lower_k(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: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
let mut outcomeId: Value = self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]);
let mut side: Value = Value::Null;
if (rawSide.as_str() == Some("yes")) || (rawSide.as_str() == Some("no")) {
if (requestedOutcomeLabel.as_str() == Some("yes")) || (requestedOutcomeLabel.as_str() == Some("no")) {
side = (if (rawSide.as_str() == requestedOutcomeLabel.as_str()) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
} else {
side = (if (rawSide.as_str() == 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);
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);
m.insert("outcomeId".to_string(), outcomeId);
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: Value = Value::Map({
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()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_7 = self.extend(request, &[params]);
let mut response: Value = self.kalshi_private_get_portfolio_fills(&[__ws_arg_7]).await;
let mut fills: Value = self.safe_list_k(response, "fills", &[Value::from(vec![])]);
let mut fillsLength: f64 = ((fills.len() as i64) as f64);
let mut trades: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1251: bool = true;
while { if !__for_first_1251 { i = (match (&(i), &(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 }); } __for_first_1251 = false; i.as_f64().unwrap_or(f64::NAN) < fillsLength } {
append_to_array(&mut trades, self.parse_my_trade(fills.as_array().and_then(|__arr| match &i { 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), &[outcomeObj.clone()]));
}
}
let mut wantedOutcome: Value = Value::Null;
if (outcome != Value::Null) {
wantedOutcome = self.safe_string(self.outcome(outcome.clone()), Value::Str("outcome".into()), &[]);
}
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1252: bool = true;
while { if !__for_first_1252 { i = (match (&(i), &(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 }); } __for_first_1252 = false; i.as_f64().unwrap_or(f64::NAN) < ((trades.len() as i64) as f64) } {
let mut trade: Value = trades.as_array().and_then(|__arr| match &i { 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);
if (wantedOutcome == Value::Null) || (self.safe_string_k(trade.clone(), "outcome", &[]).as_str() == wantedOutcome.as_str()) {
append_to_array(&mut result, trade);
}
}
}
return self.filter_by_since_limit(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: Value = self.safe_string2(fill.clone(), Value::Str("fill_id".into()), Value::Str("trade_id".into()), &[]);
let mut orderId: Value = self.safe_string_k(fill.clone(), "order_id", &[]);
let mut ticker: Value = self.safe_string2(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();
if (sideLeg.as_deref() == Some("no")) && (ticker != Value::Null) {
outcomeKey = Value::Str(format!("{}{}", ticker, 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: Value = Value::Str("buy".into());
if (action.as_deref() == Some("sell")) {
side = Value::Str("sell".into());
}
// price is the price of the leg held; kalshi reports dollars in V2, cents otherwise
let mut price: Value = Value::Null;
if (sideLeg.as_deref() == Some("no")) {
price = self.safe_number_k(fill.clone(), "no_price_dollars", &[]);
if (price == Value::Null) {
let mut noCents: Value = self.safe_number_k(fill.clone(), "no_price", &[]);
if (noCents != Value::Null) {
price = (match ((noCents).as_f64(), (Value::Int(100)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
}
} else {
price = self.safe_number_k(fill.clone(), "yes_price_dollars", &[]);
if (price == Value::Null) {
let mut yesCents: Value = self.safe_number_k(fill.clone(), "yes_price", &[]);
if (yesCents != Value::Null) {
price = (match ((yesCents).as_f64(), (Value::Int(100)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
}
}
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: Value = self.safe_bool_k(fill.clone(), "is_taker", &[Value::Bool(true)]);
let mut takerOrMaker: Value = Value::Str("maker".into());
if (isTaker.as_bool() == Some(true)) {
takerOrMaker = Value::Str("taker".into());
}
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);
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);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), 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: Value = Value::Map({
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 });
}
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).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(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: Value = Value::Int(0);
if (outcomes != Value::Null) {
outcomesLength = Value::Int(outcomes.len() as i64);
}
if outcomesLength.as_f64().unwrap_or(f64::NAN) > ((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
let mut parsed: Value = self.parse_prediction_positions(positions, &[]);
if (outcomesLength.as_f64() == Some(0.0)) {
return parsed;
}
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: Value = Value::Int(0);
let mut __for_first_1253: bool = true;
while { if !__for_first_1253 { i = (match (&(i), &(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 }); } __for_first_1253 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomes.len() as i64) as f64) } {
let mut outcomeObj: Value = self.outcome(outcomes.as_array().and_then(|__arr| match &i { 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));
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketTicker: Value = self.safe_string_k(outcomeInfo, "ticker", &[]);
if (marketTicker != Value::Null) {
if let Value::Dict(__d) = &mut wantedTickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketTicker), Value::Bool(true)); }
}
}
}
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1254: bool = true;
while { if !__for_first_1254 { i = (match (&(i), &(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 }); } __for_first_1254 = false; i.as_f64().unwrap_or(f64::NAN) < ((parsed.len() as i64) as f64) } {
let mut position: Value = parsed.as_array().and_then(|__arr| match &i { 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);
let mut positionInfo: Value = self.safe_dict_k(position.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positionTicker: Value = self.safe_string_k(positionInfo, "ticker", &[]);
if (positionTicker != Value::Null) && (in_op(&wantedTickers, &positionTicker)) {
append_to_array(&mut result, 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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_8 = self.extend(request, &[params]);
let mut response: Value = self.kalshi_private_get_portfolio_settlements(&[__ws_arg_8]).await;
let mut rawSettlements: Value = self.safe_list_k(response, "settlements", &[Value::from(vec![])]);
let mut rawSettlementsLength: f64 = ((rawSettlements.len() as i64) as f64);
let mut parsed: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1255: bool = true;
while { if !__for_first_1255 { i = (match (&(i), &(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 }); } __for_first_1255 = false; i.as_f64().unwrap_or(f64::NAN) < rawSettlementsLength } {
append_to_array(&mut parsed, self.parse_settlement(rawSettlements.as_array().and_then(|__arr| match &i { 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), &[]));
}
}
let mut wantedOutcome: Value = Value::Null;
if (outcome != Value::Null) {
wantedOutcome = self.safe_string(self.outcome(outcome.clone()), Value::Str("outcome".into()), &[]);
}
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1256: bool = true;
while { if !__for_first_1256 { i = (match (&(i), &(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 }); } __for_first_1256 = false; i.as_f64().unwrap_or(f64::NAN) < ((parsed.len() as i64) as f64) } {
let mut settlement: Value = parsed.as_array().and_then(|__arr| match &i { 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);
if (wantedOutcome == Value::Null) || (self.safe_string_k(settlement.clone(), "outcome", &[]).as_str() == wantedOutcome.as_str()) {
append_to_array(&mut result, settlement);
}
}
}
return self.filter_by_since_limit(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: Value = self.safe_string_k(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: bool = yesCount.as_f64().unwrap_or(f64::NAN) >= noCount.as_f64().unwrap_or(f64::NAN);
let mut heldLabel: Value = Value::Str("NO".into());
if heldYes {
heldLabel = Value::Str("YES".into());
}
let mut tickerMissing: bool = ticker == Value::Null;
let mut useHeldYesTicker: bool = heldYes || tickerMissing;
let mut heldTicker: Value = Value::Null;
if useHeldYesTicker {
heldTicker = ticker.clone();
} else {
heldTicker = (Value::Str(format!("{}{}", ticker, 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: Value = self.safe_string_upper_k(settlement.clone(), "market_result", &[]);
let mut won: Value = (Value::Bool(marketResult.as_str() == heldLabel.as_str()));
// kalshi reports money as dollar keys on V2, else cents
let mut payout: Value = self.safe_number_k(settlement.clone(), "revenue_dollars", &[]);
if (payout == Value::Null) {
let mut revenueCents: Value = self.safe_number_k(settlement.clone(), "revenue", &[]);
if (revenueCents != Value::Null) {
payout = (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 costKey: Value = Value::Str("no_total_cost".into());
if heldYes {
costKey = Value::Str("yes_total_cost".into());
}
let mut costDollarsKey: Value = Value::Str("no_total_cost_dollars".into());
if heldYes {
costDollarsKey = Value::Str("yes_total_cost_dollars".into());
}
let mut cost: Value = self.safe_number(settlement.clone(), costDollarsKey, &[]);
if (cost == Value::Null) {
let mut costCents: Value = self.safe_number(settlement.clone(), costKey, &[]);
if (costCents != Value::Null) {
cost = (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 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);
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);
m.insert("won".to_string(), won.clone());
m.insert("amount".to_string(), (if (heldYes) { yesCount } else { noCount }));
m.insert("price".to_string(), (if matches!(&won, Value::Bool(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: Value = self.safe_string_k(position.clone(), "ticker", &[]);
let mut outcomeObj: Value = self.safe_outcome(ticker.clone(), &[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]));
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: Value = Value::Map({
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()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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(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: Value = Value::Map({
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()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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(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: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1257: bool = true;
while { if !__for_first_1257 { i = (match (&(i), &(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 }); } __for_first_1257 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut order: Value = orders.as_array().and_then(|__arr| match &i { 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);
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")) {
append_to_array(&mut result, order);
}
}
}
return self.filter_by_since_limit(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_value_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: Value = self.safe_string_k(order.clone(), "order_id", &[]);
let mut ticker: Value = self.safe_string_k(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();
if (sideLeg.as_deref() == Some("no")) && (ticker != Value::Null) {
outcomeKey = Value::Str(format!("{}{}", ticker, 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(|__s| Value::Str(__s.into())).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: Value = Value::Str("yes_price_dollars".into());
if labelIsNo {
dollarsKey = Value::Str("no_price_dollars".into());
}
let mut centsKey: Value = Value::Str("yes_price".into());
if labelIsNo {
centsKey = Value::Str("no_price".into());
}
let mut price: Value = self.safe_number(order.clone(), dollarsKey, &[]);
if (price == Value::Null) {
let mut priceCents: Value = self.safe_number(order.clone(), 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);
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: Value = Value::Map({
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(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: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("ticker".into()), &[]);
let mut isNo: bool = outcomeObj.as_map().and_then(|__m| __m.get("label")).cloned().unwrap_or(Value::Null).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());
}
let mut yesPrice: Value = price.clone();
if isNo {
bookSide = (if (isBuy) { Value::Str("ask".into()) } else { Value::Str("bid".into()) });
if (price != Value::Null) {
yesPrice = self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &self.number_to_string(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: Value = Value::Str("good_till_canceled".into());
if isMarket {
defaultTif = Value::Str("immediate_or_cancel".into());
}
// 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 = Value::Str("immediate_or_cancel".into());
} else if (unifiedTif.as_deref() == Some("FOK")) {
defaultTif = Value::Str("fill_or_kill".into());
} else if (unifiedTif.as_deref() == Some("GTC")) {
defaultTif = Value::Str("good_till_canceled".into());
}
let mut timeInForceparamsTimeInForceVariable = self.handle_option_string_and_params(paramsOmitted, Value::Str("createOrder".into()), Value::Str("time_in_force".into()), &[defaultTif]);
let mut timeInForce: Value = timeInForceparamsTimeInForceVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsTimeInForce: Value = timeInForceparamsTimeInForceVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut stpparamsSelfTradePreventionTypeVariable = self.handle_option_string_and_params(paramsTimeInForce, Value::Str("createOrder".into()), Value::Str("self_trade_prevention_type".into()), &[Value::Str("taker_at_cross".into())]);
let mut stp: Value = stpparamsSelfTradePreventionTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSelfTradePreventionType: Value = stpparamsSelfTradePreventionTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker);
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) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.number_to_string(yesPrice)); }
}
let __ws_arg_12 = self.extend(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]);
add_element_to_object(&mut order, &Value::Str("side".into()), side);
add_element_to_object(&mut order, &Value::Str("amount".into()), amount.clone());
add_element_to_object(&mut order, &Value::Str("price".into()), 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) {
add_element_to_object(&mut order, &Value::Str("filled".into()), filledCount);
} else if (remainingCount != Value::Null) && (amount != 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) {
add_element_to_object(&mut order, &Value::Str("remaining".into()), remainingCount.clone());
}
if (order.as_map().and_then(|__m| __m.get("status")).cloned().unwrap_or(Value::Null) == Value::Null) {
let mut resolvedStatus: Value = Value::Str("open".into());
if (remainingCount != Value::Null) && (remainingCount.as_f64() == Some(0.0)) {
resolvedStatus = Value::Str("closed".into());
}
add_element_to_object(&mut order, &Value::Str("status".into()), 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 (order.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null) == Value::Null) {
add_element_to_object(&mut order, &Value::Str("id".into()), id);
}
if (order.as_map().and_then(|__m| __m.get("status")).cloned().unwrap_or(Value::Null) == Value::Null) {
add_element_to_object(&mut order, &Value::Str("status".into()), 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: Value = Value::Map({
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());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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(&[request]).await;
let mut restingOrders: Value = self.safe_list_k(restingResponse, "orders", &[Value::from(vec![])]);
let mut restingOrdersLength: f64 = ((restingOrders.len() as i64) as f64);
let mut canceledOrders: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1258: bool = true;
while { if !__for_first_1258 { i = (match (&(i), &(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 }); } __for_first_1258 = false; i.as_f64().unwrap_or(f64::NAN) < restingOrdersLength } {
let mut restingOrder: Value = restingOrders.as_array().and_then(|__arr| match &i { 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);
let mut orderId: Value = self.safe_string_k(restingOrder.clone(), "order_id", &[]);
if (orderId != Value::Null) {
let __ws_arg_14 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), orderId);
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, &[]);
add_element_to_object(&mut parsed, &Value::Str("status".into()), Value::Str("canceled".into()));
append_to_array(&mut canceledOrders, parsed);
}
}
}
return 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: Value = self.safe_string2(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 != Value::Null) {
// kalshi's event id (and slug) is the event_ticker — fetch it directly
let mut fullEvent: Value = self.fetch_raw_event_by_ticker(eventId, &[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: Value = Value::from(vec![]);
{
let mut di: Value = Value::Int(0);
let mut __for_first_1260: bool = true;
while { if !__for_first_1260 { di = (match (&(di), &(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 }); } __for_first_1260 = false; di.as_f64().unwrap_or(f64::NAN) < rawEventsLength } {
let mut parsedEvent: 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));
append_to_array(&mut result, parsedEvent.clone());
// register the parsed markets so populateOutcomes can index their outcomes
let mut parsedMarketsRaw: Value = crate::value::get_value_k(&parsedEvent, "markets");
let mut parsedMarkets: Value = (if (parsedMarketsRaw != Value::Null) { parsedMarketsRaw } else { Value::from(vec![]) });
let mut parsedMarketsLength: Value = get_array_length(&parsedMarkets);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1259: bool = true;
while { if !__for_first_1259 { mi = (match (&(mi), &(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 }); } __for_first_1259 = false; mi.as_f64().unwrap_or(f64::NAN) < parsedMarketsLength.as_f64().unwrap_or(f64::NAN) } {
let mut m: Value = get_value(&parsedMarkets, &mi);
let mut m: Value = get_value(&parsedMarkets, &mi);
add_element_to_object(&mut self.markets, &crate::value::get_value_k(&m, "market"), 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(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 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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut eventTickers: Value = Value::from(vec![]);
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
{
let mut qi: Value = Value::Int(0);
let mut __for_first_1262: bool = true;
while { if !__for_first_1262 { qi = (match (&(qi), &(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 }); } __for_first_1262 = 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.as_array().and_then(|__arr| match &qi { 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));
m.insert("order_by".to_string(), Value::Str("querymatch".into()));
m.insert("page_size".to_string(), pageSize.clone());
m
})]).await;
let mut page: Value = self.safe_list_k(searchResponse, "current_page", &[Value::from(vec![])]);
let mut pageLength: f64 = ((page.len() as i64) as f64);
{
let mut pi: Value = Value::Int(0);
let mut __for_first_1261: bool = true;
while { if !__for_first_1261 { pi = (match (&(pi), &(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 }); } __for_first_1261 = false; pi.as_f64().unwrap_or(f64::NAN) < pageLength } {
let mut et: Value = self.safe_string(page.as_array().and_then(|__arr| match &pi { 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("event_ticker".into()), &[]);
if (et != Value::Null) {
let mut already: Option<String> = self.safe_string(seen.clone(), et.clone(), &[]).as_str().map(str::to_owned);
if (already.is_none()) {
if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&et), et.clone()); }
append_to_array(&mut eventTickers, et);
}
}
}
}
}
}
let mut rawEvents: Value = Value::from(vec![]);
let mut eventTickersLength: f64 = ((eventTickers.len() as i64) as f64);
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1263: bool = true;
while { if !__for_first_1263 { ei = (match (&(ei), &(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 }); } __for_first_1263 = false; ei.as_f64().unwrap_or(f64::NAN) < eventTickersLength } {
let mut collectedLength: f64 = ((rawEvents.len() as i64) as f64);
if (limit != Value::Null) && (collectedLength >= limit.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.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), &[rest.clone()]).await;
append_to_array(&mut rawEvents, 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 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: Value = Value::Map({
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(request, &[params]);
let mut response: Value = self.kalshi_public_get_events_event_ticker(&[__ws_arg_15]).await;
let mut fullEvent: Value = self.safe_dict_k(response.clone(), "event", &[response.clone()]);
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: Value = (match params.get("tags") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut tagsLength: f64 = ((tags.len() as i64) as f64);
{
let mut ti: Value = Value::Int(0);
let mut __for_first_1265: bool = true;
while { if !__for_first_1265 { ti = (match (&(ti), &(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 }); } __for_first_1265 = 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.as_array().and_then(|__arr| match &ti { 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));
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_1264: bool = true;
while { if !__for_first_1264 { si = (match (&(si), &(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 }); } __for_first_1264 = false; si.as_f64().unwrap_or(f64::NAN) < seriesListLength } {
let mut st: Value = self.safe_string(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 != Value::Null) {
append_to_array(&mut collected, st.clone());
}
}
}
}
}
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_1266: bool = true;
while { if !__for_first_1266 { si = (match (&(si), &(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 }); } __for_first_1266 = false; si.as_f64().unwrap_or(f64::NAN) < seriesListLength } {
let mut st: Value = self.safe_string(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 != Value::Null) {
append_to_array(&mut collected, st.clone());
}
}
}
}
// 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: Value = split(&seriesParam, &Value::Str(",".into()));
let mut partsLength: f64 = ((parts.len() as i64) as f64);
{
let mut pi: Value = Value::Int(0);
let mut __for_first_1267: bool = true;
while { if !__for_first_1267 { pi = (match (&(pi), &(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 }); } __for_first_1267 = false; pi.as_f64().unwrap_or(f64::NAN) < partsLength } {
append_to_array(&mut collected, parts.as_array().and_then(|__arr| match &pi { 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));
}
}
}
// deduplicate preserving order
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut ordered: Value = Value::from(vec![]);
let mut collectedLength: f64 = ((collected.len() as i64) as f64);
{
let mut ci: Value = Value::Int(0);
let mut __for_first_1268: bool = true;
while { if !__for_first_1268 { ci = (match (&(ci), &(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 }); } __for_first_1268 = false; ci.as_f64().unwrap_or(f64::NAN) < collectedLength } {
let mut st: Value = collected.as_array().and_then(|__arr| match &ci { 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);
let mut already: Option<String> = self.safe_string(seen.clone(), st.clone(), &[]).as_str().map(str::to_owned);
if (st != Value::Null) && (st.as_str() != Some("")) && (already.is_none()) {
if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&st), st.clone()); }
append_to_array(&mut ordered, st);
}
}
}
return 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 mut rawEvents: Value = Value::from(vec![]);
let mut seriesTickersLength: f64 = ((seriesTickers.len() as i64) as f64);
let mut pageLimit: Value = 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 si: Value = Value::Int(0);
let mut __for_first_1271: bool = true;
while { if !__for_first_1271 { si = (match (&(si), &(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 }); } __for_first_1271 = false; si.as_f64().unwrap_or(f64::NAN) < seriesTickersLength } {
let mut collectedLength: f64 = ((rawEvents.len() as i64) as f64);
if (limit != Value::Null) && (collectedLength >= limit.as_f64().unwrap_or(f64::NAN)) {
break;
}
let mut cursor: Value = Value::Null;
{
let mut page: Value = Value::Int(0);
let mut __for_first_1270: bool = true;
while { if !__for_first_1270 { page = (match (&(page), &(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 }); } __for_first_1270 = false; page.as_f64().unwrap_or(f64::NAN) < maxPages.as_f64().unwrap_or(f64::NAN) } {
let mut reqLimit: Value = pageLimit.clone();
if (limit != Value::Null) {
let mut remaining: Value = (match (&(limit), &(Value::Int(rawEvents.len() as i64))) { (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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("series_ticker".to_string(), seriesTickers.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));
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) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("cursor".into(), cursor.clone()); }
}
let __ws_arg_16 = self.extend(request, &[rest.clone()]);
let mut response: Value = self.kalshi_public_get_events(&[__ws_arg_16]).await;
let mut pageEvents: Value = self.safe_list_k(response.clone(), "events", &[Value::from(vec![])]);
let mut pageEventsLength: f64 = ((pageEvents.len() as i64) as f64);
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1269: bool = true;
while { if !__for_first_1269 { ei = (match (&(ei), &(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 }); } __for_first_1269 = false; ei.as_f64().unwrap_or(f64::NAN) < pageEventsLength } {
append_to_array(&mut rawEvents, pageEvents.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));
}
}
cursor = self.safe_string_k(response, "cursor", &[]);
let mut collectedAfterPage: f64 = ((rawEvents.len() as i64) as f64);
if (limit != Value::Null) && (collectedAfterPage >= limit.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 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: Value = Value::from(vec![]);
// 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);
let mut earliestCreated: Value = Value::Null;
let mut anyActive: Value = Value::Bool(false);
let mut allResolved: Value = Value::Bool(true);
let mut latestClose: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1272: bool = true;
while { if !__for_first_1272 { i = (match (&(i), &(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 }); } __for_first_1272 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawMarkets.len() as i64) as f64) } {
let mut rawMarket: Value = rawMarkets.as_array().and_then(|__arr| match &i { 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);
let mut parsed: Value = self.parse_market(rawMarket.clone());
append_to_array(&mut marketsList, 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: Value = self.safe_string_k(rawEvent.clone(), "event_ticker", &[]);
let mut title: Value = self.safe_string_k(rawEvent.clone(), "title", &[]);
let mut hasTitle: bool = (title != Value::Null) && (title.as_str() != Some(""));
let mut eventSlug: Value = Value::Null;
if hasTitle {
eventSlug = self.shorten_slug(title.clone());
}
let mut created: Value = self.parse8601(self.safe_string_k(rawEvent.clone(), "created_date_iso", &[]));
if (created == Value::Null) {
created = earliestCreated;
}
let __ws_arg_17 = self.safe_string_k(rawEvent.clone(), "url", &[]);
let __ws_arg_18 = self.safe_string_k(rawEvent.clone(), "image_url", &[]);
let __ws_arg_19 = self.safe_string_k(rawEvent.clone(), "created_date_iso", &[]);
let __ws_arg_20 = self.iso8601(end.clone());
let __ws_arg_21 = self.safe_string_k(rawEvent.clone(), "category", &[]);
let __ws_arg_22 = self.parse8601(self.safe_string_k(rawEvent.clone(), "last_updated_date_iso", &[]));
let __ws_arg_23 = self.safe_string_k(rawEvent.clone(), "last_updated_date_iso", &[]);
let __ws_arg_24 = 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());
m.insert("slug".to_string(), ticker);
m.insert("event".to_string(), eventSlug);
m.insert("title".to_string(), title);
m.insert("markets".to_string(), marketsList);
m.insert("volume".to_string(), totalVolume);
m.insert("liquidity".to_string(), totalLiquidity);
m.insert("url".to_string(), __ws_arg_17);
m.insert("image".to_string(), __ws_arg_18);
m.insert("created".to_string(), created);
m.insert("createdDatetime".to_string(), __ws_arg_19);
m.insert("end".to_string(), end);
m.insert("endDatetime".to_string(), __ws_arg_20);
m.insert("category".to_string(), __ws_arg_21);
m.insert("lastUpdatedAt".to_string(), __ws_arg_22);
m.insert("lastUpdatedAtDatetime".to_string(), __ws_arg_23);
m.insert("resolutionSource".to_string(), __ws_arg_24);
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 mut apiGroup: Value = api.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut access: Option<String> = self.safe_string(api, Value::Int(1), &[Value::Str("public".into())]).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, &[baseUrls.as_map().and_then(|__m| __m.get("kalshi")).cloned().unwrap_or(Value::Null)]);
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: Value = Value::Map({
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
}), &[existingHeaders]);
let mut bodyValue: Value = Value::Null;
if (access.as_deref() == Some("private")) {
self.check_required_credentials(&[]);
let mut timestamp: Value = to_string_val(&self.milliseconds());
// 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 = slice(&baseUrl, &tradeApiIndex, &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 = split(&self.privateKey, &Value::Str("\\n".into()));
let mut cleanPrivateKey: Value = join(&keyParts, &Value::Str("\n".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
}
}