// 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;
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);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// 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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone(), method.clone(), params.clone(), headers.clone(), body.clone()])
}
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.get(5..).unwrap_or(&[]).to_vec()[..]),
"cancel_all_orders" => self.cancel_all_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).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.get(4..).unwrap_or(&[]).to_vec()[..]).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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_balance" => self.fetch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_event" => self.fetch_event(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_events" => self.fetch_events(&args.get(0..).unwrap_or(&[]).to_vec()[..]).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.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_markets" => self.fetch_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_orders" => self.fetch_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).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.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_raw_event_by_ticker" => self.fetch_raw_event_by_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).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.get(3..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_settlements" => self.fetch_settlements(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_status" => self.fetch_status(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers" => self.fetch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_prediction_open_interest" => self.parse_prediction_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_position" => self.parse_prediction_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_trade" => self.parse_prediction_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_settlement" => self.parse_settlement(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"resolve_event_series_tickers" => self.resolve_event_series_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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".to_string()));
m.insert("name".to_string(), Value::Str("Kalshi".to_string()));
m.insert("countries".to_string(), Value::List(vec![Value::Str("US".to_string())]));
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".to_string()));
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".to_string()));
m.insert("elections".to_string(), Value::Str("https://api.elections.kalshi.com/v1".to_string()));
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".to_string()));
m.insert("elections".to_string(), Value::Str("https://api.elections.kalshi.com/v1".to_string()));
m
}));
m.insert("www".to_string(), Value::Str("https://kalshi.com".to_string()));
m.insert("doc".to_string(), Value::List(vec![Value::Str("https://trading-api.readme.io/reference/getting-started".to_string())]));
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".to_string()).clone());
m.insert("invalid_order".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("fill_or_kill_insufficient_resting_volume".to_string(), Value::Str("OrderNotFillable".to_string()).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".to_string()));
m.insert("eventScopeParams".to_string(), Value::List(vec![Value::Str("category".to_string()), Value::Str("series_ticker".to_string())]));
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: Value = get_array_length(&queries);
// 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 is_greater_than(&queriesLength, &Value::Int(0)) {
let mut eventParams: Value = self.omit(params.clone(), Value::List(vec![Value::Str("limit".to_string())]), &[]);
let mut events: Value = self.fetch_events(&[eventParams.clone()]).await;
let mut eventsLength: Value = get_array_length(&events);
let mut queryMarkets: Value = Value::List(vec![]);
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1208: bool = true;
while { if !__for_first_1208 { ei = add(&ei, &Value::Int(1)); } __for_first_1208 = false; is_less_than(&ei, &eventsLength) } {
let mut eventMarkets: Value = self.safe_list_k(get_value(&events, &ei), "markets", &[Value::List(vec![])]);
let mut eventMarketsLength: Value = get_array_length(&eventMarkets);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1207: bool = true;
while { if !__for_first_1207 { mi = add(&mi, &Value::Int(1)); } __for_first_1207 = false; is_less_than(&mi, &eventMarketsLength) } {
append_to_array(&mut queryMarkets, get_value(&eventMarkets, &mi));
}
}
}
}
return queryMarkets;
}
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("query".to_string()), Value::Str("queries".to_string()), Value::Str("limit".to_string())]), &[]);
// 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.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("maxFetchMarketsLimit".to_string()), &[Value::Int(1000)])]);
let mut flatMarkets: Value = Value::List(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".to_string())]);
while is_true(&Value::Bool(true)) {
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 !is_equal(&cursor, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("cursor".to_string()), cursor.clone());
}
let __ws_arg_0 = self.extend(request.clone(), &[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::List(vec![])]);
let mut rawMarketsLength: Value = get_array_length(&rawMarkets);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1210: bool = true;
while { if !__for_first_1210 { i = add(&i, &Value::Int(1)); } __for_first_1210 = false; is_less_than(&i, &get_array_length(&rawMarkets)) } {
let mut raw: Value = get_value(&rawMarkets, &i);
let mut raw: Value = get_value(&rawMarkets, &i);
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.clone(), "title", &[eventTicker.clone()]);
let mut eventKey: Value = ternary(is_true(&(!is_equal(&eventTitle, &Value::Null) && !is_equal(&eventTitle, &Value::Str("".to_string())))), self.shorten_slug(eventTitle.clone()), Value::Null);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1209: bool = true;
while { if !__for_first_1209 { j = add(&j, &Value::Int(1)); } __for_first_1209 = false; is_less_than(&j, &get_array_length(&parsed)) } {
let mut m: Value = get_value(&parsed, &j);
let mut m: Value = get_value(&parsed, &j);
append_to_array(&mut flatMarkets, m.clone());
if is_true(&(!is_equal(&eventKey, &Value::Null))) && is_true(&(!is_equal(&eventKey, &Value::Str("".to_string())))) {
if !is_true(&(Value::Bool(in_op(&eventsDict, &eventKey)))) {
add_element_to_object(&mut eventsDict, &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::List(vec![]));
m
}));
}
let mut eventEntry: Value = get_value(&eventsDict, &eventKey);
let mut eventEntry: Value = get_value(&eventsDict, &eventKey);
// 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 = get_value(&eventEntry, &Value::Str("markets".to_string()));
append_to_array(&mut entryMarkets, m.clone());
add_element_to_object(&mut eventEntry, &Value::Str("markets".to_string()), entryMarkets.clone());
}
}
}
}
}
cursor = self.safe_string_k(response.clone(), "cursor", &[]);
let mut collectedLength: Value = get_array_length(&flatMarkets);
if is_true(&(is_equal(&cursor, &Value::Null) || is_equal(&cursor, &Value::Str("".to_string())))) || is_less_than(&rawMarketsLength, &limit) || is_greater_than_or_equal(&collectedLength, &maxMarkets) {
break;
}
}
self.exchange.events = eventsDict.clone();
let mut flatMarketsLength: Value = get_array_length(&flatMarkets);
if is_greater_than(&flatMarketsLength, &maxMarkets) {
return self.array_slice(flatMarkets.clone(), Value::Int(0), &[maxMarkets.clone()]);
}
return flatMarkets;
Value::Null
}
pub fn parse_binary_market_to_outcomes(&self, mut raw: Value) -> Value {
return Value::List(vec![self.parse_market(raw.clone())]);
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 is_less_than(&get_index_of(&outcomeSymbol, &Value::Str(":".to_string())), &Value::Int(0)) {
// 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(get_array_length(&outcomeSymbol));
let mut suffix: Value = slice(&outcomeSymbol, &subtract(&symbolLength, &Value::Int(3)), &Value::Null);
let mut isNo: bool = is_equal(&suffix, &Value::Str("-NO".to_string()));
let mut baseTicker: Value = ternary(is_true(&isNo), slice(&outcomeSymbol, &Value::Int(0), &subtract(&symbolLength, &Value::Int(3))), outcomeSymbol.clone());
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.clone());
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 !is_true(&(is_instance(&e, &Value::Str("BadSymbol".to_string())))) {
panic!("{}", e);
}
response = Value::Null;
}
if !is_equal(&response, &Value::Null) {
let mut rawMarket: Value = self.safe_dict_k(response.clone(), "market", &[response.clone()]);
let mut parsed: Value = self.parse_market(rawMarket.clone());
if is_equal(&self.markets, &Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
if is_equal(&parsed, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchOutcome() could not resolve parsed".to_string()))));
}
add_element_to_object(&mut self.markets, &get_value(&parsed, &Value::Str("market".to_string())), 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.clone());
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(":".to_string()));
let mut marketPart: Value = self.safe_string(handleParts.clone(), Value::Int(0), &[Value::Str("".to_string())]);
let mut parts: Value = split(&marketPart, &Value::Str("_".to_string()));
let mut seriesTicker: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
if is_true(&(!is_equal(&seriesTicker, &Value::Null))) && is_true(&(!is_equal(&seriesTicker, &Value::Str("".to_string())))) {
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.clone());
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 !is_true(&(is_instance(&e, &Value::Str("BadSymbol".to_string())))) {
panic!("{}", e);
}
}
if is_true(&self.has_outcome(outcomeSymbol.clone())) {
return self.safe_outcome(outcomeSymbol.clone(), &[]);
}
}
}
return self.super_fetch_outcome(outcomeSymbol.clone()).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::List(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_1211: bool = true;
while { if !__for_first_1211 { i = add(&i, &Value::Int(1)); } __for_first_1211 = false; is_less_than(&i, &get_array_length(&outcomeSymbols)) } {
let mut outcomeSymbol: Value = get_value(&outcomeSymbols, &i);
let mut outcomeSymbol: Value = get_value(&outcomeSymbols, &i);
if is_greater_than_or_equal(&get_index_of(&outcomeSymbol, &Value::Str(":".to_string())), &Value::Int(0)) {
continue;
}
// parseToInt-wrapped .length — see the fetchOutcome comment (php count()/python slice traps)
let mut symbolLength: Value = self.parse_to_int(get_array_length(&outcomeSymbol));
let mut suffix: Value = slice(&outcomeSymbol, &subtract(&symbolLength, &Value::Int(3)), &Value::Null);
let mut baseTicker: Value = ternary(is_true(&(is_equal(&suffix, &Value::Str("-NO".to_string())))), slice(&outcomeSymbol, &Value::Int(0), &subtract(&symbolLength, &Value::Int(3))), outcomeSymbol.clone());
if !is_true(&(Value::Bool(in_op(&seen, &baseTicker)))) {
add_element_to_object(&mut seen, &baseTicker, Value::Bool(true));
append_to_array(&mut tickers, baseTicker.clone());
}
}
}
if is_equal(&self.markets, &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 = get_array_length(&tickers);
let mut startIndex: Value = Value::Int(0);
while is_less_than(&startIndex, &tickersLength) {
let mut endIndex: Value = self.sum(&[startIndex.clone(), chunkSize.clone()]);
if is_greater_than(&endIndex, &tickersLength) {
endIndex = tickersLength.clone();
}
let mut chunk: Value = Value::List(vec![]);
{
let mut i: Value = startIndex.clone();
let mut __for_first_1212: bool = true;
while { if !__for_first_1212 { i = add(&i, &Value::Int(1)); } __for_first_1212 = false; is_less_than(&i, &endIndex) } {
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(",".to_string())));
m.insert("limit".to_string(), chunkSize.clone());
m
});
let mut response: Value = self.kalshi_public_get_markets(&[request.clone()]).await;
let mut rawMarkets: Value = self.safe_list_k(response.clone(), "markets", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1213: bool = true;
while { if !__for_first_1213 { i = add(&i, &Value::Int(1)); } __for_first_1213 = false; is_less_than(&i, &get_array_length(&rawMarkets)) } {
let mut parsed: Value = self.parse_market(get_value(&rawMarkets, &i));
if is_equal(&parsed, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchOutcomes() could not resolve parsed".to_string()))));
}
add_element_to_object(&mut self.markets, &get_value(&parsed, &Value::Str("market".to_string())), parsed.clone());
self.index_market_outcomes(parsed.clone());
}
}
startIndex = self.sum(&[startIndex.clone(), chunkSize.clone()]);
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1214: bool = true;
while { if !__for_first_1214 { i = add(&i, &Value::Int(1)); } __for_first_1214 = false; is_less_than(&i, &get_array_length(&outcomeSymbols)) } {
if !is_true(&self.has_outcome(get_value(&outcomeSymbols, &i))) {
self.fetch_outcome(get_value(&outcomeSymbols, &i)).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 is_true(&(is_equal(&response, &Value::Null))) || is_true(&(is_equal(&response, &Value::Null))) {
return Value::Null;
}
let mut error: Value = self.safe_dict_k(response.clone(), "error", &[]);
if !is_equal(&error, &Value::Null) {
let mut errorCode: Value = self.safe_string_k(error.clone(), "code", &[]);
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), errorCode.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), errorCode.clone(), 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 is_equal(&code, &Value::Int(400)) {
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
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".to_string()));
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.clone());
let mut amountStr: Value = self.number_to_string(amount.clone());
let mut oneMinusP: Value = crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &priceStr);
let mut feeCost: Value = crate::precise::Precise::stringMul(&Value::Str("0.07".to_string()), &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.clone());
m.insert("currency".to_string(), Value::Str("USD".to_string()));
m.insert("rate".to_string(), Value::Float(0.07));
m.insert("cost".to_string(), self.parse_number(feeCost.clone(), &[]));
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".to_string()), &[])]);
// markets use status 'active' while events use 'open'
let mut status: Value = self.safe_string_k(raw.clone(), "status", &[]);
let mut active: Value = Value::Bool(is_true(&(is_equal(&status, &Value::Str("active".to_string())))) || is_true(&(is_equal(&status, &Value::Str("open".to_string())))));
// resolution: kalshi sets `result` to 'yes'/'no' once the market settles (empty while trading)
let mut result: Value = self.safe_string_lower(raw.clone(), Value::Str("result".to_string()), &[]);
let mut resolved: Value = Value::Bool(is_true(&(is_equal(&status, &Value::Str("settled".to_string())))) || is_true(&(is_true(&(!is_equal(&result, &Value::Null))) && is_true(&(!is_equal(&result, &Value::Str("".to_string())))))));
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".to_string()), Value::Str("volume".to_string()), &[]);
let mut liquidity: Value = self.safe_number2(raw.clone(), Value::Str("liquidity_dollars".to_string()), Value::Str("liquidity".to_string()), &[]);
let mut openInt: Value = self.safe_number2(raw.clone(), Value::Str("open_interest_fp".to_string()), Value::Str("open_interest".to_string()), &[]);
// Derive series ticker: drop last hyphen-segment from event_ticker
let mut eventParts: Value = Value::List(vec![]);
if is_true(&(!is_equal(&eventTicker, &Value::Null))) && is_true(&(!is_equal(&eventTicker, &Value::Str("".to_string())))) {
eventParts = split(&eventTicker, &Value::Str("-".to_string()));
}
let mut seriesTicker: Value = eventTicker.clone();
let mut eventPartsLength: Value = get_array_length(&eventParts);
if is_greater_than(&eventPartsLength, &Value::Int(1)) {
let mut seriesParts: Value = self.array_slice(eventParts.clone(), Value::Int(0), &[subtract(&eventPartsLength, &Value::Int(1))]);
seriesTicker = join(&seriesParts, &Value::Str("-".to_string()));
}
// market symbol (no outcome suffix)
let mut subtitleOrTicker: Value = ternary(is_true(&(!is_equal(&subtitle, &Value::Null))), subtitle.clone(), ticker.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::List(vec![])]);
let mut firstRange: Value = self.safe_dict(priceRanges.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut stepDollars: Value = self.safe_string_k(firstRange.clone(), "step", &[]);
let mut pricePrecision: Value = self.parse_number(crate::precise::Precise::stringDiv(&self.safe_string_k(raw.clone(), "tick_size", &[Value::Str("1".to_string())]), &Value::Str("100".to_string())), &[]);
if !is_equal(&stepDollars, &Value::Null) {
pricePrecision = self.parse_number(stepDollars.clone(), &[]);
}
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.clone());
m
});
// Build outcomes
let mut outcomeLabels: Value = Value::List(vec![Value::Str("YES".to_string()), Value::Str("NO".to_string())]);
let mut outcomeIds: Value = Value::List(vec![ticker.clone(), add(&ticker, &Value::Str("-NO".to_string()))]);
let mut outcomes: Value = Value::List(vec![]);
let mut resolvedOutcome: Value = Value::Null;
{
let mut oi: Value = Value::Int(0);
let mut __for_first_1215: bool = true;
while { if !__for_first_1215 { oi = add(&oi, &Value::Int(1)); } __for_first_1215 = false; is_less_than(&oi, &get_array_length(&outcomeLabels)) } {
let mut label: Value = get_value(&outcomeLabels, &oi);
let mut label: Value = get_value(&outcomeLabels, &oi);
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 is_true(&resolved) && is_true(&(!is_equal(&result, &Value::Null))) && is_true(&(!is_equal(&result, &Value::Str("".to_string())))) {
winnerRaw = Value::Bool(is_equal(&to_lower(&label), &result));
settleFractionRaw = ternary(is_true(&(winnerRaw)), Value::Int(1), Value::Int(0));
if is_true(&winnerRaw) {
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.clone();
let mut settleFraction: Value = settleFractionRaw.clone();
append_to_array(&mut outcomes, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), get_value(&outcomeIds, &oi));
m.insert("outcomeId".to_string(), get_value(&outcomeIds, &oi));
m.insert("outcome".to_string(), outcomeHandle.clone());
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.clone());
m.insert("settleFraction".to_string(), settleFraction.clone());
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.clone());
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.clone();
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), ticker.clone());
m.insert("market".to_string(), marketSymbol.clone());
m.insert("base".to_string(), Value::Str("USD".to_string()));
m.insert("quote".to_string(), Value::Str("USD".to_string()));
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), ticker.clone());
m.insert("quoteId".to_string(), Value::Str("USD".to_string()));
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("prediction".to_string()));
m.insert("marketType".to_string(), Value::Str("binary".to_string()));
m.insert("executionModel".to_string(), Value::Str("clob".to_string()));
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.clone());
m.insert("resolved".to_string(), resolved.clone());
m.insert("resolvedOutcome".to_string(), marketResolvedOutcome.clone());
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(), ternary(is_true(&(!is_equal(&endDate, &Value::Null) && !is_equal(&endDate, &Value::Str("".to_string())))), self.parse8601(endDate.clone()), Value::Null));
m.insert("expiryDatetime".to_string(), endDate.clone());
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".to_string()));
m.insert("precision".to_string(), precision.clone());
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.clone());
m.insert("info".to_string(), self.extend(raw.clone(), &[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("volume".to_string(), volume.clone());
m.insert("liquidity".to_string(), liquidity.clone());
m.insert("openInterest".to_string(), openInt.clone());
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(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone());
m
});
let __ws_arg_1 = self.extend(request.clone(), &[params.clone()]);
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.clone(), &[outcomeObj.clone()]);
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.clone()]).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(), ternary(is_true(&(is_equal(&tradingActive, &Value::Bool(true)))), Value::Str("ok".to_string()), Value::Str("maintenance".to_string())));
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.clone());
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(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone());
m
});
let __ws_arg_2 = self.extend(request.clone(), &[params.clone()]);
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.clone(), &[outcomeObj.clone()]);
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", ... } // open interest in contracts
//
let mut timestamp: Value = self.milliseconds();
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".to_string()), Value::Str("open_interest".to_string()), &[]));
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.clone()));
m.insert("info".to_string(), interest.clone());
m
}), &[market.clone()]);
add_element_to_object(&mut openInterest, &Value::Str("outcome".to_string()), self.safe_outcome_symbol(Value::Null, &[market.clone()]));
add_element_to_object(&mut openInterest, &Value::Str("outcomeId".to_string()), self.safe_string_k(market.clone(), "outcomeId", &[]));
remove(&mut openInterest, &Value::Str("symbol".to_string()));
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.clone()]);
let mut outcomeLabel: Value = ternary(is_true(&(!is_equal(&market, &Value::Null) && !is_equal(&market, &Value::Null))), self.safe_string_k(market.clone(), "label", &[self.safe_string(get_value(&market, &Value::Str("info".to_string())), Value::Str("outcomeLabel".to_string()), &[Value::Str("YES".to_string())])]), Value::Str("YES".to_string()));
let mut isNo: Value = Value::Bool(is_equal(&to_upper(&outcomeLabel), &Value::Str("NO".to_string())));
let mut now: Value = self.milliseconds();
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 is_true(&isNo) {
bid = noBid.clone();
ask = noAsk.clone();
close = ternary(is_true(&(!is_equal(&last, &Value::Null))), self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &self.number_to_string(last.clone())), &[]), Value::Null);
} else {
bid = yesBid.clone();
ask = yesAsk.clone();
close = last.clone();
}
// the book is quoted in the yes token, the no side mirrors with sizes swapped
let mut bidSizeString: Value = ternary(is_true(&(isNo)), self.safe_string_k(raw.clone(), "yes_ask_size_fp", &[]), self.safe_string_k(raw.clone(), "yes_bid_size_fp", &[]));
let mut askSizeString: Value = ternary(is_true(&(isNo)), self.safe_string_k(raw.clone(), "yes_bid_size_fp", &[]), 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 is_true(&(!is_equal(&bidSizeString, &Value::Null))) && is_true(&crate::precise::Precise::stringGe(&bidSizeString, &Value::Str("0".to_string()))) {
bidVolume = self.parse_number(bidSizeString.clone(), &[]);
}
let mut askVolume: Value = Value::Null;
if is_true(&(!is_equal(&askSizeString, &Value::Null))) && is_true(&crate::precise::Precise::stringGe(&askSizeString, &Value::Str("0".to_string()))) {
askVolume = self.parse_number(askSizeString.clone(), &[]);
}
let mut average: Value = Value::Null;
if is_true(&(!is_equal(&bid, &Value::Null))) && is_true(&(!is_equal(&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".to_string())), &[]);
}
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcome.clone());
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("market".to_string()), Value::Str("outcome".to_string()), &[]));
m.insert("timestamp".to_string(), now.clone());
m.insert("datetime".to_string(), self.iso8601(now.clone()));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), bid.clone());
m.insert("bidVolume".to_string(), bidVolume.clone());
m.insert("ask".to_string(), ask.clone());
m.insert("askVolume".to_string(), askVolume.clone());
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.clone());
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.clone());
m.insert("baseVolume".to_string(), self.safe_number_n(raw.clone(), Value::List(vec![Value::Str("volume_24h_fp".to_string()), Value::Str("volume_24h".to_string()), Value::Str("volume".to_string())]), &[]));
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("info".to_string(), raw.clone());
m
}), &[market.clone()]);
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 is_equal(&outcomes, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles to fetch (discover them via fetchEvents ())".to_string()))));
}
// batch-resolve the uncached outcomes (one markets request per 100 tickers)
self.load_outcomes(&[outcomes.clone()]).await;
let mut targets: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1216: bool = true;
while { if !__for_first_1216 { i = add(&i, &Value::Int(1)); } __for_first_1216 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
append_to_array(&mut targets, get_value(&outcomes, &i));
}
}
// 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::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1217: bool = true;
while { if !__for_first_1217 { i = add(&i, &Value::Int(1)); } __for_first_1217 = false; is_less_than(&i, &get_array_length(&targets)) } {
let mut outcomeObj: Value = self.outcome(get_value(&targets, &i));
let mut ticker: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]);
if is_equal(&ticker, &Value::Null) {
continue;
}
if !is_true(&(Value::Bool(in_op(&outcomesByTicker, &ticker)))) {
add_element_to_object(&mut outcomesByTicker, &ticker, Value::List(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.clone());
crate::set_value(&mut outcomesByTicker, &ticker, grouped.clone());
add_element_to_object(&mut outcomesByTicker, &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 = get_array_length(&tickers);
let mut startIndex: Value = Value::Int(0);
while is_less_than(&startIndex, &tickersLength) {
let mut endIndex: Value = self.sum(&[startIndex.clone(), chunkSize.clone()]);
if is_greater_than(&endIndex, &tickersLength) {
endIndex = tickersLength.clone();
}
let mut chunk: Value = Value::List(vec![]);
{
let mut i: Value = startIndex.clone();
let mut __for_first_1218: bool = true;
while { if !__for_first_1218 { i = add(&i, &Value::Int(1)); } __for_first_1218 = false; is_less_than(&i, &endIndex) } {
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(",".to_string())));
m.insert("limit".to_string(), chunkSize.clone());
m
});
let __ws_arg_3 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.kalshi_public_get_markets(&[__ws_arg_3]).await;
let mut rawMarkets: Value = self.safe_list_k(response.clone(), "markets", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1220: bool = true;
while { if !__for_first_1220 { i = add(&i, &Value::Int(1)); } __for_first_1220 = false; is_less_than(&i, &get_array_length(&rawMarkets)) } {
let mut raw: Value = get_value(&rawMarkets, &i);
let mut raw: Value = get_value(&rawMarkets, &i);
let mut marketTicker: Value = self.safe_string_k(raw.clone(), "ticker", &[]);
if is_true(&(is_equal(&marketTicker, &Value::Null))) || !is_true(&(Value::Bool(in_op(&outcomesByTicker, &marketTicker)))) {
continue;
}
let mut grouped: Value = get_value(&outcomesByTicker, &marketTicker);
let mut grouped: Value = get_value(&outcomesByTicker, &marketTicker);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1219: bool = true;
while { if !__for_first_1219 { j = add(&j, &Value::Int(1)); } __for_first_1219 = false; is_less_than(&j, &get_array_length(&grouped)) } {
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 !is_equal(&symbolKey, &Value::Null) {
add_element_to_object(&mut result, &symbolKey, ticker.clone());
}
}
}
}
}
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(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]);
let mut isNo: bool = is_equal(&get_value(&outcomeObj, &Value::Str("label".to_string())), &Value::Str("NO".to_string()));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone());
m
});
let __ws_arg_4 = self.extend(request.clone(), &[params.clone()]);
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()]);
let mut timestamp: Value = self.milliseconds();
// Kalshi uses YES-side perspective: `yes` = bids, `no` = asks (inverted)
let mut rawYes: Value = self.safe_list_k(book.clone(), "yes_dollars", &[Value::List(vec![])]);
let mut rawNo: Value = self.safe_list_k(book.clone(), "no_dollars", &[Value::List(vec![])]);
// Convert [price_cents, size] → [price, size]
let mut bids: Value = Value::List(vec![]);
let mut asks: Value = Value::List(vec![]);
if is_true(&isNo) {
{
let mut bi: Value = Value::Int(0);
let mut __for_first_1221: bool = true;
while { if !__for_first_1221 { bi = add(&bi, &Value::Int(1)); } __for_first_1221 = false; is_less_than(&bi, &get_array_length(&rawNo)) } {
let mut price: Value = self.safe_number(get_value(&rawNo, &bi), Value::Int(0), &[]);
append_to_array(&mut bids, Value::List(vec![price.clone(), self.safe_number(get_value(&rawNo, &bi), Value::Int(1), &[])]));
}
}
{
let mut ai: Value = Value::Int(0);
let mut __for_first_1222: bool = true;
while { if !__for_first_1222 { ai = add(&ai, &Value::Int(1)); } __for_first_1222 = false; is_less_than(&ai, &get_array_length(&rawYes)) } {
let mut yesPrice: Value = self.safe_number(get_value(&rawYes, &ai), Value::Int(0), &[]);
let mut price: Value = ternary(is_true(&(!is_equal(&yesPrice, &Value::Null))), self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &self.number_to_string(yesPrice.clone())), &[]), Value::Null);
append_to_array(&mut asks, Value::List(vec![price.clone(), self.safe_number(get_value(&rawYes, &ai), Value::Int(1), &[])]));
}
}
} else {
{
let mut bi: Value = Value::Int(0);
let mut __for_first_1223: bool = true;
while { if !__for_first_1223 { bi = add(&bi, &Value::Int(1)); } __for_first_1223 = false; is_less_than(&bi, &get_array_length(&rawYes)) } {
let mut price: Value = self.safe_number(get_value(&rawYes, &bi), Value::Int(0), &[]);
append_to_array(&mut bids, Value::List(vec![price.clone(), self.safe_number(get_value(&rawYes, &bi), Value::Int(1), &[])]));
}
}
{
let mut ai: Value = Value::Int(0);
let mut __for_first_1224: bool = true;
while { if !__for_first_1224 { ai = add(&ai, &Value::Int(1)); } __for_first_1224 = false; is_less_than(&ai, &get_array_length(&rawNo)) } {
let mut noPrice: Value = self.safe_number(get_value(&rawNo, &ai), Value::Int(0), &[]);
let mut price: Value = ternary(is_true(&(!is_equal(&noPrice, &Value::Null))), self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &self.number_to_string(noPrice.clone())), &[]), Value::Null);
append_to_array(&mut asks, Value::List(vec![price.clone(), self.safe_number(get_value(&rawNo, &ai), Value::Int(1), &[])]));
}
}
}
return self.safe_prediction_order_book(self.sorted_orders(self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome.clone()]), timestamp.clone(), bids.clone(), asks.clone()), &[outcomeObj.clone()]);
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
bids = self.sort_by(bids.clone(), Value::Int(0), &[Value::Bool(true)]);
asks = self.sort_by(asks.clone(), Value::Int(0), &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcome.clone());
m.insert("bids".to_string(), bids.clone());
m.insert("asks".to_string(), asks.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
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".to_string()));
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(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]);
let mut seriesTicker: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("seriesTicker".to_string()), &[ticker.clone()]);
let mut periodMin: Value = self.safe_integer(self.timeframes.clone(), timeframe.clone(), &[]);
if is_equal(&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(", ".to_string()));
panic!("{}", crate::exchange_errors::bad_request(add(&add(&add(&add(&add(&self.id, &Value::Str(" fetchOHLCV() does not support the ".to_string())), &timeframe), &Value::Str(" timeframe (supported: ".to_string())), &supported), &Value::Str(")".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("series_ticker".to_string(), seriesTicker.clone());
m.insert("ticker".to_string(), ticker.clone());
m.insert("period_interval".to_string(), periodMin.clone());
m
});
let mut now: Value = self.seconds();
let mut tf: Value = self.parse_timeframe(timeframe.clone());
if !is_equal(&since, &Value::Null) {
let mut sinceS: Value = self.parse_to_int(divide(&since, &Value::Int(1000)));
add_element_to_object(&mut request, &Value::Str("start_ts".to_string()), sinceS.clone());
if !is_equal(&limit, &Value::Null) {
let mut end: Value = self.sum(&[sinceS.clone(), multiply(&limit, &tf)]);
add_element_to_object(&mut request, &Value::Str("end_ts".to_string()), ternary(is_true(&(is_less_than(&end, &now))), end.clone(), now.clone()));
} else {
// the candlesticks endpoint requires end_ts - default to now
add_element_to_object(&mut request, &Value::Str("end_ts".to_string()), now.clone());
}
} else {
let mut defaultLimit: Value = self.safe_integer_k(self.options.clone(), "defaultFetchOHLCVLimit", &[Value::Int(200)]);
let mut candlesCount: Value = ternary(is_true(&(!is_equal(&limit, &Value::Null))), limit.clone(), defaultLimit.clone());
add_element_to_object(&mut request, &Value::Str("end_ts".to_string()), now.clone());
add_element_to_object(&mut request, &Value::Str("start_ts".to_string()), subtract(&now, &(multiply(&candlesCount, &tf))));
}
let __ws_arg_5 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "candlesticks", &[Value::List(vec![])]);
let mut usableCandles: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1225: bool = true;
while { if !__for_first_1225 { i = add(&i, &Value::Int(1)); } __for_first_1225 = false; is_less_than(&i, &get_array_length(&candles)) } {
let mut candle: Value = get_value(&candles, &i);
let mut candle: Value = get_value(&candles, &i);
let mut priceObj: Value = self.safe_dict_k(candle.clone(), "price", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut openPrice: Value = self.safe_number_k(priceObj.clone(), "open_dollars", &[]);
let mut previousPrice: Value = self.safe_number_k(priceObj.clone(), "previous_dollars", &[]);
if is_true(&(!is_equal(&openPrice, &Value::Null))) || is_true(&(!is_equal(&previousPrice, &Value::Null))) {
append_to_array(&mut usableCandles, candle.clone());
}
}
}
// 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)
add_element_to_object(&mut self.options, &Value::Str("ohlcvCandleDurationSeconds".to_string()), tf.clone());
return self.parse_ohlc_vs(usableCandles.clone(), &[outcomeObj.clone(), timeframe.clone(), since.clone(), limit.clone()]);
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(ohlcv.clone(), Value::Str("end_period_ts".to_string()), &[]);
let mut durationSeconds: Value = self.safe_integer_k(self.options.clone(), "ohlcvCandleDurationSeconds", &[Value::Int(0)]);
let mut timestamp: Value = endTimestamp.clone();
if !is_equal(&endTimestamp, &Value::Null) {
timestamp = subtract(&endTimestamp, &multiply(&durationSeconds, &Value::Int(1000)));
}
return Value::List(vec![timestamp.clone(), 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.clone(), "close_dollars", &[previous.clone()]), self.safe_number_k(ohlcv.clone(), "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(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone());
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let __ws_arg_6 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.kalshi_public_get_markets_trades(&[__ws_arg_6]).await;
let mut trades: Value = self.safe_list_k(response.clone(), "trades", &[Value::List(vec![])]);
let mut filteredTrades: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1226: bool = true;
while { if !__for_first_1226 { i = add(&i, &Value::Int(1)); } __for_first_1226 = false; is_less_than(&i, &get_array_length(&trades)) } {
let mut trade: Value = get_value(&trades, &i);
let mut trade: Value = get_value(&trades, &i);
let mut tradeTicker: Value = self.safe_string2(trade.clone(), Value::Str("ticker".to_string()), Value::Str("market_ticker".to_string()), &[]);
if is_equal(&tradeTicker, &Value::Null) || is_equal(&tradeTicker, &ticker) {
append_to_array(&mut filteredTrades, trade.clone());
}
}
}
return self.parse_prediction_trades(filteredTrades.clone(), &[outcomeObj.clone(), since.clone(), limit.clone()]);
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".to_string()), Value::Str("price_dollars".to_string()), &[]);
let mut priceCents: Value = self.safe_number2(trade.clone(), Value::Str("yes_price".to_string()), Value::Str("price".to_string()), &[]);
let mut price: Value = Value::Null;
if !is_equal(&priceDollars, &Value::Null) {
price = priceDollars.clone();
} else if !is_equal(&priceCents, &Value::Null) {
price = divide(&priceCents, &Value::Int(100));
}
let mut amountFp: Value = self.safe_number2(trade.clone(), Value::Str("count_fp".to_string()), Value::Str("size_fp".to_string()), &[]);
let mut amount: Value = self.safe_number_k(trade.clone(), "count", &[amountFp.clone()]);
let mut rawSide: Value = self.safe_string_lower(trade.clone(), Value::Str("taker_side".to_string()), &[]);
let mut marketAny: Value = market.clone();
let mut outcomeObj: Value = self.safe_outcome(self.safe_string_k(marketAny.clone(), "outcome", &[]), &[marketAny.clone()]);
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(outcomeObj.clone(), Value::Str("label".to_string()), &[self.safe_string_lower(marketInfo.clone(), Value::Str("outcomeLabel".to_string()), &[])]);
let mut outcomeSymbol: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
let mut outcomeId: Value = self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]);
let mut side: Value = Value::Null;
if is_equal(&rawSide, &Value::Str("yes".to_string())) || is_equal(&rawSide, &Value::Str("no".to_string())) {
if is_equal(&requestedOutcomeLabel, &Value::Str("yes".to_string())) || is_equal(&requestedOutcomeLabel, &Value::Str("no".to_string())) {
side = ternary(is_true(&(is_equal(&rawSide, &requestedOutcomeLabel))), Value::Str("buy".to_string()), Value::Str("sell".to_string()));
} else {
side = ternary(is_true(&(is_equal(&rawSide, &Value::Str("yes".to_string())))), Value::Str("buy".to_string()), Value::Str("sell".to_string()));
}
}
let mut cost: Value = Value::Null;
if is_true(&(!is_equal(&price, &Value::Null))) && is_true(&(!is_equal(&amount, &Value::Null))) {
cost = multiply(&price, &amount);
}
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts.clone()));
m.insert("outcome".to_string(), outcomeSymbol.clone());
m.insert("outcomeId".to_string(), outcomeId.clone());
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("market".to_string()), Value::Str("outcome".to_string()), &[]));
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("takerOrMaker".to_string(), Value::Str("taker".to_string()));
m.insert("price".to_string(), price.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("cost".to_string(), cost.clone());
m.insert("fee".to_string(), Value::Null);
m
}), &[market.clone()]);
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 !is_equal(&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 !is_equal(&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 is_equal(&outcomeObj, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires a valid outcome".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("ticker".to_string()), self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let __ws_arg_7 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.kalshi_private_get_portfolio_fills(&[__ws_arg_7]).await;
let mut fills: Value = self.safe_list_k(response.clone(), "fills", &[Value::List(vec![])]);
let mut fillsLength: Value = get_array_length(&fills);
let mut trades: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1227: bool = true;
while { if !__for_first_1227 { i = add(&i, &Value::Int(1)); } __for_first_1227 = false; is_less_than(&i, &fillsLength) } {
append_to_array(&mut trades, self.parse_my_trade(get_value(&fills, &i), &[outcomeObj.clone()]));
}
}
let mut wantedOutcome: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
wantedOutcome = self.safe_string(self.outcome(outcome.clone()), Value::Str("outcome".to_string()), &[]);
}
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1228: bool = true;
while { if !__for_first_1228 { i = add(&i, &Value::Int(1)); } __for_first_1228 = false; is_less_than(&i, &get_array_length(&trades)) } {
let mut trade: Value = get_value(&trades, &i);
let mut trade: Value = get_value(&trades, &i);
if is_true(&(is_equal(&wantedOutcome, &Value::Null))) || is_true(&(is_equal(&self.safe_string_k(trade.clone(), "outcome", &[]), &wantedOutcome))) {
append_to_array(&mut result, trade.clone());
}
}
}
return self.filter_by_since_limit(result.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string())]);
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".to_string()), Value::Str("trade_id".to_string()), &[]);
let mut orderId: Value = self.safe_string_k(fill.clone(), "order_id", &[]);
let mut ticker: Value = self.safe_string2(fill.clone(), Value::Str("ticker".to_string()), Value::Str("market_ticker".to_string()), &[]);
// the leg the fill executed on ('yes' | 'no'); NO is addressed as <ticker>-NO
let mut sideLeg: Value = self.safe_string_lower(fill.clone(), Value::Str("side".to_string()), &[]);
let mut outcomeKey: Value = ticker.clone();
if is_true(&(is_equal(&sideLeg, &Value::Str("no".to_string())))) && is_true(&(!is_equal(&ticker, &Value::Null))) {
outcomeKey = add(&ticker, &Value::Str("-NO".to_string()));
}
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: Value = self.safe_string_lower(fill.clone(), Value::Str("action".to_string()), &[]);
let mut side: Value = ternary(is_true(&(is_equal(&action, &Value::Str("sell".to_string())))), Value::Str("sell".to_string()), Value::Str("buy".to_string()));
// price is the price of the leg held; kalshi reports dollars in V2, cents otherwise
let mut price: Value = Value::Null;
if is_equal(&sideLeg, &Value::Str("no".to_string())) {
price = self.safe_number_k(fill.clone(), "no_price_dollars", &[]);
if is_equal(&price, &Value::Null) {
let mut noCents: Value = self.safe_number_k(fill.clone(), "no_price", &[]);
if !is_equal(&noCents, &Value::Null) {
price = divide(&noCents, &Value::Int(100));
}
}
} else {
price = self.safe_number_k(fill.clone(), "yes_price_dollars", &[]);
if is_equal(&price, &Value::Null) {
let mut yesCents: Value = self.safe_number_k(fill.clone(), "yes_price", &[]);
if !is_equal(&yesCents, &Value::Null) {
price = divide(&yesCents, &Value::Int(100));
}
}
}
let mut amount: Value = self.safe_number2(fill.clone(), Value::Str("count_fp".to_string()), Value::Str("count".to_string()), &[]);
let mut cost: Value = Value::Null;
if is_true(&(!is_equal(&price, &Value::Null))) && is_true(&(!is_equal(&amount, &Value::Null))) {
cost = multiply(&price, &amount);
}
let mut isTaker: Value = self.safe_bool_k(fill.clone(), "is_taker", &[Value::Bool(true)]);
let mut takerOrMaker: Value = ternary(is_true(&(is_equal(&isTaker, &Value::Bool(true)))), Value::Str("taker".to_string()), Value::Str("maker".to_string()));
let mut feeCost: Value = self.safe_number_k(fill.clone(), "fee_cost", &[]);
let mut fee: Value = Value::Null;
if !is_equal(&feeCost, &Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost.clone());
m.insert("currency".to_string(), Value::Str("USD".to_string()));
m
});
}
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("info".to_string(), fill.clone());
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts.clone()));
m.insert("outcome".to_string(), self.safe_string_k(mkt.clone(), "outcome", &[outcomeKey.clone()]));
m.insert("outcomeId".to_string(), self.safe_string2(mkt.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]));
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".to_string()), Value::Str("outcome".to_string()), &[]));
m.insert("order".to_string(), orderId.clone());
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("takerOrMaker".to_string(), takerOrMaker.clone());
m.insert("price".to_string(), price.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("cost".to_string(), cost.clone());
m.insert("fee".to_string(), fee.clone());
m
}), &[market.clone()]);
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.clone()]).await;
return self.parse_balance(response.clone());
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.clone(), "balance", &[]);
let mut total: Value = Value::Null;
if !is_equal(&balanceCents, &Value::Null) {
total = divide(&balanceCents, &Value::Int(100));
}
add_element_to_object(&mut result, &Value::Str("USD".to_string()), 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.clone());
m
}));
return self.safe_balance(result.clone());
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 !is_equal(&outcomes, &Value::Null) {
outcomesLength = get_array_length(&outcomes);
}
if is_greater_than(&outcomesLength, &Value::Int(0)) {
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.clone()]).await;
let mut positions: Value = self.safe_list_k(response.clone(), "market_positions", &[Value::List(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.clone(), &[]);
if is_equal(&outcomesLength, &Value::Int(0)) {
return parsed;
}
let mut wantedTickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_equal(&outcomes, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchPositions() missing outcomes".to_string()))));
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1229: bool = true;
while { if !__for_first_1229 { i = add(&i, &Value::Int(1)); } __for_first_1229 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
let mut outcomeObj: Value = self.outcome(get_value(&outcomes, &i));
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketTicker: Value = self.safe_string_k(outcomeInfo.clone(), "ticker", &[]);
if !is_equal(&marketTicker, &Value::Null) {
add_element_to_object(&mut wantedTickers, &marketTicker, Value::Bool(true));
}
}
}
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1230: bool = true;
while { if !__for_first_1230 { i = add(&i, &Value::Int(1)); } __for_first_1230 = false; is_less_than(&i, &get_array_length(&parsed)) } {
let mut position: Value = get_value(&parsed, &i);
let mut position: Value = get_value(&parsed, &i);
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.clone(), "ticker", &[]);
if is_true(&(!is_equal(&positionTicker, &Value::Null))) && is_true(&(Value::Bool(in_op(&wantedTickers, &positionTicker)))) {
append_to_array(&mut result, position.clone());
}
}
}
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 !is_equal(&outcome, &Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let __ws_arg_8 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.kalshi_private_get_portfolio_settlements(&[__ws_arg_8]).await;
let mut rawSettlements: Value = self.safe_list_k(response.clone(), "settlements", &[Value::List(vec![])]);
let mut rawSettlementsLength: Value = get_array_length(&rawSettlements);
let mut parsed: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1231: bool = true;
while { if !__for_first_1231 { i = add(&i, &Value::Int(1)); } __for_first_1231 = false; is_less_than(&i, &rawSettlementsLength) } {
append_to_array(&mut parsed, self.parse_settlement(get_value(&rawSettlements, &i), &[]));
}
}
let mut wantedOutcome: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
wantedOutcome = self.safe_string(self.outcome(outcome.clone()), Value::Str("outcome".to_string()), &[]);
}
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1232: bool = true;
while { if !__for_first_1232 { i = add(&i, &Value::Int(1)); } __for_first_1232 = false; is_less_than(&i, &get_array_length(&parsed)) } {
let mut settlement: Value = get_value(&parsed, &i);
let mut settlement: Value = get_value(&parsed, &i);
if is_true(&(is_equal(&wantedOutcome, &Value::Null))) || is_true(&(is_equal(&self.safe_string_k(settlement.clone(), "outcome", &[]), &wantedOutcome))) {
append_to_array(&mut result, settlement.clone());
}
}
}
return self.filter_by_since_limit(result.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string())]);
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".to_string()), Value::Str("yes_count".to_string()), &[Value::Int(0)]);
let mut noCount: Value = self.safe_number2(settlement.clone(), Value::Str("no_count_fp".to_string()), Value::Str("no_count".to_string()), &[Value::Int(0)]);
let mut heldYes: Value = Value::Bool(is_greater_than_or_equal(&yesCount, &noCount));
let mut heldLabel: Value = ternary(is_true(&(heldYes)), Value::Str("YES".to_string()), Value::Str("NO".to_string()));
let mut tickerMissing: bool = is_equal(&ticker, &Value::Null);
let mut useHeldYesTicker: Value = Value::Bool(is_true(&heldYes) || is_true(&tickerMissing));
let mut heldTicker: Value = ternary(is_true(&(useHeldYesTicker)), ticker.clone(), (add(&ticker, &Value::Str("-NO".to_string()))));
let mut mkt: Value = self.safe_outcome(heldTicker.clone(), &[market.clone()]);
// which leg won; market_result is yes or no
let mut marketResult: Value = self.safe_string_upper(settlement.clone(), Value::Str("market_result".to_string()), &[]);
let mut won: Value = Value::Bool(is_equal(&marketResult, &heldLabel));
// kalshi reports money as dollar keys on V2, else cents
let mut payout: Value = self.safe_number_k(settlement.clone(), "revenue_dollars", &[]);
if is_equal(&payout, &Value::Null) {
let mut revenueCents: Value = self.safe_number_k(settlement.clone(), "revenue", &[]);
if !is_equal(&revenueCents, &Value::Null) {
payout = divide(&revenueCents, &Value::Int(100));
}
}
let mut costKey: Value = ternary(is_true(&(heldYes)), Value::Str("yes_total_cost".to_string()), Value::Str("no_total_cost".to_string()));
let mut costDollarsKey: Value = ternary(is_true(&(heldYes)), Value::Str("yes_total_cost_dollars".to_string()), Value::Str("no_total_cost_dollars".to_string()));
let mut cost: Value = self.safe_number(settlement.clone(), costDollarsKey.clone(), &[]);
if is_equal(&cost, &Value::Null) {
let mut costCents: Value = self.safe_number(settlement.clone(), costKey.clone(), &[]);
if !is_equal(&costCents, &Value::Null) {
cost = divide(&costCents, &Value::Int(100));
}
}
let mut pnl: Value = Value::Null;
if is_true(&(!is_equal(&payout, &Value::Null))) && is_true(&(!is_equal(&cost, &Value::Null))) {
pnl = subtract(&payout, &cost);
}
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.clone());
m.insert("id".to_string(), ticker.clone());
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts.clone()));
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".to_string()), Value::Str("id".to_string()), &[heldTicker.clone()]));
m.insert("market".to_string(), self.safe_string2(mkt.clone(), Value::Str("market".to_string()), Value::Str("outcome".to_string()), &[]));
m.insert("event".to_string(), Value::Null);
m.insert("result".to_string(), marketResult.clone());
m.insert("won".to_string(), won.clone());
m.insert("amount".to_string(), ternary(is_true(&(heldYes)), yesCount.clone(), noCount.clone()));
m.insert("price".to_string(), ternary(is_true(&(won)), Value::Int(1), Value::Int(0)));
m.insert("cost".to_string(), cost.clone());
m.insert("payout".to_string(), payout.clone());
m.insert("pnl".to_string(), pnl.clone());
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.clone()]);
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 !is_equal(&yesContracts, &Value::Null) {
positionSide = ternary(is_true(&(is_greater_than_or_equal(&yesContracts, &Value::Int(0)))), Value::Str("long".to_string()), Value::Str("short".to_string()));
contractsValue = self.parse_number(crate::precise::Precise::stringAbs(&self.number_to_string(yesContracts.clone())), &[]);
}
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.clone()]));
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("market".to_string()), Value::Str("outcome".to_string()), &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("contracts".to_string(), contractsValue.clone());
m.insert("contractSize".to_string(), Value::Int(1));
m.insert("side".to_string(), positionSide.clone());
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".to_string()));
m.insert("marginType".to_string(), Value::Str("cross".to_string()));
m.insert("percentage".to_string(), Value::Null);
m.insert("info".to_string(), position.clone());
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 !is_equal(&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".to_string()));
m
});
let mut outcomeObj: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
outcomeObj = self.outcome(outcome.clone());
if is_equal(&outcomeObj, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires a valid outcome".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("ticker".to_string()), self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]));
}
let __ws_arg_9 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.kalshi_private_get_portfolio_orders(&[__ws_arg_9]).await;
let mut orders: Value = self.safe_list_k(response.clone(), "orders", &[Value::List(vec![])]);
return self.parse_prediction_orders(orders.clone(), &[outcomeObj.clone(), since.clone(), limit.clone()]);
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 !is_equal(&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 !is_equal(&outcome, &Value::Null) {
outcomeObj = self.outcome(outcome.clone());
if is_equal(&outcomeObj, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires a valid outcome".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("ticker".to_string()), self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]));
}
let __ws_arg_10 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.kalshi_private_get_portfolio_orders(&[__ws_arg_10]).await;
let mut orders: Value = self.safe_list_k(response.clone(), "orders", &[Value::List(vec![])]);
return self.parse_prediction_orders(orders.clone(), &[outcomeObj.clone(), since.clone(), limit.clone()]);
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.clone(), Value::Null, Value::Null, params.clone()]).await;
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1233: bool = true;
while { if !__for_first_1233 { i = add(&i, &Value::Int(1)); } __for_first_1233 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut order: Value = get_value(&orders, &i);
let mut order: Value = get_value(&orders, &i);
let mut status: Value = self.safe_string_k(order.clone(), "status", &[]);
if is_true(&(is_equal(&status, &Value::Str("closed".to_string())))) || is_true(&(is_equal(&status, &Value::Str("canceled".to_string())))) {
append_to_array(&mut result, order.clone());
}
}
}
return self.filter_by_since_limit(result.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string())]);
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 !is_equal(&outcome, &Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
}
let __ws_arg_11 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id.clone());
m
}), &[params.clone()]);
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: Value = self.safe_string_lower(order.clone(), Value::Str("side".to_string()), &[]);
let mut outcomeKey: Value = ticker.clone();
if is_true(&(is_equal(&sideLeg, &Value::Str("no".to_string())))) && is_true(&(!is_equal(&ticker, &Value::Null))) {
outcomeKey = add(&ticker, &Value::Str("-NO".to_string()));
}
let mut mkt: Value = self.safe_outcome(outcomeKey.clone(), &[market.clone()]);
let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "status", &[]));
// 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: Value = self.safe_string_lower(order.clone(), Value::Str("action".to_string()), &[]);
let mut side: Value = Value::Null;
if is_equal(&action, &Value::Str("buy".to_string())) {
side = Value::Str("buy".to_string());
} else if is_equal(&action, &Value::Str("sell".to_string())) {
side = Value::Str("sell".to_string());
}
// price in the outcome's own leg: V2 returns *_price_dollars (already dollars),
// legacy returned yes_price/no_price in cents
let mut labelIsNo: Value = Value::Bool(is_equal(&self.safe_string_upper(mkt.clone(), Value::Str("label".to_string()), &[]), &Value::Str("NO".to_string())));
let mut dollarsKey: Value = ternary(is_true(&(labelIsNo)), Value::Str("no_price_dollars".to_string()), Value::Str("yes_price_dollars".to_string()));
let mut centsKey: Value = ternary(is_true(&(labelIsNo)), Value::Str("no_price".to_string()), Value::Str("yes_price".to_string()));
let mut price: Value = self.safe_number(order.clone(), dollarsKey.clone(), &[]);
if is_equal(&price, &Value::Null) {
let mut priceCents: Value = self.safe_number(order.clone(), centsKey.clone(), &[]);
if !is_equal(&priceCents, &Value::Null) {
price = divide(&priceCents, &Value::Int(100));
}
}
// 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".to_string()), Value::Str("count".to_string()), &[]);
let mut filled: Value = self.safe_number2(order.clone(), Value::Str("fill_count_fp".to_string()), Value::Str("filled_count".to_string()), &[Value::Int(0)]);
let mut remaining: Value = self.safe_number_k(order.clone(), "remaining_count_fp", &[]);
if is_true(&(is_equal(&remaining, &Value::Null))) && is_true(&(!is_equal(&amount, &Value::Null))) && is_true(&(!is_equal(&filled, &Value::Null))) {
remaining = subtract(&amount, &filled);
}
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.clone());
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.clone()));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("status".to_string(), status.clone());
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".to_string()), Value::Str("id".to_string()), &[]));
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".to_string()), Value::Str("outcome".to_string()), &[]));
m.insert("type".to_string(), self.safe_string_lower(order.clone(), Value::Str("type".to_string()), &[Value::Str("limit".to_string())]));
m.insert("timeInForce".to_string(), Value::Str("GTC".to_string()));
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), price.clone());
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.clone());
m.insert("cost".to_string(), Value::Null);
m.insert("filled".to_string(), filled.clone());
m.insert("remaining".to_string(), remaining.clone());
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::List(vec![]));
m
}), &[mkt.clone()]);
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) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("resting".to_string(), Value::Str("open".to_string()));
m.insert("executed".to_string(), Value::Str("closed".to_string()));
m.insert("canceled".to_string(), Value::Str("canceled".to_string()));
m.insert("pending".to_string(), Value::Str("open".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
/*
* @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 is_equal(&price, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &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' }".to_string()))));
}
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut ticker: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]);
let mut isNo: bool = is_equal(&get_value(&outcomeObj, &Value::Str("label".to_string())), &Value::Str("NO".to_string()));
let mut isBuy: Value = Value::Bool(is_equal(&side, &Value::Str("buy".to_string())));
// 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 = ternary(is_true(&(isBuy)), Value::Str("bid".to_string()), Value::Str("ask".to_string()));
let mut yesPrice: Value = price.clone();
if is_true(&isNo) {
bookSide = ternary(is_true(&(isBuy)), Value::Str("ask".to_string()), Value::Str("bid".to_string()));
if !is_equal(&price, &Value::Null) {
yesPrice = self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &self.number_to_string(price.clone())), &[]);
}
}
let mut isMarket: Value = Value::Bool(is_equal(&type_var, &Value::Str("market".to_string())));
// accept the unified `timeInForce` and map it onto kalshi's vocabulary; the native
// `time_in_force` param (handled below) still overrides
let mut unifiedTif: Value = self.safe_string_upper(params.clone(), Value::Str("timeInForce".to_string()), &[]);
params = self.omit(params.clone(), Value::Str("timeInForce".to_string()), &[]);
let mut defaultTif: Value = ternary(is_true(&(isMarket)), Value::Str("immediate_or_cancel".to_string()), Value::Str("good_till_canceled".to_string()));
// kalshi has BOTH immediate_or_cancel (partial ok) and fill_or_kill (all-or-nothing);
// map the unified tokens to the matching primitive rather than collapsing FOK into IOC
if is_equal(&unifiedTif, &Value::Str("IOC".to_string())) {
defaultTif = Value::Str("immediate_or_cancel".to_string());
} else if is_equal(&unifiedTif, &Value::Str("FOK".to_string())) {
defaultTif = Value::Str("fill_or_kill".to_string());
} else if is_equal(&unifiedTif, &Value::Str("GTC".to_string())) {
defaultTif = Value::Str("good_till_canceled".to_string());
}
let mut timeInForce: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("time_in_force".to_string()), &[defaultTif.clone()]); timeInForce = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut stp: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("self_trade_prevention_type".to_string()), &[Value::Str("taker_at_cross".to_string())]); stp = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ticker".to_string(), ticker.clone());
m.insert("side".to_string(), bookSide.clone());
m.insert("count".to_string(), self.number_to_string(amount.clone()));
m.insert("time_in_force".to_string(), timeInForce.clone());
m.insert("self_trade_prevention_type".to_string(), stp.clone());
m
});
if !is_equal(&yesPrice, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("price".to_string()), self.number_to_string(yesPrice.clone()));
}
let __ws_arg_12 = self.extend(request.clone(), &[params.clone()]);
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.clone()]);
add_element_to_object(&mut order, &Value::Str("side".to_string()), side.clone());
add_element_to_object(&mut order, &Value::Str("amount".to_string()), amount.clone());
add_element_to_object(&mut order, &Value::Str("price".to_string()), price.clone());
// 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.clone(), "fill_count", &[]);
if !is_equal(&filledCount, &Value::Null) {
add_element_to_object(&mut order, &Value::Str("filled".to_string()), filledCount.clone());
} else if is_true(&(!is_equal(&remainingCount, &Value::Null))) && is_true(&(!is_equal(&amount, &Value::Null))) {
add_element_to_object(&mut order, &Value::Str("filled".to_string()), subtract(&amount, &remainingCount));
}
if !is_equal(&remainingCount, &Value::Null) {
add_element_to_object(&mut order, &Value::Str("remaining".to_string()), remainingCount.clone());
}
if is_equal(&get_value(&order, &Value::Str("status".to_string())), &Value::Null) {
let mut resolvedStatus: Value = Value::Str("open".to_string());
if is_true(&(!is_equal(&remainingCount, &Value::Null))) && is_true(&(is_equal(&remainingCount, &Value::Int(0)))) {
resolvedStatus = Value::Str("closed".to_string());
}
add_element_to_object(&mut order, &Value::Str("status".to_string()), resolvedStatus.clone());
}
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 is_equal(&price, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" editOrder() requires a price - kalshi has only limit orders".to_string()))));
}
if is_equal(&amount, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" editOrder() requires an amount".to_string()))));
}
self.load_outcome(outcome.clone(), &[]).await;
self.cancel_order(id.clone(), &[outcome.clone()]).await;
return self.create_order(outcome.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]).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 !is_equal(&outcome, &Value::Null) {
outcomeObj = self.load_outcome(outcome.clone(), &[]).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.clone()]);
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.clone()]);
if is_equal(&get_value(&order, &Value::Str("id".to_string())), &Value::Null) {
add_element_to_object(&mut order, &Value::Str("id".to_string()), id.clone());
}
if is_equal(&get_value(&order, &Value::Str("status".to_string())), &Value::Null) {
add_element_to_object(&mut order, &Value::Str("status".to_string()), Value::Str("canceled".to_string()));
}
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 !is_equal(&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".to_string()));
m
});
if !is_equal(&outcome, &Value::Null) {
let mut outcomeObj: Value = self.outcome(outcome.clone());
add_element_to_object(&mut request, &Value::Str("ticker".to_string()), self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("ticker".to_string()), &[]));
}
let mut restingResponse: Value = self.kalshi_private_get_portfolio_orders(&[request.clone()]).await;
let mut restingOrders: Value = self.safe_list_k(restingResponse.clone(), "orders", &[Value::List(vec![])]);
let mut restingOrdersLength: Value = get_array_length(&restingOrders);
let mut canceledOrders: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1234: bool = true;
while { if !__for_first_1234 { i = add(&i, &Value::Int(1)); } __for_first_1234 = false; is_less_than(&i, &restingOrdersLength) } {
let mut restingOrder: Value = get_value(&restingOrders, &i);
let mut restingOrder: Value = get_value(&restingOrders, &i);
let mut orderId: Value = self.safe_string_k(restingOrder.clone(), "order_id", &[]);
if !is_equal(&orderId, &Value::Null) {
let __ws_arg_14 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), orderId.clone());
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.clone(), &[]);
add_element_to_object(&mut parsed, &Value::Str("status".to_string()), Value::Str("canceled".to_string()));
append_to_array(&mut canceledOrders, parsed.clone());
}
}
}
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 is_equal(&queries, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchEvents() missing queries".to_string()))));
}
let mut queriesLength: Value = get_array_length(&queries);
params = self.omit(params.clone(), Value::List(vec![Value::Str("query".to_string()), Value::Str("queries".to_string())]), &[]);
let mut userLimit: Value = self.safe_integer_k(params.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 !is_equal(&userLimit, &Value::Null) {
fetchCap = userLimit.clone();
}
// 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: Value = self.safe_string_k(params.clone(), "status", &[self.safe_string(self.options.clone(), Value::Str("defaultEventStatus".to_string()), &[Value::Str("open".to_string())])]);
let mut status: Value = Value::Null;
if is_true(&(is_equal(&requestedStatus, &Value::Str("active".to_string())))) || is_true(&(is_equal(&requestedStatus, &Value::Str("open".to_string())))) {
status = Value::Str("open".to_string());
} else if is_true(&(is_equal(&requestedStatus, &Value::Str("closed".to_string())))) || is_true(&(is_equal(&requestedStatus, &Value::Str("inactive".to_string())))) {
status = Value::Str("closed".to_string());
} else if is_true(&(is_equal(&requestedStatus, &Value::Str("settled".to_string())))) || is_true(&(is_equal(&requestedStatus, &Value::Str("resolved".to_string())))) {
status = Value::Str("settled".to_string());
}
// anything beyond the unified keys is forwarded verbatim to the events endpoint (kalshi filters)
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("status".to_string()), Value::Str("limit".to_string()), Value::Str("maxPages".to_string()), Value::Str("sort".to_string()), Value::Str("searchIn".to_string()), Value::Str("eventId".to_string()), Value::Str("slug".to_string()), Value::Str("tags".to_string()), Value::Str("category".to_string()), Value::Str("series_ticker".to_string())]), &[]);
if is_equal(&self.markets, &Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut eventId: Value = self.safe_string2(params.clone(), Value::Str("eventId".to_string()), Value::Str("slug".to_string()), &[]);
let mut rawEvents: Value = Value::List(vec![]);
if is_greater_than(&queriesLength, &Value::Int(0)) {
// free-text search: ranked events from the search endpoint, top `fetchCap` fetched canonically
rawEvents = self.fetch_events_by_query(queries.clone(), fetchCap.clone(), &[rest.clone()]).await;
} else if !is_equal(&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.clone(), &[rest.clone()]).await;
rawEvents = Value::List(vec![fullEvent.clone()]);
} else {
// tags / category / series_ticker resolve to a set of series; fetch their events, capped
let mut seriesTickers: Value = self.resolve_event_series_tickers(&[params.clone()]).await;
let mut seriesTickersLength: Value = get_array_length(&seriesTickers);
if is_equal(&seriesTickersLength, &Value::Int(0)) {
self.require_event_query(&[params.clone()]);
}
rawEvents = self.fetch_series_events(seriesTickers.clone(), status.clone(), fetchCap.clone(), &[rest.clone()]).await;
}
let mut rawEventsLength: Value = get_array_length(&rawEvents);
let mut result: Value = Value::List(vec![]);
{
let mut di: Value = Value::Int(0);
let mut __for_first_1236: bool = true;
while { if !__for_first_1236 { di = add(&di, &Value::Int(1)); } __for_first_1236 = false; is_less_than(&di, &rawEventsLength) } {
let mut parsedEvent: Value = self.parse_event(get_value(&rawEvents, &di));
append_to_array(&mut result, parsedEvent.clone());
// register the parsed markets so populateOutcomes can index their outcomes
let mut parsedMarketsRaw: Value = get_value(&parsedEvent, &Value::Str("markets".to_string()));
let mut parsedMarkets: Value = ternary(is_true(&(!is_equal(&parsedMarketsRaw, &Value::Null))), parsedMarketsRaw.clone(), Value::List(vec![]));
let mut parsedMarketsLength: Value = get_array_length(&parsedMarkets);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1235: bool = true;
while { if !__for_first_1235 { mi = add(&mi, &Value::Int(1)); } __for_first_1235 = false; is_less_than(&mi, &parsedMarketsLength) } {
let mut m: Value = get_value(&parsedMarkets, &mi);
let mut m: Value = get_value(&parsedMarkets, &mi);
add_element_to_object(&mut self.markets, &get_value(&m, &Value::Str("market".to_string())), 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(params.clone(), Value::List(vec![Value::Str("tags".to_string()), Value::Str("category".to_string()), Value::Str("series_ticker".to_string())]), &[]);
return self.apply_event_fetch_params(result.clone(), &[postParams.clone(), Value::List(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 = ternary(is_true(&(!is_equal(&limit, &Value::Null))), limit.clone(), 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::List(vec![]);
let mut queriesLength: Value = get_array_length(&queries);
{
let mut qi: Value = Value::Int(0);
let mut __for_first_1238: bool = true;
while { if !__for_first_1238 { qi = add(&qi, &Value::Int(1)); } __for_first_1238 = false; is_less_than(&qi, &queriesLength) } {
let mut searchResponse: Value = self.elections_public_get_search_series(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("query".to_string(), get_value(&queries, &qi));
m.insert("order_by".to_string(), Value::Str("querymatch".to_string()));
m.insert("page_size".to_string(), pageSize.clone());
m
})]).await;
let mut page: Value = self.safe_list_k(searchResponse.clone(), "current_page", &[Value::List(vec![])]);
let mut pageLength: Value = get_array_length(&page);
{
let mut pi: Value = Value::Int(0);
let mut __for_first_1237: bool = true;
while { if !__for_first_1237 { pi = add(&pi, &Value::Int(1)); } __for_first_1237 = false; is_less_than(&pi, &pageLength) } {
let mut et: Value = self.safe_string_k(get_value(&page, &pi), "event_ticker", &[]);
if !is_equal(&et, &Value::Null) {
let mut already: Value = self.safe_string(seen.clone(), et.clone(), &[]);
if is_equal(&already, &Value::Null) {
add_element_to_object(&mut seen, &et, et.clone());
append_to_array(&mut eventTickers, et.clone());
}
}
}
}
}
}
let mut rawEvents: Value = Value::List(vec![]);
let mut eventTickersLength: Value = get_array_length(&eventTickers);
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1239: bool = true;
while { if !__for_first_1239 { ei = add(&ei, &Value::Int(1)); } __for_first_1239 = false; is_less_than(&ei, &eventTickersLength) } {
let mut collectedLength: Value = get_array_length(&rawEvents);
if is_true(&(!is_equal(&limit, &Value::Null))) && is_true(&(is_greater_than_or_equal(&collectedLength, &limit))) {
break;
}
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut fullEvent: Value = self.fetch_raw_event_by_ticker(get_value(&eventTickers, &ei), &[rest.clone()]).await;
append_to_array(&mut rawEvents, fullEvent.clone());
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if !is_true(&(is_instance(&e, &Value::Str("BadSymbol".to_string())))) {
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.clone());
m.insert("with_nested_markets".to_string(), Value::Bool(true));
m
});
let __ws_arg_15 = self.extend(request.clone(), &[params.clone()]);
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 is_equal(&nestedMarkets, &Value::Null) {
add_element_to_object(&mut fullEvent, &Value::Str("markets".to_string()), self.safe_list_k(response.clone(), "markets", &[Value::List(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 mut collected: Value = Value::List(vec![]);
// tags / category -> documented /series listing
let mut tags: Value = self.safe_list_k(params.clone(), "tags", &[Value::List(vec![])]);
let mut tagsLength: Value = get_array_length(&tags);
{
let mut ti: Value = Value::Int(0);
let mut __for_first_1241: bool = true;
while { if !__for_first_1241 { ti = add(&ti, &Value::Int(1)); } __for_first_1241 = false; is_less_than(&ti, &tagsLength) } {
let mut seriesResponse: Value = self.kalshi_public_get_series(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tags".to_string(), get_value(&tags, &ti));
m
})]).await;
let mut seriesList: Value = self.safe_list_k(seriesResponse.clone(), "series", &[Value::List(vec![])]);
let mut seriesListLength: Value = get_array_length(&seriesList);
{
let mut si: Value = Value::Int(0);
let mut __for_first_1240: bool = true;
while { if !__for_first_1240 { si = add(&si, &Value::Int(1)); } __for_first_1240 = false; is_less_than(&si, &seriesListLength) } {
let mut st: Value = self.safe_string_k(get_value(&seriesList, &si), "ticker", &[]);
if !is_equal(&st, &Value::Null) {
append_to_array(&mut collected, st.clone());
}
}
}
}
}
let mut category: Value = self.safe_string_k(params.clone(), "category", &[]);
if !is_equal(&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.clone());
m
})]).await;
let mut seriesList: Value = self.safe_list_k(seriesResponse.clone(), "series", &[Value::List(vec![])]);
let mut seriesListLength: Value = get_array_length(&seriesList);
{
let mut si: Value = Value::Int(0);
let mut __for_first_1242: bool = true;
while { if !__for_first_1242 { si = add(&si, &Value::Int(1)); } __for_first_1242 = false; is_less_than(&si, &seriesListLength) } {
let mut st: Value = self.safe_string_k(get_value(&seriesList, &si), "ticker", &[]);
if !is_equal(&st, &Value::Null) {
append_to_array(&mut collected, st.clone());
}
}
}
}
// explicit series_ticker(s) — comma-separated accepted, used verbatim
let mut seriesParam: Value = self.safe_string_k(params.clone(), "series_ticker", &[]);
if !is_equal(&seriesParam, &Value::Null) {
let mut parts: Value = split(&seriesParam, &Value::Str(",".to_string()));
let mut partsLength: Value = get_array_length(&parts);
{
let mut pi: Value = Value::Int(0);
let mut __for_first_1243: bool = true;
while { if !__for_first_1243 { pi = add(&pi, &Value::Int(1)); } __for_first_1243 = false; is_less_than(&pi, &partsLength) } {
append_to_array(&mut collected, get_value(&parts, &pi));
}
}
}
// deduplicate preserving order
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut ordered: Value = Value::List(vec![]);
let mut collectedLength: Value = get_array_length(&collected);
{
let mut ci: Value = Value::Int(0);
let mut __for_first_1244: bool = true;
while { if !__for_first_1244 { ci = add(&ci, &Value::Int(1)); } __for_first_1244 = false; is_less_than(&ci, &collectedLength) } {
let mut st: Value = get_value(&collected, &ci);
let mut st: Value = get_value(&collected, &ci);
let mut already: Value = self.safe_string(seen.clone(), st.clone(), &[]);
if is_true(&(!is_equal(&st, &Value::Null))) && is_true(&(!is_equal(&st, &Value::Str("".to_string())))) && is_true(&(is_equal(&already, &Value::Null))) {
add_element_to_object(&mut seen, &st, st.clone());
append_to_array(&mut ordered, st.clone());
}
}
}
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::List(vec![]);
let mut seriesTickersLength: Value = get_array_length(&seriesTickers);
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_1247: bool = true;
while { if !__for_first_1247 { si = add(&si, &Value::Int(1)); } __for_first_1247 = false; is_less_than(&si, &seriesTickersLength) } {
let mut collectedLength: Value = get_array_length(&rawEvents);
if is_true(&(!is_equal(&limit, &Value::Null))) && is_true(&(is_greater_than_or_equal(&collectedLength, &limit))) {
break;
}
let mut cursor: Value = Value::Null;
{
let mut page: Value = Value::Int(0);
let mut __for_first_1246: bool = true;
while { if !__for_first_1246 { page = add(&page, &Value::Int(1)); } __for_first_1246 = false; is_less_than(&page, &maxPages) } {
let mut reqLimit: Value = pageLimit.clone();
if !is_equal(&limit, &Value::Null) {
let mut remaining: Value = subtract(&limit, &get_array_length(&rawEvents));
if is_less_than(&remaining, &reqLimit) {
reqLimit = remaining.clone();
}
if is_less_than_or_equal(&reqLimit, &Value::Int(0)) {
break;
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("series_ticker".to_string(), get_value(&seriesTickers, &si));
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 !is_equal(&cursor, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("cursor".to_string()), cursor.clone());
}
let __ws_arg_16 = self.extend(request.clone(), &[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::List(vec![])]);
let mut pageEventsLength: Value = get_array_length(&pageEvents);
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1245: bool = true;
while { if !__for_first_1245 { ei = add(&ei, &Value::Int(1)); } __for_first_1245 = false; is_less_than(&ei, &pageEventsLength) } {
append_to_array(&mut rawEvents, get_value(&pageEvents, &ei));
}
}
cursor = self.safe_string_k(response.clone(), "cursor", &[]);
let mut collectedAfterPage: Value = get_array_length(&rawEvents);
if is_true(&(!is_equal(&limit, &Value::Null))) && is_true(&(is_greater_than_or_equal(&collectedAfterPage, &limit))) {
break;
}
if is_true(&(is_equal(&cursor, &Value::Null))) || is_true(&(is_equal(&cursor, &Value::Str("".to_string())))) || is_true(&(is_less_than(&pageEventsLength, &reqLimit))) {
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.clone(), &[params.clone()]).await;
let mut event: Value = self.parse_event(fullEvent.clone());
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::List(vec![])]);
let mut marketsList: Value = Value::List(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_1248: bool = true;
while { if !__for_first_1248 { i = add(&i, &Value::Int(1)); } __for_first_1248 = false; is_less_than(&i, &get_array_length(&rawMarkets)) } {
let mut rawMarket: Value = get_value(&rawMarkets, &i);
let mut rawMarket: Value = get_value(&rawMarkets, &i);
let mut parsed: Value = self.parse_market(rawMarket.clone());
append_to_array(&mut marketsList, parsed.clone());
totalVolume = self.sum(&[totalVolume.clone(), self.safe_number2(rawMarket.clone(), Value::Str("volume_fp".to_string()), Value::Str("volume".to_string()), &[Value::Int(0)])]);
totalLiquidity = self.sum(&[totalLiquidity.clone(), self.safe_number2(rawMarket.clone(), Value::Str("liquidity_dollars".to_string()), Value::Str("liquidity".to_string()), &[Value::Int(0)])]);
let mut marketCreated: Value = self.parse8601(self.safe_string_k(rawMarket.clone(), "open_time", &[]));
if is_true(&(!is_equal(&marketCreated, &Value::Null))) && is_true(&(is_true(&(is_equal(&earliestCreated, &Value::Null))) || is_true(&(is_less_than(&marketCreated, &earliestCreated))))) {
earliestCreated = marketCreated.clone();
}
let mut marketStatus: Value = self.safe_string_k(rawMarket.clone(), "status", &[]);
if is_equal(&marketStatus, &Value::Str("active".to_string())) {
anyActive = Value::Bool(true);
}
let mut marketResult: Value = self.safe_string_k(rawMarket.clone(), "result", &[]);
let mut marketResolved: bool = is_true(&(is_equal(&marketStatus, &Value::Str("settled".to_string())))) || is_true(&(is_true(&(!is_equal(&marketResult, &Value::Null))) && is_true(&(!is_equal(&marketResult, &Value::Str("".to_string()))))));
if !is_true(&marketResolved) {
allResolved = Value::Bool(false);
}
let mut marketClose: Value = self.parse8601(self.safe_string_k(rawMarket.clone(), "close_time", &[]));
if is_true(&(!is_equal(&marketClose, &Value::Null))) && is_true(&(is_true(&(is_equal(&latestClose, &Value::Null))) || is_true(&(is_greater_than(&marketClose, &latestClose))))) {
latestClose = marketClose.clone();
}
}
}
// the aggregates only mean something when the payload nested any markets at all
let mut marketsCount: Value = get_array_length(&marketsList);
let mut active: Value = Value::Null;
if is_greater_than(&marketsCount, &Value::Int(0)) {
active = anyActive.clone();
}
let mut resolved: Value = self.safe_bool_k(rawEvent.clone(), "resolved", &[]);
if is_true(&(is_equal(&resolved, &Value::Null))) && is_true(&(is_greater_than(&marketsCount, &Value::Int(0)))) {
resolved = allResolved.clone();
}
let mut end: Value = self.parse8601(self.safe_string_k(rawEvent.clone(), "end_date_iso", &[]));
if is_equal(&end, &Value::Null) {
end = latestClose.clone();
}
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 = is_true(&(!is_equal(&title, &Value::Null))) && is_true(&(!is_equal(&title, &Value::Str("".to_string()))));
let mut eventSlug: Value = ternary(is_true(&hasTitle), self.shorten_slug(title.clone()), Value::Null);
let mut created: Value = self.parse8601(self.safe_string_k(rawEvent.clone(), "created_date_iso", &[]));
if is_equal(&created, &Value::Null) {
created = earliestCreated.clone();
}
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.clone());
m.insert("event".to_string(), eventSlug.clone());
m.insert("title".to_string(), title.clone());
m.insert("markets".to_string(), marketsList.clone());
m.insert("volume".to_string(), totalVolume.clone());
m.insert("liquidity".to_string(), totalLiquidity.clone());
m.insert("url".to_string(), __ws_arg_17);
m.insert("image".to_string(), __ws_arg_18);
m.insert("created".to_string(), created.clone());
m.insert("createdDatetime".to_string(), __ws_arg_19);
m.insert("end".to_string(), end.clone());
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.clone());
m.insert("resolved".to_string(), resolved.clone());
m.insert("info".to_string(), rawEvent.clone());
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
* @param {object} [headers] request headers
* @param {object} [body] request body
* @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::Str("kalshi".to_string()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".to_string()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut apiGroup: Value = ternary(is_string(&api), api.clone(), get_value(&api, &Value::Int(0)));
let mut access: Value = ternary(is_string(&api), Value::Str("public".to_string()), get_value(&api, &Value::Int(1)));
let mut baseUrls: Value = get_value(&self.urls, &Value::Str("api".to_string()));
let mut baseUrl: Value = self.safe_string(baseUrls.clone(), apiGroup.clone(), &[get_value(&baseUrls, &Value::Str("kalshi".to_string()))]);
let mut implodedPath: Value = self.implode_params(path.clone(), params.clone());
let mut url: Value = add(&add(&baseUrl, &Value::Str("/".to_string())), &implodedPath);
let mut query: Value = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
let mut querystring: Value = self.urlencode(query.clone(), &[]);
if is_equal(&method, &Value::Str("GET".to_string())) && is_true(&(!is_equal(&querystring, &Value::Str("".to_string())))) {
url = add(&url, &add(&Value::Str("?".to_string()), &querystring));
}
let mut existingHeaders: Value = ternary(is_true(&(!is_equal(&headers, &Value::Null))), headers.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
headers = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Accept".to_string(), Value::Str("application/json".to_string()));
m.insert("Content-Type".to_string(), Value::Str("application/json".to_string()));
m
}), &[existingHeaders.clone()]);
if is_equal(&access, &Value::Str("private".to_string())) {
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 = get_index_of(&baseUrl, &Value::Str("/trade-api".to_string()));
let mut versionPrefix: Value = slice(&baseUrl, &tradeApiIndex, &Value::Null);
let mut pathForSigning: Value = add(&add(&versionPrefix, &Value::Str("/".to_string())), &implodedPath);
let mut payload: Value = add(&add(×tamp, &method), &pathForSigning);
// RSA-PSS SHA-256 signature with the private key PEM
let mut keyParts: Value = split(&self.privateKey, &Value::Str("\\n".to_string()));
let mut cleanPrivateKey: Value = join(&keyParts, &Value::Str("\n".to_string()));
let mut signature: Value = rsa(payload.clone(), cleanPrivateKey.clone(), Value::Str("sha256".to_string()));
headers = self.extend(headers.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.clone());
m.insert("KALSHI-ACCESS-TIMESTAMP".to_string(), timestamp.clone());
m
})]);
if !is_equal(&method, &Value::Str("GET".to_string())) && is_true(&(!is_equal(&querystring, &Value::Str("".to_string())))) {
// kalshi expects a JSON body; the signature covers only timestamp+method+path
body = self.json(query.clone());
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), body.clone());
m.insert("headers".to_string(), headers.clone());
m
});
Value::Null
}
}