// 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 LimitlessCore {
pub exchange: crate::prediction_exchange::PredictionExchange,
}
impl LimitlessCore {
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 = LimitlessCore::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 LimitlessCore {
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on LimitlessCore.
LimitlessCore::parse_market(self, market)
}
fn parse_account(&self, account: crate::Value) -> crate::Value {
// Forward to the inherent method on LimitlessCore.
LimitlessCore::parse_account(self, account)
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on LimitlessCore.
LimitlessCore::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 LimitlessCore.
LimitlessCore::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 LimitlessCore.
LimitlessCore::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 LimitlessCore.
LimitlessCore::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 LimitlessCore.
LimitlessCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for LimitlessCore {
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 {
"apply_scale" => self.apply_scale(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"approve" => self.approve(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"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,
"cancel_orders" => self.cancel_orders(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,
"expand_group_rows" => self.expand_group_rows(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"fetch_accounts" => self.fetch_accounts(&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_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_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_orders_by_ids" => self.fetch_orders_by_ids(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions" => self.fetch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_raw_active_markets" => self.fetch_raw_active_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_raw_markets_by_tags" => self.fetch_raw_markets_by_tags(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).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,
"get_outcome_by_slug_and_label" => self.get_outcome_by_slug_and_label(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()[..]),
"get_position_from_clob_entry" => self.get_position_from_clob_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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)),
"hash_message" => self.hash_message(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_account" => self.parse_account(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_order_side" => self.parse_order_side(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_order_time_in_force" => self.parse_order_time_in_force(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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()[..]),
"redeem" => self.redeem(&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()[..]),
"sign_evm_transaction" => self.sign_evm_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_hash" => self.sign_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_message" => self.sign_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_order_request" => self.sign_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).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 LimitlessCore {
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 LimitlessCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}
impl std::ops::DerefMut for LimitlessCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.exchange) }
}
impl LimitlessCore {
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("limitless".to_string()));
m.insert("name".to_string(), Value::Str("Limitless".to_string()));
m.insert("countries".to_string(), Value::List(vec![]));
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("approve".to_string(), Value::Bool(true));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(false));
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("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("fetchOrdersByIds".to_string(), Value::Bool(true));
m.insert("fetchPositions".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.insert("redeem".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1h".to_string(), Value::Str("1h".to_string()));
m.insert("6h".to_string(), Value::Str("6h".to_string()));
m.insert("1d".to_string(), Value::Str("1d".to_string()));
m.insert("1w".to_string(), Value::Str("1w".to_string()));
m.insert("1M".to_string(), Value::Str("1m".to_string()));
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/bb10c8b4-7b97-49f5-927c-057709dbaf7e".to_string()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limitless".to_string(), Value::Str("https://api.limitless.exchange".to_string()));
m
}));
m.insert("www".to_string(), Value::Str("https://limitless.exchange".to_string()));
m.insert("doc".to_string(), Value::List(vec![Value::Str("https://docs.limitless.exchange".to_string())]));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limitless".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("markets/active".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/active/{categoryId}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("categories".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{addressOrSlug}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/categories/count".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/active/slugs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/search".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{slug}/orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{slug}/historical-price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/signing-message".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{addressOrSlug}/oracle-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{slug}/get-feed-events".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{slug}/events".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/timeline".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{slug}/timeline".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("navigation".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market-pages/by-path".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market-pages/{id}/markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("property-keys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("property-keys/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("property-keys/{id}/options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/{account}/traded-volume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/{account}/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/{account}/pnl-chart".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("auth/api-keys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("profiles/partner-accounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{slug}/user-orders".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/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{slug}/locked-balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("profiles/me".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("profiles/{account}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/pnl-chart".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/points".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/trading/allowance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/api-tokens/capabilities".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/api-tokens".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("profiles/partner-accounts/{profileId}/allowances".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("auth/logout".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/api-keys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/login".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/cancel-batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/batch-cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/status/batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/redeem".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/withdrawal-addresses".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/api-tokens/derive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("profiles/partner-accounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("profiles/partner-accounts/{profileId}/allowances/retry".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("auth/api-keys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/all/{slug}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/api-tokens/{tokenId}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("portfolio/withdrawal-addresses/{address}".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(true));
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::Float(0.02));
m.insert("taker".to_string(), Value::Float(0.02));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultFetchMarketsPages".to_string(), Value::Int(5));
m.insert("marketsPageSize".to_string(), Value::Int(25));
m.insert("usdcDecimals".to_string(), Value::Int(6));
m.insert("warnOnCancelAllOrdersWithOutcome".to_string(), Value::Bool(true));
m.insert("zeroAddress".to_string(), Value::Str("0x0000000000000000000000000000000000000000".to_string()));
m.insert("chainId".to_string(), Value::Int(8453));
m.insert("rpcUrl".to_string(), Value::Str("https://mainnet.base.org".to_string()));
m.insert("collateralAddress".to_string(), Value::Str("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913".to_string()));
m.insert("exchangeAddress".to_string(), Value::Str("0x05c748E2f4DcDe0ec9Fa8DDc40DE6b867f923fa5".to_string()));
m.insert("createMarketBuyOrderRequiresPrice".to_string(), Value::Bool(true));
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
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Order not found".to_string(), Value::Str("OrderNotFound".to_string()).clone());
m.insert("Orders not found".to_string(), Value::Str("OrderNotFound".to_string()).clone());
m.insert("already canceled".to_string(), Value::Str("OrderNotFound".to_string()).clone());
m.insert("must be a UUIDv4".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("Invalid signature".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name limitless#fetchMarkets
* @description fetches all active limitless markets paginated and returns one CCXT market per child market, each containing a list of outcome objects (YES/NO)
* @see https://docs.limitless.exchange/api-reference/markets/get-active-markets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.query] a single search query string to filter markets by
* @param {string[]} [params.queries] multiple search query strings (alternative to query)
* @param {int} [params.limit] max number of markets to collect (defaults to options.fetchMarketsLimit, 1000); caps the pages fetched
* @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 rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("query".to_string()), Value::Str("queries".to_string()), Value::Str("limit".to_string())]), &[]);
// scope the listing: without a search query loadMarkets would otherwise page through
// every active limitless market. Cap the total number of markets collected.
let mut maxMarkets: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("fetchMarketsLimit".to_string()), &[Value::Int(1000)])]);
let mut allRaw: Value = Value::List(vec![]);
let mut queriesLength: Value = get_array_length(&queries);
if is_greater_than(&queriesLength, &Value::Int(0)) {
let mut requestedLimit: Value = self.safe_integer_k(params.clone(), "limit", &[Value::Int(50)]);
// the search endpoint rejects limit > 50 - cap the per-query request and let
// maxMarkets bound the overall collection
let mut limit: Value = crate::runtime::Math::min(&requestedLimit, &Value::Int(50));
let mut searchRest: Value = self.omit(rest.clone(), Value::List(vec![Value::Str("limit".to_string())]), &[]);
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1250: bool = true;
while { if !__for_first_1250 { i = add(&i, &Value::Int(1)); } __for_first_1250 = false; is_less_than(&i, &get_array_length(&queries)) } {
let mut q: Value = get_value(&queries, &i);
let mut q: Value = get_value(&queries, &i);
let __ws_arg_0 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("query".to_string(), q.clone());
m.insert("limit".to_string(), limit.clone());
m
}), &[searchRest.clone()]);
let mut response: Value = self.limitless_public_get_markets_search(&[__ws_arg_0]).await;
let mut found: Value = self.safe_list_k(response.clone(), "markets", &[Value::List(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1249: bool = true;
while { if !__for_first_1249 { j = add(&j, &Value::Int(1)); } __for_first_1249 = false; is_less_than(&j, &get_array_length(&found)) } {
let mut raw: Value = get_value(&found, &j);
let mut raw: Value = get_value(&found, &j);
let mut slug: Value = self.safe_string_k(raw.clone(), "slug", &[]);
if is_true(&(!is_equal(&slug, &Value::Null) && !is_equal(&slug, &Value::Str("".to_string())))) && !is_true(&(Value::Bool(in_op(&seen, &slug)))) {
add_element_to_object(&mut seen, &slug, Value::Bool(true));
append_to_array(&mut allRaw, raw.clone());
}
}
}
}
}
} else {
let mut page: Value = Value::Int(1);
let mut pageSize: Value = self.safe_integer_k(self.options.clone(), "marketsPageSize", &[Value::Int(25)]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("page".to_string(), page.clone());
m.insert("limit".to_string(), pageSize.clone());
m
});
let __ws_arg_1 = self.extend(request.clone(), &[rest.clone()]);
let mut firstPageResponse: Value = self.limitless_public_get_markets_active(&[__ws_arg_1]).await;
let mut totalMarketsCount: Value = self.safe_integer_k(firstPageResponse.clone(), "totalMarketsCount", &[]);
let mut firstData: Value = self.safe_list_k(firstPageResponse.clone(), "data", &[Value::List(vec![])]);
allRaw = self.array_concat(allRaw.clone(), firstData.clone());
let mut promises: Value = Value::List(vec![]);
let mut cappedPages: Value = math_ceil(÷(&maxMarkets, &pageSize));
let mut knownTotal: Value = ternary(is_true(&(!is_equal(&totalMarketsCount, &Value::Null))), totalMarketsCount.clone(), Value::Int(0));
let mut allPages: Value = math_ceil(÷(&knownTotal, &pageSize));
let mut totalPages: Value = crate::runtime::Math::min(&allPages, &cappedPages);
{
let mut i: Value = Value::Int(2);
let mut __for_first_1251: bool = true;
while { if !__for_first_1251 { i = add(&i, &Value::Int(1)); } __for_first_1251 = false; is_less_than_or_equal(&i, &totalPages) } {
page = i.clone();
add_element_to_object(&mut request, &Value::Str("page".to_string()), page.clone());
let __ws_arg_2 = self.extend(request.clone(), &[rest.clone()]);
append_to_array(&mut promises, self.limitless_public_get_markets_active(&[__ws_arg_2]).await);
}
}
let mut responses: Value = promise_all(&promises).await;
let mut length: Value = get_array_length(&responses);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1252: bool = true;
while { if !__for_first_1252 { j = add(&j, &Value::Int(1)); } __for_first_1252 = false; is_less_than(&j, &length) } {
let mut response: Value = self.safe_dict(responses.clone(), j.clone(), &[]);
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
allRaw = self.array_concat(allRaw.clone(), data.clone());
}
}
let mut lastPageResponse: Value = self.safe_dict(responses.clone(), subtract(&length, &Value::Int(1)), &[]);
let mut lastPageData: Value = self.safe_list_k(lastPageResponse.clone(), "data", &[Value::List(vec![])]);
let mut lastPageLength: Value = get_array_length(&lastPageData);
let mut allRawLength: Value = get_array_length(&allRaw);
if is_greater_than_or_equal(&lastPageLength, &pageSize) && is_less_than(&allRawLength, &maxMarkets) {
while is_true(&Value::Bool(true)) {
page = self.sum(&[page.clone(), Value::Int(1)]);
add_element_to_object(&mut request, &Value::Str("page".to_string()), page.clone());
let __ws_arg_3 = self.extend(request.clone(), &[rest.clone()]);
let mut response: Value = self.limitless_public_get_markets_active(&[__ws_arg_3]).await;
let mut responseRows: Value = Value::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
responseRows = response.clone();
}
let mut rawPageMarkets: Value = self.safe_list_k(response.clone(), "data", &[responseRows.clone()]);
let mut page_markets: Value = ternary(is_true(&(!is_equal(&rawPageMarkets, &Value::Null))), rawPageMarkets.clone(), Value::List(vec![]));
let mut pageMarketsLength: Value = get_array_length(&page_markets);
if is_equal(&pageMarketsLength, &Value::Int(0)) {
break;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1253: bool = true;
while { if !__for_first_1253 { i = add(&i, &Value::Int(1)); } __for_first_1253 = false; is_less_than(&i, &get_array_length(&page_markets)) } {
let mut raw: Value = get_value(&page_markets, &i);
let mut raw: Value = get_value(&page_markets, &i);
append_to_array(&mut allRaw, raw.clone());
}
}
let mut allRawCount: Value = get_array_length(&allRaw);
if is_less_than(&pageMarketsLength, &pageSize) || is_greater_than_or_equal(&allRawCount, &maxMarkets) {
break;
}
}
}
}
let mut markets: Value = Value::List(vec![]);
let mut eventGroups: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
// group rows carry their tradeable children in a nested `markets` list — expand them
// into regular rows before parsing (a group row itself has no tokens)
let mut expandedRaw: Value = self.expand_group_rows(allRaw.clone());
{
let mut i: Value = Value::Int(0);
let mut __for_first_1254: bool = true;
while { if !__for_first_1254 { i = add(&i, &Value::Int(1)); } __for_first_1254 = false; is_less_than(&i, &get_array_length(&expandedRaw)) } {
let mut raw: Value = get_value(&expandedRaw, &i);
let mut raw: Value = get_value(&expandedRaw, &i);
let mut groupId: Value = self.safe_string_n(raw.clone(), Value::List(vec![Value::Str("groupSlug".to_string()), Value::Str("groupId".to_string())]), &[self.safe_string_k(raw.clone(), "slug", &[])]);
let mut eventKey: Value = ternary(is_true(&(!is_equal(&groupId, &Value::Null) && !is_equal(&groupId, &Value::Str("".to_string())))), self.shorten_slug(groupId.clone()), Value::Null);
let mut m: Value = self.parse_market(raw.clone());
append_to_array(&mut markets, 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(&eventGroups, &eventKey)))) {
add_element_to_object(&mut eventGroups, &eventKey, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("groupId".to_string(), groupId.clone());
m.insert("title".to_string(), self.safe_string2(raw.clone(), Value::Str("groupTitle".to_string()), Value::Str("title".to_string()), &[groupId.clone()]));
m.insert("raw".to_string(), raw.clone());
m.insert("markets".to_string(), Value::List(vec![]));
m
}));
}
let mut eventGroup: Value = get_value(&eventGroups, &eventKey);
let mut eventGroup: Value = get_value(&eventGroups, &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 eventGroup['markets'] loses the element in go
let mut groupMarkets: Value = get_value(&eventGroup, &Value::Str("markets".to_string()));
append_to_array(&mut groupMarkets, m.clone());
add_element_to_object(&mut eventGroup, &Value::Str("markets".to_string()), groupMarkets.clone());
}
}
}
let mut eventsDict: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut eventKeys: Value = object_keys(&eventGroups);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1255: bool = true;
while { if !__for_first_1255 { i = add(&i, &Value::Int(1)); } __for_first_1255 = false; is_less_than(&i, &get_array_length(&eventKeys)) } {
let mut eventKey: Value = get_value(&eventKeys, &i);
let mut eventKey: Value = get_value(&eventKeys, &i);
let mut g: Value = get_value(&eventGroups, &eventKey);
let mut g: Value = get_value(&eventGroups, &eventKey);
add_element_to_object(&mut eventsDict, &eventKey, self.parse_event(g.clone()));
}
}
self.exchange.events = eventsDict.clone();
let mut marketsLength: Value = get_array_length(&markets);
if is_greater_than(&marketsLength, &maxMarkets) {
return self.array_slice(markets.clone(), Value::Int(0), &[maxMarkets.clone()]);
}
return markets;
Value::Null
}
pub fn parse_market(&self, mut raw: Value) -> Value {
//
// {
// "id":"36814",
// "automationType":"manual",
// "conditionId":"0x11287d02d8067ff3d3d8bd21b212ebcfdc20b638f7f6440e4115f649e6b57015",
// "negRiskRequestId":null,
// "description":"<p>This market will resolve to “Yes” if Donald Trump resigns or is removed as President or otherwise ceases to be the President of the United States for any period of time by December 31, 2026, 11:59 PM ET. Otherwise, this market will resolve to “No”.</p><p>An announcement of Donald Trump's resignation/removal before this market's end date will immediately resolve this market to \\""Yes\\"", regardless of when the announced resignation/removal goes into effect.</p><p>Only permanent removal from office will qualify. Temporary removal (e.g. temporary invocation of the 25th Amendment under Section 3 or a Section 4 invocation not sustained by both Houses of Congress) or impeachment without removal will not count.</p><p>A sustained invocation of the Twenty-Fifth Amendment, Section 4 (i.e., if both Houses of Congress, by two-thirds vote, uphold the Vice President and Cabinet’s determination of presidential inability) will qualify for a \\""Yes\\"" resolution.</p><p>The resolution source for this market will be a consensus of credible reporting.</p>",
// "collateralToken":{
// "address":"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
// "decimals":"6",
// "symbol":"USDC"
// },
// "title":"💎 Trump out as President before 2027?",
// "proxyTitle":null,
// "expirationDate":"Jan 1, 2027",
// "expirationTimestamp":"1798779540000",
// "createdAt":"2026-01-20T18:17:48.298Z",
// "updatedAt":"2026-02-24T17:00:11.833Z",
// "categories":[
// "Politics"
// ],
// "status":"FUNDED",
// "expired":false,
// "hidden":false,
// "creator":{
// "name":"Limitless",
// "imageURI":"https://limitless.exchange/assets/images/logo.svg",
// "link":"https://x.com/trylimitless"
// },
// "tags":[
// "Limitless"
// ],
// "volume":"290091252",
// "volumeFormatted":"290.091252",
// "tokens":{
// "yes":"56154308742753982686710750162015444986563701968079760676518531584453506363044",
// "no":"32572248812801208874557774576516861470423415416073401354576860825663488568217"
// },
// "prices":[
// 0.164,
// 0.836
// ],
// "isOther":false,
// "isRewardable":true,
// "slug":"trump-out-as-president-before-2027-1768933068297",
// "tradeType":"clob",
// "venue":{
// "exchange":"0x05c748E2f4DcDe0ec9Fa8DDc40DE6b867f923fa5",
// "adapter":null
// },
// "marketType":"single",
// "priorityIndex":"0",
// "winningOutcomeIndex":null,
// "metadata":{
// "fee":true,
// "isBannered":false,
// "isPolyArbitrage":true
// },
// "trends":{
// "hourly":{
// "value":"3",
// "rank":"395"
// }
// },
// "settings":{
// "minSize":"100000000",
// "maxSpread":"0.035",
// "dailyReward":"5",
// "rewardsEpoch":"0.003472222222222222",
// "c":"3",
// "rebateRate":"0"
// },
// "imageUrl":"https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png",
// "logo":"https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png"
// }
//
let mut slug: Value = self.safe_string_k(raw.clone(), "slug", &[]);
let mut address: Value = self.safe_string_k(raw.clone(), "address", &[slug.clone()]);
// groupSlug is stamped by expandGroupRows on children of a group row — prefer it over
// the child's own numeric groupId so symbols/handles derive from the readable slug
let mut groupId: Value = self.safe_string_n(raw.clone(), Value::List(vec![Value::Str("groupSlug".to_string()), Value::Str("groupId".to_string())]), &[slug.clone()]);
// CTF condition id — needed to redeem a resolved winning position
let mut conditionId: Value = self.safe_string_k(raw.clone(), "conditionId", &[]);
let mut tokens: Value = self.safe_value_k(raw.clone(), "tokens", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// the listing exposes `expired` + `status` (FUNDED/RESOLVED/…), not an `active` flag; a
// market is tradeable only while it is FUNDED and not yet expired
let mut isExpired: Value = self.safe_bool_k(raw.clone(), "expired", &[Value::Bool(false)]);
let mut marketStatus: Value = self.safe_string_k(raw.clone(), "status", &[]);
let mut active: Value = Value::Bool(is_true(&(!is_equal(&isExpired, &Value::Bool(true)))) && is_true(&(is_equal(&marketStatus, &Value::Str("FUNDED".to_string())))));
// expiry is a ms timestamp string (`expirationTimestamp`); `deadline`/`expiresAt` do not exist
let mut expiryTimestamp: Value = self.safe_integer_k(raw.clone(), "expirationTimestamp", &[]);
// limitless reports lifetime volume (human-readable in `volumeFormatted`), not a 24h figure
let mut volume24h: Value = self.safe_number_k(raw.clone(), "volumeFormatted", &[]);
// resolution: winningOutcomeIndex is null until the market resolves, then the winning outcome index
let mut winningOutcomeIndex: Value = self.safe_integer_k(raw.clone(), "winningOutcomeIndex", &[]);
let mut marketResolved: Value = Value::Bool(!is_equal(&winningOutcomeIndex, &Value::Null));
let mut resolvedOutcome: Value = Value::Null;
let mut marketSymbol: Value = self.slug_to_market_symbol(groupId.clone(), slug.clone());
// amount precision comes from the collateral token decimals (USDC, 6); limitless does not
// expose a price tick, so 0.001 is the platform convention
let mut collateralToken: Value = self.safe_dict_k(raw.clone(), "collateralToken", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut collateralDecimals: Value = self.safe_integer_k(collateralToken.clone(), "decimals", &[self.safe_integer(self.options.clone(), Value::Str("usdcDecimals".to_string()), &[Value::Int(6)])]);
let mut precision: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(self.parse_precision(&[self.number_to_string(collateralDecimals.clone())]), &[]));
m.insert("price".to_string(), Value::Float(0.001));
m
});
let mut outcomes: Value = Value::List(vec![]);
let mut tokenEntries: Value = object_keys(&tokens);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1256: bool = true;
while { if !__for_first_1256 { i = add(&i, &Value::Int(1)); } __for_first_1256 = false; is_less_than(&i, &get_array_length(&tokenEntries)) } {
let mut outcomeLabel: Value = get_value(&tokenEntries, &i);
let mut outcomeLabel: Value = get_value(&tokenEntries, &i);
let mut tokenData: Value = get_value(&tokens, &outcomeLabel);
let mut tokenData: Value = get_value(&tokens, &outcomeLabel);
let mut tokenId: Value = tokenData.clone();
let mut outcomeHandle: Value = self.slug_to_outcome_symbol(groupId.clone(), slug.clone(), outcomeLabel.clone());
// winningOutcomeIndex indexes the API's canonical outcome order (yes=0, no=1 for
// limitless's binary yes/no markets). Object.keys iteration order is NOT stable across
// languages (Go randomizes map iteration), so map the leg to its canonical index by
// label rather than by loop position — otherwise Go/Java flag the wrong winner
let mut labelLower: Value = to_lower(&outcomeLabel);
let mut legIndex: Value = i.clone();
if is_equal(&labelLower, &Value::Str("yes".to_string())) {
legIndex = Value::Int(0);
} else if is_equal(&labelLower, &Value::Str("no".to_string())) {
legIndex = Value::Int(1);
}
let mut winnerRaw: Value = Value::Null;
let mut settleFractionRaw: Value = Value::Null;
if is_true(&marketResolved) {
winnerRaw = Value::Bool(is_equal(&legIndex, &winningOutcomeIndex));
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("outcome".to_string(), outcomeHandle.clone());
m.insert("outcomeId".to_string(), tokenId.clone());
m.insert("market".to_string(), marketSymbol.clone());
m.insert("label".to_string(), outcomeLabel.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("slug".to_string(), slug.clone());
m.insert("address".to_string(), address.clone());
m.insert("conditionId".to_string(), conditionId.clone());
m.insert("outcomeLabel".to_string(), outcomeLabel.clone());
m.insert("tokenId".to_string(), tokenId.clone());
m.insert("volume24h".to_string(), volume24h.clone());
m
}));
m
}));
}
}
let mut outcomesLength: Value = get_array_length(&outcomes);
// 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(), slug.clone());
m.insert("market".to_string(), marketSymbol.clone());
m.insert("marketType".to_string(), ternary(is_true(&(is_greater_than(&outcomesLength, &Value::Int(2)))), Value::Str("categorical".to_string()), Value::Str("binary".to_string())));
m.insert("executionModel".to_string(), Value::Str("clob".to_string()));
m.insert("collateral".to_string(), Value::Str("USDC".to_string()));
m.insert("base".to_string(), slug.clone());
m.insert("quote".to_string(), Value::Str("USDC".to_string()));
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), slug.clone());
m.insert("quoteId".to_string(), Value::Str("USDC".to_string()));
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("prediction".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(), marketResolved.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(), expiryTimestamp.clone());
m.insert("expiryDatetime".to_string(), self.iso8601(expiryTimestamp.clone()));
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("taker".to_string(), Value::Float(0.02));
m.insert("maker".to_string(), Value::Float(0.02));
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(0));
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.001));
m.insert("max".to_string(), Value::Float(0.999));
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("slug".to_string(), slug.clone());
m.insert("address".to_string(), address.clone());
m.insert("volume24h".to_string(), volume24h.clone());
m
})]));
m.insert("created".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name limitless#fetchEvent
* @description fetches a single prediction-market event by its market slug or address
* @see https://docs.limitless.exchange/api-reference/markets/get-market
* @param {string} id the market slug or address
* @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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("addressOrSlug".to_string(), id.clone());
m
});
let __ws_arg_4 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_public_get_markets_address_or_slug(&[__ws_arg_4]).await;
// a group response carries its tradeable children in `markets` (each a full market row
// with tokens) — expandGroupRows unwraps them; a single market has no nested markets
// and wraps as its own one-market event, which parseEvent's loop then parses
let mut rows: Value = self.expand_group_rows(Value::List(vec![response.clone()]));
let mut wrapped: Value = self.extend(response.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("markets".to_string(), rows.clone());
m
})]);
let mut event: Value = self.parse_event(wrapped.clone());
self.index_event_outcomes(event.clone());
return event;
Value::Null
}
/*
* @ignore
* @method
* @name limitless#expandGroupRows
* @description flattens listing rows — a 'group' row carries no tradeable tokens itself and
* its children (each a full market row with tokens) appear nowhere else in the listing, so
* each group row is replaced by its nested markets, tagged with the group's slug and title
* (the child's own groupId is an opaque numeric venue id) so they regroup under one readable event
* @param {object[]} rawRows raw listing rows, single-market and group rows mixed
* @returns {object[]} raw single-market rows only
*/
pub fn expand_group_rows(&self, mut rawRows: Value) -> Value {
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1258: bool = true;
while { if !__for_first_1258 { i = add(&i, &Value::Int(1)); } __for_first_1258 = false; is_less_than(&i, &get_array_length(&rawRows)) } {
let mut raw: Value = get_value(&rawRows, &i);
let mut raw: Value = get_value(&rawRows, &i);
let mut rowType: Value = self.safe_string_k(raw.clone(), "marketType", &[]);
let mut nestedMarkets: Value = self.safe_list_k(raw.clone(), "markets", &[]);
if is_true(&(is_equal(&rowType, &Value::Str("group".to_string())))) && is_true(&(!is_equal(&nestedMarkets, &Value::Null))) {
let mut groupSlug: Value = self.safe_string_k(raw.clone(), "slug", &[]);
let mut groupTitle: Value = self.safe_string_k(raw.clone(), "title", &[groupSlug.clone()]);
let mut nestedMarketsLength: Value = get_array_length(&nestedMarkets);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1257: bool = true;
while { if !__for_first_1257 { j = add(&j, &Value::Int(1)); } __for_first_1257 = false; is_less_than(&j, &nestedMarketsLength) } {
// extend copies — the raw child stays untouched
let mut tagged: Value = self.extend(get_value(&nestedMarkets, &j), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("groupSlug".to_string(), groupSlug.clone());
m.insert("groupTitle".to_string(), groupTitle.clone());
m
})]);
append_to_array(&mut result, tagged.clone());
}
}
} else {
append_to_array(&mut result, raw.clone());
}
}
}
return result;
Value::Null
}
pub fn parse_event(&self, mut event: Value) -> Value {
// {
// "groupId":"trump-out-as-president-before-2027-1768933068297",
// "title":"💎 Trump out as President before 2027?",
// "raw":{
// "id":"36814",
// "automationType":"manual",
// "conditionId":"0x11287d02d8067ff3d3d8bd21b212ebcfdc20b638f7f6440e4115f649e6b57015",
// "negRiskRequestId":null,
// "description":"<p>This market will resolve to “Yes” if Donald Trump resigns or is removed as President or otherwise ceases to be the President of the United States for any period of time by December 31, 2026, 11:59 PM ET. Otherwise, this market will resolve to “No”.</p><p>An announcement of Donald Trump's resignation/removal before this market's end date will immediately resolve this market to \\""Yes\\"", regardless of when the announced resignation/removal goes into effect.</p><p>Only permanent removal from office will qualify. Temporary removal (e.g. temporary invocation of the 25th Amendment under Section 3 or a Section 4 invocation not sustained by both Houses of Congress) or impeachment without removal will not count.</p><p>A sustained invocation of the Twenty-Fifth Amendment, Section 4 (i.e., if both Houses of Congress, by two-thirds vote, uphold the Vice President and Cabinet’s determination of presidential inability) will qualify for a \\""Yes\\"" resolution.</p><p>The resolution source for this market will be a consensus of credible reporting.</p>",
// "collateralToken":{
// "address":"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
// "decimals":"6",
// "symbol":"USDC"
// },
// "title":"💎 Trump out as President before 2027?",
// "proxyTitle":null,
// "expirationDate":"Jan 1, 2027",
// "expirationTimestamp":"1798779540000",
// "createdAt":"2026-01-20T18:17:48.298Z",
// "updatedAt":"2026-02-24T17:00:11.833Z",
// "categories":[
// "Politics"
// ],
// "status":"FUNDED",
// "expired":false,
// "hidden":false,
// "creator":{
// "name":"Limitless",
// "imageURI":"https://limitless.exchange/assets/images/logo.svg",
// "link":"https://x.com/trylimitless"
// },
// "tags":[
// "Limitless"
// ],
// "volume":"290091252",
// "volumeFormatted":"290.091252",
// "tokens":{
// "yes":"56154308742753982686710750162015444986563701968079760676518531584453506363044",
// "no":"32572248812801208874557774576516861470423415416073401354576860825663488568217"
// },
// "prices":[
// 0.164,
// 0.836
// ],
// "isOther":false,
// "isRewardable":true,
// "slug":"trump-out-as-president-before-2027-1768933068297",
// "tradeType":"clob",
// "venue":{
// "exchange":"0x05c748E2f4DcDe0ec9Fa8DDc40DE6b867f923fa5",
// "adapter":null
// },
// "marketType":"single",
// "priorityIndex":"0",
// "winningOutcomeIndex":null,
// "metadata":{
// "fee":true,
// "isBannered":false,
// "isPolyArbitrage":true
// },
// "trends":{
// "hourly":{
// "value":"3",
// "rank":"395"
// }
// },
// "settings":{
// "minSize":"100000000",
// "maxSpread":"0.035",
// "dailyReward":"5",
// "rewardsEpoch":"0.003472222222222222",
// "c":"3",
// "rebateRate":"0"
// },
// "imageUrl":"https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png",
// "logo":"https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png"
// },
// "markets":[
// {
// "id":"trump-out-as-president-before-2027-1768933068297",
// "symbol":"TRUMP_OUT_PRESIDENT_2027_1768933068297",
// "base":"trump-out-as-president-before-2027-1768933068297",
// "quote":"USDC",
// "baseId":"trump-out-as-president-before-2027-1768933068297",
// "quoteId":"USDC",
// "type":"prediction",
// "spot":false,
// "margin":false,
// "swap":false,
// "future":false,
// "option":false,
// "prediction":true,
// "active":true,
// "contract":false,
// "taker":0.02,
// "maker":0.02,
// "percentage":true,
// "tierBased":false,
// "feeSide":"get",
// "precision":{
// "amount":0.000001,
// "price":0.001
// },
// "limits":{
// "leverage":{
// "min":1,
// "max":1
// },
// "amount":{
// "min":0
// },
// "price":{
// "min":0.001,
// "max":0.999
// },
// "cost":{
// }
// },
// "outcomes":[
// {
// "id":"trump-out-as-president-before-2027-1768933068297/yes",
// "symbol":"TRUMP_OUT_PRESIDENT_2027_1768933068297:YES",
// "marketSymbol":"TRUMP_OUT_PRESIDENT_2027_1768933068297",
// "label":"yes",
// "active":true,
// "info":{
// "slug":"trump-out-as-president-before-2027-1768933068297",
// "address":"trump-out-as-president-before-2027-1768933068297",
// "outcomeLabel":"yes",
// "tokenId":"trump-out-as-president-before-2027-1768933068297/yes"
// }
// },
// {
// "id":"trump-out-as-president-before-2027-1768933068297/no",
// "symbol":"TRUMP_OUT_PRESIDENT_2027_1768933068297:NO",
// "marketSymbol":"TRUMP_OUT_PRESIDENT_2027_1768933068297",
// "label":"no",
// "active":true,
// "info":{
// "slug":"trump-out-as-president-before-2027-1768933068297",
// "address":"trump-out-as-president-before-2027-1768933068297",
// "outcomeLabel":"no",
// "tokenId":"trump-out-as-president-before-2027-1768933068297/no"
// }
// }
// ],
// "info":{
// "id":"36814",
// "automationType":"manual",
// "conditionId":"0x11287d02d8067ff3d3d8bd21b212ebcfdc20b638f7f6440e4115f649e6b57015",
// "negRiskRequestId":null,
// "description":"<p>This market will resolve to “Yes” if Donald Trump resigns or is removed as President or otherwise ceases to be the President of the United States for any period of time by December 31, 2026, 11:59 PM ET. Otherwise, this market will resolve to “No”.</p><p>An announcement of Donald Trump's resignation/removal before this market's end date will immediately resolve this market to \\""Yes\\"", regardless of when the announced resignation/removal goes into effect.</p><p>Only permanent removal from office will qualify. Temporary removal (e.g. temporary invocation of the 25th Amendment under Section 3 or a Section 4 invocation not sustained by both Houses of Congress) or impeachment without removal will not count.</p><p>A sustained invocation of the Twenty-Fifth Amendment, Section 4 (i.e., if both Houses of Congress, by two-thirds vote, uphold the Vice President and Cabinet’s determination of presidential inability) will qualify for a \\""Yes\\"" resolution.</p><p>The resolution source for this market will be a consensus of credible reporting.</p>",
// "collateralToken":{
// "address":"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
// "decimals":"6",
// "symbol":"USDC"
// },
// "title":"💎 Trump out as President before 2027?",
// "proxyTitle":null,
// "expirationDate":"Jan 1, 2027",
// "expirationTimestamp":"1798779540000",
// "createdAt":"2026-01-20T18:17:48.298Z",
// "updatedAt":"2026-02-24T17:00:11.833Z",
// "categories":[
// "Politics"
// ],
// "status":"FUNDED",
// "expired":false,
// "hidden":false,
// "creator":{
// "name":"Limitless",
// "imageURI":"https://limitless.exchange/assets/images/logo.svg",
// "link":"https://x.com/trylimitless"
// },
// "tags":[
// "Limitless"
// ],
// "volume":"290091252",
// "volumeFormatted":"290.091252",
// "tokens":{
// "yes":"56154308742753982686710750162015444986563701968079760676518531584453506363044",
// "no":"32572248812801208874557774576516861470423415416073401354576860825663488568217"
// },
// "prices":[
// 0.164,
// 0.836
// ],
// "isOther":false,
// "isRewardable":true,
// "slug":"trump-out-as-president-before-2027-1768933068297",
// "tradeType":"clob",
// "venue":{
// "exchange":"0x05c748E2f4DcDe0ec9Fa8DDc40DE6b867f923fa5",
// "adapter":null
// },
// "marketType":"single",
// "priorityIndex":"0",
// "winningOutcomeIndex":null,
// "metadata":{
// "fee":true,
// "isBannered":false,
// "isPolyArbitrage":true
// },
// "trends":{
// "hourly":{
// "value":"3",
// "rank":"395"
// }
// },
// "settings":{
// "minSize":"100000000",
// "maxSpread":"0.035",
// "dailyReward":"5",
// "rewardsEpoch":"0.003472222222222222",
// "c":"3",
// "rebateRate":"0"
// },
// "imageUrl":"https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png",
// "logo":"https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png",
// "address":"trump-out-as-president-before-2027-1768933068297"
// }
// }
// ]
// }
let mut groupId: Value = self.safe_string_k(event.clone(), "address", &[self.safe_string(event.clone(), Value::Str("groupId".to_string()), &[self.safe_string(event.clone(), Value::Str("slug".to_string()), &[])])]);
let mut endDate: Value = self.safe_string_k(event.clone(), "deadline", &[self.safe_string(event.clone(), Value::Str("expiresAt".to_string()), &[])]);
let mut title: Value = self.safe_string_k(event.clone(), "title", &[groupId.clone()]);
let mut hasGroupId: bool = is_true(&(!is_equal(&groupId, &Value::Null))) && is_true(&(!is_equal(&groupId, &Value::Str("".to_string()))));
let mut eventSlug: Value = ternary(is_true(&hasGroupId), self.shorten_slug(groupId.clone()), Value::Null);
let mut hasEndDate: bool = is_true(&(!is_equal(&endDate, &Value::Null))) && is_true(&(!is_equal(&endDate, &Value::Str("".to_string()))));
let mut endTimestamp: Value = ternary(is_true(&hasEndDate), self.parse8601(endDate.clone()), Value::Null);
let mut markets: Value = Value::List(vec![]);
let mut rawMarkets: Value = self.safe_list_k(event.clone(), "markets", &[Value::List(vec![])]);
// aggregate 24h volume across the markets so sort by volume works
let mut totalVolume: Value = Value::Int(0);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1259: bool = true;
while { if !__for_first_1259 { i = add(&i, &Value::Int(1)); } __for_first_1259 = 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);
// an already-parsed ccxt market row carries the unified 'market' handle + outcomes
// with 'symbol' kept as a legacy fallback — don't run it through parseMarket again
let mut marketSymbol: Value = self.safe_string2(rawMarket.clone(), Value::Str("market".to_string()), Value::Str("symbol".to_string()), &[]);
let mut marketOutcomes: Value = self.safe_list_k(rawMarket.clone(), "outcomes", &[]);
if !is_equal(&marketSymbol, &Value::Null) && !is_equal(&marketOutcomes, &Value::Null) {
append_to_array(&mut markets, rawMarket.clone());
} else {
append_to_array(&mut markets, self.parse_market(rawMarket.clone()));
}
let mut marketInfo: Value = self.safe_dict_k(rawMarket.clone(), "info", &[rawMarket.clone()]);
// use volumeFormatted (human units) — the raw `volume` is 1e-6 fixed-point, which would
// make the event volume 1,000,000x too big and useless for cross-venue ranking
totalVolume = self.sum(&[totalVolume.clone(), self.safe_number_k(marketInfo.clone(), "volumeFormatted", &[Value::Int(0)])]);
}
}
let __ws_arg_5 = self.safe_string_k(event.clone(), "description", &[]);
let __ws_arg_6 = self.safe_number_k(event.clone(), "liquidity", &[]);
let __ws_arg_7 = self.safe_string_k(event.clone(), "url", &[]);
let __ws_arg_8 = self.safe_string_k(event.clone(), "imageUrl", &[self.safe_string(event.clone(), Value::Str("image".to_string()), &[])]);
let __ws_arg_9 = self.safe_bool_k(event.clone(), "active", &[Value::Bool(true)]);
let __ws_arg_10 = self.safe_bool_k(event.clone(), "resolved", &[Value::Bool(false)]);
let __ws_arg_11 = self.safe_string_k(event.clone(), "category", &[]);
let __ws_arg_12 = self.safe_list_k(event.clone(), "tags", &[]);
let __ws_arg_13 = self.parse8601(self.safe_string_k(event.clone(), "createdAt", &[]));
let __ws_arg_14 = self.safe_string_k(event.clone(), "createdAt", &[]);
let __ws_arg_15 = self.parse8601(self.safe_string_k(event.clone(), "updatedAt", &[]));
let __ws_arg_16 = self.safe_string_k(event.clone(), "resolutionSource", &[]);
return self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), groupId.clone());
m.insert("slug".to_string(), groupId.clone());
m.insert("event".to_string(), eventSlug.clone());
m.insert("title".to_string(), title.clone());
m.insert("description".to_string(), __ws_arg_5);
m.insert("markets".to_string(), markets.clone());
m.insert("volume".to_string(), totalVolume.clone());
m.insert("liquidity".to_string(), __ws_arg_6);
m.insert("url".to_string(), __ws_arg_7);
m.insert("image".to_string(), __ws_arg_8);
m.insert("active".to_string(), __ws_arg_9);
m.insert("resolved".to_string(), __ws_arg_10);
m.insert("category".to_string(), __ws_arg_11);
m.insert("tags".to_string(), __ws_arg_12);
m.insert("created".to_string(), __ws_arg_13);
m.insert("createdDatetime".to_string(), __ws_arg_14);
m.insert("end".to_string(), endTimestamp.clone());
m.insert("endDatetime".to_string(), endDate.clone());
m.insert("lastUpdatedAt".to_string(), __ws_arg_15);
m.insert("resolutionSource".to_string(), __ws_arg_16);
m.insert("info".to_string(), event.clone());
m
}), &[]);
Value::Null
}
/*
* @method
* @name limitless#fetchTicker
* @description fetches the current price and best bid/ask for a single outcome token, combining the market detail and order book endpoints
* @see https://docs.limitless.exchange/api-reference/markets/get-market
* @see https://docs.limitless.exchange/api-reference/trading/orderbook
* @param {string} outcome unified outcome like TRUMP_OUT_PRESIDENT_2027:YES or an outcome token id
* @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 slug: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("slug".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("addressOrSlug".to_string(), slug.clone());
m
});
let __ws_arg_17 = self.extend(request.clone(), &[params.clone()]);
let mut promises: Value = Value::List(vec![self.limitless_public_get_markets_address_or_slug(&[__ws_arg_17]).await, self.limitless_public_get_markets_slug_orderbook(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), slug.clone());
m
})]).await]);
let mut responses: Value = promise_all(&promises).await;
let mut response: Value = get_value(&responses, &Value::Int(0));
//
// {
// "id": "36814",
// "automationType": "manual",
// "conditionId": "0x11287d02d8067ff3d3d8bd21b212ebcfdc20b638f7f6440e4115f649e6b57015",
// "negRiskRequestId": null,
// "description": "<p>This market will resolve to Yes if Donald Trump resigns or is removed as President or otherwise ceases to be the President of the United States for any period of time by December 31, 2026, 11:59 PM ET. Otherwise, this market will resolve to No.</p><p>An announcement of Donald Trump's resignation/removal before this market's end date will immediately resolve this market to Yes, regardless of when the announced resignation/removal goes into effect.</p><p>Only permanent removal from office will qualify. Temporary removal (e.g. temporary invocation of the 25th Amendment under Section 3 or a Section 4 invocation not sustained by both Houses of Congress) or impeachment without removal will not count.</p><p>A sustained invocation of the Twenty-Fifth Amendment, Section 4 (i.e., if both Houses of Congress, by two-thirds vote, uphold the Vice President and Cabinets determination of presidential inability) will qualify for a Yes resolution.</p><p>The resolution source for this market will be a consensus of credible reporting.</p>",
// "collateralToken": {
// "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
// "decimals": "6",
// "symbol": "USDC"
// },
// "title": "Trump out as President before 2027?",
// "proxyTitle": null,
// "expirationDate": "Jan 1, 2027",
// "expirationTimestamp": "1798779540000",
// "createdAt": "2026-01-20T18:17:48.298Z",
// "updatedAt": "2026-04-09T10:47:02.254Z",
// "categories": [ "Politics" ],
// "status": "FUNDED",
// "expired": false,
// "hidden": false,
// "creator": {
// "name": "Limitless",
// "imageURI": "https://limitless.exchange/assets/images/logo.svg",
// "link": "https://x.com/trylimitless"
// },
// "tags": [ "Limitless" ],
// "volume": "1032001807",
// "volumeFormatted": "1032.001807",
// "tokens": {
// "yes": "56154308742753982686710750162015444986563701968079760676518531584453506363044",
// "no": "32572248812801208874557774576516861470423415416073401354576860825663488568217"
// },
// "prices": [ 0.155, 0.845 ],
// "tradePrices": {
// "buy": { "market": [Array], "limit": [Array] },
// "sell": { "market": [Array], "limit": [Array] }
// },
// "isOther": false,
// "isRewardable": true,
// "slug": "trump-out-as-president-before-2027-1768933068297",
// "tradeType": "clob",
// "venue": {
// "exchange": "0x05c748E2f4DcDe0ec9Fa8DDc40DE6b867f923fa5",
// "adapter": null
// },
// "marketType": "single",
// "priorityIndex": "0",
// "winningOutcomeIndex": null,
// "metadata": { "fee": true, "isBannered": false, "isPolyArbitrage": true },
// "settings": {
// "minSize": "100000000",
// "maxSpread": "0.035",
// "dailyReward": "5",
// "rewardsEpoch": "0.003472222222222222",
// "c": "3",
// "rebateRate": "0"
// },
// "imageUrl": "https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png",
// "logo": "https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png"
// }
//
let mut tickerInput: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market".to_string(), response.clone());
m.insert("book".to_string(), get_value(&responses, &Value::Int(1)));
m
});
return self.parse_prediction_ticker(tickerInput.clone(), &[outcomeObj.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name limitless#parsePredictionTicker
* @description parses a raw market object, or a composite market + book dict, into a unified ticker for the specified outcome token
* @param {object} ticker a raw limitless market object or a dict with market and book entries
* @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 ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "id": "36814",
// "automationType": "manual",
// "conditionId": "0x11287d02d8067ff3d3d8bd21b212ebcfdc20b638f7f6440e4115f649e6b57015",
// "negRiskRequestId": null,
// "description": "<p>This market will resolve to Yes if Donald Trump resigns or is removed as President or otherwise ceases to be the President of the United States for any period of time by December 31, 2026, 11:59 PM ET. Otherwise, this market will resolve to No.</p><p>An announcement of Donald Trump's resignation/removal before this market's end date will immediately resolve this market to Yes, regardless of when the announced resignation/removal goes into effect.</p><p>Only permanent removal from office will qualify. Temporary removal (e.g. temporary invocation of the 25th Amendment under Section 3 or a Section 4 invocation not sustained by both Houses of Congress) or impeachment without removal will not count.</p><p>A sustained invocation of the Twenty-Fifth Amendment, Section 4 (i.e., if both Houses of Congress, by two-thirds vote, uphold the Vice President and Cabinets determination of presidential inability) will qualify for a Yes resolution.</p><p>The resolution source for this market will be a consensus of credible reporting.</p>",
// "collateralToken": {
// "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
// "decimals": "6",
// "symbol": "USDC"
// },
// "title": "Trump out as President before 2027?",
// "proxyTitle": null,
// "expirationDate": "Jan 1, 2027",
// "expirationTimestamp": "1798779540000",
// "createdAt": "2026-01-20T18:17:48.298Z",
// "updatedAt": "2026-04-09T10:47:02.254Z",
// "categories": [ "Politics" ],
// "status": "FUNDED",
// "expired": false,
// "hidden": false,
// "creator": {
// "name": "Limitless",
// "imageURI": "https://limitless.exchange/assets/images/logo.svg",
// "link": "https://x.com/trylimitless"
// },
// "tags": [ "Limitless" ],
// "volume": "1032001807",
// "volumeFormatted": "1032.001807",
// "tokens": {
// "yes": "56154308742753982686710750162015444986563701968079760676518531584453506363044",
// "no": "32572248812801208874557774576516861470423415416073401354576860825663488568217"
// },
// "prices": [ 0.155, 0.845 ],
// "tradePrices": {
// "buy": { "market": [Array], "limit": [Array] },
// "sell": { "market": [Array], "limit": [Array] }
// },
// "isOther": false,
// "isRewardable": true,
// "slug": "trump-out-as-president-before-2027-1768933068297",
// "tradeType": "clob",
// "venue": {
// "exchange": "0x05c748E2f4DcDe0ec9Fa8DDc40DE6b867f923fa5",
// "adapter": null
// },
// "marketType": "single",
// "priorityIndex": "0",
// "winningOutcomeIndex": null,
// "metadata": { "fee": true, "isBannered": false, "isPolyArbitrage": true },
// "settings": {
// "minSize": "100000000",
// "maxSpread": "0.035",
// "dailyReward": "5",
// "rewardsEpoch": "0.003472222222222222",
// "c": "3",
// "rebateRate": "0"
// },
// "imageUrl": "https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png",
// "logo": "https://cdn.limitless.exchange/markets-logo/36814/9daba01d-6bcd-4a2c-9187-f4264b7191da.png"
// }
//
// ticker is either a plain raw market object, or a composite dict { 'market': rawMarket, 'book': rawOrderbook }
let mut raw: Value = ticker.clone();
let mut book: Value = Value::Null;
if is_true(&Value::Bool(in_op(&ticker, &Value::Str("market".to_string())))) {
raw = self.safe_dict_k(ticker.clone(), "market", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
book = self.safe_dict_k(ticker.clone(), "book", &[]);
}
let mut rawLabel: Value = ternary(is_true(&(!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 isYes: Value = Value::Bool(!is_equal(&to_lower(&rawLabel), &Value::Str("no".to_string())));
let mut bidStr: Value = Value::Null;
let mut askStr: Value = Value::Null;
let mut bidSizeStr: Value = Value::Null;
let mut askSizeStr: Value = Value::Null;
let mut lastStr: Value = Value::Null;
let mut midStr: Value = Value::Null;
if !is_equal(&book, &Value::Null) {
// the book endpoint is quoted in the yes token, the no side mirrors at 1 - price
let mut rawBids: Value = self.safe_list_k(book.clone(), "bids", &[Value::List(vec![])]);
let mut rawAsks: Value = self.safe_list_k(book.clone(), "asks", &[Value::List(vec![])]);
let mut rawBidsLength: Value = get_array_length(&rawBids);
let mut rawAsksLength: Value = get_array_length(&rawAsks);
let mut yesBestBid: Value = ternary(is_true(&(is_greater_than(&rawBidsLength, &Value::Int(0)))), get_value(&rawBids, &Value::Int(0)), Value::Null);
let mut yesBestAsk: Value = ternary(is_true(&(is_greater_than(&rawAsksLength, &Value::Int(0)))), get_value(&rawAsks, &Value::Int(0)), Value::Null);
let mut yesBidPrice: Value = self.safe_string_k(yesBestBid.clone(), "price", &[]);
let mut yesBidSize: Value = self.safe_string_k(yesBestBid.clone(), "size", &[]);
let mut yesAskPrice: Value = self.safe_string_k(yesBestAsk.clone(), "price", &[]);
let mut yesAskSize: Value = self.safe_string_k(yesBestAsk.clone(), "size", &[]);
let mut yesLast: Value = self.safe_string_k(book.clone(), "lastTradePrice", &[]);
let mut yesMid: Value = self.safe_string_k(book.clone(), "midpoint", &[]);
if is_true(&isYes) {
bidStr = yesBidPrice.clone();
bidSizeStr = yesBidSize.clone();
askStr = yesAskPrice.clone();
askSizeStr = yesAskSize.clone();
lastStr = yesLast.clone();
midStr = yesMid.clone();
} else {
if !is_equal(&yesAskPrice, &Value::Null) {
bidStr = crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &yesAskPrice);
}
bidSizeStr = yesAskSize.clone();
if !is_equal(&yesBidPrice, &Value::Null) {
askStr = crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &yesBidPrice);
}
askSizeStr = yesBidSize.clone();
if !is_equal(&yesLast, &Value::Null) {
lastStr = crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &yesLast);
}
if !is_equal(&yesMid, &Value::Null) {
midStr = crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &yesMid);
}
}
}
let mut prices: Value = self.safe_list_k(raw.clone(), "prices", &[Value::List(vec![])]);
let mut pricesLength: Value = get_array_length(&prices);
if is_true(&(is_equal(&lastStr, &Value::Null))) && is_true(&(is_greater_than(&pricesLength, &Value::Int(0)))) {
lastStr = ternary(is_true(&(isYes)), self.safe_string(prices.clone(), Value::Int(0), &[]), self.safe_string(prices.clone(), Value::Int(1), &[]));
}
// volume and book sizes are in USDC micro-units (6 decimals)
let mut rawVolume: Value = self.safe_string_k(raw.clone(), "volume", &[]);
let mut volumeStr: Value = Value::Null;
if !is_equal(&rawVolume, &Value::Null) {
volumeStr = crate::precise::Precise::stringDiv(&rawVolume, &Value::Str("1000000".to_string()));
}
if !is_equal(&bidSizeStr, &Value::Null) {
bidSizeStr = crate::precise::Precise::stringDiv(&bidSizeStr, &Value::Str("1000000".to_string()));
}
if !is_equal(&askSizeStr, &Value::Null) {
askSizeStr = crate::precise::Precise::stringDiv(&askSizeStr, &Value::Str("1000000".to_string()));
}
let mut now: Value = self.milliseconds();
let mut outcomeSymbol: Value = self.safe_outcome_symbol(Value::Null, &[market.clone()]);
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcomeSymbol.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
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(), self.parse_number(bidStr.clone(), &[]));
m.insert("bidVolume".to_string(), self.parse_number(bidSizeStr.clone(), &[]));
m.insert("ask".to_string(), self.parse_number(askStr.clone(), &[]));
m.insert("askVolume".to_string(), self.parse_number(askSizeStr.clone(), &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), self.parse_number(lastStr.clone(), &[]));
m.insert("last".to_string(), self.parse_number(lastStr.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(), self.parse_number(midStr.clone(), &[]));
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), self.parse_number(volumeStr.clone(), &[]));
m.insert("info".to_string(), ticker.clone());
m
}), &[]);
Value::Null
}
/*
* @method
* @name limitless#fetchTickers
* @description fetches tickers for multiple outcome tokens, grouping requested outcomes by their parent market (two requests per market: detail + order book)
* @see https://docs.limitless.exchange/api-reference/markets/get-market
* @see https://docs.limitless.exchange/api-reference/trading/orderbook
* @param {string[]} outcomes unified outcomes or outcome token ids — required: limitless has 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()))));
}
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
// resolve the uncached outcomes first, then group by parent market to fetch each
// market and book only once
self.load_outcomes(&[outcomes.clone()]).await;
let mut outcomesBySlug: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut slugs: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1260: bool = true;
while { if !__for_first_1260 { i = add(&i, &Value::Int(1)); } __for_first_1260 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
let mut outcomeObj: Value = self.outcome(get_value(&outcomes, &i));
let mut slug: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("slug".to_string()), &[]);
if is_equal(&slug, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchTickers() missing slug".to_string()))));
}
if !is_true(&(Value::Bool(in_op(&outcomesBySlug, &slug)))) {
if !is_equal(&slug, &Value::Null) {
add_element_to_object(&mut outcomesBySlug, &slug, Value::List(vec![]));
}
append_to_array(&mut slugs, slug.clone());
}
// reassign after push, plain mutation through a local is lost in transpiled php (arrays are value types there)
let mut grouped: Value = self.safe_value(outcomesBySlug.clone(), slug.clone(), &[]);
append_to_array(&mut grouped, outcomeObj.clone());
if !is_equal(&slug, &Value::Null) {
add_element_to_object(&mut outcomesBySlug, &slug, grouped.clone());
}
}
}
let mut promises: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1261: bool = true;
while { if !__for_first_1261 { i = add(&i, &Value::Int(1)); } __for_first_1261 = false; is_less_than(&i, &get_array_length(&slugs)) } {
let mut slug: Value = get_value(&slugs, &i);
let mut slug: Value = get_value(&slugs, &i);
let __ws_arg_18 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("addressOrSlug".to_string(), slug.clone());
m
}), &[params.clone()]);
append_to_array(&mut promises, self.limitless_public_get_markets_address_or_slug(&[__ws_arg_18]).await);
append_to_array(&mut promises, self.limitless_public_get_markets_slug_orderbook(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), slug.clone());
m
})]).await);
}
}
let mut responses: Value = promise_all(&promises).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1263: bool = true;
while { if !__for_first_1263 { i = add(&i, &Value::Int(1)); } __for_first_1263 = false; is_less_than(&i, &get_array_length(&slugs)) } {
let mut slug: Value = get_value(&slugs, &i);
let mut slug: Value = get_value(&slugs, &i);
let mut detailIndex: Value = multiply(&i, &Value::Int(2));
let mut detail: Value = get_value(&responses, &detailIndex);
let mut detail: Value = get_value(&responses, &detailIndex);
let mut book: Value = get_value(&responses, &self.sum(&[detailIndex.clone(), Value::Int(1)]));
let mut tickerInput: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market".to_string(), detail.clone());
m.insert("book".to_string(), book.clone());
m
});
let mut grouped: Value = get_value(&outcomesBySlug, &slug);
let mut grouped: Value = get_value(&outcomesBySlug, &slug);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1262: bool = true;
while { if !__for_first_1262 { j = add(&j, &Value::Int(1)); } __for_first_1262 = false; is_less_than(&j, &get_array_length(&grouped)) } {
let mut ticker: Value = self.parse_prediction_ticker(tickerInput.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());
}
}
}
}
}
return result;
Value::Null
}
/*
* @method
* @name limitless#fetchTrades
* @description fetches recent public trades for a single outcome token from the market events feed
* @see https://docs.limitless.exchange/api-reference/trading/market-events
* @param {string} outcome unified outcome like TRUMP_OUT_PRESIDENT_2027:YES or an outcome token id
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum number of trades to return
* @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 slug: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("slug".to_string()), &[]);
let mut tokenId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), slug.clone());
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let __ws_arg_19 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_public_get_markets_slug_events(&[__ws_arg_19]).await;
//
// {
// "events": [
// {
// "createdAt": "2026-06-12T15:24:25.617Z",
// "makerAmount": "19996200",
// "matchedSize": "2500000",
// "price": 0.332,
// "profile": { "account": "0x0572B4Aa431e730d1d19cc7CFea7D6C0Bc07096f" },
// "side": 0,
// "takerAmount": "830000",
// "title": "",
// "tokenId": "34504808738227095158010759634880534083339296329182698784451980951930485131851",
// "txHash": "0x432344fc63f26f37e3ffe3aca45bcfcba6b7addfc07d04de4410855c0a56a175"
// }
// ],
// "limit": 30,
// "page": 1,
// "totalPages": 1,
// "totalRows": 13
// }
//
let mut rows: Value = self.safe_list_k(response.clone(), "events", &[Value::List(vec![])]);
let mut filtered: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1264: bool = true;
while { if !__for_first_1264 { i = add(&i, &Value::Int(1)); } __for_first_1264 = false; is_less_than(&i, &get_array_length(&rows)) } {
let mut row: Value = get_value(&rows, &i);
let mut row: Value = get_value(&rows, &i);
let mut rowTokenId: Value = self.safe_string_k(row.clone(), "tokenId", &[]);
if is_true(&(!is_equal(&tokenId, &Value::Null))) && is_true(&(!is_equal(&rowTokenId, &Value::Null))) && is_true(&(!is_equal(&rowTokenId, &tokenId))) {
continue;
}
append_to_array(&mut filtered, row.clone());
}
}
return self.parse_prediction_trades(filtered.clone(), &[outcomeObj.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name limitless#fetchOrderBook
* @description fetches the order book for a single outcome token, converting 6-decimal USDC sizes to whole units, no outcomes are quoted at 1 - price with the sides swapped
* @see https://docs.limitless.exchange/api-reference/trading/orderbook
* @param {string} outcome unified outcome like TRUMP_OUT_PRESIDENT_2027:YES or an outcome token id
* @param {int} [limit] not used by limitless fetchOrderBook
* @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 slug: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("slug".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), slug.clone());
m
});
let __ws_arg_20 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_public_get_markets_slug_orderbook(&[__ws_arg_20]).await;
//
// {
// "bids": [
// { "price": "0.14", "size": "12360330000", "side": "BUY" },
// { "price": "0.1", "size": "1000000", "side": "BUY" },
// { "price": "0.003", "size": "500000000", "side": "BUY" }
// ],
// "asks": [
// { "price": "0.161", "size": "222000000", "side": "SELL" },
// { "price": "0.996", "size": "5555000000", "side": "SELL" },
// { "price": "0.997", "size": "500000000", "side": "SELL" }
// ],
// "tokenId": "56154308742753982686710750162015444986563701968079760676518531584453506363044",
// "adjustedMidpoint": "0.1505",
// "midpoint": "0.1505",
// "maxSpread": "0.035",
// "minSize": "100000000",
// "lastTradePrice": "0.161"
// }
//
let mut timestamp: Value = self.milliseconds();
let mut decimals: Value = self.safe_integer_k(self.options.clone(), "usdcDecimals", &[Value::Int(6)]);
// sizes are scaled by 10^decimals, USDC uses 6 decimals
let mut scaleStr: Value = self.parse_precision(&[self.number_to_string(negate(&decimals))]);
let mut outcomeLabel: Value = self.safe_string_lower(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("outcomeLabel".to_string()), &[Value::Str("yes".to_string())]);
let mut isYes: Value = Value::Bool(!is_equal(&outcomeLabel, &Value::Str("no".to_string())));
let mut rawBids: Value = self.safe_list_k(response.clone(), "bids", &[Value::List(vec![])]);
let mut rawAsks: Value = self.safe_list_k(response.clone(), "asks", &[Value::List(vec![])]);
// the book endpoint is quoted in the yes token, the no side mirrors at 1 - price with bids and asks swapped
let mut bidsSource: Value = ternary(is_true(&(isYes)), rawBids.clone(), rawAsks.clone());
let mut asksSource: Value = ternary(is_true(&(isYes)), rawAsks.clone(), rawBids.clone());
let mut bids: Value = Value::List(vec![]);
let mut asks: Value = Value::List(vec![]);
{
let mut bi: Value = Value::Int(0);
let mut __for_first_1265: bool = true;
while { if !__for_first_1265 { bi = add(&bi, &Value::Int(1)); } __for_first_1265 = false; is_less_than(&bi, &get_array_length(&bidsSource)) } {
let mut priceStr: Value = self.safe_string_k(get_value(&bidsSource, &bi), "price", &[]);
if !is_true(&isYes) && is_true(&(!is_equal(&priceStr, &Value::Null))) {
priceStr = crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &priceStr);
}
let mut sizeStr: Value = self.safe_string_k(get_value(&bidsSource, &bi), "size", &[]);
if !is_equal(&sizeStr, &Value::Null) {
sizeStr = crate::precise::Precise::stringDiv(&sizeStr, &scaleStr);
}
append_to_array(&mut bids, Value::List(vec![self.parse_number(priceStr.clone(), &[]), self.parse_number(sizeStr.clone(), &[])]));
}
}
{
let mut ai: Value = Value::Int(0);
let mut __for_first_1266: bool = true;
while { if !__for_first_1266 { ai = add(&ai, &Value::Int(1)); } __for_first_1266 = false; is_less_than(&ai, &get_array_length(&asksSource)) } {
let mut priceStr: Value = self.safe_string_k(get_value(&asksSource, &ai), "price", &[]);
if !is_true(&isYes) && is_true(&(!is_equal(&priceStr, &Value::Null))) {
priceStr = crate::precise::Precise::stringSub(&Value::Str("1".to_string()), &priceStr);
}
let mut sizeStr: Value = self.safe_string_k(get_value(&asksSource, &ai), "size", &[]);
if !is_equal(&sizeStr, &Value::Null) {
sizeStr = crate::precise::Precise::stringDiv(&sizeStr, &scaleStr);
}
append_to_array(&mut asks, Value::List(vec![self.parse_number(priceStr.clone(), &[]), self.parse_number(sizeStr.clone(), &[])]));
}
}
let mut orderbook: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), self.safe_outcome_symbol(outcome.clone(), &[outcomeObj.clone()]));
m.insert("bids".to_string(), self.sort_by(bids.clone(), Value::Int(0), &[Value::Bool(true)]));
m.insert("asks".to_string(), self.sort_by(asks.clone(), Value::Int(0), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("nonce".to_string(), Value::Null);
m
});
return self.safe_prediction_order_book(orderbook.clone(), &[outcomeObj.clone()]);
Value::Null
}
/*
* @method
* @name limitless#fetchOHLCV
* @description fetches historical prices for a single limitless market outcome and maps them to OHLCV format, uses the `interval` query parameter and selects the YES/NO series that matches the requested outcome
* @see https://docs.limitless.exchange/api-reference/trading/historical-price
* @param {string} outcome outcome, e.g. "TRUMP_OUT:YES"
* @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("1d".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 slug: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("slug".to_string()), &[]);
let mut outcomeLabel: Value = self.safe_string_upper(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("outcomeLabel".to_string()), &[]);
let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[Value::Str("1d".to_string())]);
let __ws_arg_21 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), slug.clone());
m.insert("interval".to_string(), interval.clone());
m
}), &[params.clone()]);
let mut response: Value = self.limitless_public_get_markets_slug_historical_price(&[__ws_arg_21]).await;
//
// {
// "data": [
// {
// "timestamp": 1705318200000,
// "price": 0.1655
// },
// ]
// }
//
//
// [
// {
// "title": "YES Token",
// "prices": [
// {
// "price": 0.75,
// "timestamp": "2024-01-15T10:30:00Z"
// },
// ]
// },
// {
// "title": "NO Token",
// "prices": [
// {
// "price": 0.25,
// "timestamp": "2024-01-15T10:30:00Z"
// }
// ]
// }
// ]
//
let mut responseRows: Value = Value::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
responseRows = response.clone();
}
let mut rawHistoryList: Value = self.safe_list_k(response.clone(), "data", &[self.safe_list(response.clone(), Value::Str("prices".to_string()), &[responseRows.clone()])]);
let mut rawHistory: Value = ternary(is_true(&(!is_equal(&rawHistoryList, &Value::Null))), rawHistoryList.clone(), Value::List(vec![]));
let mut history: Value = rawHistory.clone();
let mut rawHistoryLength: Value = get_array_length(&rawHistory);
if is_greater_than(&rawHistoryLength, &Value::Int(0)) {
let mut first: Value = self.safe_dict(rawHistory.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut firstPrices: Value = self.safe_list_k(first.clone(), "prices", &[]);
if !is_equal(&firstPrices, &Value::Null) {
let mut selectedSeries: Value = first.clone();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1267: bool = true;
while { if !__for_first_1267 { i = add(&i, &Value::Int(1)); } __for_first_1267 = false; is_less_than(&i, &get_array_length(&rawHistory)) } {
let mut series: Value = self.safe_dict(rawHistory.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut title: Value = self.safe_string_upper(series.clone(), Value::Str("title".to_string()), &[Value::Str("".to_string())]);
if is_equal(&title, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchOHLCV() missing title".to_string()))));
}
if is_true(&(!is_equal(&outcomeLabel, &Value::Null))) && is_true(&(is_greater_than_or_equal(&get_index_of(&title, &outcomeLabel), &Value::Int(0)))) {
selectedSeries = series.clone();
break;
}
}
}
history = self.safe_list_k(selectedSeries.clone(), "prices", &[Value::List(vec![])]);
}
}
// the endpoint returns raw price points, not candles - bucket them into
// timeframe-aligned candles (single points would carry unaligned timestamps)
let mut pseudoTrades: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1268: bool = true;
while { if !__for_first_1268 { i = add(&i, &Value::Int(1)); } __for_first_1268 = false; is_less_than(&i, &get_array_length(&history)) } {
let mut point: Value = get_value(&history, &i);
let mut point: Value = get_value(&history, &i);
let mut pointPrice: Value = self.safe_number_k(point.clone(), "price", &[]);
let mut pointTs: Value = self.safe_integer_k(point.clone(), "timestamp", &[]);
if is_equal(&pointTs, &Value::Null) {
let mut tsString: Value = self.safe_string_k(point.clone(), "timestamp", &[]);
pointTs = ternary(is_true(&(!is_equal(&tsString, &Value::Null) && !is_equal(&tsString, &Value::Str("".to_string())))), self.parse8601(tsString.clone()), Value::Null);
} else if is_less_than(&pointTs, &Value::Int(1000000000000)) {
// old responses may return unix seconds
pointTs = multiply(&pointTs, &Value::Int(1000));
}
if is_true(&(!is_equal(&pointPrice, &Value::Null))) && is_true(&(!is_equal(&pointTs, &Value::Null))) {
append_to_array(&mut pseudoTrades, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timestamp".to_string(), pointTs.clone());
m.insert("price".to_string(), pointPrice.clone());
m.insert("amount".to_string(), Value::Int(0));
m
}));
}
}
}
// the endpoint returns points NEWEST-first, so sort ascending by timestamp before bucketing —
// otherwise candles come back descending and open/close are inverted within each bucket
// — the first point seen would be the latest, not the earliest. sortBy is stable, so equal
// timestamps keep their relative order consistently across languages
let mut sorted: Value = self.sort_by(pseudoTrades.clone(), Value::Str("timestamp".to_string()), &[]);
let mut ms: Value = multiply(&self.parse_timeframe(timeframe.clone()), &Value::Int(1000));
let mut candles: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut bucketOrder: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1269: bool = true;
while { if !__for_first_1269 { i = add(&i, &Value::Int(1)); } __for_first_1269 = false; is_less_than(&i, &get_array_length(&sorted)) } {
let mut point: Value = get_value(&sorted, &i);
let mut point: Value = get_value(&sorted, &i);
let mut pTs: Value = self.safe_integer_k(point.clone(), "timestamp", &[]);
let mut pPrice: Value = self.safe_number_k(point.clone(), "price", &[]);
if is_equal(&pTs, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" method() missing pTs".to_string()))));
}
let mut bucket: Value = multiply(&self.parse_to_int(divide(&pTs, &ms)), &ms);
let mut key: Value = to_string_val(&bucket);
if !is_true(&(Value::Bool(in_op(&candles, &key)))) {
add_element_to_object(&mut candles, &key, Value::List(vec![bucket.clone(), pPrice.clone(), pPrice.clone(), pPrice.clone(), pPrice.clone(), Value::Int(0)]));
append_to_array(&mut bucketOrder, key.clone());
} else {
let mut candle: Value = get_value(&candles, &key);
let mut candle: Value = get_value(&candles, &key);
let mut pPriceOrZero: Value = ternary(is_true(&(is_equal(&pPrice, &Value::Null))), Value::Int(0), pPrice.clone());
{ let __be_tmp = crate::runtime::Math::max(&get_value(&candle, &Value::Int(2)), &pPriceOrZero); add_element_to_object(&mut candle, &Value::Int(2), __be_tmp); };
let mut candleLow: Value = ternary(is_true(&(is_equal(&get_value(&candle, &Value::Int(3)), &Value::Null))), pPrice.clone(), get_value(&candle, &Value::Int(3)));
let mut pPriceOrCandleLow: Value = ternary(is_true(&(is_equal(&pPrice, &Value::Null))), get_value(&candle, &Value::Int(3)), pPrice.clone());
add_element_to_object(&mut candle, &Value::Int(3), crate::runtime::Math::min(&candleLow, &pPriceOrCandleLow));
add_element_to_object(&mut candle, &Value::Int(4), pPrice.clone());
add_element_to_object(&mut candles, &key, candle.clone()); // php arrays are value types - write the mutation back
}
}
}
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1270: bool = true;
while { if !__for_first_1270 { i = add(&i, &Value::Int(1)); } __for_first_1270 = false; is_less_than(&i, &get_array_length(&bucketOrder)) } {
append_to_array(&mut result, get_value(&candles, &get_value(&bucketOrder, &i)));
}
}
return self.filter_by_since_limit(result.clone(), &[since.clone(), limit.clone(), Value::Int(0)]);
Value::Null
}
/*
* @method
* @name limitless#fetchOrders
* @description fetches orders for the authenticated user for a single outcome
* @see https://docs.limitless.exchange/api-reference/orders/get-user-orders
* @param {string} [outcome] outcome, e.g. "TRUMP_OUT:YES"
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @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) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchOrders requires an outcome argument".to_string()))));
}
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), self.safe_string_k(info.clone(), "slug", &[]));
m.insert("statuses".to_string(), Value::List(vec![Value::Str("LIVE".to_string()), Value::Str("MATCHED".to_string())]));
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let __ws_arg_22 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_private_get_markets_slug_user_orders(&[__ws_arg_22]).await;
return self.parse_prediction_orders(self.to_array(response.clone()), &[Value::Null, since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name limitless#fetchOpenOrders
* @description fetches open orders for the authenticated user for a single outcome
* @see https://docs.limitless.exchange/api-reference/orders/get-user-orders
* @param {string} [outcome] outcome, e.g. "TRUMP_OUT:YES"
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @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) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchOpenOrders requires an outcome argument".to_string()))));
}
self.load_outcome(outcome.clone(), &[]).await;
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("statuses".to_string(), Value::List(vec![Value::Str("LIVE".to_string())]));
m
})]);
return self.fetch_orders(&[outcome.clone(), since.clone(), limit.clone(), params.clone()]).await;
Value::Null
}
/*
* @method
* @name limitless#fetchClosedOrders
* @description fetches closed orders for the authenticated user for a single outcome
* @see https://docs.limitless.exchange/api-reference/orders/get-user-orders
* @param {string} [outcome] outcome, e.g. "TRUMP_OUT:YES"
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @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
}));
if is_equal(&outcome, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchClosedOrders requires an outcome argument".to_string()))));
}
self.load_outcome(outcome.clone(), &[]).await;
params = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("statuses".to_string(), Value::List(vec![Value::Str("MATCHED".to_string())]));
m
})]);
return self.fetch_orders(&[outcome.clone(), since.clone(), limit.clone(), params.clone()]).await;
Value::Null
}
/*
* @method
* @name limitless#fetchOrdersByIds
* @description fetch orders by the list of order id
* @see https://docs.limitless.exchange/api-reference/trading/order-status-batch
* @param {string[]} ids list of order id
* @param {string} [outcome] market outcome, e.g. "TRUMP_OUT:YES"
* @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_by_ids(&mut self, mut ids: 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
}));
if !is_equal(&outcome, &Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
}
let mut length: Value = get_array_length(&ids);
if is_greater_than(&length, &Value::Int(50)) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchOrdersByIds can only fetch up to 50 orders at a time".to_string()))));
}
let mut items: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1271: bool = true;
while { if !__for_first_1271 { i = add(&i, &Value::Int(1)); } __for_first_1271 = false; is_less_than(&i, &length) } {
let mut id: Value = self.safe_string(ids.clone(), i.clone(), &[]);
let mut item: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id.clone());
m
});
append_to_array(&mut items, item.clone());
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("items".to_string(), items.clone());
m
});
let __ws_arg_23 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_private_post_orders_status_batch(&[__ws_arg_23]).await;
//
// {
// "results": [
// {
// "index": 0,
// "status": "found",
// "orderId": "ff0dcbf1-f7de-43f0-b6f1-16b972a17f49",
// "data": {
// "order": {
// "createdAt": "2026-05-04T10:26:01.334Z",
// "id": "ff0dcbf1-f7de-43f0-b6f1-16b972a17f49",
// "makerAmount": "9999360",
// "takerAmount": "10752000",
// "expiration": null,
// "signatureType": 2,
// "salt": "277966495716",
// "maker": "0xAb2B9833FC8B8f55F4De7C4A0FAb8577EF0F7b36",
// "signer": "0x82a0f074C6C0C11aA370D7FBF077668c31fCc990",
// "taker": "0x0000000000000000000000000000000000000000",
// "tokenId": "46235703925185836960484608024734446969378108670784413458211837874003718039438",
// "side": 0,
// "feeRateBps": 300,
// "nonce": "0",
// "signature": "0x1640c8558d8c627017b2c6ac71a79770d177033afeb9be72842803afcd12938f23308c507935011ad6d10acc299e5367f76b4f806eb025c15cb05739de11260d1b",
// "orderType": "FAK",
// "price": "0.93",
// "marketId": 112523,
// "ownerId": 1315134,
// "market": {
// "id": 112523,
// "slug": "doge-above-dollar010859-on-may-4-2000-utc-1777838401426",
// "title": "DOGE above $0.10859 on May 4, 20:00 UTC?",
// "status": "FUNDED",
// "yesPositionId": "46235703925185836960484608024734446969378108670784413458211837874003718039438",
// "noPositionId": "101714389600295994108208140228744407174156865974966685440205519669272948152879"
// },
// "owner": {
// "id": 1315134,
// "account": "0x7CFF82f72b991B6B2b661e404389fD8a40bCD21B",
// "client": "eoa",
// "tradeWalletOption": "smartWallet",
// "smartWallet": "0xAb2B9833FC8B8f55F4De7C4A0FAb8577EF0F7b36",
// "points": 0,
// "referredUsersCount": 0
// }
// },
// "makerMatches": [
// {
// "id": "be44a183-ec56-4076-a69c-10283321abd6",
// "matchedSize": "10752000",
// "fillPrice": "0.93",
// "fillCost": "9999360",
// "orderId": "3255c786-3f30-4115-a99f-72be478f2e44",
// "order": {
// "id": "3255c786-3f30-4115-a99f-72be478f2e44",
// "maker": "0x8274600A3a9DC84747E6dEb49380F6B1DE2C505d",
// "price": "0.07",
// "side": 0,
// "tokenId": "101714389600295994108208140228744407174156865974966685440205519669272948152879",
// "owner": {
// "id": 202602,
// "account": "0x8274600A3a9DC84747E6dEb49380F6B1DE2C505d",
// "client": "eoa",
// "tradeWalletOption": null,
// "smartWallet": null,
// "username": null,
// "displayName": "0x8274600A3a9DC84747E6dEb49380F6B1DE2C505d",
// "pfpUrl": null,
// "socialUrl": null,
// "points": 0,
// "referredUsersCount": 0
// }
// }
// }
// ],
// "execution": {
// "feeRateBps": 300,
// "effectiveFeeBps": 59,
// "matched": true,
// "settlementStatus": "MINED",
// "tradeEventId": "44c46a93-f5cb-40f5-a52f-bd55bb97641e",
// "txHash": "0x101cda4b605007440b382c35a27531605c7fc1b29a7c803b19237586a74c10e8",
// "totalsRaw": {
// "contractsGross": "10752000",
// "contractsFee": "63436",
// "contractsNet": "10688564",
// "usdGross": "9999360",
// "usdFee": "0",
// "usdNet": "9999360"
// }
// }
// }
// }
// ]
// }
//
let mut results: Value = self.safe_list_k(response.clone(), "results", &[Value::List(vec![])]);
let mut found: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1272: bool = true;
while { if !__for_first_1272 { i = add(&i, &Value::Int(1)); } __for_first_1272 = false; is_less_than(&i, &get_array_length(&results)) } {
let mut item: Value = self.safe_dict(results.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut itemStatus: Value = self.safe_string_k(item.clone(), "status", &[]);
if is_equal(&itemStatus, &Value::Str("found".to_string())) {
append_to_array(&mut found, item.clone());
}
}
}
return self.parse_prediction_orders(found.clone(), &[]);
Value::Null
}
/*
* @method
* @name limitless#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.limitless.exchange/api-reference/trading/order-status-batch
* @param {string} id the order id
* @param {string} [outcome] market outcome, e.g. "TRUMP_OUT:YES"
* @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
}));
if !is_equal(&outcome, &Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
}
let mut orders: Value = self.fetch_orders_by_ids(Value::List(vec![id.clone()]), &[outcome.clone(), params.clone()]).await;
let mut order: Value = self.safe_dict(orders.clone(), Value::Int(0), &[]);
if is_equal(&order, &Value::Null) {
panic!("{}", crate::exchange_errors::order_not_found(add(&add(&self.id, &Value::Str(" fetchOrder() could not find order ".to_string())), &id)));
}
return order;
Value::Null
}
/*
* @ignore
* @method
* @name limitless#parsePredictionOrder
* @description parses a raw limitless 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);
//
// fetchOrders, fetchOpenOrders, fetchClosedOrders
// {
// "createdAt": "2026-05-04T08:57:06.448Z",
// "id": "c4b1a83a-219f-48db-a9be-1ddadf0bc14c",
// "ownerId": 1315134,
// "marketId": "112523",
// "token": "46235703925185836960484608024734446969378108670784413458211837874003718039438",
// "type": "GTC",
// "status": "LIVE",
// "side": "BUY",
// "makerAmount": "1000040",
// "takerAmount": "10870000",
// "price": "0.092",
// "originalSize": "10870000",
// "remainingSize": "10870000"
// }
//
// fetchOrdersByIds, fetchOrder
// {
// "index": 0,
// "status": "found",
// "orderId": "ff0dcbf1-f7de-43f0-b6f1-16b972a17f49",
// "data": {
// "order": {
// "createdAt": "2026-05-04T10:26:01.334Z",
// "id": "ff0dcbf1-f7de-43f0-b6f1-16b972a17f49",
// "makerAmount": "9999360",
// "takerAmount": "10752000",
// "expiration": null,
// "signatureType": 2,
// "salt": "277966495716",
// "maker": "0xAb2B9833FC8B8f55F4De7C4A0FAb8577EF0F7b36",
// "signer": "0x82a0f074C6C0C11aA370D7FBF077668c31fCc990",
// "taker": "0x0000000000000000000000000000000000000000",
// "tokenId": "46235703925185836960484608024734446969378108670784413458211837874003718039438",
// "side": 0,
// "feeRateBps": 300,
// "nonce": "0",
// "signature": "0x1640c8558d8c627017b2c6ac71a79770d177033afeb9be72842803afcd12938f23308c507935011ad6d10acc299e5367f76b4f806eb025c15cb05739de11260d1b",
// "orderType": "FAK",
// "price": "0.93",
// "marketId": 112523,
// "ownerId": 1315134,
// "market": {
// "id": 112523,
// "slug": "doge-above-dollar010859-on-may-4-2000-utc-1777838401426",
// "title": "DOGE above $0.10859 on May 4, 20:00 UTC?",
// "status": "FUNDED",
// "yesPositionId": "46235703925185836960484608024734446969378108670784413458211837874003718039438",
// "noPositionId": "101714389600295994108208140228744407174156865974966685440205519669272948152879"
// },
// "owner": {
// "id": 1315134,
// "account": "0x7CFF82f72b991B6B2b661e404389fD8a40bCD21B",
// "client": "eoa",
// "tradeWalletOption": "smartWallet",
// "smartWallet": "0xAb2B9833FC8B8f55F4De7C4A0FAb8577EF0F7b36",
// "points": 0,
// "referredUsersCount": 0
// }
// },
// "makerMatches": [
// {
// "id": "be44a183-ec56-4076-a69c-10283321abd6",
// "matchedSize": "10752000",
// "fillPrice": "0.93",
// "fillCost": "9999360",
// "orderId": "3255c786-3f30-4115-a99f-72be478f2e44",
// "order": {
// "id": "3255c786-3f30-4115-a99f-72be478f2e44",
// "maker": "0x8274600A3a9DC84747E6dEb49380F6B1DE2C505d",
// "price": "0.07",
// "side": 0,
// "tokenId": "101714389600295994108208140228744407174156865974966685440205519669272948152879",
// "owner": {
// "id": 202602,
// "account": "0x8274600A3a9DC84747E6dEb49380F6B1DE2C505d",
// "client": "eoa",
// "tradeWalletOption": null,
// "smartWallet": null,
// "username": null,
// "displayName": "0x8274600A3a9DC84747E6dEb49380F6B1DE2C505d",
// "pfpUrl": null,
// "socialUrl": null,
// "points": 0,
// "referredUsersCount": 0
// }
// }
// }
// ],
// "execution": {
// "feeRateBps": 300,
// "effectiveFeeBps": 59,
// "matched": true,
// "settlementStatus": "MINED",
// "tradeEventId": "44c46a93-f5cb-40f5-a52f-bd55bb97641e",
// "txHash": "0x101cda4b605007440b382c35a27531605c7fc1b29a7c803b19237586a74c10e8",
// "totalsRaw": {
// "contractsGross": "10752000",
// "contractsFee": "63436",
// "contractsNet": "10688564",
// "usdGross": "9999360",
// "usdFee": "0",
// "usdNet": "9999360"
// }
// }
// }
// }
let mut data: Value = self.safe_dict_k(order.clone(), "data", &[]);
let mut rawOrder: Value = self.safe_dict_k(data.clone(), "order", &[order.clone()]);
// createOrder returns the order nested under an 'order' key
let mut wrappedOrder: Value = self.safe_dict_k(rawOrder.clone(), "order", &[]);
if !is_equal(&wrappedOrder, &Value::Null) {
rawOrder = wrappedOrder.clone();
}
let mut id: Value = self.safe_string_k(rawOrder.clone(), "id", &[]);
let mut tokenId: Value = self.safe_string2(rawOrder.clone(), Value::Str("token".to_string()), Value::Str("tokenId".to_string()), &[]);
let mut mkt: Value = self.safe_outcome(tokenId.clone(), &[market.clone()]);
let mut outcomeSymbol: Value = self.safe_string_k(mkt.clone(), "outcome", &[]);
let mut rawSide: Value = self.safe_string_k(rawOrder.clone(), "side", &[]);
let mut side: Value = self.parse_order_side(rawSide.clone());
let mut price: Value = self.safe_string_k(rawOrder.clone(), "price", &[]);
let mut amountKey: Value = ternary(is_true(&(is_equal(&side, &Value::Str("buy".to_string())))), Value::Str("takerAmount".to_string()), Value::Str("makerAmount".to_string())); // todo check
let mut amount: Value = self.safe_string(rawOrder.clone(), amountKey.clone(), &[]);
let mut remaining: Value = self.safe_string_k(rawOrder.clone(), "remainingSize", &[]);
let mut datetime: Value = self.safe_string_k(rawOrder.clone(), "createdAt", &[]);
let mut ts: Value = self.parse8601(datetime.clone());
let mut timeInForce: Value = self.safe_string2(rawOrder.clone(), Value::Str("type".to_string()), Value::Str("orderType".to_string()), &[]);
let mut type_var: Value = Value::Null;
if is_equal(&timeInForce, &Value::Str("GTC".to_string())) {
type_var = Value::Str("limit".to_string());
} else if is_equal(&timeInForce, &Value::Str("FAK".to_string())) {
type_var = Value::Str("market".to_string());
}
let mut rawStatus: Value = self.safe_string_k(rawOrder.clone(), "status", &[]);
let mut execution: Value = self.safe_dict_k(data.clone(), "execution", &[]);
let mut fee: Value = Value::Null;
let mut filled: Value = Value::Null;
let mut cost: Value = Value::Null;
if !is_equal(&execution, &Value::Null) {
rawStatus = self.safe_string_k(execution.clone(), "settlementStatus", &[]);
let mut totals: Value = self.safe_dict_k(execution.clone(), "totalsRaw", &[]);
cost = self.safe_string_k(totals.clone(), "usdGross", &[]);
filled = self.safe_string_k(totals.clone(), "contractsGross", &[]);
let mut feeCurrency: Value = Value::Str("USDC".to_string());
let mut feeCost: Value = self.safe_string_k(totals.clone(), "usdFee", &[]);
if is_equal(&side, &Value::Str("buy".to_string())) {
feeCurrency = outcomeSymbol.clone();
feeCost = self.safe_string_k(totals.clone(), "contractsFee", &[]);
}
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(self.apply_scale(feeCost.clone(), &[]), &[]));
m.insert("currency".to_string(), feeCurrency.clone());
m
});
}
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(), Value::Null);
m.insert("info".to_string(), order.clone());
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), datetime.clone());
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("status".to_string(), self.parse_order_status(rawStatus.clone()));
m.insert("outcome".to_string(), outcomeSymbol.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(mkt.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(mkt.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(mkt.clone(), "market", &[]));
m.insert("type".to_string(), type_var.clone());
m.insert("timeInForce".to_string(), self.parse_order_time_in_force(timeInForce.clone()));
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(), self.apply_scale(amount.clone(), &[]));
m.insert("cost".to_string(), self.apply_scale(cost.clone(), &[]));
m.insert("filled".to_string(), self.apply_scale(filled.clone(), &[]));
m.insert("remaining".to_string(), self.apply_scale(remaining.clone(), &[]));
m.insert("fee".to_string(), fee.clone());
m.insert("trades".to_string(), Value::List(vec![]));
m
}), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name limitless#parseOrderStatus
* @description maps an order status string to the CCXT unified status vocabulary
* @param {string} status the raw limitless 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("LIVE".to_string(), Value::Str("open".to_string()));
m.insert("MATCHED".to_string(), Value::Str("closed".to_string()));
m.insert("PENDING".to_string(), Value::Str("pending".to_string()));
m.insert("MINED".to_string(), Value::Str("closed".to_string()));
m.insert("CONFIRMED".to_string(), Value::Str("closed".to_string()));
m.insert("FAILED".to_string(), Value::Str("rejected".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name limitless#parseOrderTimeInForce
* @description maps an order time in force string to the CCXT unified type vocabulary
* @param {string} timeInForce the raw limitless time in force
* @returns {string} the unified time in force
*/
pub fn parse_order_time_in_force(&self, mut timeInForce: Value) -> Value {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("FAK".to_string(), Value::Str("FOK".to_string()));
m
});
return self.safe_string(timeInForces.clone(), timeInForce.clone(), &[timeInForce.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name limitless#parseOrderSide
* @description maps an order side string to the CCXT unified side vocabulary
* @param {string} side the raw limitless order side
* @returns {string} the unified order side
*/
pub fn parse_order_side(&self, mut side: Value) -> Value {
let mut sides: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("BUY".to_string(), Value::Str("buy".to_string()));
m.insert("SELL".to_string(), Value::Str("sell".to_string()));
m.insert("0".to_string(), Value::Str("buy".to_string()));
m.insert("1".to_string(), Value::Str("sell".to_string()));
m
});
return self.safe_string(sides.clone(), side.clone(), &[side.clone()]);
Value::Null
}
pub fn apply_scale(&self, mut amount: Value, optional_args: &[Value]) -> Value {
let mut multiply = get_arg(optional_args, 0, Value::Bool(false));
let mut decimals: Value = self.safe_integer_k(self.options.clone(), "usdcDecimals", &[Value::Int(6)]);
let mut scale: Value = self.number_to_string(crate::runtime::Math::pow(&Value::Int(10), &decimals));
if is_true(&multiply) {
return crate::precise::Precise::stringMul(&amount, &scale);
} else {
return crate::precise::Precise::stringDiv(&amount, &scale);
}
Value::Null
}
pub fn parse_account(&self, mut account: Value) -> Value {
let mut accountId: Value = self.safe_string_k(account.clone(), "id", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), accountId.clone());
m.insert("type".to_string(), Value::Null);
m.insert("code".to_string(), Value::Null);
m.insert("info".to_string(), account.clone());
m
});
Value::Null
}
/*
* @method
* @name limitless#fetchAccounts
* @description query for account id and info
* @see https://docs.limitless.exchange/api-reference/portfolio/get-current-profile
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [account structures]
*/
pub async fn fetch_accounts(&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.limitless_private_get_profiles_me(&[params.clone()]).await;
let mut responseList: Value = Value::List(vec![response.clone()]);
return self.parse_accounts(responseList.clone(), &[]);
Value::Null
}
/*
* @method
* @name limitless#createOrder
* @description places a limit or market order on limitless for the given outcome token
* @see https://docs.limitless.exchange/api-reference/orders/create-order
* @param {string} outcome outcome, e.g. "TRUMP_OUT:YES"
* @param {string} type 'limit' or 'market'
* @param {string} side 'buy' or 'sell'
* @param {float} amount amount of outcome tokens
* @param {float} [price] limit price (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
}));
let mut accounts: Value = self.load_accounts(&[]).await;
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut account: Value = self.safe_dict(accounts.clone(), Value::Int(0), &[]);
let mut accountInfo: Value = self.safe_dict_k(account.clone(), "info", &[]);
// the trade wallet is chosen by `tradeWalletOption`: 'smartWallet' profiles trade through
// the `smartWallet` address, plain 'eoa' profiles trade directly from `account`. the
// smartWallet field can stay populated after switching to eoa, so key off the option here
let mut tradeWalletOption: Value = self.safe_string_k(accountInfo.clone(), "tradeWalletOption", &[]);
let mut usesSmartWallet: Value = Value::Bool(is_equal(&tradeWalletOption, &Value::Str("smartWallet".to_string())));
let mut walletFromAccount: Value = ternary(is_true(&(usesSmartWallet)), self.safe_string_k(accountInfo.clone(), "smartWallet", &[]), self.safe_string_k(accountInfo.clone(), "account", &[]));
let mut maker: Value = ternary(is_true(&(!is_equal(&self.walletAddress, &Value::Str("".to_string())))), self.walletAddress.clone(), walletFromAccount.clone());
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("maker".to_string()), &[maker.clone()]); maker = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
self.check_address(&[maker.clone()]);
#[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
panic!("{}", crate::exchange_errors::invalid_address(add(&self.id, &Value::Str(" createOrder requires a valid maker address. Set the \"maker\" parameter to a valid address or set the \"walletAddress\" property in the constructor options.".to_string()))));
}
// when the profile trades through a smart wallet the order must be signed by the
// linked embedded (owner) wallet, not by the smart wallet itself
let mut embeddedAddress: Value = self.safe_string_k(accountInfo.clone(), "embeddedAccount", &[]);
let mut hasEmbedded: bool = !is_equal(&embeddedAddress, &Value::Null);
let mut isSmartWallet: bool = is_true(&usesSmartWallet) && is_true(&hasEmbedded);
let mut signer: Value = maker.clone();
if is_true(&isSmartWallet) {
signer = embeddedAddress.clone();
}
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("signer".to_string()), &[signer.clone()]); signer = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
self.check_address(&[signer.clone()]);
#[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
panic!("{}", crate::exchange_errors::invalid_address(add(&self.id, &Value::Str(" createOrder requires a valid signer address. Set the \"signer\" parameter to a valid address or set the \"walletAddress\" property in the constructor options.".to_string()))));
}
let mut taker: Value = self.safe_string_k(self.options.clone(), "nullAddress", &[Value::Str("0x0000000000000000000000000000000000000000".to_string())]);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("taker".to_string()), &[taker.clone()]); taker = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
self.check_address(&[taker.clone()]);
#[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
panic!("{}", crate::exchange_errors::invalid_address(add(&self.id, &Value::Str(" createOrder requires a valid taker address. Set the \"taker\" parameter to a valid address or set the \"nullAddress\" property in the constructor options.".to_string()))));
}
let mut nonce: Value = self.milliseconds();
let mut sides: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("buy".to_string(), Value::Int(0));
m.insert("sell".to_string(), Value::Int(1));
m
});
if is_equal(&side, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrder() requires a side argument".to_string()))));
}
let mut sideValue: Value = self.safe_integer(sides.clone(), to_lower(&side), &[]);
let mut rank: Value = self.safe_dict_k(accountInfo.clone(), "rank", &[]);
// signatureType: 0 = EOA, 2 = smart-wallet (the embedded owner signs on behalf of the safe)
let mut signatureType: Value = ternary(is_true(&isSmartWallet), Value::Int(2), Value::Int(0));
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("signatureType".to_string()), &[signatureType.clone()]); signatureType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut signRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("salt".to_string(), nonce.clone());
m.insert("maker".to_string(), maker.clone());
m.insert("signer".to_string(), signer.clone());
m.insert("taker".to_string(), taker.clone());
m.insert("tokenId".to_string(), get_value(&outcomeObj, &Value::Str("outcomeId".to_string())));
m.insert("nonce".to_string(), Value::Int(0));
m.insert("feeRateBps".to_string(), self.safe_integer_k(rank.clone(), "feeRateBps", &[Value::Int(0)]));
m.insert("side".to_string(), sideValue.clone());
m.insert("signatureType".to_string(), signatureType.clone());
m
});
// the contract expects expiration as a uint256; non-zero values are rejected by the API (GTC orders use 0)
let mut expirationInt: Value = self.safe_integer_k(params.clone(), "expiration", &[]);
if !is_equal(&expirationInt, &Value::Null) {
params = self.omit(params.clone(), Value::Str("expiration".to_string()), &[]);
add_element_to_object(&mut signRequest, &Value::Str("expiration".to_string()), self.number_to_string(expirationInt.clone()));
} else {
add_element_to_object(&mut signRequest, &Value::Str("expiration".to_string()), Value::Str("0".to_string()));
}
let mut amountString: Value = self.number_to_string(amount.clone());
let mut priceString: Value = self.number_to_string(price.clone());
let mut makerAmount: Value = Value::Null;
let mut takerAmount: Value = Value::Null;
let mut isMarket: Value = Value::Bool(is_equal(&type_var, &Value::Str("market".to_string())));
let mut postOnly: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_post_only(isMarket.clone(), Value::Bool(false), &[params.clone()]); postOnly = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut timeInForce: Value = self.safe_string_k(params.clone(), "timeInForce", &[]);
params = self.omit(params.clone(), Value::Str("timeInForce".to_string()), &[]);
if is_equal(&timeInForce, &Value::Null) {
timeInForce = ternary(is_true(&isMarket), Value::Str("FOK".to_string()), Value::Str("GTC".to_string()));
}
let mut marketSymbol: Value = self.safe_string_k(outcomeObj.clone(), "market", &[]);
if is_true(&isMarket) && is_true(&(is_equal(&side, &Value::Str("buy".to_string())))) {
let mut createMarketBuyOrderRequiresPrice: Value = Value::Bool(true);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("createMarketBuyOrderRequiresPrice".to_string()), &[Value::Bool(true)]); createMarketBuyOrderRequiresPrice = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut cost: Value = self.safe_number_k(params.clone(), "cost", &[]);
params = self.omit(params.clone(), Value::Str("cost".to_string()), &[]);
if is_true(&createMarketBuyOrderRequiresPrice) {
if is_true(&(is_equal(&price, &Value::Null))) && is_true(&(is_equal(&cost, &Value::Null))) {
panic!("{}", crate::exchange_errors::invalid_order(add(&self.id, &Value::Str(" createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument".to_string()))));
} else {
let mut quoteAmount: Value = self.parse_to_numeric(crate::precise::Precise::stringMul(&amountString, &priceString));
let mut costRequest: Value = ternary(is_true(&(!is_equal(&cost, &Value::Null))), cost.clone(), quoteAmount.clone());
makerAmount = self.cost_to_prediction_precision(outcome.clone(), costRequest.clone());
}
} else {
makerAmount = self.cost_to_prediction_precision(outcome.clone(), amount.clone());
}
} else if is_true(&isMarket) {
makerAmount = self.amount_to_prediction_precision(outcome.clone(), amount.clone());
} else {
let mut calculatedCost: Value = crate::precise::Precise::stringMul(&amountString, &priceString);
if is_equal(&side, &Value::Str("buy".to_string())) {
makerAmount = self.cost_to_prediction_precision(outcome.clone(), calculatedCost.clone());
takerAmount = self.amount_to_prediction_precision(outcome.clone(), amount.clone());
} else {
makerAmount = self.amount_to_prediction_precision(outcome.clone(), amount.clone());
takerAmount = self.cost_to_prediction_precision(outcome.clone(), calculatedCost.clone());
}
}
// amounts must be integers (uint256): parseNumber yields a float that the Python EIP-712 encoder rejects
add_element_to_object(&mut signRequest, &Value::Str("makerAmount".to_string()), self.parse_to_int(self.apply_scale(makerAmount.clone(), &[Value::Bool(true)])));
add_element_to_object(&mut signRequest, &Value::Str("takerAmount".to_string()), ternary(is_true(&isMarket), Value::Int(1), self.parse_to_int(self.apply_scale(takerAmount.clone(), &[Value::Bool(true)]))));
let mut signature: Value = self.sign_order_request(signRequest.clone(), marketSymbol.clone());
add_element_to_object(&mut signRequest, &Value::Str("signature".to_string()), signature.clone());
// price is an unsigned hint required by the API for GTC/FAK orders (not part of the EIP-712 struct)
if !is_true(&isMarket) && is_true(&(!is_equal(&price, &Value::Null))) {
add_element_to_object(&mut signRequest, &Value::Str("price".to_string()), self.parse_number(priceString.clone(), &[]));
}
let mut slug: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("slug".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ownerId".to_string(), self.safe_integer_k(account.clone(), "id", &[]));
m.insert("order".to_string(), signRequest.clone());
m.insert("marketSlug".to_string(), slug.clone());
m.insert("orderType".to_string(), timeInForce.clone());
m
});
if is_true(&postOnly) {
add_element_to_object(&mut request, &Value::Str("postOnly".to_string()), postOnly.clone());
}
let __ws_arg_24 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_private_post_orders(&[__ws_arg_24]).await;
let mut parsedOrder: Value = self.parse_prediction_order(response.clone(), &[outcomeObj.clone()]);
// the create-order response omits a status field; a freshly accepted order is open
if is_equal(&get_value(&parsedOrder, &Value::Str("status".to_string())), &Value::Null) {
add_element_to_object(&mut parsedOrder, &Value::Str("status".to_string()), Value::Str("open".to_string()));
}
return parsedOrder;
Value::Null
}
pub fn sign_order_request(&self, mut signRequest: Value, mut marketSymbol: Value) -> Value {
self.check_required_credentials(&[]);
if is_equal(&self.privateKey, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrder() requires a privateKey (the embedded/trading wallet key) to sign orders".to_string()))));
}
let mut market: Value = self.market(marketSymbol.clone());
let mut info: Value = self.safe_dict_k(market.clone(), "info", &[]);
let mut venue: Value = self.safe_dict_k(info.clone(), "venue", &[]);
let mut exchange: Value = self.safe_string_k(venue.clone(), "exchange", &[]);
let mut domain: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("chainId".to_string(), Value::Int(8453));
m.insert("name".to_string(), Value::Str("Limitless CTF Exchange".to_string()));
m.insert("verifyingContract".to_string(), exchange.clone());
m.insert("version".to_string(), Value::Str("1".to_string()));
m
});
let mut messageTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Order".to_string(), Value::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("salt".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("maker".to_string()));
m.insert("type".to_string(), Value::Str("address".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("signer".to_string()));
m.insert("type".to_string(), Value::Str("address".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("taker".to_string()));
m.insert("type".to_string(), Value::Str("address".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("tokenId".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("makerAmount".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("takerAmount".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("expiration".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("feeRateBps".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("side".to_string()));
m.insert("type".to_string(), Value::Str("uint8".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("signatureType".to_string()));
m.insert("type".to_string(), Value::Str("uint8".to_string()));
m
})]));
m
});
let mut msg: Value = self.eth_encode_structured_data(domain.clone(), messageTypes.clone(), signRequest.clone());
return self.sign_message(msg.clone(), self.privateKey.clone());
Value::Null
}
pub fn hash_message(&self, mut message: Value) -> Value {
return add(&Value::Str("0x".to_string()), &self.hash(message.clone(), Value::Str("keccak".to_string()), &[Value::Str("hex".to_string())]));
Value::Null
}
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Value {
let mut signature: Value = ecdsa(slice(&hash, &negate(&Value::Int(64)), &Value::Null), slice(&privateKey, &negate(&Value::Int(64)), &Value::Null), Value::Str("secp256k1".to_string()), Value::Null);
let mut r: Value = get_value(&signature, &Value::Str("r".to_string()));
let mut s: Value = get_value(&signature, &Value::Str("s".to_string()));
let mut v: Value = self.int_to_base16(self.sum(&[Value::Int(27), get_value(&signature, &Value::Str("v".to_string()))]), &[]);
let mut rPadded: Value = pad_start(&r, &Value::Int(64), &Value::Str("0".to_string()));
let mut sPadded: Value = pad_start(&s, &Value::Int(64), &Value::Str("0".to_string()));
let mut result: Value = add(&add(&add(&Value::Str("0x".to_string()), &rPadded), &sPadded), &v);
return to_lower(&result);
Value::Null
}
pub fn sign_message(&self, mut message: Value, mut privateKey: Value) -> Value {
return self.sign_hash(self.hash_message(message.clone()), slice(&privateKey, &negate(&Value::Int(64)), &Value::Null));
Value::Null
}
pub fn sign_evm_transaction(&self, mut tx: Value, mut privateKey: Value) -> Value {
// builds and signs an EIP-1559 (type 0x02) transaction, returning the signed raw tx hex
let mut accessList: Value = self.rlp_encode_list(Value::List(vec![]));
let mut fields: Value = Value::List(vec![self.rlp_encode_bytes(self.int_to_rlp_hex(self.safe_integer_k(tx.clone(), "chainId", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "nonce", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "maxPriorityFeePerGas", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "maxFeePerGas", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "gasLimit", &[]))), self.rlp_encode_bytes(self.remove0x_prefix(self.safe_string_k(tx.clone(), "to", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "value", &[Value::Str("0x0".to_string())]))), self.rlp_encode_bytes(self.remove0x_prefix(self.safe_string_k(tx.clone(), "data", &[Value::Str("0x".to_string())]))), accessList.clone()]);
let mut payload: Value = add(&Value::Str("02".to_string()), &self.rlp_encode_list(fields.clone()));
let mut hashHex: Value = self.hash(self.base16_to_binary(payload.clone(), &[]), Value::Str("keccak".to_string()), &[Value::Str("hex".to_string())]);
let mut signature: Value = ecdsa(hashHex.clone(), self.remove0x_prefix(privateKey.clone()), Value::Str("secp256k1".to_string()), Value::Null);
let mut rHex: Value = self.safe_string_k(signature.clone(), "r", &[]);
let mut sHex: Value = self.safe_string_k(signature.clone(), "s", &[]);
rHex = self.pad_hex_to_even(rHex.clone());
sHex = self.pad_hex_to_even(sHex.clone());
let mut yParity: Value = self.safe_integer_k(signature.clone(), "v", &[]);
let mut signedFields: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1273: bool = true;
while { if !__for_first_1273 { i = add(&i, &Value::Int(1)); } __for_first_1273 = false; is_less_than(&i, &get_array_length(&fields)) } {
append_to_array(&mut signedFields, get_value(&fields, &i));
}
}
append_to_array(&mut signedFields, self.rlp_encode_bytes(self.int_to_rlp_hex(yParity.clone())));
append_to_array(&mut signedFields, self.rlp_encode_bytes(rHex.clone()));
append_to_array(&mut signedFields, self.rlp_encode_bytes(sHex.clone()));
return add(&Value::Str("0x02".to_string()), &self.rlp_encode_list(signedFields.clone()));
Value::Null
}
/*
* @method
* @name limitless#approve
* @description sets the on-chain ERC20 collateral (USDC) allowance for the limitless exchange contract on Base, which is required before an EOA maker can place orders ("Insufficient collateral allowance" otherwise). Sends a real on-chain transaction signed with the privateKey and waits for the receipt
* @param {object} [params] extra parameters
* @param {string} [params.token] the collateral token address (default USDC on Base)
* @param {string} [params.spender] the exchange contract to approve (default the limitless CTF exchange); read from a market's venue when omitted
* @param {string} [params.owner] the token holder address (default this.walletAddress or the address derived from the privateKey)
* @param {float} [params.amount] the allowance in USDC (default: unlimited / maxUint256)
* @param {string} [params.rpcUrl] the Base RPC url to broadcast through
* @param {string} [params.gasLimit] gas limit hex for the approve tx (default '0x186a0')
* @returns {object} the transaction receipt
*/
pub async fn approve(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if is_equal(&self.privateKey, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" approve() requires a privateKey to sign the on-chain transaction".to_string()))));
}
let mut rpcUrl: Value = self.safe_string_k(params.clone(), "rpcUrl", &[self.safe_string(self.options.clone(), Value::Str("rpcUrl".to_string()), &[])]);
let mut chainId: Value = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(8453)]);
let mut token: Value = self.safe_string_k(params.clone(), "token", &[self.safe_string(self.options.clone(), Value::Str("collateralAddress".to_string()), &[])]);
let mut spender: Value = self.safe_string_k(params.clone(), "spender", &[self.safe_string(self.options.clone(), Value::Str("exchangeAddress".to_string()), &[])]);
let mut owner: Value = self.safe_string_k(params.clone(), "owner", &[self.walletAddress.clone()]);
if is_equal(&owner, &Value::Null) {
owner = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
}
let mut gasLimit: Value = self.safe_string_k(params.clone(), "gasLimit", &[Value::Str("0x186a0".to_string())]);
let mut maxUint: Value = Value::Str("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".to_string());
let mut amountHex: Value = maxUint.clone();
let mut amount: Value = self.safe_string_k(params.clone(), "amount", &[]);
if !is_equal(&amount, &Value::Null) {
let mut decimals: Value = self.safe_integer_k(self.options.clone(), "usdcDecimals", &[Value::Int(6)]);
// scale the human USDC amount to base units (amount / 10^-decimals = amount * 10^decimals)
let mut scaled: Value = crate::precise::Precise::stringDiv(&amount, &self.parse_precision(&[self.number_to_string(decimals.clone())]));
let mut amountInt: Value = self.parse_to_int(scaled.clone());
let mut amountBase16: Value = self.int_to_base16(amountInt.clone(), &[]);
amountHex = pad_start(&amountBase16, &Value::Int(64), &Value::Str("0".to_string()));
}
// approve(spender, amount) -> selector 0x095ea7b3
let mut approveData: Value = add(&add(&Value::Str("0x095ea7b3".to_string()), &self.pad_hex_address(spender.clone())), &amountHex);
let mut txHash: Value = self.send_evm_transaction(rpcUrl.clone(), chainId.clone(), owner.clone(), token.clone(), Value::Str("0x0".to_string()), approveData.clone(), gasLimit.clone()).await;
return self.wait_for_transaction_receipt(rpcUrl.clone(), txHash.clone(), &[]).await;
Value::Null
}
/*
* @method
* @name limitless#cancelOrder
* @description cancels a single open order by id
* @see https://docs.limitless.exchange/api-reference/orders/cancel-order
* @param {string} id order id
* @param {string} [outcome] outcome, e.g. "TRUMP_OUT:YES"
* @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
}));
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("order_id".to_string(), id.clone());
m
});
let __ws_arg_25 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_private_delete_orders_order_id(&[__ws_arg_25]).await;
// the delete response carries no order body, so backfill the id and the resulting status
let mut order: Value = self.parse_prediction_order(response.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 limitless#redeem
* @description redeem a resolved winning position back to collateral (gasless — the operator settles on-chain)
* @see https://docs.limitless.exchange/api-reference/portfolio/redeem
* @param {string} [outcome] a unified outcome on the resolved market to redeem (used to resolve the market conditionId)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.conditionId] the CTF condition id (bytes32 hex) to redeem directly, instead of resolving it from an outcome
* @returns {object} the raw redemption response
*/
pub async fn redeem(&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
}));
let mut conditionId: Value = self.safe_string2(params.clone(), Value::Str("conditionId".to_string()), Value::Str("condition_id".to_string()), &[]);
if is_equal(&conditionId, &Value::Null) {
if is_equal(&outcome, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" redeem() requires an outcome or a params.conditionId".to_string()))));
}
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
conditionId = self.safe_string(self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("conditionId".to_string()), &[]);
}
if is_equal(&conditionId, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" redeem() could not resolve the market conditionId - pass params.conditionId (a bytes32 hex string)".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("conditionId".to_string(), conditionId.clone());
m
});
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("conditionId".to_string()), Value::Str("condition_id".to_string())]), &[]);
let __ws_arg_26 = self.extend(request.clone(), &[rest.clone()]);
let mut response: Value = self.limitless_private_post_portfolio_redeem(&[__ws_arg_26]).await;
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("id".to_string(), conditionId.clone());
m.insert("conditionId".to_string(), conditionId.clone());
m
});
Value::Null
}
/*
* @method
* @name limitless#cancelOrders
* @description cancel multiple orders at the same time
* @see https://docs.limitless.exchange/api-reference/trading/cancel-batch
* @param {string[]} ids order ids
* @param {string} [outcome] unified market outcome, default is undefined
* @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_orders(&mut self, mut ids: 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
}));
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("orderIds".to_string(), ids.clone());
m
});
let __ws_arg_27 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_private_post_orders_cancel_batch(&[__ws_arg_27]).await;
let mut canceled: Value = self.safe_list_k(response.clone(), "canceled", &[Value::List(vec![])]);
let mut failed: Value = self.safe_list_k(response.clone(), "failed", &[Value::List(vec![])]);
let mut failedLethgn: Value = get_array_length(&failed);
if is_greater_than(&failedLethgn, &Value::Int(0)) {
let mut message: Value = self.json(response.clone());
let mut feedback: Value = add(&add(&self.id, &Value::Str(" cancelOrders failed: ".to_string())), &message);
panic!("{}", crate::exchange_errors::order_not_found(feedback));
}
return self.parse_prediction_orders(canceled.clone(), &[]);
Value::Null
}
/*
* @method
* @name limitless#cancelAllOrders
* @description cancels all open orders for one market slug
* @see https://docs.limitless.exchange/api-reference/orders/cancel-all-orders
* @param {string} [outcome] outcome, e.g. "TRUMP_OUT:YES"
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.slug] the market slug to cancel all orders for
* @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) {
let mut warn: Value = Value::Bool(true);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("cancelAllOrders".to_string()), Value::Str("warnOnCancelAllOrdersWithOutcome".to_string()), &[warn.clone()]); warn = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&warn) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" cancelAllOrders cancels all orders for entire slug (both YES and NO outcomes). Please provide params.slug to specify the slug, or set the warnOnCancelAllOrdersWithOutcome option to false to suppress this warning message.".to_string()))));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut slug: Value = self.safe_string_k(params.clone(), "slug", &[]);
if !is_equal(&outcome, &Value::Null) {
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
add_element_to_object(&mut request, &Value::Str("slug".to_string()), self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("slug".to_string()), &[]));
} else if is_equal(&slug, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelAllOrders requires either an outcome argument or a slug parameter".to_string()))));
}
let __ws_arg_28 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_private_delete_orders_all_slug(&[__ws_arg_28]).await;
return Value::List(vec![self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
}), &[])]);
Value::Null
}
/*
* @method
* @name limitless#fetchMyTrades
* @description fetch all trades made by the user
* @see https://docs.limitless.exchange/api-reference/trades/get-trades
* @param {string} [outcome] outcome, e.g. "TRUMP_OUT:YES"
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @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
}));
// resolve the handle for the final filter — the caller may have passed an outcomeId
let mut outcomeSymbol: Value = outcome.clone();
if !is_equal(&outcome, &Value::Null) {
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
outcomeSymbol = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
}
let mut paginate: Value = Value::Bool(false);
let mut maxLimit: Value = Value::Int(100);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchMyTrades".to_string()), Value::Str("paginate".to_string()), &[paginate.clone()]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
params = self.omit(params.clone(), Value::Str("paginate".to_string()), &[]);
return self.fetch_paginated_call_cursor(Value::Str("fetchMyTrades".to_string()), &[outcome.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("nextCursor".to_string()), Value::Str("cursor".to_string()), Value::Null, maxLimit.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()), crate::runtime::Math::min(&limit, &maxLimit));
}
let __ws_arg_29 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.limitless_private_get_portfolio_history(&[__ws_arg_29]).await;
//
// {
// "data": [
// {
// "action": "loss",
// "blockTimestamp": 1778144400,
// "collateralAmount": "2",
// "collateralSymbol": "USDC",
// "collateralToken": "7",
// "conditionId": "0x0c61db7449dd8f8c81cd856f53d4186cf30888e27eb025d10c7908fa94ba736e",
// "market": {
// "closed": true,
// "collateral": {
// "symbol": "USDC",
// "id": "7",
// "decimals": 6},
// "group": null,
// "condition_id": "0x0c61db7449dd8f8c81cd856f53d4186cf30888e27eb025d10c7908fa94ba736e",
// "conditionId": "0x0c61db7449dd8f8c81cd856f53d4186cf30888e27eb025d10c7908fa94ba736e",
// "funding": "0",
// "id": "117515",
// "slug": "doge-up-or-down-1-hour-1778140801775",
// "title": "DOGE Up or Down - 1 hour",
// "expirationDate": "2026-05-07T09:00:00.000Z"
// },
// "outcomeIndex": 1,
// "pnl": "-2000000",
// "title": "DOGE Up or Down - 1 hour"
// },
// {
// "blockTimestamp": 1778144137,
// "collateralAmount": "2",
// "market": {
// "closed": true,
// "collateral": {
// "symbol": "USDC",
// "id": "7",
// "decimals": 6
// },
// "group": null,
// "condition_id": "0x0c61db7449dd8f8c81cd856f53d4186cf30888e27eb025d10c7908fa94ba736e",
// "conditionId": "0x0c61db7449dd8f8c81cd856f53d4186cf30888e27eb025d10c7908fa94ba736e",
// "funding": "0",
// "id": "117515",
// "slug": "doge-up-or-down-1-hour-1778140801775",
// "title": "DOGE Up or Down - 1 hour",
// "expirationDate": "2026-05-07T09:00:00.000Z"
// },
// "outcomeTokenAmount": "10",
// "outcomeTokenAmounts": [
// "10",
// "0"
// ],
// "outcomeIndex": 0,
// "outcomeTokenPrice": "0.2",
// "strategy": "Limit Buy",
// "transactionHash": "0x1e1167f09bb65ad3037610ae4f2521b696f7109f535e148ea388d42fdb6e2a10"
// }
// ],
// "nextCursor": null
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
// response contains both trade, settlement, split and merge history
// we filter out the settlements here and only return the trades
let mut trades: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1274: bool = true;
while { if !__for_first_1274 { i = add(&i, &Value::Int(1)); } __for_first_1274 = false; is_less_than(&i, &get_array_length(&data)) } {
let mut item: Value = self.safe_dict(data.clone(), i.clone(), &[]);
let mut strategy: Value = self.safe_string_lower(item.clone(), Value::Str("strategy".to_string()), &[]);
if !is_equal(&strategy, &Value::Null) {
let mut buyIndex: Value = get_index_of(&strategy, &Value::Str("buy".to_string()));
let mut sellIndex: Value = get_index_of(&strategy, &Value::Str("sell".to_string()));
if is_true(&(is_greater_than_or_equal(&buyIndex, &Value::Int(0)))) || is_true(&(is_greater_than_or_equal(&sellIndex, &Value::Int(0)))) {
append_to_array(&mut trades, item.clone());
}
}
}
}
let mut parsedTrades: Value = self.parse_prediction_trades(trades.clone(), &[Value::Null]);
return self.filter_by_outcome_since_limit(parsedTrades.clone(), &[outcomeSymbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name limitless#parsePredictionTrade
* @description parses a raw trade from either the public market events feed or the private portfolio history 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 matchedSize: Value = self.safe_string_k(trade.clone(), "matchedSize", &[]);
if !is_equal(&matchedSize, &Value::Null) {
// public market events feed trade, see fetchTrades for the response sample
let mut ts: Value = self.parse8601(self.safe_string_k(trade.clone(), "createdAt", &[]));
let mut sideRaw: Value = self.safe_string_k(trade.clone(), "side", &[]);
let mut feedSide: Value = Value::Null;
if is_equal(&sideRaw, &Value::Str("0".to_string())) {
feedSide = Value::Str("buy".to_string());
} else if is_equal(&sideRaw, &Value::Str("1".to_string())) {
feedSide = Value::Str("sell".to_string());
}
let mut amountStr: Value = crate::precise::Precise::stringDiv(&matchedSize, &Value::Str("1000000".to_string()));
let mut priceStr: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut costStr: Value = Value::Null;
if !is_equal(&priceStr, &Value::Null) {
costStr = crate::precise::Precise::stringMul(&priceStr, &amountStr);
}
let mut feedOutcome: Value = self.safe_outcome_symbol(Value::Null, &[market.clone()]);
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "txHash", &[]));
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(), feedOutcome.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), feedSide.clone());
m.insert("takerOrMaker".to_string(), Value::Str("taker".to_string()));
m.insert("price".to_string(), self.parse_number(priceStr.clone(), &[]));
m.insert("amount".to_string(), self.parse_number(amountStr.clone(), &[]));
m.insert("cost".to_string(), self.parse_number(costStr.clone(), &[]));
m.insert("fee".to_string(), Value::Null);
m
}), &[]);
}
//
// {
// "blockTimestamp": 1778144137,
// "collateralAmount": "2",
// "market": {
// "closed": true,
// "collateral": {
// "symbol": "USDC",
// "id": "7",
// "decimals": 6
// },
// "group": null,
// "condition_id": "0x0c61db7449dd8f8c81cd856f53d4186cf30888e27eb025d10c7908fa94ba736e",
// "conditionId": "0x0c61db7449dd8f8c81cd856f53d4186cf30888e27eb025d10c7908fa94ba736e",
// "funding": "0",
// "id": "117515",
// "slug": "doge-up-or-down-1-hour-1778140801775",
// "title": "DOGE Up or Down - 1 hour",
// "expirationDate": "2026-05-07T09:00:00.000Z"
// },
// "outcomeTokenAmount": "10",
// "outcomeTokenAmounts": [
// "10",
// "0"
// ],
// "outcomeIndex": 0,
// "outcomeTokenPrice": "0.2",
// "strategy": "Limit Buy",
// "transactionHash": "0x1e1167f09bb65ad3037610ae4f2521b696f7109f535e148ea388d42fdb6e2a10"
// }
//
let mut id: Value = self.safe_string_k(trade.clone(), "transactionHash", &[]);
let mut timestamp: Value = self.safe_integer_product(trade.clone(), Value::Str("blockTimestamp".to_string()), Value::Int(1000), &[]);
let mut price: Value = self.safe_string_k(trade.clone(), "outcomeTokenPrice", &[]);
let mut amount: Value = self.safe_string_k(trade.clone(), "outcomeTokenAmount", &[]);
let mut cost: Value = self.safe_string_k(trade.clone(), "collateralAmount", &[]);
let mut rawSide: Value = self.safe_string_lower(trade.clone(), Value::Str("strategy".to_string()), &[]);
if is_equal(&rawSide, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" parsePredictionTrade() missing rawSide".to_string()))));
}
let mut sellIndex: Value = get_index_of(&rawSide, &Value::Str("sell".to_string()));
let mut side: Value = ternary(is_true(&(is_greater_than_or_equal(&sellIndex, &Value::Int(0)))), Value::Str("sell".to_string()), Value::Str("buy".to_string()));
let mut type_var: Value = Value::Null;
let mut takerOrMaker: Value = Value::Null;
if is_equal(&rawSide, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" parsePredictionTrade() missing rawSide".to_string()))));
}
if is_greater_than_or_equal(&get_index_of(&rawSide, &Value::Str("limit".to_string())), &Value::Int(0)) {
type_var = Value::Str("limit".to_string());
takerOrMaker = Value::Str("maker".to_string());
if is_equal(&rawSide, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" method() missing rawSide".to_string()))));
}
} else if is_greater_than_or_equal(&get_index_of(&rawSide, &Value::Str("market".to_string())), &Value::Int(0)) {
type_var = Value::Str("market".to_string());
takerOrMaker = Value::Str("taker".to_string());
}
let mut rawMarket: Value = self.safe_dict_k(trade.clone(), "market", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut slug: Value = self.safe_string_k(rawMarket.clone(), "slug", &[]);
let mut outcomeIndex: Value = self.safe_integer_k(trade.clone(), "outcomeIndex", &[]);
let mut label: Value = ternary(is_true(&(is_equal(&outcomeIndex, &Value::Int(0)))), Value::Str("yes".to_string()), Value::Str("no".to_string()));
let mut outcome: Value = self.get_outcome_by_slug_and_label(slug.clone(), label.clone(), &[market.clone()]);
let mut tradeOutcome: Value = self.safe_string_k(outcome.clone(), "outcome", &[]);
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(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("outcome".to_string(), tradeOutcome.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(trade.clone(), "asset", &[]));
m.insert("label".to_string(), self.safe_string_k(outcome.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcome.clone(), "market", &[]));
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), type_var.clone());
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(), Value::Null);
m
}), &[]);
Value::Null
}
pub fn get_outcome_by_slug_and_label(&self, mut slug: Value, mut label: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut mkt: Value = self.safe_market(&[slug.clone(), market.clone()]);
let mut outcomes: Value = self.safe_list_k(mkt.clone(), "outcomes", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1275: bool = true;
while { if !__for_first_1275 { i = add(&i, &Value::Int(1)); } __for_first_1275 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
let mut outcome: Value = self.safe_dict(outcomes.clone(), i.clone(), &[]);
let mut outcomeLabel: Value = self.safe_string_k(outcome.clone(), "label", &[]);
if is_equal(&outcomeLabel, &label) {
return outcome;
}
}
}
return Value::Null;
Value::Null
}
/*
* @method
* @name limitless#fetchPositions
* @description fetches open positions for the authenticated limitless user from the portfolio endpoint
* @see https://docs.limitless.exchange/api-reference/portfolio/get-positions
* @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 symbolsLength: Value = Value::Int(0);
if !is_equal(&outcomes, &Value::Null) {
symbolsLength = get_array_length(&outcomes);
}
if is_greater_than(&symbolsLength, &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 (raw slugs/labels stay available in info when the cache is cold)
let mut response: Value = self.limitless_private_get_portfolio_positions(&[params.clone()]).await;
//
// {
// "rewards": {
// "todaysRewards": "0",
// "totalUnpaidRewards": "0",
// "totalUserRewardsLastEpoch": "0",
// "rewardsChartData": [],
// "rewardsByEpoch": []
// },
// "points": "0.00000000",
// "accumulativePoints": "0.00000000",
// "amm": [],
// "group": [],
// "clob": [
// {
// "market": {
// "slug": "btc-above-dollar7982448-on-may-11-1000-utc-1777888806248",
// "status": "FUNDED",
// "title": "BTC Up or Down - 1 week",
// "conditionId": "0xdcd8264cd09a6c50fca35eca24cda13e70f705e8b9ca7df7edb1c53d5e14ef91",
// "id": 113280,
// "address": null,
// "closed": false,
// "expirationDate": "2026-05-11T10:00:00.000Z",
// "deadline": "2026-05-11T10:00:00.000Z",
// "negRiskRequestId": null,
// "winningOutcomeIndex": null,
// "yesPositionId": "93872239373494820196551522390839917813776244436120184186867916673676200558660",
// "noPositionId": "63415751165356883207530164011662686422066216695676262832702521399916548381548",
// "collateralToken": {
// "id": 7,
// "decimals": 6,
// "symbol": "USDC",
// "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
// },
// "venue": {
// "exchange": "0x05c748E2f4DcDe0ec9Fa8DDc40DE6b867f923fa5",
// "adapter": null,
// "operator": null
// },
// "group": {}
// },
// "latestTrade": {
// "outcomeTokenPrice": 0.991,
// "latestNoPrice": 0.009,
// "latestYesPrice": 0.991
// },
// "orders": {
// "liveOrders": [],
// "totalCollateralLocked": "0"
// },
// "positions": {
// "no": {
// "cost": "0",
// "fillPrice": "0",
// "marketValue": "0",
// "realisedPnl": "0",
// "unrealizedPnl": "0"
// },
// "yes": {
// "cost": "995720",
// "fillPrice": "991000",
// "marketValue": "999919",
// "realisedPnl": "0",
// "unrealizedPnl": "0"
// }
// },
// "tokensBalance": {
// "no": "0",
// "yes": "1004763"
// },
// "rewards": {
// "isEarning": false,
// "epochs": []
// },
// "makerAddress": "0xAb2B9833FC8B8f55F4De7C4A0FAb8577EF0F7b36"
// }
// ]
// }
//
let mut clob: Value = self.safe_list_k(response.clone(), "clob", &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
let mut labels: Value = Value::List(vec![Value::Str("yes".to_string()), Value::Str("no".to_string())]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1277: bool = true;
while { if !__for_first_1277 { i = add(&i, &Value::Int(1)); } __for_first_1277 = false; is_less_than(&i, &get_array_length(&clob)) } {
let mut entry: Value = self.safe_dict(clob.clone(), i.clone(), &[]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1276: bool = true;
while { if !__for_first_1276 { j = add(&j, &Value::Int(1)); } __for_first_1276 = false; is_less_than(&j, &get_array_length(&labels)) } {
let mut label: Value = self.safe_string(labels.clone(), j.clone(), &[]);
let mut position: Value = self.get_position_from_clob_entry(label.clone(), &[entry.clone()]);
if !is_equal(&position, &Value::Null) {
append_to_array(&mut result, position.clone());
}
}
}
}
}
return result;
Value::Null
}
pub fn get_position_from_clob_entry(&self, mut label: Value, optional_args: &[Value]) -> Value {
let mut entry = get_arg(optional_args, 0, Value::Null);
if is_equal(&entry, &Value::Null) {
return Value::Null;
}
let mut tokensBalance: Value = self.safe_dict_k(entry.clone(), "tokensBalance", &[]);
let mut contracts: Value = self.omit_zero(self.safe_string(tokensBalance.clone(), label.clone(), &[]));
if is_equal(&contracts, &Value::Null) {
return Value::Null;
}
let mut positions: Value = self.safe_dict_k(entry.clone(), "positions", &[]);
let mut position: Value = self.safe_dict(positions.clone(), label.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawMarket: Value = self.safe_dict_k(entry.clone(), "market", &[]);
let mut slug: Value = self.safe_string_k(rawMarket.clone(), "slug", &[]);
let mut outcomeObj: Value = self.get_outcome_by_slug_and_label(slug.clone(), label.clone(), &[]);
let mut parsed: Value = self.parse_prediction_position(position.clone(), &[outcomeObj.clone()]);
add_element_to_object(&mut parsed, &Value::Str("contracts".to_string()), self.parse_number(self.apply_scale(contracts.clone(), &[]), &[]));
let mut latestTrade: Value = self.safe_dict_k(entry.clone(), "latestTrade", &[]);
let mut key: Value = Value::Str("latestYesPrice".to_string());
if is_equal(&label, &Value::Str("no".to_string())) {
key = Value::Str("latestNoPrice".to_string());
}
add_element_to_object(&mut parsed, &Value::Str("markPrice".to_string()), self.safe_number(latestTrade.clone(), key.clone(), &[]));
add_element_to_object(&mut parsed, &Value::Str("info".to_string()), entry.clone());
return self.safe_prediction_position(parsed.clone());
Value::Null
}
/*
* @ignore
* @method
* @name limitless#parsePredictionPosition
* @description parses a raw limitless 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);
//
// {
// "cost": "995720",
// "fillPrice": "991000",
// "marketValue": "999919",
// "realisedPnl": "0",
// "unrealizedPnl": "0"
// }
//
let mut outcomeSymbol: Value = self.safe_string_k(market.clone(), "outcome", &[]);
let mut notional: Value = self.apply_scale(self.safe_string_k(position.clone(), "marketValue", &[]), &[]);
let mut unrealizedPnl: Value = self.apply_scale(self.safe_string_k(position.clone(), "unrealizedPnl", &[]), &[]);
let mut realizedPnl: Value = self.apply_scale(self.safe_string_k(position.clone(), "realisedPnl", &[]), &[]);
let mut collateral: Value = self.apply_scale(self.safe_string_k(position.clone(), "cost", &[]), &[]);
let mut entryPrice: Value = self.apply_scale(self.safe_string_k(position.clone(), "fillPrice", &[]), &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Null);
m.insert("outcome".to_string(), outcomeSymbol.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("contracts".to_string(), Value::Null);
m.insert("contractSize".to_string(), Value::Int(1));
m.insert("side".to_string(), Value::Str("long".to_string()));
m.insert("notional".to_string(), self.parse_number(notional.clone(), &[]));
m.insert("leverage".to_string(), Value::Int(1));
m.insert("unrealizedPnl".to_string(), self.parse_number(unrealizedPnl.clone(), &[]));
m.insert("realizedPnl".to_string(), self.parse_number(realizedPnl.clone(), &[]));
m.insert("collateral".to_string(), self.parse_number(collateral.clone(), &[]));
m.insert("entryPrice".to_string(), self.parse_number(entryPrice.clone(), &[]));
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 limitless#fetchEvents
* @description fetches prediction-market events matching the given scope (query/queries/tags/eventId/slug — required) and caches their markets and outcomes on the instance
* @see https://docs.limitless.exchange/api-reference/markets/search
* @param {object} [params] extra exchange-specific parameters
* @param {string} [params.query] a single search term; an eventId/slug does a direct lookup and tags resolve to limitless categories, paging only those categories' listings
* @param {string[]} [params.queries] multiple search terms (alternative to query)
* @param {string[]} [params.tags] category names to scope by (matched against GET /categories, e.g. ['crypto'])
* @param {string} [params.eventId] direct lookup by market address or slug
* @param {int} [params.limit] maximum number of markets per query, defaults to 50
* @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
}));
self.require_event_query(&[params.clone()]);
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);
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()), Value::Str("sort".to_string()), Value::Str("searchIn".to_string()), Value::Str("eventId".to_string()), Value::Str("slug".to_string()), Value::Str("status".to_string())]), &[]);
let mut eventId: Value = self.safe_string2(params.clone(), Value::Str("eventId".to_string()), Value::Str("slug".to_string()), &[]);
// always fetch fresh from the API (never serve the possibly-cold cache): a query searches, an
// eventId/slug does a direct lookup, and any other scope (tags) pages the active-markets listing
let mut rawMarkets: Value = Value::List(vec![]);
if is_greater_than(&queriesLength, &Value::Int(0)) {
let mut requestedLimit: Value = self.safe_integer_k(params.clone(), "limit", &[Value::Int(50)]);
// the search endpoint rejects limit > 50 - cap the per-query request
let mut limit: Value = crate::runtime::Math::min(&requestedLimit, &Value::Int(50));
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1279: bool = true;
while { if !__for_first_1279 { i = add(&i, &Value::Int(1)); } __for_first_1279 = false; is_less_than(&i, &get_array_length(&queries)) } {
if is_equal(&queries, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchEvents() missing queries".to_string()))));
}
let mut q: Value = get_value(&queries, &i);
let mut q: Value = get_value(&queries, &i);
let __ws_arg_30 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("query".to_string(), q.clone());
m.insert("limit".to_string(), limit.clone());
m
}), &[rest.clone()]);
let mut response: Value = self.limitless_public_get_markets_search(&[__ws_arg_30]).await;
let mut found: Value = self.safe_list_k(response.clone(), "markets", &[Value::List(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1278: bool = true;
while { if !__for_first_1278 { j = add(&j, &Value::Int(1)); } __for_first_1278 = false; is_less_than(&j, &get_array_length(&found)) } {
let mut raw: Value = get_value(&found, &j);
let mut raw: Value = get_value(&found, &j);
let mut rawSlug: Value = self.safe_string_k(raw.clone(), "slug", &[]);
if is_true(&(!is_equal(&rawSlug, &Value::Null) && !is_equal(&rawSlug, &Value::Str("".to_string())))) && !is_true(&(Value::Bool(in_op(&seen, &rawSlug)))) {
add_element_to_object(&mut seen, &rawSlug, Value::Bool(true));
append_to_array(&mut rawMarkets, raw.clone());
}
}
}
}
}
} else if !is_equal(&eventId, &Value::Null) {
let __ws_arg_31 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("addressOrSlug".to_string(), eventId.clone());
m
}), &[rest.clone()]);
let mut response: Value = self.limitless_public_get_markets_address_or_slug(&[__ws_arg_31]).await;
append_to_array(&mut rawMarkets, response.clone());
} else {
// tags scope: resolve the tags to limitless categories and page only those
// categories' listings server-side — never the whole active listing
let mut requestedTags: Value = self.safe_list_k(params.clone(), "tags", &[Value::List(vec![])]);
let mut listRaw: Value = self.fetch_raw_markets_by_tags(requestedTags.clone(), &[params.clone()]).await;
let mut listRawLength: Value = get_array_length(&listRaw);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1280: bool = true;
while { if !__for_first_1280 { i = add(&i, &Value::Int(1)); } __for_first_1280 = false; is_less_than(&i, &listRawLength) } {
append_to_array(&mut rawMarkets, get_value(&listRaw, &i));
}
}
}
if is_equal(&self.exchange.events, &Value::Null) {
self.exchange.events = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if is_equal(&self.markets, &Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut eventGroups: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
// group rows carry their tradeable children in a nested `markets` list — expand them
// into regular rows before parsing (a group row itself has no tokens)
let mut expandedMarkets: Value = self.expand_group_rows(rawMarkets.clone());
let mut rawMarketsLength: Value = get_array_length(&expandedMarkets);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1281: bool = true;
while { if !__for_first_1281 { i = add(&i, &Value::Int(1)); } __for_first_1281 = false; is_less_than(&i, &rawMarketsLength) } {
let mut raw: Value = get_value(&expandedMarkets, &i);
let mut raw: Value = get_value(&expandedMarkets, &i);
let mut groupId: Value = self.safe_string_n(raw.clone(), Value::List(vec![Value::Str("groupSlug".to_string()), Value::Str("groupId".to_string())]), &[self.safe_string_k(raw.clone(), "slug", &[])]);
let mut eventKey: Value = ternary(is_true(&(!is_equal(&groupId, &Value::Null) && !is_equal(&groupId, &Value::Str("".to_string())))), self.shorten_slug(groupId.clone()), Value::Null);
let mut m: Value = self.parse_market(raw.clone());
if is_equal(&m, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchEvents() missing m".to_string()))));
}
add_element_to_object(&mut self.markets, &get_value(&m, &Value::Str("market".to_string())), 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(&eventGroups, &eventKey)))) {
add_element_to_object(&mut eventGroups, &eventKey, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("groupId".to_string(), groupId.clone());
m.insert("title".to_string(), self.safe_string2(raw.clone(), Value::Str("groupTitle".to_string()), Value::Str("title".to_string()), &[groupId.clone()]));
m.insert("raw".to_string(), raw.clone());
m.insert("markets".to_string(), Value::List(vec![]));
m
}));
}
let mut eventGroup: Value = get_value(&eventGroups, &eventKey);
let mut eventGroup: Value = get_value(&eventGroups, &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 eventGroup['markets'] loses the element in go
let mut groupMarkets: Value = get_value(&eventGroup, &Value::Str("markets".to_string()));
append_to_array(&mut groupMarkets, m.clone());
add_element_to_object(&mut eventGroup, &Value::Str("markets".to_string()), groupMarkets.clone());
}
}
}
let mut result: Value = Value::List(vec![]);
let mut eventKeys: Value = object_keys(&eventGroups);
let mut eventKeysLength: Value = get_array_length(&eventKeys);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1282: bool = true;
while { if !__for_first_1282 { i = add(&i, &Value::Int(1)); } __for_first_1282 = false; is_less_than(&i, &eventKeysLength) } {
let mut g: Value = get_value(&eventGroups, &get_value(&eventKeys, &i));
let mut ev: Value = self.parse_event(g.clone());
append_to_array(&mut result, ev.clone());
}
}
// setEvents keys events by id/slug/handle; populateOutcomes rebuilds the outcome cache
self.set_events(result.clone());
self.populate_outcomes();
// the limitless search endpoint is FUZZY — it returns nearest-neighbour markets even
// for queries that match nothing — so default searchIn to 'both' to post-filter the
// results literally by title/description (an explicit params.searchIn still wins).
// tags were already applied server-side (category-scoped listing); strip them before the
// client-side pass — events built from raw markets carry venue tags, not category names,
// so the base tag filter would wrongly drop server-matched events
let mut searchParams: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("searchIn".to_string(), Value::Str("both".to_string()));
m
}), &[params.clone()]);
let mut postParams: Value = self.omit(searchParams.clone(), Value::List(vec![Value::Str("tags".to_string())]), &[]);
return self.apply_event_fetch_params(result.clone(), &[postParams.clone(), queries.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name limitless#fetchRawActiveMarkets
* @description pages the active-markets listing (or a single category's listing), bounded by limit (or options.fetchMarketsLimit)
* @param {object} [params] extra exchange-specific parameters
* @param {int} [params.limit] max number of raw markets to collect
* @param {string} [categoryId] a limitless category id — pages only that category's listing
* @returns {object[]} raw limitless market objects
*/
pub async fn fetch_raw_active_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 categoryId = get_arg(optional_args, 1, Value::Null);
let mut maxMarkets: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("fetchMarketsLimit".to_string()), &[Value::Int(1000)])]);
let mut pageSize: Value = self.safe_integer_k(self.options.clone(), "marketsPageSize", &[Value::Int(25)]);
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()), Value::Str("sort".to_string()), Value::Str("searchIn".to_string()), Value::Str("eventId".to_string()), Value::Str("slug".to_string()), Value::Str("status".to_string()), Value::Str("tags".to_string())]), &[]);
let mut allRaw: Value = Value::List(vec![]);
let mut page: Value = Value::Int(1);
let mut collected: Value = Value::Int(0);
while is_true(&Value::Bool(true)) {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("page".to_string(), page.clone());
m.insert("limit".to_string(), pageSize.clone());
m
});
let mut response: Value = Value::Null;
if !is_equal(&categoryId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("categoryId".to_string()), categoryId.clone());
let __ws_arg_32 = self.extend(request.clone(), &[rest.clone()]);
response = self.limitless_public_get_markets_active_category_id(&[__ws_arg_32]).await;
} else {
let __ws_arg_33 = self.extend(request.clone(), &[rest.clone()]);
response = self.limitless_public_get_markets_active(&[__ws_arg_33]).await;
}
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut dataLength: Value = get_array_length(&data);
if is_equal(&dataLength, &Value::Int(0)) {
break;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1283: bool = true;
while { if !__for_first_1283 { i = add(&i, &Value::Int(1)); } __for_first_1283 = false; is_less_than(&i, &dataLength) } {
if is_less_than(&collected, &maxMarkets) {
append_to_array(&mut allRaw, get_value(&data, &i));
collected = self.sum(&[collected.clone(), Value::Int(1)]);
}
}
}
page = self.sum(&[page.clone(), Value::Int(1)]);
if is_less_than(&dataLength, &pageSize) || is_greater_than_or_equal(&collected, &maxMarkets) {
break;
}
}
return allRaw;
Value::Null
}
/*
* @ignore
* @method
* @name limitless#fetchRawMarketsByTags
* @description resolves the requested tags to limitless categories via GET /categories, then pages only those categories' active listings server-side
* @param {string[]} tags tag/category names to match (case-insensitive substring match on the category name)
* @param {object} [params] extra exchange-specific parameters
* @param {int} [params.limit] max number of raw markets to collect per category
* @returns {object[]} raw limitless market objects, deduped by slug
*/
pub async fn fetch_raw_markets_by_tags(&mut self, mut tags: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut categoriesResponse: Value = self.limitless_public_get_categories(&[]).await;
let mut categories: Value = Value::List(vec![]);
if is_true(&Value::Bool(is_array(&categoriesResponse))) {
categories = categoriesResponse.clone();
}
let mut wanted: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1284: bool = true;
while { if !__for_first_1284 { i = add(&i, &Value::Int(1)); } __for_first_1284 = false; is_less_than(&i, &get_array_length(&tags)) } {
append_to_array(&mut wanted, to_lower(&get_value(&tags, &i)));
}
}
let mut categoryIds: Value = Value::List(vec![]);
let mut categoriesLength: Value = get_array_length(&categories);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1286: bool = true;
while { if !__for_first_1286 { i = add(&i, &Value::Int(1)); } __for_first_1286 = false; is_less_than(&i, &categoriesLength) } {
let mut category: Value = get_value(&categories, &i);
let mut category: Value = get_value(&categories, &i);
let mut name: Value = self.safe_string_lower(category.clone(), Value::Str("name".to_string()), &[Value::Str("".to_string())]);
let mut categoryId: Value = self.safe_string_k(category.clone(), "id", &[]);
let mut matched: bool = false;
{
let mut wi: Value = Value::Int(0);
let mut __for_first_1285: bool = true;
while { if !__for_first_1285 { wi = add(&wi, &Value::Int(1)); } __for_first_1285 = false; is_less_than(&wi, &get_array_length(&wanted)) } {
if is_equal(&name, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchRawMarketsByTags() missing name".to_string()))));
}
if is_greater_than_or_equal(&get_index_of(&name, &get_value(&wanted, &wi)), &Value::Int(0)) {
matched = true;
break;
}
}
}
if is_true(&matched) && is_true(&(!is_equal(&categoryId, &Value::Null))) {
append_to_array(&mut categoryIds, categoryId.clone());
}
}
}
let mut categoryIdsLength: Value = get_array_length(&categoryIds);
if is_equal(&categoryIdsLength, &Value::Int(0)) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchEvents() could not match the requested tags to any limitless category — GET /categories lists the valid names".to_string()))));
}
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut allRaw: Value = Value::List(vec![]);
{
let mut ci: Value = Value::Int(0);
let mut __for_first_1288: bool = true;
while { if !__for_first_1288 { ci = add(&ci, &Value::Int(1)); } __for_first_1288 = false; is_less_than(&ci, &categoryIdsLength) } {
let mut categoryMarkets: Value = self.fetch_raw_active_markets(&[params.clone(), get_value(&categoryIds, &ci)]).await;
let mut categoryMarketsLength: Value = get_array_length(&categoryMarkets);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1287: bool = true;
while { if !__for_first_1287 { mi = add(&mi, &Value::Int(1)); } __for_first_1287 = false; is_less_than(&mi, &categoryMarketsLength) } {
let mut raw: Value = get_value(&categoryMarkets, &mi);
let mut raw: Value = get_value(&categoryMarkets, &mi);
let mut slug: Value = self.safe_string_k(raw.clone(), "slug", &[]);
if is_true(&(!is_equal(&slug, &Value::Null))) && !is_true(&(Value::Bool(in_op(&seen, &slug)))) {
add_element_to_object(&mut seen, &slug, Value::Bool(true));
append_to_array(&mut allRaw, raw.clone());
}
}
}
}
}
return allRaw;
Value::Null
}
/*
* @ignore
* @method
* @name limitless#sign
* @description builds the request URL and attaches the lmts authentication headers for private endpoints
* @param {string} path the endpoint path
* @param {string|string[]} [section] 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 section = get_arg(optional_args, 0, Value::Str("limitless".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(§ion), section.clone(), get_value(§ion, &Value::Int(0)));
let mut access: Value = ternary(is_string(§ion), Value::Str("public".to_string()), get_value(§ion, &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("limitless".to_string()))]);
let mut url: Value = add(&Value::Str("/".to_string()), &self.implode_params(path.clone(), params.clone()));
let mut query: Value = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
let mut querystring: Value = self.urlencode_with_array_repeat(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));
}
if is_equal(&access, &Value::Str("private".to_string())) {
let mut bodyString: Value = Value::Str("".to_string());
if is_equal(&headers, &Value::Null) {
headers = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if is_equal(&method, &Value::Str("POST".to_string())) && is_true(&(!is_equal(&querystring, &Value::Str("".to_string())))) {
bodyString = self.json(query.clone());
body = bodyString.clone();
let mut headerDefaults: 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
}), &[headerDefaults.clone()]);
}
self.check_required_credentials(&[]);
let mut timestamp: Value = self.iso8601(self.milliseconds());
let mut newline: Value = Value::Str("\n".to_string()); // eslint-disable-line quotes
let mut payload: Value = add(&add(&add(&add(&add(&add(×tamp, &newline), &method), &newline), &url), &newline), &bodyString);
let mut signature: Value = self.hmac(self.encode(payload.clone()), self.base64_to_binary(self.secret.clone(), &[]), Value::Str("sha256".to_string()), &[Value::Str("base64".to_string())]);
headers = self.extend(headers.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("lmts-api-key".to_string(), self.apiKey.clone());
m.insert("lmts-timestamp".to_string(), timestamp.clone());
m.insert("lmts-signature".to_string(), signature.clone());
m
})]);
}
url = add(&baseUrl, &url);
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
}
/*
* @ignore
* @method
* @name limitless#handleErrors
* @description maps limitless error responses to ccxt exceptions
*/
pub fn handle_errors(&self, mut statusCode: Value, mut statusText: Value, mut url: Value, mut method: Value, mut responseHeaders: Value, mut responseBody: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if is_equal(&response, &Value::Null) {
return Value::Null;
}
if is_true(&(is_greater_than_or_equal(&statusCode, &Value::Int(200)))) && is_true(&(is_less_than(&statusCode, &Value::Int(300)))) {
return Value::Null;
}
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &responseBody);
// the API returns either a string message or an array of field-validation errors
let mut message: Value = self.safe_string_k(response.clone(), "message", &[]);
if !is_equal(&message, &Value::Null) {
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), message.clone(), feedback.clone());
}
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), responseBody.clone(), feedback.clone());
// a 400 is a client-side bad request (bad params, or a business rule like "market not
// resolved"), not a transport outage — throw BadRequest with the exchange message instead
// of letting the base map the bare 400 to a retryable network-unavailable error
if is_equal(&statusCode, &Value::Int(400)) {
panic!("{}", crate::exchange_errors::bad_request(feedback));
}
return Value::Null;
Value::Null
}
}