// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
use crate::pro::*;
use crate::prediction_exchange_generated::PredictionBase;
use crate::prediction_exchange::PredictionRuntime;
pub struct SxbetCore {
pub exchange: crate::prediction_exchange::PredictionExchange,
}
impl SxbetCore {
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 = SxbetCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for SxbetCore {
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on SxbetCore.
SxbetCore::parse_prediction_order(self, order, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on SxbetCore.
SxbetCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on SxbetCore.
SxbetCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for SxbetCore {
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_sxbet_ws_snapshot" => self.apply_sxbet_ws_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"approve" => self.approve(&args[..]).await,
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"clamp_sxbet_per_page" => self.clamp_sxbet_per_page(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"connect_sxbet_centrifugo" => self.connect_sxbet_centrifugo(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_erc20_name" => self.fetch_erc20_name(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_event" => self.fetch_event(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_events" => self.fetch_events(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_raw_markets_paged" => self.fetch_raw_markets_paged(&args[..]).await,
"fetch_settlements" => self.fetch_settlements(&args[..]).await,
"fetch_sxbet_best_odds" => self.fetch_sxbet_best_odds(args.get(0).cloned().unwrap_or_default().to_str_vec(), &args[1.min(args.len())..]).await,
"fetch_sxbet_book_snapshot" => self.fetch_sxbet_book_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_sxbet_proxy" => self.fetch_sxbet_proxy().await,
"fetch_sxbet_realtime_token" => self.fetch_sxbet_realtime_token().await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"filter_raw_markets_by_fixture" => self.filter_raw_markets_by_fixture(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"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)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_text_message" => { self.handle_text_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"hex_to_int" => self.hex_to_int(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"load_sx_obv3_metadata" => self.load_sx_obv3_metadata().await,
"matches_event_query" => self.matches_event_query(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_event" => self.parse_event(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_settlement" => self.parse_settlement(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_sxbet_cancel_response" => self.parse_sxbet_cancel_response(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_sxbet_market" => self.parse_sxbet_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_sxbet_snapshot_best_odds" => self.parse_sxbet_snapshot_best_odds(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_sxbet_tickers_by_hash" => self.parse_sxbet_tickers_by_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_sxbet_v3_book_sides" => self.parse_sxbet_v3_book_sides(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).map(|v| v.is_truthy()).unwrap_or(false)),
"parse_sxbet_v3_fill" => self.parse_sxbet_v3_fill(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_sxbet_v3_position" => self.parse_sxbet_v3_position(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_sxbet_v3_public_trade" => self.parse_sxbet_v3_public_trade(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"pong" => self.pong(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"request_id" => self.request_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"subscribe_sxbet_channel" => self.subscribe_sxbet_channel(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// 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 SxbetCore {
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 SxbetCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}
impl std::ops::DerefMut for SxbetCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.exchange) }
}
impl SxbetCore {
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("sxbet".into()));
m.insert("name".to_string(), Value::Str("SX Bet".into()));
m.insert("countries".to_string(), Value::from(vec![]));
m.insert("rateLimit".to_string(), Value::Int(120));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
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("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".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(false));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchSettlements".to_string(), Value::Bool(true));
m.insert("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("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
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/6d1d1e37-2b9c-4011-93c6-c9c25cd2c2f7".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sxbet".to_string(), Value::Str("https://api.sx.bet".into()));
m.insert("ws".to_string(), Value::Str("wss://realtime.sx.bet/connection/websocket".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sxbet".to_string(), Value::Str("https://api.toronto.sx.bet".into()));
m.insert("ws".to_string(), Value::Str("wss://realtime.toronto.sx.bet/connection/websocket".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://sx.bet".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.sx.bet".into())]));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sxbet".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("metadata/obv3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orderbook-v3/snapshot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trades-v3/public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
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/find".to_string(), Value::Int(1));
m.insert("markets/popular".to_string(), Value::Int(1));
m.insert("trades/consolidated".to_string(), Value::Int(1));
m.insert("trades/orders".to_string(), Value::Int(1));
m.insert("trades/portfolio/refunds".to_string(), Value::Int(1));
m.insert("fixture/active".to_string(), Value::Int(1));
m.insert("fixture/status".to_string(), Value::Int(1));
m.insert("sports".to_string(), Value::Int(1));
m.insert("leagues".to_string(), Value::Int(1));
m.insert("leagues/active".to_string(), Value::Int(1));
m.insert("teams".to_string(), Value::Int(1));
m.insert("live-scores".to_string(), Value::Int(1));
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("user/realtime-token-v3/api-key".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("user/proxy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("user/balance-v3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("user/transfer-to-proxy/pending".to_string(), Value::Int(1));
m.insert("user/transfer-to-proxy/status".to_string(), Value::Int(1));
m.insert("orders-v3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders-v3/{orderId}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders-v3/odds/best".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trades-v3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fills-v3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions-v3".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("orders-v3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders-v3/event".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders-v3/all".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("orders-v3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("user/deploy-proxy".to_string(), Value::Int(1));
m.insert("user/transfer-to-proxy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("heartbeat/v3".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("walletAddress".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::Int(0));
m.insert("taker".to_string(), Value::Int(0));
m
}));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("INSUFFICIENT_BALANCE".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("INVALID_MARKET".to_string(), Value::Str("BadRequest".into()));
m.insert("ORDERS_ALREADY_EXIST".to_string(), Value::Str("DuplicateOrderId".into()));
m.insert("TOO_MANY_DIFFERENT_MARKETS".to_string(), Value::Str("BadRequest".into()));
m.insert("ORDERS_MUST_HAVE_IDENTICAL_MARKET".to_string(), Value::Str("BadRequest".into()));
m.insert("BAD_BASE_TOKEN".to_string(), Value::Str("BadRequest".into()));
m.insert("INSUFFICIENT_KYC".to_string(), Value::Str("PermissionDenied".into()));
m.insert("PROXY_NOT_DEPLOYED".to_string(), Value::Str("AccountNotEnabled".into()));
m.insert("INVALID_USER".to_string(), Value::Str("AuthenticationError".into()));
m.insert("BAD_AUTH".to_string(), Value::Str("AuthenticationError".into()));
m.insert("ERC20_PERMIT_BAD_SPENDER".to_string(), Value::Str("BadRequest".into()));
m.insert("BASE_TOKENS_NOT_SAME".to_string(), Value::Str("BadRequest".into()));
m.insert("MARKETS_NOT_SAME".to_string(), Value::Str("BadRequest".into()));
m.insert("DIRECTIONS_NOT_SAME".to_string(), Value::Str("BadRequest".into()));
m.insert("INVALID_ORDERS".to_string(), Value::Str("OrderNotFillable".into()));
m.insert("INVALID_ODDS".to_string(), Value::Str("InvalidOrder".into()));
m.insert("PERCENTAGEODDS_UNDEFINED_OR_MALFORMED".to_string(), Value::Str("InvalidOrder".into()));
m.insert("TOTAL_BET_SIZE_TOO_LOW".to_string(), Value::Str("InvalidOrder".into()));
m.insert("MATCH_STATE_INVALID".to_string(), Value::Str("MarketClosed".into()));
m.insert("PROXY_ACCOUNT_INVALID".to_string(), Value::Str("BadRequest".into()));
m.insert("RATE_LIMIT_ORDER_REQUEST_MARKET_COUNT".to_string(), Value::Str("BadRequest".into()));
m.insert("BOTH_SPORTXEVENTID_MARKETHASHES_PRESENT".to_string(), Value::Str("BadRequest".into()));
m.insert("BAD_MARKET_HASHES".to_string(), Value::Str("BadRequest".into()));
m.insert("Order not found".to_string(), Value::Str("OrderNotFound".into()));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("no longer supported".to_string(), Value::Str("NotSupported".into()));
m.insert("must be".to_string(), Value::Str("BadRequest".into()));
m.insert("Insufficient available balance".to_string(), Value::Str("InsufficientFunds".into()));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketsPageSize".to_string(), Value::Int(100));
m.insert("maxMarketsPages".to_string(), Value::Int(50));
m.insert("eventScopeParams".to_string(), Value::from(vec![Value::Str("leagueId".into()), Value::Str("sportId".into())]));
m.insert("chains".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("4162".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rpcUrl".to_string(), Value::Str("https://rpc-rollup.sx.technology".into()));
m
}));
m.insert("79479957".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rpcUrl".to_string(), Value::Str("https://rpc-rollup.toronto.sx.technology".into()));
m
}));
m
}));
m.insert("approveDeadlineSeconds".to_string(), Value::Int(7200));
m.insert("defaultOrderExpirySeconds".to_string(), Value::Int(86400));
m.insert("bestOddsBatchSize".to_string(), Value::Int(100));
m.insert("cancelOrdersBatchSize".to_string(), Value::Int(100));
m.insert("tradesLimit".to_string(), Value::Int(1000));
m.insert("ordersLimit".to_string(), Value::Int(1000));
m.insert("myTradesLimit".to_string(), Value::Int(1000));
m
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("keepAlive".to_string(), Value::Int(30000));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name sxbet#fetchMarkets
* @description retrieves data on all active markets, each becomes one market with its two sides listed under the outcomes key
* @see https://docs.sx.bet/api-reference/get-markets-active
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.limit] max number of markets to collect (defaults to options.marketsPageSize * options.maxMarketsPages, 5000)
* @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 rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("limit".into())]), &[]);
let mut userLimit: Value = self.safe_integer_k(params, "limit", &[]);
let mut rawMarkets: Vec<Value> = self.fetch_raw_markets_paged(&[rest, userLimit.clone()]).await.as_array().cloned().unwrap_or_default();
let mut markets: Vec<Value> = Vec::new();
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1492: bool = true;
while { if !__for_first_1492 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1492 = false; i.as_f64().unwrap_or(f64::NAN) < rawMarketsLength } {
markets.push(self.parse_sxbet_market(rawMarkets.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)));
}
}
let mut marketsLength: f64 = ((markets.len() as i64) as f64);
if (userLimit != Value::Null) && (marketsLength > userLimit.as_f64().unwrap_or(f64::NAN)) {
return self.array_slice(Value::from(markets), Value::Int(0), &[userLimit]);
}
return Value::from(markets);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#fetchRawMarketsPaged
* @description pages through GET /markets/active (cursor-based via paginationKey/nextKey), stopping once options.maxMarketsPages pages or userLimit raw markets have been collected
* @param {object} [extra] extra request params merged into every page (e.g. leagueId, sportId, sportXeventId)
* @param {int} [userLimit] stop collecting once this many raw markets have been gathered
* @returns {object[]} the raw (unparsed) sx.bet market objects
*/
pub async fn fetch_raw_markets_paged(&mut self, optional_args: &[Value]) -> Value {
let mut extra = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userLimit = get_arg(optional_args, 1, Value::Null);
let mut pageSize: Value = self.safe_integer_k(self.options.clone(), "marketsPageSize", &[Value::Int(100)]);
let mut maxPages: Value = self.safe_integer_k(self.options.clone(), "maxMarketsPages", &[Value::Int(50)]);
let mut rawMarkets: Vec<Value> = Vec::new();
let mut collectCap: Value = self.safe_integer(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), userLimit);
m
}), Value::Str("limit".into()), &[]);
let mut paginationKey: Value = Value::Null;
let mut page: Value = self.parse_to_int(Value::Int(0));
loop {
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("pageSize".to_string(), pageSize.clone());
m
});
if (paginationKey != Value::Null) {
request.insert("paginationKey".into(), paginationKey.clone());
}
let __ws_arg_0 = self.extend(Value::Map(request), &[extra.clone()]);
let mut response: Value = self.sxbet_public_get_markets_active(&[__ws_arg_0]).await;
let mut result: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut pageMarkets: Vec<Value> = self.safe_list_k(result.clone(), "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut pageMarketsLength: f64 = ((pageMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1493: bool = true;
while { if !__for_first_1493 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1493 = false; i.as_f64().unwrap_or(f64::NAN) < pageMarketsLength } {
rawMarkets.push(pageMarkets.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
}
}
paginationKey = self.safe_string_k(result, "nextKey", &[]);
page = self.parse_to_int((match (&(page), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }));
let mut collectedLength: Value = self.parse_to_int(Value::Int(rawMarkets.len() as i64));
if (pageMarketsLength < pageSize.as_f64().unwrap_or(f64::NAN)) || (page.as_f64().unwrap_or(f64::NAN) >= maxPages.as_f64().unwrap_or(f64::NAN)) || (paginationKey == Value::Null) || ((collectCap != Value::Null) && (collectedLength.as_f64().unwrap_or(f64::NAN) >= collectCap.as_f64().unwrap_or(f64::NAN))) {
break;
}
}
return Value::from(rawMarkets);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#filterRawMarketsByFixture
* @description keeps only the raw markets belonging to one fixture — the venue's own sportXeventId filter on /markets/active is unreliable (observed live returning every fixture), so the scope is enforced client-side
* @param {object[]} rawMarkets the raw sx.bet market objects
* @param {string} sportXeventId the fixture id to keep
* @returns {object[]} the raw markets of that fixture only
*/
pub fn filter_raw_markets_by_fixture(&self, mut rawMarkets: Value, mut sportXeventId: Value) -> Value {
let __rawMarkets_empty = Vec::new();
let rawMarkets = rawMarkets.as_array().unwrap_or(&__rawMarkets_empty);
let mut result: Vec<Value> = Vec::new();
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1494: bool = true;
while { if !__for_first_1494 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1494 = false; i.as_f64().unwrap_or(f64::NAN) < rawMarketsLength } {
let mut raw: Value = rawMarkets.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if (self.safe_string_k(raw.clone(), "sportXeventId", &[]).as_str() == sportXeventId.as_str()) {
result.push(raw);
}
}
}
return Value::from(result);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseSxbetMarket
* @description converts a single raw sx.bet market into one ccxt market whose two sides become the outcomes
* @param {object} raw the raw sx.bet market object
* @returns {object} a [market structure](https://docs.ccxt.com/#/?id=market-structure)
*/
pub fn parse_sxbet_market(&self, mut raw: Value) -> Value {
//
// {
// "status": "ACTIVE",
// "marketHash": "0x7154aa3580267e276cccd0f4f826464a05e3efd8e1c81d7717bef6b5ae88b07d",
// "outcomeOneName": "Los Angeles Rams",
// "outcomeTwoName": "San Francisco 49ers",
// "outcomeVoidName": "NO_CONTEST",
// "teamOneName": "Los Angeles Rams",
// "teamTwoName": "San Francisco 49ers",
// "type": 226,
// "gameTime": 1789086900,
// "line": -2.5, // present on spread/total markets only
// "sportXeventId": "L18870109",
// "liveEnabled": true,
// "sportLabel": "Football",
// "sportId": 8,
// "leagueId": 243,
// "leagueLabel": "NFL",
// "mainLine": true,
// "isQuarterLineMarket": false
// }
//
let mut marketHash: Value = self.safe_string_k(raw.clone(), "marketHash", &[Value::Str("".into())]);
let teamOneName: String = self.safe_string_k_opt(raw.clone(), "teamOneName", &[]).unwrap_or_default();
let teamTwoName: String = self.safe_string_k_opt(raw.clone(), "teamTwoName", &[]).unwrap_or_default();
let mut outcomeOneName: Option<String> = self.safe_string_k_opt(raw.clone(), "outcomeOneName", &[]);
let mut outcomeTwoName: Option<String> = self.safe_string_k_opt(raw.clone(), "outcomeTwoName", &[]);
let mut eventSlug: Value = self.shorten_slug(Value::Str(format!("{}{}", Value::Str(format!("{}{}", teamOneName, Value::Str(" ".into())).into()), teamTwoName).into()));
// one fixture carries many markets (moneyline, several spread/total lines, quarter/half
// variants) whose outcomeOneName text can coincide or nearly coincide, so a text-only
// slug isn't guaranteed unique. suffix with the market hash instead (always unique,
// letters+digits only so it survives shortenSlug in one atomic word)
let mut hashSuffix: Value = marketHash.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 6).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null);
let mut marketSlug: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.shorten_slug(outcomeOneName.clone().map(Value::from).unwrap_or(Value::Null)), Value::Str("_".into())).into()), hashSuffix).into());
let mut marketSymbol: Value = self.slug_to_market_symbol(eventSlug.clone(), marketSlug.clone());
let mut status: Option<String> = self.safe_string_upper_k(raw.clone(), "status", &[]).as_str().map(str::to_owned);
let mut active: Value = (Value::Bool(status.as_deref() == Some("ACTIVE")));
// guard against a zero sentinel for "no scheduled game time" - safeTimestamp would
// turn it into the 1970 epoch
let mut gameTime: Value = Value::Null;
if (self.safe_integer_k(raw.clone(), "gameTime", &[Value::Int(0)]).as_f64() != Some(0.0)) {
gameTime = self.safe_timestamp_k(raw.clone(), "gameTime", &[]);
}
let mut outcomeLabels: Value = Value::from(vec![outcomeOneName.clone().map(Value::from).unwrap_or(Value::Null), outcomeTwoName.clone().map(Value::from).unwrap_or(Value::Null)]);
let mut outcomeIds: Value = Value::from(vec![marketHash.clone(), Value::Str(format!("{}{}", marketHash, Value::Str("-2".into())).into())]);
let mut outcomes: Vec<Value> = Vec::new();
{
let mut oi: i64 = 0;
let mut __for_first_1495: bool = true;
while { if !__for_first_1495 { oi += 1; } __for_first_1495 = false; oi < (outcomeLabels.len() as i64) } {
let mut label: Value = outcomeLabels.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null);
let mut outcomeHandle: Value = self.slug_to_outcome_symbol(eventSlug.clone(), marketSlug.clone(), label.clone());
outcomes.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), outcomeIds.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), outcomeIds.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null));
m.insert("outcome".to_string(), outcomeHandle);
m.insert("market".to_string(), marketSymbol.clone());
m.insert("label".to_string(), label);
m.insert("active".to_string(), active.clone());
m.insert("winner".to_string(), Value::Null);
m.insert("settleFraction".to_string(), Value::Null);
m.insert("info".to_string(), raw.clone());
m
}));
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketHash.clone());
m.insert("market".to_string(), marketSymbol);
m.insert("base".to_string(), Value::Str("USDC".into()));
m.insert("quote".to_string(), Value::Str("USDC".into()));
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), marketHash);
m.insert("quoteId".to_string(), Value::Str("USDC".into()));
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("prediction".into()));
m.insert("marketType".to_string(), Value::Str("binary".into()));
m.insert("executionModel".to_string(), Value::Str("clob".into()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("active".to_string(), active);
m.insert("resolved".to_string(), Value::Bool(false));
m.insert("resolvedOutcome".to_string(), Value::Null);
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(), gameTime.clone());
m.insert("expiryDatetime".to_string(), self.iso8601(gameTime));
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("taker".to_string(), Value::Int(0));
m.insert("maker".to_string(), Value::Int(0));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("feeSide".to_string(), Value::Str("get".into()));
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Float(0.000001));
m.insert("price".to_string(), Value::Float(0.00125));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(1));
m.insert("max".to_string(), Value::Int(1));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(1));
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(0));
m.insert("max".to_string(), Value::Int(1));
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(1));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("outcomes".to_string(), Value::from(outcomes));
m.insert("info".to_string(), raw);
m.insert("created".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name sxbet#fetchEvents
* @description fetches sx.bet fixtures (one fixture = one event, its markets are every moneyline/spread/total line on that fixture) scoped by eventId, leagueId, sportId or a free-text query/tags match against team and league names — always live from the API, never the local cache (it POPULATES the cache for later event()/outcome lookups). query/queries/tags are matched client-side over a bounded scan of /markets/active — the venue's GET /search covers team names only (not league or sport labels) and is not wired here yet
* @see https://docs.sx.bet/api-reference/get-markets-active
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.eventId] direct lookup by unified event id (the sx.bet sportXeventId, e.g. 'L18870109')
* @param {string} [params.query] free-text search matched against team and league names
* @param {string[]} [params.queries] multiple free-text searches (alternative to query, unioned)
* @param {string[]} [params.tags] matched identically to query/queries (sx.bet has no tag taxonomy)
* @param {int} [params.leagueId] sx.bet league id (e.g. 243 for NFL) — fetched server-side
* @param {int} [params.sportId] sx.bet sport id (e.g. 8 for Football) — fetched server-side
* @param {string} [params.status] 'active' | 'inactive' | 'closed' | 'all'
* @param {int} [params.limit] max number of events to return
* @returns {object[]} an array of event structures
*/
pub async fn fetch_events(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.require_event_query(&[params.clone()]);
let mut eventId: Option<String> = self.safe_string2_opt(params.clone(), Value::Str("eventId".into()), Value::Str("slug".into()), &[]);
let mut leagueId: Option<String> = self.safe_string_k_opt(params.clone(), "leagueId", &[]);
let mut sportId: Option<String> = self.safe_string_k_opt(params.clone(), "sportId", &[]);
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
let mut tags: Vec<Value> = self.safe_list_k(params.clone(), "tags", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut tagsLength: f64 = ((tags.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1496: bool = true;
while { if !__for_first_1496 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1496 = false; i.as_f64().unwrap_or(f64::NAN) < tagsLength } {
append_to_array(&mut queries, tags.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
}
}
let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("leagueId".into()), Value::Str("sportId".into()), Value::Str("query".into()), Value::Str("queries".into()), Value::Str("tags".into()), Value::Str("status".into()), Value::Str("sort".into()), Value::Str("searchIn".into()), Value::Str("limit".into())]), &[]);
let mut rawMarkets: Value = Value::Null;
if (eventId.is_some()) {
let __ws_arg_1 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sportXeventId".to_string(), eventId.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[rest.clone()]);
rawMarkets = self.fetch_raw_markets_paged(&[__ws_arg_1, Value::Null]).await;
// the venue's sportXeventId filter on /markets/active is unreliable (observed live
// returning every fixture) — enforce the scope client-side
rawMarkets = self.filter_raw_markets_by_fixture(rawMarkets.clone(), eventId.clone().map(Value::from).unwrap_or(Value::Null));
} else if (leagueId.is_some()) {
let __ws_arg_2 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leagueId".to_string(), leagueId.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[rest.clone()]);
rawMarkets = self.fetch_raw_markets_paged(&[__ws_arg_2, Value::Null]).await;
} else if (sportId.is_some()) {
let __ws_arg_3 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sportId".to_string(), sportId.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[rest.clone()]);
rawMarkets = self.fetch_raw_markets_paged(&[__ws_arg_3, Value::Null]).await;
} else {
// no server-side scope left, only query/tags — full scan honoring the fetchMarkets
// bound, then filter client-side (the venue's /search covers team names only)
rawMarkets = self.fetch_raw_markets_paged(&[rest, Value::Null]).await;
}
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
if queriesLength > ((0i64) as f64) {
let mut filtered: Value = Value::from(vec![]);
let mut preFilterLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1497: bool = true;
while { if !__for_first_1497 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1497 = false; i.as_f64().unwrap_or(f64::NAN) < preFilterLength } {
if self.matches_event_query(rawMarkets.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), queries.clone()).as_bool() == Some(true) {
if let Value::Arr(__a) = &mut filtered { std::sync::Arc::make_mut(__a).push(rawMarkets.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)); }
}
}
}
rawMarkets = filtered;
}
let mut grouped: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut order: Vec<Value> = Vec::new();
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1498: bool = true;
while { if !__for_first_1498 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1498 = false; i.as_f64().unwrap_or(f64::NAN) < rawMarketsLength } {
let mut raw: Value = rawMarkets.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut sportXeventId: Option<String> = self.safe_string_k_opt(raw.clone(), "sportXeventId", &[]);
if (sportXeventId.is_none()) {
continue;
}
if !(matches!((&grouped, &sportXeventId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut grouped { std::sync::Arc::make_mut(__d).insert(sportXeventId.as_deref().unwrap_or("null").to_string(), Value::from(vec![])); }
order.push(sportXeventId.clone().map(Value::from).unwrap_or(Value::Null));
}
crate::runtime::append_to_object_array(&mut grouped, &sportXeventId.clone().map(Value::from).unwrap_or(Value::Null), raw);
}
}
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut result: Vec<Value> = Vec::new();
let mut orderLength: f64 = ((order.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1500: bool = true;
while { if !__for_first_1500 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1500 = false; i.as_f64().unwrap_or(f64::NAN) < orderLength } {
let mut fixtureId: Value = order.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut event: Value = self.parse_event(fixtureId.clone(), (if let (Some(__m), Some(__k)) = (grouped.as_map(), fixtureId.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null }));
let mut evMarkets: Vec<Value> = self.safe_list_k(event.clone(), "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut evMarketsLength: f64 = ((evMarkets.len() as i64) as f64);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1499: bool = true;
while { if !__for_first_1499 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_1499 = false; j.as_f64().unwrap_or(f64::NAN) < evMarketsLength } {
let mut m: Value = evMarkets.get(j.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
add_element_to_object(&mut self.markets, &crate::value::get_value_k(&m, "market"), m.clone());
}
}
result.push(event);
}
}
self.populate_outcomes();
self.set_events(Value::from(result.clone()));
let mut postParams: Value = self.omit(params, Value::from(vec![Value::Str("leagueId".into()), Value::Str("sportId".into()), Value::Str("query".into()), Value::Str("queries".into()), Value::Str("tags".into())]), &[]);
return self.apply_event_fetch_params(Value::from(result), &[postParams, Value::from(vec![])]);
Value::Null
}
/*
* @method
* @name sxbet#fetchEvent
* @description fetches a single sx.bet fixture (event) by its sportXeventId
* @see https://docs.sx.bet/api-reference/get-markets-active
* @param {string} id the sx.bet sportXeventId, e.g. 'L18870109'
* @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 __ws_arg_4 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sportXeventId".to_string(), id.clone());
m
}), &[params]);
let mut rawMarkets: Value = self.fetch_raw_markets_paged(&[__ws_arg_4, Value::Null]).await;
// enforce the fixture scope client-side — see filterRawMarketsByFixture
rawMarkets = self.filter_raw_markets_by_fixture(rawMarkets.clone(), id.clone());
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
if (rawMarketsLength == 0.0) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchEvent() could not find an active fixture ".into())).into()), id)));
}
let mut event: Value = self.parse_event(id, rawMarkets);
self.index_event_outcomes(event.clone());
self.set_events(Value::from(vec![event.clone()]));
return event;
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#matchesEventQuery
* @description checks a raw market's team/league names against a list of free-text queries, matching in either direction (a short user query inside a long name, or — since fetchEvents derives its fallback test query from an already-slugified handle — a long joined query containing a short name)
* @param {object} raw the raw sx.bet market object
* @param {string[]} queries lowercase-insensitive free-text queries
* @returns {boolean} whether any query matches any of the market's team/league/outcome names
*/
pub fn matches_event_query(&self, mut raw: Value, mut queries: Value) -> Value {
let __raw_empty = indexmap::IndexMap::new();
let raw = raw.as_map().unwrap_or(&__raw_empty);
let __queries_empty = Vec::new();
let queries = queries.as_array().unwrap_or(&__queries_empty);
let mut fields: Value = Value::from(vec![(match raw.get("teamOneName") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }),
(match raw.get("teamTwoName") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }), (match raw.get("leagueLabel") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()),
Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }), (match raw.get("sportLabel") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()),
Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }), (match raw.get("outcomeOneName") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }),
(match raw.get("outcomeTwoName") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null })]);
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
{
let mut qi: Value = Value::Int(0);
let mut __for_first_1502: bool = true;
while { if !__for_first_1502 { if let Value::Int(n) = &mut qi { *n += 1; } } __for_first_1502 = false; qi.as_f64().unwrap_or(f64::NAN) < queriesLength } {
let mut query: Value = (queries.get((qi).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)).as_str().map(|__s| Value::Str(__s.to_lowercase().into())).unwrap_or(Value::Null);
if (query.as_str() == Some("")) {
continue;
}
{
let mut fi: i64 = 0;
let mut __for_first_1501: bool = true;
while { if !__for_first_1501 { fi += 1; } __for_first_1501 = false; fi < (fields.len() as i64) } {
let mut field: Value = fields.as_array().map(Vec::as_slice).unwrap_or_default().get(fi as usize).cloned().unwrap_or(Value::Null);
if (field == Value::Null) {
continue;
}
let mut fieldLower: Value = (if let Some(__s) = field.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null });
if (Value::Int(query.as_str().zip(fieldLower.as_str()).and_then(|(__s, __n)| __s.find(__n)).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) || (Value::Int(fieldLower.as_str().zip(query.as_str()).and_then(|(__s, __n)| __s.find(__n)).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) {
return Value::Bool(true);
}
}
}
}
}
return Value::Bool(false);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseEvent
* @description groups a fixture's raw markets (all sharing one sportXeventId) into one unified event structure
* @param {string} fixtureId the sx.bet sportXeventId
* @param {object[]} rawMarkets the raw sx.bet market objects belonging to this fixture
* @returns {object} an event structure
*/
pub fn parse_event(&self, mut fixtureId: Value, mut rawMarkets: Value) -> Value {
let mut marketsList: Vec<Value> = Vec::new();
let mut anyActive: Value = Value::Bool(false);
let mut earliestGameTime: Value = self.safe_integer(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), Value::Str("gameTime".into()), &[]);
let mut teamOneName: Value = Value::Null;
let mut teamTwoName: Value = Value::Null;
let mut leagueLabel: Value = Value::Null;
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1503: bool = true;
while { if !__for_first_1503 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1503 = false; i.as_f64().unwrap_or(f64::NAN) < rawMarketsLength } {
let mut raw: Value = rawMarkets.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut parsed: Value = self.parse_sxbet_market(raw.clone());
if (parsed == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" parseEvent() could not resolve parsed market".into()))));
}
marketsList.push(parsed.clone());
if matches!(self.safe_bool_k(parsed, "active", &[Value::Bool(false)]), Value::Bool(true)) {
anyActive = Value::Bool(true);
}
if (teamOneName == Value::Null) {
teamOneName = self.safe_string_k(raw.clone(), "teamOneName", &[]);
teamTwoName = self.safe_string_k(raw.clone(), "teamTwoName", &[]);
leagueLabel = self.safe_string_k(raw.clone(), "leagueLabel", &[]);
}
let mut gameTime: Value = self.safe_integer_k(raw, "gameTime", &[]);
// skip the zero sentinel for "no scheduled game time" so it can't become the epoch
if (gameTime != Value::Null) && (gameTime.as_f64() != Some(0.0)) && ((earliestGameTime == Value::Null) || (gameTime.as_f64().unwrap_or(f64::NAN) < earliestGameTime.as_f64().unwrap_or(f64::NAN))) {
earliestGameTime = gameTime;
}
}
}
let mut end: Value = self.safe_timestamp(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("gameTime".to_string(), earliestGameTime);
m
}), Value::Str("gameTime".into()), &[]);
// some fixtures carry no team names on their market rows - fall back to the fixture id
// so the unified event handle is never empty or built from stringified nulls
let mut title: Value = Value::Null;
let mut eventSlug: Value = Value::Null;
if (teamOneName != Value::Null) && (teamTwoName != Value::Null) {
title = Value::Str(format!("{}{}", Value::Str(format!("{}{}", teamOneName, Value::Str(" vs ".into())).into()), teamTwoName).into());
eventSlug = self.shorten_slug(Value::Str(format!("{}{}", Value::Str(format!("{}{}", teamOneName, Value::Str(" ".into())).into()), teamTwoName).into()));
} else {
eventSlug = self.shorten_slug(fixtureId.clone());
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), fixtureId.clone());
m.insert("slug".to_string(), fixtureId);
m.insert("event".to_string(), eventSlug);
m.insert("title".to_string(), title);
m.insert("description".to_string(), Value::Null);
m.insert("category".to_string(), leagueLabel);
m.insert("tags".to_string(), Value::Null);
m.insert("markets".to_string(), Value::from(marketsList));
m.insert("mutuallyExclusive".to_string(), Value::Bool(false));
m.insert("active".to_string(), anyActive);
m.insert("resolved".to_string(), Value::Null);
m.insert("volume".to_string(), Value::Null);
m.insert("liquidity".to_string(), Value::Null);
m.insert("created".to_string(), Value::Null);
m.insert("createdDatetime".to_string(), Value::Null);
m.insert("end".to_string(), end.clone());
m.insert("endDatetime".to_string(), self.iso8601(end));
m.insert("image".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), rawMarkets);
m
});
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#loadSxObv3Metadata
* @description fetches and caches GET /metadata/obv3 - the v3 orderbook metadata carrying the ready-made EIP-712 domain, the active base asset and the order size limits
* @see https://docs.sx.bet/api-reference/get-metadata-obv3
* @returns {object} the cached obv3 metadata data object
*/
pub async fn load_sx_obv3_metadata(&mut self) -> Value {
let mut cached: Value = self.safe_dict_k(self.options.clone(), "sxObv3Metadata", &[]);
if (cached != Value::Null) {
return cached;
}
let mut response: Value = self.sxbet_public_get_metadata_obv3(&[]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("sxObv3Metadata".into(), data.clone()); }
return data;
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#roundOddsToLadder
* @description rounds an implied probability (0-1) to sx.bet's odds ladder (oddsLadderStepSize is in units of 1e-5, e.g. 125 -> a 0.125% step) — a maker's percentageOdds is rejected unless it lands exactly on the ladder
* @param {string} probability the implied probability in decimal-string form (0-1)
* @param {string} oddsLadderStepSize the raw oddsLadderStepSize from /metadata/obv3 (e.g. '125')
* @returns {string} the probability rounded to the nearest ladder step, in decimal-string form
*/
pub fn round_odds_to_ladder(&self, mut probability: Value, mut oddsLadderStepSize: Value) -> Option<String> {
let mut tickSize: Value = crate::precise::Precise::stringDivPrec(&oddsLadderStepSize, &Value::Str("100000".into()), &Value::Int(10));
return self.decimal_to_precision(probability, Value::Int(crate::runtime::ROUND), tickSize, &[Value::Int(crate::runtime::TICK_SIZE)]).as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name sxbet#hashEip712Digest
* @description hashes an EIP-712 encoded payload (domainSeparator‖structHash, prefixed with 0x1901 by ethEncodeStructuredData) down to the final 32-byte digest to sign, used by sx.bet's taker-fill and cancel signatures
* @param {Uint8Array} encoded the output of this.ethEncodeStructuredData (domain, types, message)
* @returns {string} the 32-byte digest to ecdsa-sign, in '0x'-prefixed hex form
*/
pub fn hash_eip712_digest(&self, mut encoded: Value) -> Option<String> {
return Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(encoded, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into()).as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name sxbet#signDigest
* @description ecdsa-signs a 32-byte digest and assembles the r‖s‖v hex signature sx.bet expects
* @param {string} digest the '0x'-prefixed 32-byte digest to sign
* @param {string} privateKey the signer's private key
* @returns {string} a '0x'-prefixed 65-byte hex signature (r‖s‖v)
*/
pub fn sign_digest(&self, mut digest: Value, mut privateKey: Value) -> Option<String> {
let mut signature: Value = ecdsa(digest.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null),
privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null), Value::Str("secp256k1".into()), Value::Null);
// assign to bare locals before padStart — the php transpiler's str_pad regex only
// matches a simple identifier, an expression form leaks a raw padStart() call
let mut rRaw: Value = signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null);
let mut sRaw: Value = signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null);
let mut r: Value = rRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
let mut s: Value = sRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
let mut v: Value = self.int_to_base16(self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]), &[]);
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), r).into()), s).into()), v).into()).as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name sxbet#fetchErc20Name
* @description reads an ERC20 token's name() via eth_call (needed for the Permit EIP-712 domain — must match the token's real on-chain name or the signature fails verification)
* @param {string} rpcUrl the RPC endpoint to call
* @param {string} tokenAddress the token contract address
* @returns {string} the token's on-chain name
*/
pub async fn fetch_erc20_name(&mut self, mut rpcUrl: Value, mut tokenAddress: Value) -> Value {
let mut nameCallData: String = "0x06fdde03".to_string(); // name()
let mut result: Value = self.eth_rpc(rpcUrl, Value::Str("eth_call".into()), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("to".to_string(), tokenAddress);
m.insert("data".to_string(), Value::from(nameCallData));
m
}), Value::Str("latest".into())])).await;
let mut hex: Value = self.remove0x_prefix(result);
// dynamic ABI string return: [32-byte offset][32-byte length][utf8 bytes, right-padded]
let mut lengthHex: Value = hex.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(64); let __j = __l.min(128); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null);
let mut length: Value = self.parse_to_int(self.hex_to_int(lengthHex));
let mut dataEnd: Value = self.sum(&[Value::Int(128), (match (&(length), &(Value::Int(2))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
let mut dataHex: Value = (match (&(hex), 128i64, (match &(dataEnd) { Value::Int(__n) => Some(*__n), Value::Float(__f) => Some(*__f as i64), Value::Str(__s) => __s.parse::<i64>().ok(), Value::Bool(__b) => Some(if *__b { 1 } else { 0 }), _ => None })) { (Value::Str(__sv), __b,
__e) => match (__sv.chars().count() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l, Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i,
__j) => if __i <= __j { Value::Str(__sv.chars().skip(__i as usize).take((__j - __i) as usize).collect::<String>().into()) } else { Value::Str(String::new().into()) } } }, (Value::Arr(__a), __b, __e) => match (__a.len() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l,
Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i, __j) => if __i <= __j { Value::Array(__a[__i as usize..__j as usize].to_vec()) } else { Value::Array(vec![]) } } }, _ => Value::Null });
return self.decode(self.base16_to_binary(dataHex, &[]));
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#hexToInt
* @description parses a hex string (no '0x' prefix) into an integer — plain digit-by-digit, since JS's parseInt (hex, 16) two-argument form has no portable equivalent across languages/transpilers. Only used for small values (byte lengths, permit nonces), safe well within the float-precision range
* @param {string} hex the hex string, no '0x' prefix
* @returns {int} the parsed integer
*/
pub fn hex_to_int(&self, mut hex: Value) -> Value {
let mut digits: String = "0123456789abcdef".to_string();
let mut lowerHex: Value = (if let Some(__s) = hex.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null });
let mut hexLength: f64 = ((lowerHex.len() as i64) as f64);
let mut result: Value = self.parse_to_int(Value::Int(0));
{
let mut i: Value = Value::Int(0);
let mut __for_first_1504: bool = true;
while { if !__for_first_1504 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1504 = false; i.as_f64().unwrap_or(f64::NAN) < hexLength } {
let mut ch: Value = get_value(&lowerHex, &i);
let mut digitValue: Value = self.parse_to_int(Value::Int(Some(digits.as_str()).zip(ch.as_str()).and_then(|(__s, __n)| __s.find(__n)).map(|__i| __i as i64).unwrap_or(-1)));
let mut shifted: Value = (match (&(result), &(Value::Int(16))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
result = self.parse_to_int(self.sum(&[shifted, digitValue]));
}
}
return result;
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#fetchSxbetProxy
* @description fetches the account's obv3 proxy wallet state
* @see https://docs.sx.bet/api-reference/get-user-proxy
* @returns {object} the raw proxy data ({obv3ProxyWalletAddress, deployed, multisigSafeAddress})
*/
pub async fn fetch_sxbet_proxy(&mut self) -> Value {
let mut response: Value = self.sxbet_private_get_user_proxy(&[]).await;
return self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
/*
* @method
* @name sxbet#approve
* @description funds the account's obv3 proxy wallet - v3 trading capital must sit inside the proxy. Deploys the proxy first when absent, then moves USDC from the wallet into it via a gasless EIP-2612 Permit signature (POST /user/transfer-to-proxy)
* @see https://docs.sx.bet/api-reference/post-user-transfer-to-proxy
* @see https://docs.sx.bet/api-reference/post-user-deploy-proxy
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {float} [params.amount] the USDC amount to move into the proxy (required)
* @param {string} [params.tokenAddress] the token to transfer, defaults to the active base token
* @param {string} [params.spender] the transfer executor granted the permit, defaults to options.transferToProxySpender or the obv3 transferToProxyExecutorAddress
* @param {int} [params.deadline] unix seconds the permit signature expires at, defaults to options.approveDeadlineSeconds from now
* @param {string} [params.rpcUrl] overrides the chain's default RPC endpoint (see options.chains)
* @returns {object} a dict with the raw response and the transfer sessionId
*/
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(&[]);
let mut amount: Value = self.safe_number_k(params.clone(), "amount", &[]);
if (amount == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" approve() requires params.amount - the USDC amount to move into the proxy wallet".into()))));
}
let mut proxy: Value = self.fetch_sxbet_proxy().await;
let mut deployed: bool = self.safe_bool_k_opt(proxy, "deployed", &[Value::Bool(false)]).unwrap_or(false);
if !(deployed) {
self.sxbet_private_post_user_deploy_proxy(&[]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1505: bool = true;
while { if !__for_first_1505 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1505 = false; i.as_f64().unwrap_or(f64::NAN) < ((30i64) as f64) } {
self.sleep(Value::Int(2000)).await;
let mut state: Value = self.fetch_sxbet_proxy().await;
if matches!(self.safe_bool_k(state, "deployed", &[Value::Bool(false)]), Value::Bool(true)) {
break;
}
}
}
}
let mut obv3: Value = self.load_sx_obv3_metadata().await;
let mut activeAsset: Value = self.safe_dict_k(obv3.clone(), "activeAsset", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut chainId: Option<i64> = self.safe_integer_k(obv3.clone(), "chainId", &[]).as_i64();
let mut usdcAddress: Option<String> = self.safe_string_k_opt(activeAsset, "baseToken", &[]);
// the permit spender is the venue's transfer-to-proxy executor, published in /metadata/obv3
let mut executorAddress: Option<String> = self.safe_string_k_opt(obv3, "transferToProxyExecutorAddress", &[]);
let mut tokenAddress: Value = self.safe_string_k(params.clone(), "tokenAddress", &[usdcAddress.map(Value::from).unwrap_or(Value::Null)]);
if (tokenAddress == Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" approve() could not resolve the base token address from /metadata/obv3".into()))));
}
let spenderparamsSpenderVariable: Vec<Value> = self.handle_option_string_and_params2(params, Value::Str("approve".into()), Value::Str("spender".into()), Value::Str("transferToProxySpender".into()), &[executorAddress.map(Value::from).unwrap_or(Value::Null)]).as_array().cloned().unwrap_or_default();
let mut spender: Value = spenderparamsSpenderVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsSpender: Value = spenderparamsSpenderVariable.get(1).cloned().unwrap_or(Value::Null);
if (spender == Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" approve() could not resolve the transfer-to-proxy executor from /metadata/obv3 - pass params.spender".into()))));
}
let mut chains: Value = self.safe_dict_k(self.options.clone(), "chains", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut chainConfig: Value = self.safe_dict(chains, self.number_to_string(Value::from(chainId)), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rpcUrl: Value = self.safe_string_k(paramsSpender.clone(), "rpcUrl", &[self.safe_string(chainConfig, Value::Str("rpcUrl".into()), &[])]);
if (rpcUrl == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" approve() has no RPC endpoint configured for chainId ".into())).into()), self.number_to_string(Value::from(chainId))).into()), Value::Str(" - pass params.rpcUrl".into()))));
}
let mut owner: Value = self.walletAddress.clone();
let mut nonceCallData: Value = Value::Str(format!("{}{}", Value::Str("0x7ecebe00".into()), self.pad_hex_address(owner.clone())).into()); // nonces(address)
let mut nonceResult: Value = self.eth_rpc(rpcUrl.clone(), Value::Str("eth_call".into()), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("to".to_string(), tokenAddress.clone());
m.insert("data".to_string(), nonceCallData);
m
}), Value::Str("latest".into())])).await;
let mut nonceHex: Value = self.hex_to_rlp_bytes(nonceResult);
let mut nonce: Value = (if (nonceHex.as_str() == Some("")) { Value::Str("0".into()) } else { self.number_to_string(self.hex_to_int(nonceHex)) });
let mut tokenName: Value = self.fetch_erc20_name(rpcUrl, tokenAddress.clone()).await;
let mut defaultDeadlineSeconds: Value = self.safe_integer_k(self.options.clone(), "approveDeadlineSeconds", &[Value::Int(7200)]);
let mut deadline: Value = self.safe_integer_k(paramsSpender.clone(), "deadline", &[self.sum(&[self.seconds(), defaultDeadlineSeconds])]);
let mut value: Value = self.decimal_to_precision(crate::precise::Precise::stringMul(&self.number_to_string(amount), &Value::Str("1000000".into())), Value::Int(crate::runtime::ROUND), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), tokenName);
m.insert("version".to_string(), Value::Str("1".into()));
m.insert("chainId".to_string(), Value::from(chainId));
m.insert("verifyingContract".to_string(), tokenAddress.clone());
m
});
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("Permit".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("owner".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("spender".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("value".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("deadline".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
})]));
m
});
let mut messageData: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("owner".to_string(), owner.clone());
m.insert("spender".to_string(), spender.clone());
m.insert("value".to_string(), value.clone());
m.insert("nonce".to_string(), nonce);
m.insert("deadline".to_string(), deadline.clone());
m
});
let mut encoded: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map(messageTypes), Value::Map(messageData));
let mut digest: Value = self.hash_eip712_digest(encoded).map(Value::from).unwrap_or(Value::Null);
let mut signature: Value = self.sign_digest(digest, self.privateKey.clone()).map(Value::from).unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("owner".to_string(), owner);
m.insert("spender".to_string(), spender);
m.insert("tokenAddress".to_string(), tokenAddress);
m.insert("value".to_string(), value);
m.insert("deadline".to_string(), self.number_to_string(deadline));
m.insert("signature".to_string(), signature);
m
});
let mut rest: Value = self.omit(paramsSpender, Value::from(vec![Value::Str("amount".into()), Value::Str("tokenAddress".into()), Value::Str("deadline".into()), Value::Str("rpcUrl".into())]), &[]);
let __ws_arg_5 = self.extend(Value::Map(request), &[rest]);
let mut response: Value = self.sxbet_private_post_user_transfer_to_proxy(&[__ws_arg_5]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("id".to_string(), self.safe_string_k(data, "sessionId", &[]));
m
});
Value::Null
}
/*
* @method
* @name sxbet#createOrder
* @description places an order on sx.bet's v3 unified orderbook - a 'limit' order rests with GTC time-in-force, a 'market' order fills immediately with IOC (or FOK via params.timeInForce). sx.bet has no shares - 'amount' is the USDC stake to risk, and 'price' is the implied probability (0-1) of the requested outcome. 'sell' bets the OPPOSITE outcome of the one requested (sx.bet is bilateral: there is no owned position to sell, only the complementary side of the same market)
* @see https://docs.sx.bet/api-reference/post-orders-v3
* @param {string} outcome unified outcome or outcome token id
* @param {string} type 'limit' (GTC resting order) or 'market' (IOC immediate fill)
* @param {string} side 'buy' backs the requested outcome, 'sell' backs the complementary one
* @param {float} amount the USDC amount to stake/risk
* @param {float} [price] implied probability (0-1) of the requested outcome; required for both order types
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.timeInForce] overrides the derived value - 'GTC', 'IOC' or 'FOK'
* @param {int} [params.expiry] unix seconds the order expires at; must be in the future (zero and past values are rejected, so is anything inside the fixture's betting-delay window - /metadata/obv3 resolves the delay per sport/league, live vs pregame), defaults to options.defaultOrderExpirySeconds from now
* @param {string} [params.salt] overrides the random salt differentiating this order
* @param {string} [params.clientOrderId] caller-chosen id echoed back on reads (max 64 chars)
* @param {boolean} [params.waitForOutcome] wait for the matching outcome inline (default true)
* @param {boolean} [params.useBetCredits] fund the stake from bet credits instead of the proxy balance (IOC/FOK only)
* @param {string} [params.externalUserId] partner attribution id echoed back on order, fill and trade reads
* @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
}));
self.check_required_credentials(&[]);
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
if (type_var.as_str() != Some("limit")) && (type_var.as_str() != Some("market")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder() type must be 'limit' or 'market', got ".into())).into()), type_var)));
}
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price - the implied probability of the requested outcome".into()))));
}
// the venue has no post-only or trigger mechanics - reject the unified params instead
// of forwarding fields the exchange would silently ignore
let mut postOnly: bool = self.safe_bool_k_opt(params.clone(), "postOnly", &[Value::Bool(false)]).unwrap_or(false);
if postOnly {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support postOnly - GTC orders may cross on entry".into()))));
}
let mut triggerPrice: Option<String> = self.safe_string_n(params.clone(), Value::from(vec![Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]).as_str().map(str::to_owned);
if (triggerPrice.is_some()) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support trigger, stop-loss or take-profit orders".into()))));
}
let mut marketHash: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[Value::Str("".into())]);
let mut outcomeId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]);
let mut isOutcomeOne: Value = (Value::Bool(outcomeId == marketHash));
let mut isBuy: bool = side.as_str() == Some("buy");
// 'sell' bets the complementary outcome, mirroring the requested outcome's own probability -
// matches the normalize-to-one-book convention used by other prediction venues
let mut isMakerBettingOutcomeOne: Value = (if (isBuy) { isOutcomeOne.clone() } else { Value::Bool(!(matches!(&isOutcomeOne, Value::Bool(true)))) });
let mut priceStr: Value = self.number_to_string(price);
let mut probability: Value = (if (isBuy) { priceStr.clone() } else { crate::precise::Precise::stringSub(&Value::Str("1".into()), &priceStr) });
let mut obv3: Value = self.load_sx_obv3_metadata().await;
let mut domain: Value = self.safe_dict_k(obv3.clone(), "domain", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut activeAsset: Value = self.safe_dict_k(obv3.clone(), "activeAsset", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut baseToken: Option<String> = self.safe_string_k_opt(activeAsset, "baseToken", &[]);
let mut oddsLadderStepSize: Value = self.number_to_string(self.safe_integer_k(obv3, "oddsLadderStepSize", &[Value::Int(125)]));
let mut roundedProbability: Value = self.round_odds_to_ladder(probability, oddsLadderStepSize).map(Value::from).unwrap_or(Value::Null);
let mut percentageOdds: Value = self.decimal_to_precision(crate::precise::Precise::stringMul(&roundedProbability, &Value::Str("100000000000000000000".into())), Value::Int(crate::runtime::ROUND), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
let mut amountStr: Value = self.number_to_string(amount.clone());
let mut totalBetSize: Value = self.decimal_to_precision(crate::precise::Precise::stringMul(&amountStr, &Value::Str("1000000".into())), Value::Int(crate::runtime::ROUND), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
let mut saltNumber: Value = self.safe_string_k(params.clone(), "salt", &[self.number_to_string(self.milliseconds())]);
// the request body carries the salt in 32-byte-hex form; the signed struct carries the
// same value in uint256 form - both parse to one number server-side. assign to bare locals
// before padStart - see the transpiler notes
let mut saltHexRaw: Value = self.int_to_base16(self.parse_to_int(saltNumber.clone()), &[]);
let mut saltHexPadded: Value = saltHexRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
let mut saltHex: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), saltHexPadded).into());
let mut defaultExpirySeconds: Value = self.safe_integer_k(self.options.clone(), "defaultOrderExpirySeconds", &[Value::Int(86400)]);
let mut expiry: Value = self.safe_integer_k(params.clone(), "expiry", &[self.sum(&[self.seconds(), defaultExpirySeconds])]);
let mut defaultTif: String = "IOC".to_string();
if (type_var.as_str() == Some("limit")) {
defaultTif = "GTC".to_string();
}
let timeInForceparamsTimeInForceVariable: Vec<Value> = self.handle_option_string_and_params(params, Value::Str("createOrder".into()), Value::Str("timeInForce".into()), &[Value::from(defaultTif)]).as_array().cloned().unwrap_or_default();
let mut timeInForce: Value = timeInForceparamsTimeInForceVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsTimeInForce: Value = timeInForceparamsTimeInForceVariable.get(1).cloned().unwrap_or(Value::Null);
// an explicit IOC/FOK on a 'limit' order is honored verbatim - the venue executes exactly
// that time-in-force. only GTC on a 'market' order is refused: it would silently rest,
// contradicting the immediate-fill semantics the type promises
if (type_var.as_str() == Some("market")) && (timeInForce.as_str() == Some("GTC")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() market orders cannot be GTC - use type 'limit' for a resting order".into()))));
}
let mut maker: Value = self.walletAddress.clone();
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("Order".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("marketHash".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("baseToken".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("totalBetSize".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("percentageOdds".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("salt".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("expiry".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("maker".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("isMakerBettingOutcomeOne".into()));
m.insert("type".to_string(), Value::Str("bool".into()));
m
})]));
m
});
let mut messageData: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketHash".to_string(), marketHash.clone());
m.insert("baseToken".to_string(), baseToken.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("totalBetSize".to_string(), totalBetSize.clone());
m.insert("percentageOdds".to_string(), percentageOdds.clone());
m.insert("salt".to_string(), saltNumber);
m.insert("expiry".to_string(), expiry.clone());
m.insert("maker".to_string(), maker.clone());
m.insert("isMakerBettingOutcomeOne".to_string(), isMakerBettingOutcomeOne.clone());
m
});
let mut encoded: Value = self.eth_encode_structured_data(domain, Value::Map(messageTypes), Value::Map(messageData));
let mut digest: Value = self.hash_eip712_digest(encoded).map(Value::from).unwrap_or(Value::Null);
let mut orderSignature: Value = self.sign_digest(digest, self.privateKey.clone()).map(Value::from).unwrap_or(Value::Null);
let mut orderItem: indexmap::IndexMap<String, Value> = {
let mut m = indexmap::IndexMap::new();
m.insert("marketHash".to_string(), marketHash);
m.insert("maker".to_string(), maker);
m.insert("totalBetSize".to_string(), totalBetSize);
m.insert("percentageOdds".to_string(), percentageOdds);
m.insert("salt".to_string(), saltHex);
m.insert("expiry".to_string(), expiry);
m.insert("baseToken".to_string(), baseToken.map(Value::from).unwrap_or(Value::Null));
m.insert("isMakerBettingOutcomeOne".to_string(), isMakerBettingOutcomeOne);
m.insert("timeInForce".to_string(), timeInForce.clone());
m.insert("orderSignature".to_string(), orderSignature);
m
};
let mut clientOrderId: Option<String> = self.safe_string_k_opt(paramsTimeInForce.clone(), "clientOrderId", &[]);
if (clientOrderId.is_some()) {
orderItem.insert("clientOrderId".into(), clientOrderId.clone().map(Value::from).unwrap_or(Value::Null));
}
// useBetCredits and externalUserId are per-order fields - route them into the order item,
// not the top-level body, where the venue would silently ignore them
let mut useBetCredits: Option<bool> = self.safe_bool_k_opt(paramsTimeInForce.clone(), "useBetCredits", &[]);
if (useBetCredits.is_some()) {
orderItem.insert("useBetCredits".into(), useBetCredits.map(Value::Bool).unwrap_or(Value::Null));
}
let mut externalUserId: Option<String> = self.safe_string_k_opt(paramsTimeInForce.clone(), "externalUserId", &[]);
if (externalUserId.is_some()) {
orderItem.insert("externalUserId".into(), externalUserId.map(Value::from).unwrap_or(Value::Null));
}
let mut waitForOutcome: bool = self.safe_bool_k_opt(paramsTimeInForce.clone(), "waitForOutcome", &[Value::Bool(true)]).unwrap_or(true);
let mut rest: Value = self.omit(paramsTimeInForce, Value::from(vec![Value::Str("salt".into()), Value::Str("expiry".into()), Value::Str("clientOrderId".into()), Value::Str("waitForOutcome".into()), Value::Str("useBetCredits".into()), Value::Str("externalUserId".into())]), &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), Value::from(vec![Value::Map(orderItem)]));
m.insert("waitForOutcome".to_string(), Value::Bool(waitForOutcome));
m
});
let __ws_arg_6 = self.extend(Value::Map(request), &[rest]);
let mut response: Value = self.sxbet_private_post_orders_v3(&[__ws_arg_6]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut results: Value = self.safe_list_k(data, "orders", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(results, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Option<String> = self.safe_string_upper_k(first.clone(), "status", &[]).as_str().map(str::to_owned);
if (status.as_deref() == Some("FAILED")) {
let mut reason: Value = self.safe_string_k(first.clone(), "reason", &[Value::Str("FAILED".into())]);
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder() rejected: ".into())).into()), reason).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), reason.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::invalid_order(feedback));
}
// with waitForOutcome the venue reports the matching result inline:
// "outcome": { "state": "FULLY_FILLED", "fillAmount": "2000000", "remainingAmount": "0", "matchIds": [...] }
// documented states: RESTED, FULLY_FILLED, PARTIAL_FILL_DONE, PARTIAL_FILL_RESTED, TIMEOUT and
// CANCELLED with cancelReason NO_LIQUIDITY, INTERNAL_ERROR, ENGINE_SHUTDOWN, EXPIRED or INSUFFICIENT_BALANCE
let mut matchOutcome: Value = self.safe_dict_k(first.clone(), "outcome", &[]);
let mut usdcDecimals: Value = Value::Str("1000000".into());
let mut filled: Value = Value::Null;
let mut remaining: Value = Value::Null;
let mut orderStatus: Value = Value::Null;
if (matchOutcome != Value::Null) {
let mut fillAmountRaw: Option<String> = self.safe_string_k_opt(matchOutcome.clone(), "fillAmount", &[]);
let mut remainingRaw: Option<String> = self.safe_string_k_opt(matchOutcome.clone(), "remainingAmount", &[]);
if (fillAmountRaw.is_some()) {
filled = self.parse_number(crate::precise::Precise::stringDivPrec(&fillAmountRaw.clone().map(Value::from).unwrap_or(Value::Null), &usdcDecimals, &Value::Int(6)), &[]);
}
if (remainingRaw.is_some()) {
remaining = self.parse_number(crate::precise::Precise::stringDivPrec(&remainingRaw.clone().map(Value::from).unwrap_or(Value::Null), &usdcDecimals, &Value::Int(6)), &[]);
}
let mut state: Option<String> = self.safe_string_upper_k(matchOutcome.clone(), "state", &[]).as_str().map(str::to_owned);
if (state.as_deref() == Some("RESTED")) || (state.as_deref() == Some("PARTIAL_FILL_RESTED")) {
orderStatus = Value::Str("open".into());
} else if (state.as_deref() == Some("FULLY_FILLED")) {
orderStatus = Value::Str("closed".into());
} else if (state.as_deref() == Some("PARTIAL_FILL_DONE")) {
// the unmatched remainder of an IOC was cancelled by the venue
orderStatus = Value::Str("canceled".into());
} else if (state.as_deref() == Some("CANCELLED")) {
// the documented field is cancelReason; 'reason' is kept for older responses
let mut reason: Value = self.safe_string_upper2(matchOutcome, Value::Str("cancelReason".into()), Value::Str("reason".into()), &[]);
orderStatus = (if (reason.as_str() == Some("EXPIRED")) { Value::Str("expired".into()) } else { Value::Str("canceled".into()) });
}
}
let mut now: Value = self.milliseconds();
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string2(first.clone(), Value::Str("orderId".into()), Value::Str("orderHash".into()), &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(first, "clientOrderId", &[clientOrderId.map(Value::from).unwrap_or(Value::Null)]));
m.insert("info".to_string(), response);
m.insert("timestamp".to_string(), now.clone());
m.insert("datetime".to_string(), self.iso8601(now));
m.insert("status".to_string(), orderStatus);
m.insert("filled".to_string(), filled.clone());
m.insert("remaining".to_string(), remaining);
m.insert("cost".to_string(), filled);
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), outcomeId);
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("type".to_string(), type_var);
m.insert("timeInForce".to_string(), timeInForce);
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.parse_number(roundedProbability, &[]));
m.insert("amount".to_string(), amount);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m
}), &[outcomeObj]);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseSxbetCancelResponse
* @description parses the shared v3 cancel response ({cancelled, notCancelled, unconfirmed}) into order structures
* @param {object} response the raw DELETE /orders-v3 response
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub fn parse_sxbet_cancel_response(&self, mut response: Value) -> Value {
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: Vec<Value> = Vec::new();
// by-id cancels report 'cancelled'; the /all and /event paths submit asynchronously and
// report 'cancelledSubmitted' instead - treat both like cancelled
let mut cancelled: Value = self.safe_list2(data.clone(), Value::Str("cancelled".into()), Value::Str("cancelledSubmitted".into()), &[Value::from(vec![])]);
let mut cancelledLength: f64 = ((cancelled.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1506: bool = true;
while { if !__for_first_1506 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1506 = false; i.as_f64().unwrap_or(f64::NAN) < cancelledLength } {
result.push(self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string(cancelled.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), Value::Str("orderId".into()), &[]));
m.insert("status".to_string(), Value::Str("canceled".into()));
m.insert("info".to_string(), response.clone());
m
}), &[]));
}
}
let mut notCancelled: Vec<Value> = self.safe_list_k(data.clone(), "notCancelled", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut notCancelledLength: f64 = ((notCancelled.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1507: bool = true;
while { if !__for_first_1507 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1507 = false; i.as_f64().unwrap_or(f64::NAN) < notCancelledLength } {
// the venue reports why (e.g. NOT_FOUND) - the order was not cancelled, report it honestly
result.push(self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string(notCancelled.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), Value::Str("orderId".into()), &[]));
m.insert("status".to_string(), Value::Null);
m.insert("info".to_string(), response.clone());
m
}), &[]));
}
}
let mut unconfirmed: Vec<Value> = self.safe_list_k(data, "unconfirmed", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut unconfirmedLength: f64 = ((unconfirmed.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1508: bool = true;
while { if !__for_first_1508 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1508 = false; i.as_f64().unwrap_or(f64::NAN) < unconfirmedLength } {
result.push(self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string(unconfirmed.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), Value::Str("orderId".into()), &[]));
m.insert("status".to_string(), Value::Null);
m.insert("info".to_string(), response.clone());
m
}), &[]));
}
}
return Value::from(result);
Value::Null
}
/*
* @method
* @name sxbet#cancelOrder
* @description cancels one resting maker order - v3 cancels are plain api-key-authenticated DELETE requests, no signature involved
* @see https://docs.sx.bet/api-reference/delete-orders-v3
* @param {string} id the order id
* @param {string} [outcome] not used by sxbet.cancelOrder
* @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
}));
self.check_required_credentials(&[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id);
m
})]));
m
});
let __ws_arg_7 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.sxbet_private_delete_orders_v3(&[__ws_arg_7]).await;
let mut orders: Value = self.parse_sxbet_cancel_response(response);
let mut first: Value = self.safe_dict(orders, Value::Int(0), &[]);
return first;
Value::Null
}
/*
* @method
* @name sxbet#cancelOrders
* @description cancels multiple resting maker orders in one request - v3 cancels are plain api-key-authenticated DELETE requests, no signature involved
* @see https://docs.sx.bet/api-reference/delete-orders-v3
* @param {string[]} ids the order ids to cancel
* @param {string} [outcome] not used by sxbet.cancelOrders
* @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
}));
self.check_required_credentials(&[]);
let mut idsLength: Value = Value::Int(ids.len() as i64);
if (idsLength.as_f64() == Some(0.0)) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires a non-empty ids argument".into()))));
}
// the venue caps one cancel request at maxCancelOrders ids (100, see /metadata/obv3) -
// chunk larger batches instead of letting the whole request 400
let mut chunkSize: Value = self.safe_integer_k(self.options.clone(), "cancelOrdersBatchSize", &[Value::Int(100)]);
let mut chunkCount: Value = self.parse_to_int((match ((self.sum(&[idsLength.clone(), (match (&(chunkSize), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x),
Value::Float(y)) => Value::Float(x - y), _ => Value::Null })])).as_f64(), (chunkSize).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
let mut result: Value = Value::from(vec![]);
{
let mut c: Value = Value::Int(0);
let mut __for_first_1510: bool = true;
while { if !__for_first_1510 { if let Value::Int(n) = &mut c { *n += 1; } } __for_first_1510 = false; c.as_f64().unwrap_or(f64::NAN) < chunkCount.as_f64().unwrap_or(f64::NAN) } {
let mut chunkIndex: Value = self.parse_to_int(c.clone());
let mut chunkWidth: Value = self.parse_to_int(chunkSize.clone());
let mut start: Value = (match (&(chunkIndex), &(chunkWidth)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut nextChunkIndex: Value = (match (&(chunkIndex), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
let mut chunkEnd: Value = (match (&(nextChunkIndex), &(chunkWidth)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut end: Value = chunkEnd.clone();
if chunkEnd.as_f64().unwrap_or(f64::NAN) > idsLength.as_f64().unwrap_or(f64::NAN) {
end = self.parse_to_int(idsLength.clone());
}
let mut orderItems: Vec<Value> = Vec::new();
let mut chunkIds: Value = self.array_slice(ids.clone(), start, &[end]);
let mut chunkIdsLength: Value = get_array_length(&chunkIds);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1509: bool = true;
while { if !__for_first_1509 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1509 = false; i.as_f64().unwrap_or(f64::NAN) < chunkIdsLength.as_f64().unwrap_or(f64::NAN) } {
orderItems.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), get_value(&chunkIds, &i));
m
}));
}
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), Value::from(orderItems));
m
});
let __ws_arg_8 = self.extend(Value::Map(request), &[params.clone()]);
let mut response: Value = self.sxbet_private_delete_orders_v3(&[__ws_arg_8]).await;
result = self.array_concat(result.clone(), self.parse_sxbet_cancel_response(response));
}
}
return result;
Value::Null
}
/*
* @method
* @name sxbet#cancelAllOrders
* @description cancels every resting maker order of the account, or every order of one fixture via params.eventId - v3 cancels are plain api-key-authenticated DELETE requests, no signature involved
* @see https://docs.sx.bet/api-reference/delete-orders-v3-all
* @see https://docs.sx.bet/api-reference/delete-orders-v3-event
* @param {string} [outcome] not used by sxbet.cancelAllOrders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.eventId] cancels every order across every market of this fixture instead of the account-wide path (params.sportXeventId is accepted too)
* @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
}));
self.check_required_credentials(&[]);
let mut eventId: Option<String> = self.safe_string2_opt(params.clone(), Value::Str("eventId".into()), Value::Str("sportXeventId".into()), &[]);
let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("eventId".into()), Value::Str("sportXeventId".into())]), &[]);
let mut isEventScoped: bool = eventId.is_some();
let mut response: Value = Value::Null;
if isEventScoped {
// the event route takes eventId in the QUERY string, not the body - sign() urlencodes
// body-less DELETE params
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("eventId".to_string(), eventId.clone().map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_9 = self.extend(Value::Map(request), &[rest.clone()]);
response = self.sxbet_private_delete_orders_v3_event(&[__ws_arg_9]).await;
} else {
response = self.sxbet_private_delete_orders_v3_all(&[rest.clone()]).await;
}
let mut result: Value = Value::from(vec![]);
result = self.array_concat(result.clone(), self.parse_sxbet_cancel_response(response.clone()));
// both paths paginate their async submission - keep going on the SAME route while more remain
let mut hasMore: Value = self.safe_bool(self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("hasMore".into()), &[Value::Bool(false)]);
{
let mut guard: Value = Value::Int(0);
let mut __for_first_1511: bool = true;
while { if !__for_first_1511 { if let Value::Int(n) = &mut guard { *n += 1; } } __for_first_1511 = false; guard.as_f64().unwrap_or(f64::NAN) < ((50i64) as f64) } {
if !(hasMore.as_bool() == Some(true)) {
break;
}
let mut nextResponse: Value = Value::Null;
if isEventScoped {
let mut nextRequest: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("eventId".to_string(), eventId.clone().map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_10 = self.extend(Value::Map(nextRequest), &[rest.clone()]);
nextResponse = self.sxbet_private_delete_orders_v3_event(&[__ws_arg_10]).await;
} else {
nextResponse = self.sxbet_private_delete_orders_v3_all(&[rest.clone()]).await;
}
result = self.array_concat(result.clone(), self.parse_sxbet_cancel_response(nextResponse.clone()));
hasMore = self.safe_bool(self.safe_dict_k(nextResponse, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("hasMore".into()), &[Value::Bool(false)]);
}
}
return result;
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parsePredictionOrder
* @description parses one raw GET /orders row into a unified prediction order. every sx.bet maker order is a 'buy' of the outcome it bets on (isMakerBettingOutcomeOne selects the side), priced at the maker's own implied probability
* @param {object} order the raw sx.bet order object
* @param {object} [market] the outcome object the order belongs to (resolved from the cache by outcomeId when omitted)
* @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);
//
// {
// "id": "0x112a4f19f20395aefcdb5d26f3f8aab0d96b1aff7ce346c0bfb13d9490340cdf",
// "marketHash": "0xbf06c6379c922d8118612d1d7493b20f6df6929437fbf6022904327f9516a2eb",
// "userAddress": "0xbcc6D643e4159A75ED1dB4e13330230B82F2AEe5",
// "wallet": "0x4361123dbdc1D812fdf7D27045aF358C9C8AA70A",
// "isBettingOutcomeOne": true,
// "percentageOdds": "40000000000000000000",
// "totalBetSize": "3000000",
// "remainingSize": "3000000",
// "expiry": null,
// "status": "ACTIVE",
// "inactiveReason": null,
// "eventId": "L12003787",
// "createdAt": "2026-07-31T18:45:42.636Z",
// "updatedAt": "2026-07-31T18:45:42.838Z"
// }
//
let mut orderId: Option<String> = self.safe_string2_opt(order.clone(), Value::Str("id".into()), Value::Str("orderId".into()), &[]);
let mut marketHash: Value = self.safe_string_k(order.clone(), "marketHash", &[Value::Str("".into())]);
let mut isBettingOutcomeOne: bool = self.safe_bool_k_opt(order.clone(), "isBettingOutcomeOne", &[Value::Bool(true)]).unwrap_or(true);
let mut outcomeId: Value = Value::Null;
if isBettingOutcomeOne {
outcomeId = marketHash.clone();
} else {
outcomeId = (Value::Str(format!("{}{}", marketHash, Value::Str("-2".into())).into()));
}
let mut outcomeObj: Value = self.safe_outcome(outcomeId.clone(), &[market]);
let mut oneDenom: Value = Value::Str("100000000000000000000".into());
let mut usdcDecimals: Value = Value::Str("1000000".into());
let mut percentageOdds: Option<String> = self.safe_string_k_opt(order.clone(), "percentageOdds", &[]);
let mut price: Value = (if (percentageOdds.is_some()) { self.parse_number(crate::precise::Precise::stringDiv(&percentageOdds.clone().map(Value::from).unwrap_or(Value::Null), &oneDenom), &[]) } else { Value::Null });
let mut totalBetSize: Value = self.safe_string_k(order.clone(), "totalBetSize", &[Value::Str("0".into())]);
let mut remainingSize: Value = self.safe_string_k(order.clone(), "remainingSize", &[totalBetSize.clone()]);
let mut filledRaw: Value = crate::precise::Precise::stringSub(&totalBetSize, &remainingSize);
let mut amount: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&totalBetSize, &usdcDecimals, &Value::Int(6)), &[]);
let mut filled: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&filledRaw, &usdcDecimals, &Value::Int(6)), &[]);
let mut remaining: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&remainingSize, &usdcDecimals, &Value::Int(6)), &[]);
let mut orderStatus: Option<String> = self.safe_string_upper_k(order.clone(), "status", &[]).as_str().map(str::to_owned);
let mut inactiveReason: Option<String> = self.safe_string_upper_k(order.clone(), "inactiveReason", &[]).as_str().map(str::to_owned);
let mut status: String = "open".to_string();
if (orderStatus.as_deref() == Some("INACTIVE")) {
// documented inactiveReason enum: FILLED, USER_REQUESTED, EXPIRED, NO_LIQUIDITY,
// INSUFFICIENT_BALANCE, EVENT_LIFECYCLE, MARKET_HALTED, HEARTBEAT_TIMEOUT, SYSTEM
if (inactiveReason.as_deref() == Some("FILLED")) {
status = "closed".to_string();
} else if (inactiveReason.as_deref() == Some("EXPIRED")) {
status = "expired".to_string();
} else {
status = "canceled".to_string();
}
}
let mut timestamp: Value = self.parse8601(self.safe_string_k(order.clone(), "createdAt", &[]));
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), orderId.map(Value::from).unwrap_or(Value::Null));
m.insert("clientOrderId".to_string(), self.safe_string_k(order.clone(), "clientOrderId", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), self.parse8601(self.safe_string_k(order.clone(), "updatedAt", &[])));
m.insert("status".to_string(), Value::from(status));
m.insert("type".to_string(), Value::Str("limit".into()));
m.insert("timeInForce".to_string(), Value::Null);
m.insert("side".to_string(), Value::Str("buy".into()));
m.insert("price".to_string(), price);
m.insert("average".to_string(), Value::Null);
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), remaining);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[outcomeId]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("info".to_string(), order);
m
}), &[outcomeObj]);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#clampSxbetPerPage
* @description clamps a user limit to the venue's hard perPage ceiling - every v3 listing route rejects perPage above 100, and deeper history is reachable through the nextKey cursor instead
* @param {int} limit the user-requested limit
* @returns {int} the limit clamped to at most 100
*/
pub fn clamp_sxbet_per_page(&self, mut limit: Value) -> Value {
if (limit == Value::Null) {
return limit;
}
let mut requested: Value = self.parse_to_int(limit.clone());
if requested.as_f64().unwrap_or(f64::NAN) >= ((100i64) as f64) {
return Value::Int(100);
}
return limit;
Value::Null
}
/*
* @method
* @name sxbet#fetchOpenOrders
* @description fetches the account's resting maker orders via the api-key-authenticated GET /orders-v3 (the route is hardcoded to ACTIVE orders and scoped to the key's account)
* @see https://docs.sx.bet/api-reference/get-orders-v3
* @param {string} [outcome] unified outcome or outcomeId — narrows to that outcome's market
* @param {int} [since] applied client-side (the route has no date filter; rows carry createdAt)
* @param {int} [limit] the maximum number of orders to return (server-side perPage, max 100, default 50)
* @param {object} [params] extra parameters specific to the exchange API endpoint (e.g. eventId, sortBy, sortAsc, nextKey)
* @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
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
request.insert("marketHash".into(), self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[]));
}
if (limit != Value::Null) {
request.insert("perPage".into(), self.clamp_sxbet_per_page(limit.clone()));
}
let __ws_arg_11 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.sxbet_private_get_orders_v3(&[__ws_arg_11]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawOrders: Value = self.safe_list_k(data, "orders", &[Value::from(vec![])]);
return self.parse_prediction_orders(rawOrders, &[outcomeObj, since, limit]);
Value::Null
}
/*
* @method
* @name sxbet#fetchOrders
* @description fetches the account's maker orders. sx.bet's GET /orders-v3 listing is hardcoded to ACTIVE orders — filled/cancelled/expired orders leave the listing permanently (their history is only reconstructable from fills), so this returns the same set that fetchOpenOrders returns
* @see https://docs.sx.bet/api-reference/get-orders-v3
* @param {string} [outcome] unified outcome or outcomeId — narrows to that outcome's market
* @param {int} [since] applied client-side (the route has no date filter; rows carry createdAt)
* @param {int} [limit] the maximum number of orders to return (server-side perPage, max 100, default 50)
* @param {object} [params] extra parameters specific to the exchange API endpoint (e.g. eventId, sortBy, sortAsc, nextKey)
* @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
}));
return self.fetch_open_orders(&[outcome, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name sxbet#fetchOrder
* @description fetches a single maker order by its order hash - unlike the listing, GET /orders-v3/{orderId} also serves filled, cancelled and expired orders while they still exist. a missing or foreign id 404s with 'Order not found', surfaced through handleErrors's OrderNotFound mapping
* @see https://docs.sx.bet/api-reference/get-order-v3
* @param {string} id the order hash
* @param {string} [outcome] unified outcome or outcomeId (labelling hint only, the request needs just the id)
* @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
}));
self.check_required_credentials(&[]);
if (id == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder() requires an id argument".into()))));
}
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id);
m
});
let __ws_arg_12 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.sxbet_private_get_orders_v3_order_id(&[__ws_arg_12]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut row: Value = self.safe_dict_k(data.clone(), "order", &[data.clone()]);
return self.parse_prediction_order(row, &[outcomeObj]);
Value::Null
}
/*
* @method
* @name sxbet#fetchTrades
* @description fetches the public trade tape of one outcome's market — every bettor's settled and in-flight bets on that market. the venue requires the trades listing to be scoped, so the outcome argument is mandatory
* @see https://docs.sx.bet/api-reference/get-trades-v3-public
* @param {string} outcome unified outcome or outcomeId
* @param {int} [since] timestamp in ms of the earliest trade to return — applied client-side over the newest page (the public tape serves newest-first and has no date filter; older pages are reachable through params.nextKey)
* @param {int} [limit] the maximum number of trades to return (server-side perPage, max 100, default 50)
* @param {object} [params] extra parameters specific to the exchange API endpoint (e.g. eventId, nextKey)
* @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
}));
if (outcome == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTrades() requires an outcome argument - the venue requires the trades listing to be scoped".into()))));
}
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketHash".to_string(), self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[]));
m
});
if (limit != Value::Null) {
request.insert("perPage".into(), self.clamp_sxbet_per_page(limit.clone()));
}
let __ws_arg_13 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.sxbet_public_get_trades_v3_public(&[__ws_arg_13]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawTrades: Vec<Value> = self.safe_list_k(data, "trades", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut trades: Value = Value::from(vec![]);
let mut rawTradesLength: f64 = ((rawTrades.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1512: bool = true;
while { if !__for_first_1512 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1512 = false; i.as_f64().unwrap_or(f64::NAN) < rawTradesLength } {
if let Value::Arr(__a) = &mut trades { std::sync::Arc::make_mut(__a).push(self.parse_sxbet_v3_public_trade(rawTrades.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null))); }
}
}
// the venue serves the tape newest-first - the unified contract is ascending by timestamp
trades = self.sort_by(trades.clone(), Value::Str("timestamp".into()), &[]);
let mut sym: Option<String> = self.safe_string_k_opt(outcomeObj, "outcome", &[]);
return self.filter_by_value_since_limit(trades, Value::Str("outcome".into()), &[sym.map(Value::from).unwrap_or(Value::Null), since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name sxbet#fetchMyTrades
* @description fetches the account's fills (matched legs of its own orders, both taker and maker side) via the api-key-authenticated GET /fills-v3
* @see https://docs.sx.bet/api-reference/get-fills-v3
* @param {string} [outcome] unified outcome or outcomeId — narrows to that outcome's market and drops the opposite side's legs
* @param {int} [since] timestamp in ms of the earliest fill to fetch (server-side startDate)
* @param {int} [limit] the maximum number of fills to return (server-side perPage, max 100, default 50)
* @param {object} [params] extra parameters specific to the exchange API endpoint (e.g. tradeId, orderId, endDate, sortAsc, nextKey)
* @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
}));
self.check_required_credentials(&[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
}
if (since != Value::Null) {
request.insert("startDate".into(), self.iso8601(since.clone()));
}
if (limit != Value::Null) && (outcome == Value::Null) {
// with an outcome filter the rows are narrowed client-side - a server-side page
// size would truncate the page before the filter and under-fill the result
request.insert("perPage".into(), self.clamp_sxbet_per_page(limit.clone()));
}
let __ws_arg_14 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.sxbet_private_get_fills_v3(&[__ws_arg_14]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawFills: Vec<Value> = self.safe_list_k(data, "fills", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut trades: Value = Value::from(vec![]);
let mut rawFillsLength: f64 = ((rawFills.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1513: bool = true;
while { if !__for_first_1513 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1513 = false; i.as_f64().unwrap_or(f64::NAN) < rawFillsLength } {
if let Value::Arr(__a) = &mut trades { std::sync::Arc::make_mut(__a).push(self.parse_sxbet_v3_fill(rawFills.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[])); }
}
}
trades = self.sort_by(trades.clone(), Value::Str("timestamp".into()), &[]);
let mut sym: Value = (if (outcomeObj != Value::Null) { self.safe_string_k(outcomeObj, "outcome", &[]) } else { Value::Null });
return self.filter_by_value_since_limit(trades, Value::Str("outcome".into()), &[sym, since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseSxbetV3Fill
* @description parses one GET /fills-v3 row into a unified trade - each fill is one maker/taker match of the wallet's own order
* @param {object} fill the raw fill row
* @param {object} [market] the outcome object labelling hint
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_sxbet_v3_fill(&self, mut fill: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "id": "0xec8e...:0x02d2...:0x1fec...",
// "matchId": "0xec8e...", "orderId": "0x02d2...", "tradeId": "0xac6b...",
// "marketHash": "0x1fec...", "isParlay": false,
// "userAddress": "0xbcc6...", "wallet": "0x4361...",
// "fillAmount": "333334", "fillOdds": "40000000000000000000",
// "returnAmount": "833335", "isBettingOutcomeOne": false,
// "isMaker": false, "status": "LOCKED", "txHash": "0x6430...",
// "ceRefundAmount": "0", "ceRefundFeeAmount": "0",
// "usedBetCredits": false, "createdAt": "2026-07-31T18:47:09.586Z",
// "updatedAt": "2026-07-31T18:47:12.837Z", "settlement": null
// }
//
let mut marketHash: Value = self.safe_string_k(fill.clone(), "marketHash", &[Value::Str("".into())]);
let mut isBettingOutcomeOne: bool = self.safe_bool_k_opt(fill.clone(), "isBettingOutcomeOne", &[Value::Bool(true)]).unwrap_or(true);
let mut outcomeId: Value = Value::Null;
if isBettingOutcomeOne {
outcomeId = marketHash.clone();
} else {
outcomeId = (Value::Str(format!("{}{}", marketHash, Value::Str("-2".into())).into()));
}
let mut outcomeObj: Value = self.safe_outcome(outcomeId.clone(), &[market.clone()]);
let mut oneDenom: Value = Value::Str("100000000000000000000".into());
let mut usdcDecimals: Value = Value::Str("1000000".into());
let mut fillOdds: Option<String> = self.safe_string_k_opt(fill.clone(), "fillOdds", &[]);
let mut price: Value = (if (fillOdds.is_some()) { self.parse_number(crate::precise::Precise::stringDiv(&fillOdds.clone().map(Value::from).unwrap_or(Value::Null), &oneDenom), &[]) } else { Value::Null });
let mut fillAmount: Value = self.safe_string_k(fill.clone(), "fillAmount", &[Value::Str("0".into())]);
let mut amount: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&fillAmount, &usdcDecimals, &Value::Int(6)), &[]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(fill.clone(), "createdAt", &[]));
// isMaker: true when the account's order was the resting one - absent on older rows
let mut isMaker: Option<bool> = self.safe_bool_k_opt(fill.clone(), "isMaker", &[]);
let mut takerOrMaker: Value = Value::Null;
if (isMaker.is_some()) {
takerOrMaker = (if isMaker == Some(true) { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
}
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(fill.clone(), "id", &[]));
m.insert("info".to_string(), fill.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[outcomeId]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m.insert("order".to_string(), self.safe_string_k(fill, "orderId", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), Value::Str("buy".into()));
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount.clone());
m.insert("cost".to_string(), amount);
m.insert("fee".to_string(), Value::Null);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name sxbet#fetchBalance
* @description fetches the account's order-spendable proxy balance from GET /user/balance-v3 - v3 trading capital sits inside the obv3 proxy wallet (funded via approve()), and GTC posting is checked against availableAmount. free is the spendable availableAmount, used the escrowedAmount locked behind open bets
* @see https://docs.sx.bet/api-reference/get-user-balance-v3
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut obv3: Value = self.load_sx_obv3_metadata().await;
let mut activeAsset: Value = self.safe_dict_k(obv3, "activeAsset", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut usdcAddress: Value = self.safe_string_lower_k(activeAsset, "baseToken", &[Value::Str("".into())]);
let mut response: Value = self.sxbet_private_get_user_balance_v3(&[params]).await;
//
// { "status": "success", "data": { "balances": [ {
// "userAddress": "0xC3f4...", "wallet": "0x19D1...",
// "tokenAddress": "0x1BC6...", "escrowAddress": "0x0Db3...",
// "availableAmount": "0", "pendingAvailableAmount": "0",
// "escrowedAmount": "0", "pendingEscrowAmount": "0" } ] } }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut balances: Value = self.safe_list_k(data, "balances", &[Value::from(vec![])]);
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
});
let mut usdcDecimals: Value = Value::Str("1000000".into());
let mut balancesLength: f64 = ((balances.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1514: bool = true;
while { if !__for_first_1514 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1514 = false; i.as_f64().unwrap_or(f64::NAN) < balancesLength } {
let mut row: Value = self.safe_dict(balances.clone(), i.clone(), &[]);
let mut tokenAddress: Value = self.safe_string_lower_k(row.clone(), "tokenAddress", &[Value::Str("".into())]);
// every sxbet market is denominated in the active base token, surfaced under 'USDC';
// rows of any other token keep their contract address for the code
let mut code: Value = self.safe_string_k(row.clone(), "tokenAddress", &[Value::Str("".into())]);
if (tokenAddress == usdcAddress) {
code = Value::Str("USDC".into());
}
let mut free: Value = crate::precise::Precise::stringDivPrec(&self.safe_string_k(row.clone(), "availableAmount", &[Value::Str("0".into())]), &usdcDecimals, &Value::Int(6));
let mut used: Value = crate::precise::Precise::stringDivPrec(&self.safe_string_k(row, "escrowedAmount", &[Value::Str("0".into())]), &usdcDecimals, &Value::Int(6));
result.insert(crate::runtime::stringify_param(&code), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("free".to_string(), self.parse_number(free.clone(), &[]));
m.insert("used".to_string(), self.parse_number(used.clone(), &[]));
m.insert("total".to_string(), self.parse_number(crate::precise::Precise::stringAdd(&free, &used), &[]));
m
}));
}
}
return self.safe_balance(Value::Map(result));
Value::Null
}
/*
* @method
* @name sxbet#fetchPositions
* @description fetches the account's open positions from the venue's per-market aggregates (GET /positions-v3, MATCHED and LOCKED bets by default; override with params.status - the enum is MATCHED, LOCKED, SETTLED, FAILED, and pnl is populated only when the filter is exclusively SETTLED). contracts is the total stake at risk, entryPrice the blended implied probability of the market's best-case outcome
* @see https://docs.sx.bet/api-reference/get-positions-v3
* @param {string[]} [outcomes] filter by unified outcomes or outcomeIds
* @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
}));
self.check_required_credentials(&[]);
// copy to a plain list so the transpilers and the strict null checks see one shape
let mut outcomesList: Value = (if (outcomes == Value::Null) { Value::from(vec![]) } else { outcomes });
let mut outcomesLength: f64 = ((outcomesList.len() as i64) as f64);
let mut wantedMarkets: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if outcomesLength > ((0i64) as f64) {
self.load_outcomes(&[outcomesList.clone()]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1515: bool = true;
while { if !__for_first_1515 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1515 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
let mut outcomeObj: Value = self.outcome(outcomesList.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
let mut hash: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[Value::Str("".into())]);
wantedMarkets.insert(crate::runtime::stringify_param(&hash), Value::Bool(true));
}
}
}
// open exposure lives in MATCHED and LOCKED bets - the venue requires an explicit status
// list drawn from MATCHED, LOCKED, SETTLED, FAILED
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), self.safe_string_k(params.clone(), "status", &[Value::Str("MATCHED,LOCKED".into())]));
m
});
let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("status".into())]), &[]);
let __ws_arg_15 = self.extend(Value::Map(request), &[rest]);
let mut response: Value = self.sxbet_private_get_positions_v3(&[__ws_arg_15]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawPositions: Vec<Value> = self.safe_list_k(data, "positions", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut result: Vec<Value> = Vec::new();
let mut rawPositionsLength: f64 = ((rawPositions.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1516: bool = true;
while { if !__for_first_1516 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1516 = false; i.as_f64().unwrap_or(f64::NAN) < rawPositionsLength } {
let mut raw: Value = rawPositions.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut marketHash: Value = self.safe_string_k(raw.clone(), "marketHash", &[Value::Str("".into())]);
if outcomesLength > ((0i64) as f64) {
if (self.safe_bool(Value::Map(wantedMarkets.clone()), marketHash, &[]) == Value::Null) {
continue;
}
}
result.push(self.parse_sxbet_v3_position(raw));
}
}
return Value::from(result);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseSxbetV3Position
* @description parses one GET /positions-v3 row (per-market aggregate) into a unified position on the market's best-case outcome
* @param {object} raw the raw position row
* @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub fn parse_sxbet_v3_position(&self, mut raw: Value) -> Value {
//
// {
// "marketHash": "0x8120...", "market": {...},
// "totalStake": "300000000", "maxWin": "200000000", "maxLoss": "-100000000",
// "isOutcomeOneMaxWin": true,
// "odds": {"outcomeOne": "40000000000000000000", "outcomeTwo": "50000000000000000000"},
// "pnl": null, "tradeCount": 2,
// "betTime": "2026-03-13T21:14:02.118Z", "updatedAt": "2026-03-13T22:03:41.502Z"
// }
//
let mut marketHash: Value = self.safe_string_k(raw.clone(), "marketHash", &[Value::Str("".into())]);
let mut isOutcomeOneMaxWin: bool = self.safe_bool_k_opt(raw.clone(), "isOutcomeOneMaxWin", &[Value::Bool(true)]).unwrap_or(true);
let mut outcomeId: Value = Value::Null;
if isOutcomeOneMaxWin {
outcomeId = marketHash.clone();
} else {
outcomeId = (Value::Str(format!("{}{}", marketHash, Value::Str("-2".into())).into()));
}
let mut outcomeObj: Value = self.safe_outcome(outcomeId.clone(), &[]);
let mut oneDenom: Value = Value::Str("100000000000000000000".into());
let mut usdcDecimals: Value = Value::Str("1000000".into());
let mut odds: Value = self.safe_dict_k(raw.clone(), "odds", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ownOdds: Value = Value::Null;
if isOutcomeOneMaxWin {
ownOdds = self.safe_string_k(odds.clone(), "outcomeOne", &[]);
} else {
ownOdds = self.safe_string_k(odds, "outcomeTwo", &[]);
}
let mut entryPrice: Value = (if (ownOdds != Value::Null) { self.parse_number(crate::precise::Precise::stringDiv(&ownOdds, &oneDenom), &[]) } else { Value::Null });
let mut totalStake: Value = self.safe_string_k(raw.clone(), "totalStake", &[Value::Str("0".into())]);
let mut pnl: Option<String> = self.safe_string_k_opt(raw.clone(), "pnl", &[]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(raw.clone(), "betTime", &[]));
return self.safe_prediction_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[outcomeId]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastUpdateTimestamp".to_string(), self.parse8601(self.safe_string_k(raw.clone(), "updatedAt", &[])));
m.insert("contracts".to_string(), self.parse_number(crate::precise::Precise::stringDivPrec(&totalStake, &usdcDecimals, &Value::Int(6)), &[]));
m.insert("entryPrice".to_string(), entryPrice);
m.insert("markPrice".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), Value::Null);
m.insert("realizedPnl".to_string(), (if (pnl.is_some()) { self.parse_number(crate::precise::Precise::stringDivPrec(&pnl.clone().map(Value::from).unwrap_or(Value::Null), &usdcDecimals, &Value::Int(6)), &[]) } else { Value::Null }));
m.insert("side".to_string(), Value::Str("long".into()));
m.insert("info".to_string(), raw);
m
}));
Value::Null
}
/*
* @method
* @name sxbet#fetchSettlements
* @description fetches the account's settled bets — each settled GET /trades-v3 row becomes one settlement with the resolved winner, the payout (stake / odds when won, the stake back when the market voided, zero when lost) and the realized pnl
* @see https://docs.sx.bet/api-reference/get-trades-v3
* @param {string} [outcome] filter to a single unified outcome or outcomeId
* @param {int} [since] timestamp in ms of the earliest settlement to fetch (server-side startDate on the bet time)
* @param {int} [limit] the maximum number of settlements to fetch (server-side perPage, max 100, default 50)
* @param {object} [params] extra parameters specific to the exchange API endpoint (e.g. eventId, endDate, sortAsc, nextKey)
* @returns {object[]} a list of prediction settlement structures
*/
pub async fn fetch_settlements(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("SETTLED".into()));
m
});
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
request.insert("marketHash".into(), self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[Value::Str("".into())]));
}
let mut wantedOutcomeId: Option<String> = self.safe_string_k_opt(outcomeObj, "outcomeId", &[]);
if (since != Value::Null) {
request.insert("startDate".into(), self.iso8601(since));
}
if (limit != Value::Null) && (outcome == Value::Null) {
// the outcome scope narrows rows client-side (the venue filter is per market, not
// per side) - a server-side page size would under-fill the filtered result
request.insert("perPage".into(), self.clamp_sxbet_per_page(limit));
}
let __ws_arg_16 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.sxbet_private_get_trades_v3(&[__ws_arg_16]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawTrades: Vec<Value> = self.safe_list_k(data, "trades", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut result: Vec<Value> = Vec::new();
let mut rawTradesLength: f64 = ((rawTrades.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1517: bool = true;
while { if !__for_first_1517 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1517 = false; i.as_f64().unwrap_or(f64::NAN) < rawTradesLength } {
let mut settlement: Value = self.parse_settlement(rawTrades.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[]);
if (wantedOutcomeId.is_none()) || (self.safe_string_k(settlement.clone(), "outcomeId", &[]).as_str() == wantedOutcomeId.as_deref()) {
result.push(settlement);
}
}
}
return Value::from(result);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseSettlement
* @description parses one settled GET /trades-v3 row into the unified prediction settlement shape. the raw `outcome` field carries the winner, 1 or 2, with 0 for a voided market, and the full payout of a winning bet is stake / odds (the implied probability the bettor received)
* @param {object} trade the raw settled sx.bet trade
* @param {object} [market] a resolved outcome/market hint
* @returns {object} a prediction settlement structure
*/
pub fn parse_settlement(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// TradeV3 row with a settlement sub-object:
// {
// "tradeId": "0xac6b...", "marketHash": "0x1fec...",
// "isBettingOutcomeOne": false, "totalStake": "1000000", "totalReturn": "2500000",
// "weightedAverageOdds": "40000000000000000000", "status": "SETTLED",
// "betTime": "2026-07-31T18:47:09.577Z",
// "settlement": { "outcome": 2, "settleReturnAmount": "2500000",
// "settleFeeAmount": "0", "settleCeRefundAmount": "0",
// "settleDate": "2026-08-01T00:10:00.000Z" }
// }
//
let mut marketHash: Value = self.safe_string_k(trade.clone(), "marketHash", &[Value::Str("".into())]);
let mut isBettingOutcomeOne: bool = self.safe_bool_k_opt(trade.clone(), "isBettingOutcomeOne", &[Value::Bool(true)]).unwrap_or(true);
let mut outcomeId: Value = Value::Null;
if isBettingOutcomeOne {
outcomeId = marketHash.clone();
} else {
outcomeId = (Value::Str(format!("{}{}", marketHash, Value::Str("-2".into())).into()));
}
let mut outcomeObj: Value = self.safe_outcome(outcomeId.clone(), &[market]);
let mut settlement: Value = self.safe_dict_k(trade.clone(), "settlement", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut winner: Value = self.safe_integer_k(settlement.clone(), "outcome", &[]);
let mut isVoid: bool = winner.as_f64() == Some(0.0);
let mut heldNumber: Value = (if isBettingOutcomeOne { Value::Int(1) } else { Value::Int(2) });
let mut won: Value = (if ((winner != Value::Null) && !isVoid) { (Value::Bool(winner.as_f64() == heldNumber.as_f64())) } else { Value::Null });
let mut usdcDecimals: Value = Value::Str("1000000".into());
let mut stake: Value = crate::precise::Precise::stringDivPrec(&self.safe_string_k(trade.clone(), "totalStake", &[Value::Str("0".into())]), &usdcDecimals, &Value::Int(6));
let mut payout: Value = crate::precise::Precise::stringDivPrec(&self.safe_string_k(settlement.clone(), "settleReturnAmount", &[Value::Str("0".into())]), &usdcDecimals, &Value::Int(6));
let mut pnl: Value = crate::precise::Precise::stringSub(&payout, &stake);
// resolve the winning side's human label through the cached market when available
let mut resultLabel: Value = Value::Null;
if isVoid {
resultLabel = Value::Str("VOID".into());
} else if (winner != Value::Null) {
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut labelKey: String = "outcomeTwoName".to_string();
if (winner.as_f64() == Some(1.0)) {
labelKey = "outcomeOneName".to_string();
}
resultLabel = self.safe_string(info, Value::from(labelKey), &[self.number_to_string(winner)]);
}
let mut timestamp: Value = self.parse8601(self.safe_string_k(settlement, "settleDate", &[]));
let mut settlePrice: Value = Value::Null;
if (won != Value::Null) {
settlePrice = (if won.as_bool() == Some(true) { Value::Int(1) } else { Value::Int(0) });
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), self.safe_string_k(trade, "tradeId", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[outcomeId.clone()]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[outcomeId]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m.insert("event".to_string(), Value::Null);
m.insert("result".to_string(), resultLabel);
m.insert("won".to_string(), won);
m.insert("amount".to_string(), self.parse_number(stake.clone(), &[]));
m.insert("price".to_string(), settlePrice);
m.insert("cost".to_string(), self.parse_number(stake, &[]));
m.insert("payout".to_string(), self.parse_number(payout, &[]));
m.insert("pnl".to_string(), self.parse_number(pnl, &[]));
m
});
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#fetchSxbetBookSnapshot
* @description fetches the v3 aggregated order book snapshot of one market ({outcomeOne, outcomeTwo, version} price levels)
* @see https://docs.sx.bet/api-reference/get-orderbook-snapshot
* @param {string} marketHash the market hash
* @returns {object} the raw snapshot data
*/
pub async fn fetch_sxbet_book_snapshot(&mut self, mut marketHash: Value) -> Value {
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketHash".to_string(), marketHash);
m
});
let mut response: Value = self.sxbet_public_get_orderbook_v3_snapshot(&[Value::Map(request)]).await;
return self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
/*
* @method
* @name sxbet#fetchTicker
* @description fetches the current best resting odds for a single sx.bet outcome. sx.bet is a peer-to-peer odds book (no matched-trade tape or candles), so bid/ask are the best (highest) percentageOdds resting on this outcome's own side and its mirror (1 - best percentageOdds resting on the opposite outcome)
* @see https://docs.sx.bet/api-reference/get-orderbook-snapshot
* @param {string} outcome unified outcome handle or outcomeId (marketHash or marketHash + '-2')
* @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 marketHash: Option<String> = self.safe_string_opt(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[]);
// the book snapshot is public and carries the same top of book - the batched best-odds
// route needs an apiKey, so it only pays off for the multi-market path
let mut snapshot: Value = self.fetch_sxbet_book_snapshot(marketHash.map(Value::from).unwrap_or(Value::Null)).await;
let mut raw: Value = self.parse_sxbet_snapshot_best_odds(snapshot);
return self.parse_prediction_ticker(raw, &[outcomeObj]);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#fetchSxbetBestOdds
* @description fetches the best resting level of both sides for a set of markets in one request
* @see https://docs.sx.bet/api-reference/get-best-odds-v3
* @param {string[]} marketHashes the market hashes to query, at most 100 per call
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} the raw bestOdds rows ({marketHash, outcomeOne, outcomeTwo})
*/
pub async fn fetch_sxbet_best_odds(&mut self, marketHashes: Vec<String>, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketHashes".to_string(), Value::Str(marketHashes.join(",").into()));
m
});
let __ws_arg_17 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.sxbet_private_get_orders_v3_odds_best(&[__ws_arg_17]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_list_k(data, "bestOdds", &[Value::from(vec![])]);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseSxbetSnapshotBestOdds
* @description reduces a v3 book snapshot to the legacy best-odds shape the ticker parser consumes ({marketHash, outcomeOne: {percentageOdds}, outcomeTwo: {percentageOdds}})
* @param {object} snapshot the raw snapshot data
* @returns {object} the best-odds shaped dict
*/
pub fn parse_sxbet_snapshot_best_odds(&self, mut snapshot: Value) -> Value {
let __snapshot_empty = indexmap::IndexMap::new();
let snapshot = snapshot.as_map().unwrap_or(&__snapshot_empty);
// levels arrive sorted best-first; the best level's odds mirror the v2 best-odds fields
let mut oneLevels: Value = (match snapshot.get("outcomeOne") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut twoLevels: Value = (match snapshot.get("outcomeTwo") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut bestOne: Value = self.safe_dict(oneLevels, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bestTwo: Value = self.safe_dict(twoLevels, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketHash".to_string(), (match snapshot.get("marketHash") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("outcomeOne".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("percentageOdds".to_string(), self.safe_string_k(bestOne, "percentageOdds", &[]));
m
}));
m.insert("outcomeTwo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("percentageOdds".to_string(), self.safe_string_k(bestTwo, "percentageOdds", &[]));
m
}));
m
});
Value::Null
}
/*
* @method
* @name sxbet#fetchTickers
* @description fetches the current best resting odds for multiple sx.bet outcomes, one book snapshot per market
* @see https://docs.sx.bet/api-reference/get-orderbook-snapshot
* @param {string[]} outcomes unified outcomes - required: sx.bet has thousands of markets and no endpoint returning all of them at once
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [prediction ticker structures](https://docs.ccxt.com/#/?id=prediction-ticker-structure) indexed by outcome
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcomes == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTickers() requires an outcomes argument - sx.bet has thousands of markets and serves best odds per market list".into()))));
}
let mut outcomesList: Value = outcomes;
let mut outcomesLength: f64 = ((outcomesList.len() as i64) as f64);
let mut hashesOrder: Value = Value::from(vec![]);
let mut seenHashes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1518: bool = true;
while { if !__for_first_1518 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1518 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
self.load_outcome(outcomesList.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[]).await;
let mut outcomeObj: Value = self.outcome(outcomesList.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
let mut marketHash: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[Value::Str("".into())]);
if (self.safe_bool(Value::Map(seenHashes.clone()), marketHash.clone(), &[]) == Value::Null) {
seenHashes.insert(crate::runtime::stringify_param(&marketHash), Value::Bool(true));
if let Value::Arr(__a) = &mut hashesOrder { std::sync::Arc::make_mut(__a).push(marketHash.clone()); }
}
}
}
// both outcomes of a market share one row, and the venue takes at most 100 hashes per call.
// the batched route is apiKey-authenticated, so fall back to the public per-market
// snapshots when the instance carries no credentials
let mut rowsByHash: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut hashesLength: Value = Value::Int(hashesOrder.len() as i64);
let mut hasApiKey: bool = !(self.is_empty_string(self.apiKey.clone()).as_bool() == Some(true));
if !hasApiKey {
{
let mut i: Value = Value::Int(0);
let mut __for_first_1519: bool = true;
while { if !__for_first_1519 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1519 = false; i.as_f64().unwrap_or(f64::NAN) < hashesLength.as_f64().unwrap_or(f64::NAN) } {
let mut marketHash: Value = hashesOrder.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut snapshot: Value = self.fetch_sxbet_book_snapshot(marketHash.clone()).await;
rowsByHash.insert(crate::runtime::stringify_param(&marketHash), self.parse_sxbet_snapshot_best_odds(snapshot));
}
}
return self.parse_sxbet_tickers_by_hash(outcomesList.clone(), Value::Map(rowsByHash.clone()));
}
let mut chunkSize: Value = self.safe_integer_k(self.options.clone(), "bestOddsBatchSize", &[Value::Int(100)]);
let mut chunkCount: Value = self.parse_to_int((match ((self.sum(&[hashesLength.clone(), (match (&(chunkSize), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x),
Value::Float(y)) => Value::Float(x - y), _ => Value::Null })])).as_f64(), (chunkSize).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
{
let mut c: Value = Value::Int(0);
let mut __for_first_1521: bool = true;
while { if !__for_first_1521 { if let Value::Int(n) = &mut c { *n += 1; } } __for_first_1521 = false; c.as_f64().unwrap_or(f64::NAN) < chunkCount.as_f64().unwrap_or(f64::NAN) } {
let mut chunkIndex: Value = self.parse_to_int(c.clone());
let mut chunkWidth: Value = self.parse_to_int(chunkSize.clone());
let mut start: Value = (match (&(chunkIndex), &(chunkWidth)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut nextChunkIndex: Value = (match (&(chunkIndex), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
let mut chunkEnd: Value = (match (&(nextChunkIndex), &(chunkWidth)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut end: Value = chunkEnd.clone();
if chunkEnd.as_f64().unwrap_or(f64::NAN) > hashesLength.as_f64().unwrap_or(f64::NAN) {
end = self.parse_to_int(hashesLength.clone());
}
let mut chunk: Value = self.array_slice(hashesOrder.clone(), start, &[end]);
let mut rows: Vec<Value> = self.fetch_sxbet_best_odds(chunk.to_str_vec(), &[params.clone()]).await.as_array().cloned().unwrap_or_default();
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1520: bool = true;
while { if !__for_first_1520 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_1520 = false; j.as_f64().unwrap_or(f64::NAN) < rowsLength } {
let mut row: Value = rows.get(j.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut rowHash: Option<String> = self.safe_string_k_opt(row.clone(), "marketHash", &[]);
if (rowHash.is_some()) {
rowsByHash.insert(rowHash.as_deref().unwrap_or("null").to_string(), row);
}
}
}
}
}
return self.parse_sxbet_tickers_by_hash(outcomesList, Value::Map(rowsByHash));
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseSxbetTickersByHash
* @description assembles the unified tickers dict from best-odds shaped rows keyed by market hash
* @param {string[]} outcomesList the requested unified outcomes
* @param {object} rowsByHash best-odds rows indexed by market hash
* @returns {object} a dictionary of [prediction ticker structures](https://docs.ccxt.com/#/?id=prediction-ticker-structure) indexed by outcome
*/
pub fn parse_sxbet_tickers_by_hash(&self, mut outcomesList: Value, mut rowsByHash: Value) -> Value {
let __outcomesList_empty = Vec::new();
let outcomesList = outcomesList.as_array().unwrap_or(&__outcomesList_empty);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomesLength: f64 = ((outcomesList.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1522: bool = true;
while { if !__for_first_1522 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1522 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
let mut outcomeObj: Value = self.outcome(outcomesList.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
let mut marketHash: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[Value::Str("".into())]);
let mut raw: Value = self.safe_dict(rowsByHash.clone(), marketHash, &[]);
if (raw == Value::Null) {
continue;
}
let mut ticker: Value = self.parse_prediction_ticker(raw, &[outcomeObj]);
let mut sym: Option<String> = self.safe_string_k_opt(ticker.clone(), "outcome", &[]);
if (sym.is_some()) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(sym.as_deref().unwrap_or("null").to_string(), ticker); }
}
}
}
return result;
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parsePredictionTicker
* @description parses one /orders/odds/best entry into a unified ticker for one side of the market
* @param {object} raw one bestOdds entry ({ marketHash, baseToken, outcomeOne: { percentageOdds, updatedAt }, outcomeTwo: {...} })
* @param {object} [market] the outcome object the ticker belongs to
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub fn parse_prediction_ticker(&self, mut raw: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "marketHash": "0x48ce0ef287c59fb3bb3ca6deb80de0d5791eb761ea8e16d6f03c8e93ef28d1de",
// "baseToken": "0x6629Ce1Cf35Cc1329ebB4F63202F3f197b3F050B",
// "outcomeOne": { "percentageOdds": "50250000000000000000", "updatedAt": 1785697831141 },
// "outcomeTwo": { "percentageOdds": "48000000000000000000", "updatedAt": 1785699649869 }
// }
//
let mut marketAny: Value = market.clone();
let mut outcomeObj: Value = self.safe_outcome(self.safe_string_k(marketAny.clone(), "outcome", &[]), &[marketAny]);
let mut outcomeId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]);
let mut marketHash: Value = self.safe_string_k(raw.clone(), "marketHash", &[]);
let mut isOutcomeOne: bool = outcomeId == marketHash;
let mut outcomeOneOdds: Value = self.safe_dict_k(raw.clone(), "outcomeOne", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut outcomeTwoOdds: Value = self.safe_dict_k(raw.clone(), "outcomeTwo", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ownOdds: Value = outcomeTwoOdds.clone();
if isOutcomeOne {
ownOdds = outcomeOneOdds.clone();
}
let mut oppositeOdds: Value = outcomeOneOdds;
if isOutcomeOne {
oppositeOdds = outcomeTwoOdds;
}
// percentageOdds is the maker's own implied probability * 1e20 (sx.bet protocol format);
// the opposite side's best resting maker mirrors into this outcome's ask via 1 - p
let mut oneDenom: Value = Value::Str("100000000000000000000".into());
let mut ownPercentage: Option<String> = self.safe_string_k_opt(ownOdds.clone(), "percentageOdds", &[]);
let mut oppositePercentage: Option<String> = self.safe_string_k_opt(oppositeOdds, "percentageOdds", &[]);
let mut bid: Value = (if (ownPercentage.is_some()) { self.parse_number(crate::precise::Precise::stringDiv(&ownPercentage.clone().map(Value::from).unwrap_or(Value::Null), &oneDenom), &[]) } else { Value::Null });
let mut ask: Value = (if (oppositePercentage.is_some()) { self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &crate::precise::Precise::stringDiv(&oppositePercentage.clone().map(Value::from).unwrap_or(Value::Null), &oneDenom)), &[]) } else { Value::Null });
let mut updatedAt: Value = self.safe_integer_k(ownOdds, "updatedAt", &[]);
let mut now: Value = self.milliseconds();
let mut timestamp: Value = (if (updatedAt != Value::Null) { updatedAt } else { now });
let mut average: Value = Value::Null;
if (bid != Value::Null) && (ask != Value::Null) {
average = self.parse_number(crate::precise::Precise::stringDiv(&crate::precise::Precise::stringAdd(&self.number_to_string(bid.clone()), &self.number_to_string(ask.clone())), &Value::Str("2".into())), &[]);
}
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), outcomeId);
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), bid.clone());
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), ask);
m.insert("askVolume".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), bid.clone());
m.insert("last".to_string(), bid);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), average);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("info".to_string(), raw);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name sxbet#fetchOrderBook
* @description fetches the resting maker order book for a single sx.bet outcome. bids are maker orders already betting on this outcome (priced at each maker's own implied probability, sized by their remaining stake); asks mirror the opposite outcome's maker orders (price = 1 - their implied probability, sized by how much a taker could bet against them, per sx.bet's remaining-taker-space formula) — the same YES/NO-style mirrored construction used across this codebase's other binary prediction venues
* @see https://docs.sx.bet/api-reference/get-orderbook-snapshot
* @param {string} outcome unified outcome handle or outcomeId
* @param {int} [limit] the maximum number of bids/asks to return
* @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 marketHash: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[]);
let mut outcomeId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]);
let mut isOutcomeOne: bool = outcomeId == marketHash;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketHash".to_string(), marketHash);
m
});
let __ws_arg_18 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.sxbet_public_get_orderbook_v3_snapshot(&[__ws_arg_18]).await;
let mut snapshot: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut sides: Value = self.parse_sxbet_v3_book_sides(snapshot, isOutcomeOne);
let mut sortedBids: Value = self.safe_list_k(sides.clone(), "bids", &[Value::from(vec![])]);
let mut sortedAsks: Value = self.safe_list_k(sides, "asks", &[Value::from(vec![])]);
if (limit != Value::Null) {
let mut bidsLength: f64 = ((sortedBids.len() as i64) as f64);
if limit.as_f64().unwrap_or(f64::NAN) < bidsLength {
sortedBids = self.array_slice(sortedBids.clone(), Value::Int(0), &[limit.clone()]);
}
let mut asksLength: f64 = ((sortedAsks.len() as i64) as f64);
if limit.as_f64().unwrap_or(f64::NAN) < asksLength {
sortedAsks = self.array_slice(sortedAsks.clone(), Value::Int(0), &[limit]);
}
}
let mut timestamp: Value = self.milliseconds();
return self.safe_prediction_order_book(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome]));
m.insert("bids".to_string(), sortedBids);
m.insert("asks".to_string(), sortedAsks);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("nonce".to_string(), Value::Null);
m
}), &[outcomeObj]);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseSxbetV3BookSides
* @description converts a v3 aggregated book snapshot into sorted [price, amount] bid/ask levels for one outcome; shared by fetchOrderBook and the websocket book handler
* @param {object} snapshot the raw snapshot ({outcomeOne, outcomeTwo} level lists of {percentageOdds, size})
* @param {boolean} isOutcomeOne whether the book is built for the market's outcome one
* @returns {object} a dict with sorted 'bids' and 'asks' lists
*/
pub fn parse_sxbet_v3_book_sides(&self, mut snapshot: Value, isOutcomeOne: bool) -> Value {
let __snapshot_empty = indexmap::IndexMap::new();
let snapshot = snapshot.as_map().unwrap_or(&__snapshot_empty);
let mut oneDenom: Value = Value::Str("100000000000000000000".into());
let mut usdcDecimals: Value = Value::Str("1000000".into());
let mut ownLevels: Value = (if isOutcomeOne { (match snapshot.get("outcomeOne") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) }) } else { (match snapshot.get("outcomeTwo") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) }) });
let mut oppositeLevels: Value = (if isOutcomeOne { (match snapshot.get("outcomeTwo") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) }) } else { (match snapshot.get("outcomeOne") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) }) });
let mut bids: Vec<Value> = Vec::new();
let mut ownLevelsLength: f64 = ((ownLevels.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1523: bool = true;
while { if !__for_first_1523 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1523 = false; i.as_f64().unwrap_or(f64::NAN) < ownLevelsLength } {
let mut level: Value = self.safe_dict(ownLevels.clone(), i.clone(), &[]);
let mut percentageOdds: Option<String> = self.safe_string_k_opt(level.clone(), "percentageOdds", &[]);
let mut size: Value = self.safe_string_k(level.clone(), "size", &[Value::Str("0".into())]);
let mut price: Value = self.parse_number(crate::precise::Precise::stringDiv(&percentageOdds.clone().map(Value::from).unwrap_or(Value::Null), &oneDenom), &[]);
let mut amount: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&size, &usdcDecimals, &Value::Int(6)), &[]);
bids.push(Value::from(vec![price.clone(), amount.clone()]));
}
}
let mut asks: Vec<Value> = Vec::new();
let mut oppositeLevelsLength: f64 = ((oppositeLevels.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1524: bool = true;
while { if !__for_first_1524 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1524 = false; i.as_f64().unwrap_or(f64::NAN) < oppositeLevelsLength } {
let mut level: Value = self.safe_dict(oppositeLevels.clone(), i.clone(), &[]);
let mut percentageOdds: Option<String> = self.safe_string_k_opt(level.clone(), "percentageOdds", &[]);
let mut size: Value = self.safe_string_k(level, "size", &[Value::Str("0".into())]);
// the opposite side's resting stake mirrors into this outcome's ask - the price is the
// complement, and the takeable amount follows the remaining-taker-space formula
let mut price: Value = self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &crate::precise::Precise::stringDiv(&percentageOdds.clone().map(Value::from).unwrap_or(Value::Null), &oneDenom)), &[]);
let mut ratio: Value = crate::precise::Precise::stringDivPrec(&oneDenom, &percentageOdds.clone().map(Value::from).unwrap_or(Value::Null), &Value::Int(12));
let mut remainingTaker: Value = crate::precise::Precise::stringSub(&crate::precise::Precise::stringMul(&size, &ratio), &size);
let mut amount: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&remainingTaker, &usdcDecimals, &Value::Int(6)), &[]);
asks.push(Value::from(vec![price, amount]));
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("bids".to_string(), self.sort_by(Value::from(bids), Value::Int(0), &[Value::Bool(true)]));
m.insert("asks".to_string(), self.sort_by(Value::from(asks), Value::Int(0), &[]));
m
});
Value::Null
}
pub fn set_ws_option(&self, mut group: Value, mut key: Value, mut value: Value) {
let mut entry: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
entry.insert(crate::runtime::stringify_param(&key), value);
let __ws_arg_19 = self.safe_dict(self.options.clone(), group.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
{ let __be_tmp = self.extend(__ws_arg_19, &[Value::Map(entry)]); if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&group), __be_tmp); } }
}
pub fn request_id(&self, mut url: Value) -> Value {
let mut existing: Value = self.safe_value_k(self.options.clone(), "requestId", &[]);
if (existing == Value::Null) {
{ let __be_tmp = self.create_safe_dictionary(&[]); if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("requestId".into(), __be_tmp); } }
}
let mut options: Value = self.options.as_map().and_then(|__m| __m.get("requestId")).cloned().unwrap_or(Value::Null);
let mut previousValue: Value = self.safe_integer(options.clone(), url.clone(), &[Value::Int(0)]);
let mut newValue: Value = self.sum(&[previousValue, Value::Int(1)]);
if (url != Value::Null) {
if let Value::Dict(__bf03d0) = unsafe { crate::runtime::coerce_value_to_mut(&self.options) } { let __bf03e1 = std::sync::Arc::make_mut(__bf03d0).entry("requestId".to_string()).or_insert(Value::Null); if let Value::Dict(__r05d) = __bf03e1 { std::sync::Arc::make_mut(__r05d).insert(crate::runtime::stringify_param(&url), newValue.clone()); } }
}
return newValue;
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#registerSxbetWsRequest
* @description tracks an outgoing Centrifugo connect/subscribe command by its request id, so an error reply can be correlated back to the awaiting future and its registered subscription hash (see handleCentrifugoFrame)
* @param {int} requestId the id sent with the command
* @param {string} messageHash the future hash the caller awaits
* @param {string} subscription the subscription hash registered by watch() ('connect' or the channel name)
*/
pub fn register_sxbet_ws_request(&self, mut requestId: Value, mut messageHash: Value, mut subscription: Value) {
let mut requestIdString: Value = self.number_to_string(requestId);
self.set_ws_option(Value::Str("wsPendingRequests".into()), requestIdString, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHash".to_string(), messageHash);
m.insert("subscription".to_string(), subscription);
m
}));
}
/*
* @ignore
* @method
* @name sxbet#fetchSxbetRealtimeToken
* @description fetches the short-lived Centrifugo connection token from the relayer; requires the apiKey credential (X-Api-Key header)
* @see https://docs.sx.bet/developers/realtime-initialization
* @returns {string} the JWT connection token
*/
pub async fn fetch_sxbet_realtime_token(&mut self) -> Value {
if (self.apiKey.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" websocket streaming requires the apiKey credential - the realtime token endpoint authenticates with the X-Api-Key header".into()))));
}
let mut response: Value = self.sxbet_private_get_user_realtime_token_v3_api_key(&[]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_string2(data, Value::Str("token".into()), Value::Str("realtimeToken".into()), &[self.safe_string_k(response, "token", &[])]);
Value::Null
}
pub async fn connect_sxbet_centrifugo(&mut self, mut url: Value) -> Value {
// Centrifugo requires a token-carrying connect command before any subscribe. This sends it once
// per connection and resolves when the connect reply arrives (see handleCentrifugoFrame). The base
// clears client.subscriptions on reconnect, so an absent 'connect' marker means a fresh handshake.
let mut client: Value = self.client(&[url.clone()]);
let __ch = crate::pro::ws_client::ClientHandle::from_value(client.clone());
let mut connectSent: Value = self.safe_value(__ch.subscriptions.clone(), Value::Str("connect".into()), &[]);
if (connectSent == Value::Null) {
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wsConnected".into(), Value::Bool(false)); }
let mut token: Value = self.fetch_sxbet_realtime_token().await;
let mut requestId: Value = self.request_id(url.clone());
self.register_sxbet_ws_request(requestId.clone(), Value::Str("centrifugoConnected".into()), Value::Str("connect".into()));
let mut connectMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("connect".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token".to_string(), token);
m.insert("name".to_string(), Value::Str("ccxt".into()));
m
}));
m.insert("id".to_string(), requestId);
m
});
return self.watch(url, Value::Str("centrifugoConnected".into()), &[Value::Map(connectMsg), Value::Str("connect".into())]).await;
}
if matches!(self.safe_bool_k(self.options.clone(), "wsConnected", &[Value::Bool(false)]), Value::Bool(true)) {
return Value::Null;
}
return crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str("centrifugoConnected".into())])).await;
Value::Null
}
pub async fn pong(&mut self, mut client: Value, optional_args: &[Value]) -> Value {
let mut message = get_arg(optional_args, 0, Value::Null);
// Centrifugo server pings are empty frames; reply with the same empty frame to keep the link alive
client.send(&[Value::Str("{}".into())]);
Value::Null
}
pub async fn subscribe_sxbet_channel(&mut self, mut messageHash: Value, mut channel: Value) -> Value {
let mut url: Option<String> = self.safe_string_opt(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("ws".into()), &[]);
// finish the connect handshake first so the subscribe frame follows the connect reply
self.connect_sxbet_centrifugo(url.clone().map(Value::from).unwrap_or(Value::Null)).await;
let mut requestId: Value = self.request_id(url.clone().map(Value::from).unwrap_or(Value::Null));
self.register_sxbet_ws_request(requestId.clone(), messageHash.clone(), channel.clone());
let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("subscribe".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), channel.clone());
m
}));
m.insert("id".to_string(), requestId);
m
});
return self.watch(url.map(Value::from).unwrap_or(Value::Null), messageHash, &[Value::Map(subscribeMsg), channel]).await;
Value::Null
}
pub fn handle_text_message(&mut self, mut client: Value, mut message: Value) {
let mut lines: Vec<Value> = Value::Array(if let Some(__s) = message.as_str() { __s.split("\n").map(Value::from).collect() } else { Vec::new() }).as_array().cloned().unwrap_or_default();
let mut linesLength: f64 = ((lines.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1525: bool = true;
while { if !__for_first_1525 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1525 = false; i.as_f64().unwrap_or(f64::NAN) < linesLength } {
let mut line: Value = lines.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if ((line.len() as i64) as f64) > ((0i64) as f64) {
let mut parsed: Value = json_parse(&line);
self.handle_centrifugo_frame(client.clone(), parsed);
}
}
}
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
// Centrifugo packs several commands per frame joined by newlines; a multi-command frame fails the
// base JSON.parse and arrives here in raw-string form, a single command arrives already parsed
self.handle_centrifugo_frame(client, message);
}
pub fn handle_centrifugo_frame(&mut self, mut client: Value, mut msg: Value) {
let mut __ch = crate::pro::ws_client::ClientHandle::from_value(client.clone());
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &msg { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut keys: Vec<Value> = object_keys(&msg).as_array().cloned().unwrap_or_default();
let mut keysLength: f64 = ((keys.len() as i64) as f64);
if (keysLength == 0.0) {
self.spawn(&[Value::Null.clone(), client.clone(), msg.clone()]);
return;
}
let mut requestIdString: Option<String> = match __pro_message.get("id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
let mut pendingRequests: Value = self.safe_dict_k(self.options.clone(), "wsPendingRequests", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut pendingEntry: Value = self.safe_dict(pendingRequests.clone(), requestIdString.clone().map(Value::from).unwrap_or(Value::Null), &[]);
let mut errorReply: Value = (match __pro_message.get("error").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
if (errorReply != Value::Null) {
// a rejected connect (bad or expired realtime token) or subscribe (unauthorized or
// unknown channel) - fail the awaiting future and clear the subscription hash that
// watch() registered at send time, so the next call re-sends the command instead
// of waiting forever behind a marker that will never be served
let mut error = Value::from(crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), json_stringify(&msg))));
if (pendingEntry != Value::Null) {
let mut failedHash: Option<String> = self.safe_string_k_opt(pendingEntry.clone(), "messageHash", &[]);
let mut subscription: Option<String> = self.safe_string_k_opt(pendingEntry.clone(), "subscription", &[]);
if (subscription.as_deref() == Some("connect")) {
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wsConnected".into(), Value::Bool(false)); }
}
if (subscription.is_some()) && (__ch.has_subscription(&subscription.clone().map(Value::from).unwrap_or(Value::Null))) {
__ch.remove_subscription(&subscription.clone().map(Value::from).unwrap_or(Value::Null));
}
{ let __be_tmp = self.omit(pendingRequests.clone(), requestIdString.clone().map(Value::from).unwrap_or(Value::Null), &[]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wsPendingRequests".into(), __be_tmp); } }
client.reject(&[Value::from(error.clone()), failedHash.map(Value::from).unwrap_or(Value::Null)]);
} else {
// an error that cannot be correlated to one command fails the whole connection
client.reject(&[Value::from(error)]);
}
return;
}
if (pendingEntry != Value::Null) {
// a successful command ack - the tracked request has served its purpose
{ let __be_tmp = self.omit(pendingRequests, requestIdString.map(Value::from).unwrap_or(Value::Null), &[]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wsPendingRequests".into(), __be_tmp); } }
}
let mut connectReply: Value = (match __pro_message.get("connect").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
if (connectReply != Value::Null) {
// connect acknowledged - unblock connectSxbetCentrifugo so channel subscribes can be sent
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wsConnected".into(), Value::Bool(true)); }
client.resolve(&[Value::Bool(true), Value::Str("centrifugoConnected".into())]);
return;
}
let mut push: Value = (match __pro_message.get("push").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Null });
if (push == Value::Null) {
return;
}
let mut channel: Option<String> = self.safe_string_k_opt(push.clone(), "channel", &[]);
if (channel.is_none()) {
return;
}
let mut pub_val: Value = self.safe_dict_k(push, "pub", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_value_k(pub_val, "data", &[]);
if (data == Value::Null) {
return;
}
// rows arrive either shaped like one object or like an array of objects - normalize to a list
let mut rows: Value = Value::from(vec![]);
if (matches!(&data, Value::Arr(_))) {
rows = data.clone();
} else {
rows = Value::from(vec![data]);
}
let mut parts: Value = Value::Array(if let Some(__s) = channel.as_deref() { __s.split(":").map(Value::from).collect() } else { Vec::new() });
let mut channelType: Option<String> = self.safe_string(parts, Value::Int(0), &[]).as_str().map(str::to_owned);
if (channelType.as_deref() == Some("orderbook_v3")) {
self.handle_order_book(client.clone(), rows.clone());
} else if (channelType.as_deref() == Some("best_odds_v3")) {
self.handle_ticker(client.clone(), rows.clone());
} else if (channelType.as_deref() == Some("recent_trades_v3")) {
self.handle_trades(client.clone(), rows.clone());
} else if (channelType.as_deref() == Some("account")) {
// per-account channels: account:orders_v3_#addr / account:fills_v3_#addr
if channel.as_deref().unwrap_or("").contains("orders_v3") {
self.handle_order(client.clone(), rows.clone());
} else if channel.as_deref().unwrap_or("").contains("fills_v3") {
self.handle_my_trade(client, rows);
}
}
}
/*
* @method
* @name sxbet#watchOrderBook
* @description streams the order book of an outcome - the v3 channel publishes the entire aggregated book on every update with a monotonic version, so each message replaces the held book
* @see https://docs.sx.bet/api-reference/channel-orderbook-v3
* @param {string} outcome unified outcome or outcome token id
* @param {int} [limit] the maximum number of order book entries to return
* @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 watch_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 sym: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[Value::Str("".into())]);
let mut marketHash: Value = self.safe_string(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[Value::Str("".into())]);
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("orderbook_v3:".into()), marketHash).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook::".into()), sym).into());
let mut url: Option<String> = self.safe_string_opt(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("ws".into()), &[]);
self.connect_sxbet_centrifugo(url.clone().map(Value::from).unwrap_or(Value::Null)).await;
let mut client: Value = self.client(&[url.clone().map(Value::from).unwrap_or(Value::Null)]);
let __ch = crate::pro::ws_client::ClientHandle::from_value(client.clone());
let mut isNewSubscription: bool = self.safe_value(__ch.subscriptions.clone(), channel.clone(), &[]) == Value::Null;
if (self.safe_value(self.orderbooks.clone(), sym.clone(), &[]) == Value::Null) {
// seed from the REST snapshot so the book is served before the first publication
self.set_ws_option(Value::Str("wsWatchedBooks".into()), sym.clone(), marketHash.clone());
let mut snapshot: Value = self.fetch_sxbet_book_snapshot(marketHash).await;
self.apply_sxbet_ws_snapshot(snapshot);
if (self.safe_value(self.orderbooks.clone(), sym.clone(), &[]) == Value::Null) {
let mut emptyBook: Value = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&sym), emptyBook); }
}
}
let mut requestId: Value = self.request_id(url.clone().map(Value::from).unwrap_or(Value::Null));
self.register_sxbet_ws_request(requestId.clone(), messageHash.clone(), channel.clone());
let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("subscribe".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), channel.clone());
m
}));
m.insert("id".to_string(), requestId);
m
});
let mut future: Value = self.watch(url.map(Value::from).unwrap_or(Value::Null), messageHash.clone(), &[Value::Map(subscribeMsg), channel]).await;
if isNewSubscription {
// return the freshly-seeded book immediately instead of blocking until the next publication
client.resolve(&[self.safe_value(self.orderbooks.clone(), sym, &[]), messageHash]);
}
let mut orderbook: Value = crate::exchange_stubs::ws_await_flight(&future).await;
return orderbook.limit();
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#applySxbetWsSnapshot
* @description applies one full v3 book publication ({marketHash, version, outcomeOne, outcomeTwo}) to every watched outcome of that market, honoring the monotonic version
* @param {object} snapshot the raw book publication
* @returns {string[]} the outcome handles whose books were refreshed
*/
pub fn apply_sxbet_ws_snapshot(&self, mut snapshot: Value) -> Value {
let mut marketHash: Value = self.safe_string_k(snapshot.clone(), "marketHash", &[]);
let mut version: Value = self.safe_string_k(snapshot.clone(), "version", &[Value::Str("".into())]);
let mut refreshed: Vec<Value> = Vec::new();
if (marketHash == Value::Null) {
return Value::from(refreshed);
}
let mut held: Value = self.safe_string(self.safe_dict_k(self.options.clone(), "wsBookVersions", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), marketHash.clone(), &[Value::Str("".into())]);
// versions are fixed-width numeric strings - replace only on a strictly newer publication
if (held.as_str() != Some("")) && ((match (version.as_str(), held.as_str()) { (Some(__x), Some(__y)) => (match (__x.parse::<f64>(), __y.parse::<f64>()) { (Ok(__p), Ok(__q)) => __p < __q, _ => __x < __y }) || __x == __y, (None, None) => true, _ => false })) {
return Value::from(refreshed);
}
self.set_ws_option(Value::Str("wsBookVersions".into()), marketHash.clone(), version);
let mut watchedBooks: Value = self.safe_dict_k(self.options.clone(), "wsWatchedBooks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut watchedSyms: Vec<Value> = Value::Array(watchedBooks.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).as_array().cloned().unwrap_or_default();
let mut timestamp: Value = self.milliseconds();
let mut watchedSymsLength: f64 = ((watchedSyms.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1526: bool = true;
while { if !__for_first_1526 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1526 = false; i.as_f64().unwrap_or(f64::NAN) < watchedSymsLength } {
let mut sym: Value = watchedSyms.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if (self.safe_string(watchedBooks.clone(), sym.clone(), &[]).as_str() != marketHash.as_str()) {
continue;
}
let mut outcomeObj: Value = self.outcome(sym.clone());
let mut outcomeId: Value = self.safe_string_k(outcomeObj, "outcomeId", &[]);
let mut isOutcomeOne: bool = outcomeId == marketHash;
let mut sides: Value = self.parse_sxbet_v3_book_sides(snapshot.clone(), isOutcomeOne);
let mut orderbook: Value = self.safe_value(self.orderbooks.clone(), sym.clone(), &[]);
if (orderbook == Value::Null) {
orderbook = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut self.orderbooks.clone() { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&sym), orderbook.clone()); }
}
let mut bookSnapshot: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("bids".to_string(), self.safe_list_k(sides.clone(), "bids", &[Value::from(vec![])]));
m.insert("asks".to_string(), self.safe_list_k(sides, "asks", &[Value::from(vec![])]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("nonce".to_string(), Value::Null);
m
});
orderbook.reset(Value::Map(bookSnapshot));
refreshed.push(sym);
}
}
return Value::from(refreshed);
Value::Null
}
pub fn handle_order_book(&self, mut client: Value, mut rows: Value) {
let __rows_empty = Vec::new();
let rows = rows.as_array().unwrap_or(&__rows_empty);
//
// {
// "marketHash": "0x...",
// "version": "00100000000000010015000",
// "outcomeOne": [ { "percentageOdds": "40000000000000000000", "size": "1000000" } ],
// "outcomeTwo": []
// }
//
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1528: bool = true;
while { if !__for_first_1528 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1528 = false; i.as_f64().unwrap_or(f64::NAN) < rowsLength } {
let mut refreshed: Value = self.apply_sxbet_ws_snapshot(rows.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
let mut refreshedLength: f64 = ((refreshed.len() as i64) as f64);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1527: bool = true;
while { if !__for_first_1527 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_1527 = false; j.as_f64().unwrap_or(f64::NAN) < refreshedLength } {
let mut sym: Value = refreshed.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
client.resolve(&[self.safe_value(self.orderbooks.clone(), sym.clone(), &[]), Value::Str(format!("{}{}", Value::Str("orderbook::".into()), sym).into())]);
}
}
}
}
}
/*
* @method
* @name sxbet#watchTicker
* @description streams best-odds updates of an outcome; the venue channel is global, entries are filtered down to the requested outcome's market
* @see https://docs.sx.bet/api-reference/channel-best-odds-v3
* @param {string} outcome unified outcome or 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 watch_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 sym: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[Value::Str("".into())]);
let mut marketHash: Option<String> = self.safe_string_opt(outcomeObj.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("marketHash".into()), &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker::".into()), sym).into());
self.set_ws_option(Value::Str("wsWatchedTickers".into()), sym.clone(), marketHash.clone().map(Value::from).unwrap_or(Value::Null));
let mut url: Option<String> = self.safe_string_opt(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("ws".into()), &[]);
self.connect_sxbet_centrifugo(url.clone().map(Value::from).unwrap_or(Value::Null)).await;
let mut client: Value = self.client(&[url.clone().map(Value::from).unwrap_or(Value::Null)]);
let mut channel: String = "best_odds_v3:global".to_string();
let mut hydrated: bool = false;
if (self.safe_dict(self.safe_dict_k(self.options.clone(), "wsTickers", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), sym.clone(), &[]) == Value::Null) {
// hydrate from the REST snapshot so the first call does not hang until the
// market's next top-of-book change - the channel is global, so the seed must fire
// for every newly watched market, not only on a fresh subscription
let mut snapshot: Value = self.fetch_sxbet_book_snapshot(marketHash.map(Value::from).unwrap_or(Value::Null)).await;
let mut raw: Value = self.parse_sxbet_snapshot_best_odds(snapshot);
let mut ticker: Value = self.parse_prediction_ticker(raw, &[outcomeObj]);
self.set_ws_option(Value::Str("wsTickers".into()), sym.clone(), ticker);
hydrated = true;
}
let mut requestId: Value = self.request_id(url.clone().map(Value::from).unwrap_or(Value::Null));
self.register_sxbet_ws_request(requestId.clone(), messageHash.clone(), Value::from(channel.clone()));
let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("subscribe".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::from(channel.clone()));
m
}));
m.insert("id".to_string(), requestId);
m
});
let mut future: Value = self.watch(url.map(Value::from).unwrap_or(Value::Null), messageHash.clone(), &[Value::Map(subscribeMsg), Value::from(channel)]).await;
if hydrated {
let __ws_arg_20 = self.safe_dict_k(self.options.clone(), "wsTickers", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
client.resolve(&[self.safe_dict(__ws_arg_20, sym, &[]), messageHash]);
}
let mut tickerResult: Value = crate::exchange_stubs::ws_await_flight(&future).await;
return tickerResult;
Value::Null
}
pub fn handle_ticker(&self, mut client: Value, mut rows: Value) {
//
// {
// "marketHash": "0xbf06...16a2eb",
// "outcomeOne": { "percentageOdds": "40000000000000000000", "size": "1000000" },
// "outcomeTwo": null
// }
//
let mut watchedTickers: Value = self.safe_dict_k(self.options.clone(), "wsWatchedTickers", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut watchedSyms: Vec<Value> = Value::Array(watchedTickers.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).as_array().cloned().unwrap_or_default();
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1530: bool = true;
while { if !__for_first_1530 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1530 = false; i.as_f64().unwrap_or(f64::NAN) < rowsLength } {
let mut entry: Value = self.safe_dict(rows.clone(), i.clone(), &[]);
let mut marketHash: Option<String> = self.safe_string_k_opt(entry.clone(), "marketHash", &[]);
if (marketHash.is_none()) {
continue;
}
// every publication carries BOTH sides (null = no resting liquidity), so the legacy
// best-odds shape rebuilds directly without any merge cache
let mut bestOne: Value = self.safe_dict_k(entry.clone(), "outcomeOne", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bestTwo: Value = self.safe_dict_k(entry, "outcomeTwo", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut raw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketHash".to_string(), marketHash.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("outcomeOne".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("percentageOdds".to_string(), self.safe_string_k(bestOne, "percentageOdds", &[]));
m
}));
m.insert("outcomeTwo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("percentageOdds".to_string(), self.safe_string_k(bestTwo, "percentageOdds", &[]));
m
}));
m
});
let mut watchedSymsLength: f64 = ((watchedSyms.len() as i64) as f64);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1529: bool = true;
while { if !__for_first_1529 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_1529 = false; j.as_f64().unwrap_or(f64::NAN) < watchedSymsLength } {
let mut sym: Value = watchedSyms.get(j.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if (self.safe_string(watchedTickers.clone(), sym.clone(), &[]).as_str() != marketHash.as_deref()) {
continue;
}
let mut outcomeObj: Value = self.outcome(sym.clone());
let mut ticker: Value = self.parse_prediction_ticker(Value::Map(raw.clone()), &[outcomeObj]);
self.set_ws_option(Value::Str("wsTickers".into()), sym.clone(), ticker.clone());
client.resolve(&[ticker, Value::Str(format!("{}{}", Value::Str("ticker::".into()), sym).into())]);
}
}
}
}
}
/*
* @method
* @name sxbet#watchTrades
* @description streams public bets of an outcome; the venue channel is global, entries are filtered down to the requested outcome
* @see https://docs.sx.bet/api-reference/channel-recent-trades-v3
* @param {string} outcome unified outcome or outcome token id
* @param {int} [since] timestamp in ms of the earliest trade to return
* @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 watch_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 sym: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trades::".into()), sym).into());
let mut trades: Value = self.subscribe_sxbet_channel(messageHash, Value::Str("recent_trades_v3:global".into())).await;
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#parseSxbetV3PublicTrade
* @description parses one recent_trades_v3 publication (public TradeV3 shape) into a unified trade
* @param {object} trade the raw public trade row
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_sxbet_v3_public_trade(&self, mut trade: Value) -> Value {
let mut marketHash: Value = self.safe_string_k(trade.clone(), "marketHash", &[Value::Str("".into())]);
let mut isBettingOutcomeOne: bool = self.safe_bool_k_opt(trade.clone(), "isBettingOutcomeOne", &[Value::Bool(true)]).unwrap_or(true);
let mut outcomeId: Value = Value::Null;
if isBettingOutcomeOne {
outcomeId = marketHash.clone();
} else {
outcomeId = (Value::Str(format!("{}{}", marketHash, Value::Str("-2".into())).into()));
}
let mut outcomeObj: Value = self.safe_outcome(outcomeId.clone(), &[]);
let mut oneDenom: Value = Value::Str("100000000000000000000".into());
let mut usdcDecimals: Value = Value::Str("1000000".into());
let mut odds: Option<String> = self.safe_string_k_opt(trade.clone(), "weightedAverageOdds", &[]);
let mut price: Value = (if (odds.is_some()) { self.parse_number(crate::precise::Precise::stringDiv(&odds.clone().map(Value::from).unwrap_or(Value::Null), &oneDenom), &[]) } else { Value::Null });
let mut stake: Value = self.safe_string_k(trade.clone(), "totalStake", &[Value::Str("0".into())]);
let mut amount: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&stake, &usdcDecimals, &Value::Int(6)), &[]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(trade.clone(), "betTime", &[]));
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "tradeId", &[]));
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[outcomeId]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), Value::Str("buy".into()));
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount.clone());
m.insert("cost".to_string(), amount);
m.insert("fee".to_string(), Value::Null);
m
}), &[]);
Value::Null
}
pub fn handle_trades(&mut self, mut client: Value, mut rows: Value) {
let __rows_empty = Vec::new();
let rows = rows.as_array().unwrap_or(&__rows_empty);
//
// { "trade": { "tradeId": "0xac6b...", "marketHash": "0x1fec...", "isBettingOutcomeOne": true,
// "totalStake": "1000000", "weightedAverageOdds": "40000000000000000000",
// "betTime": "2026-07-31T18:22:41.000Z", ... } }
//
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1531: bool = true;
while { if !__for_first_1531 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1531 = false; i.as_f64().unwrap_or(f64::NAN) < rowsLength } {
let mut rawRow: Value = rows.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut row: Value = self.safe_dict_k(rawRow.clone(), "trade", &[rawRow.clone()]);
let mut trade: Value = self.parse_sxbet_v3_public_trade(row);
let mut sym: Option<String> = self.safe_string_k_opt(trade.clone(), "outcome", &[]);
if (sym.is_none()) {
continue;
}
if (self.trades.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.trades = __t; }
}
if (self.safe_value(self.trades.clone(), sym.clone().map(Value::from).unwrap_or(Value::Null), &[]) == Value::Null) {
let mut tradesLimit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(sym.as_deref().unwrap_or("null").to_string(), ArrayCache::new(tradesLimit)); }
}
let mut stored: Value = (if let (Some(__m), Some(__k)) = (self.trades.as_map(), sym.as_deref()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
stored.append(trade);
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("trades::".into()), sym.map(Value::from).unwrap_or(Value::Null)).into())]);
}
}
}
/*
* @method
* @name sxbet#watchMyTrades
* @description streams the authenticated wallet's fills over its per-account v3 channel
* @see https://docs.sx.bet/api-reference/channel-fills-v3
* @param {string} [outcome] unified outcome or outcome token id to narrow the stream down to
* @param {int} [since] timestamp in ms of the earliest trade to return
* @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 watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchMyTrades() requires a walletAddress".into()))));
}
let mut messageHash: Value = Value::Str("myTrades".into());
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let sym: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
messageHash = Value::Str(format!("{}{}", Value::Str("myTrades::".into()), sym).into());
}
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("account:fills_v3_#".into()), self.walletAddress.clone()).into());
let mut trades: Value = self.subscribe_sxbet_channel(messageHash, channel).await;
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
pub fn handle_my_trade(&mut self, mut client: Value, mut rows: Value) {
let __rows_empty = Vec::new();
let rows = rows.as_array().unwrap_or(&__rows_empty);
//
// FillV3 rows - identical to GET /fills-v3
//
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1532: bool = true;
while { if !__for_first_1532 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1532 = false; i.as_f64().unwrap_or(f64::NAN) < rowsLength } {
let mut rawRow: Value = rows.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut row: Value = self.safe_dict_k(rawRow.clone(), "fill", &[rawRow.clone()]);
let mut trade: Value = self.parse_sxbet_v3_fill(row, &[]);
let mut sym: Option<String> = self.safe_string_k_opt(trade.clone(), "outcome", &[]);
if (sym.is_none()) {
continue;
}
if (self.myTrades.clone() == Value::Null) {
let mut myTradesLimit: Value = self.safe_integer_k(self.options.clone(), "myTradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheByOutcomeById::new(myTradesLimit);
}
let mut stored: Value = self.myTrades.clone();
stored.append(trade);
client.resolve(&[stored.clone(), Value::Str("myTrades".into())]);
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("myTrades::".into()), sym.map(Value::from).unwrap_or(Value::Null)).into())]);
}
}
}
/*
* @method
* @name sxbet#watchOrders
* @description streams updates of the authenticated wallet's orders over its per-account v3 channel
* @see https://docs.sx.bet/api-reference/channel-orders-v3
* @param {string} [outcome] unified outcome or outcome token id to narrow the stream down to
* @param {int} [since] timestamp in ms of the earliest order to return
* @param {int} [limit] the maximum number of orders to return
* @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 watch_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 (self.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchOrders() requires a walletAddress".into()))));
}
let mut messageHash: Value = Value::Str("orders".into());
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let sym: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
messageHash = Value::Str(format!("{}{}", Value::Str("orders::".into()), sym).into());
}
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("account:orders_v3_#".into()), self.walletAddress.clone()).into());
let mut orders: Value = self.subscribe_sxbet_channel(messageHash, channel).await;
return self.filter_by_since_limit(orders, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
pub fn handle_order(&mut self, mut client: Value, mut rows: Value) {
let __rows_empty = Vec::new();
let rows = rows.as_array().unwrap_or(&__rows_empty);
//
// OrderV3 rows - identical to GET /orders-v3 (plus INACTIVE states with inactiveReason)
//
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1533: bool = true;
while { if !__for_first_1533 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1533 = false; i.as_f64().unwrap_or(f64::NAN) < rowsLength } {
let mut rawRow: Value = rows.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut row: Value = self.safe_dict_k(rawRow.clone(), "order", &[rawRow.clone()]);
let mut order: Value = self.parse_prediction_order(row, &[]);
if (self.orders.clone() == Value::Null) {
let mut cacheLimit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheByOutcomeById::new(cacheLimit);
}
let mut stored: Value = self.orders.clone();
stored.append(order.clone());
client.resolve(&[stored.clone(), Value::Str("orders".into())]);
let mut sym: Option<String> = self.safe_string_k_opt(order, "outcome", &[]);
if (sym.is_some()) {
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("orders::".into()), sym.map(Value::from).unwrap_or(Value::Null)).into())]);
}
}
}
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
// sx.bet returns { "error": "Bad Request", "message": <code or [strings]>, "statusCode": 4xx }
// map the known codes to ccxt errors so callers can distinguish a rejected order or a
// validation problem from a transport outage (the base otherwise maps a bare 4xx to the
// exchange-not-available error). unmapped codes fall through to the base http-status handling
if (response == Value::Null) {
return Value::Null;
}
let mut message: Value = self.safe_value_k(response, "message", &[]);
if (message == Value::Null) {
return Value::Null;
}
// validation failures arrive in string-array form, business errors in single-code-string form
let mut messageString: Value = Value::Null;
if (matches!(&message, Value::Arr(_))) {
messageString = join(&message, &Value::Str(", ".into()));
} else {
messageString = message;
}
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), messageString.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), messageString, feedback.clone());
// a 400 is a client-side bad request (bad params, invalid order), not a transport outage —
// throw BadRequest instead of letting the base map the bare 400 to a retryable network-unavailable error
if (code.as_f64() == Some(400.0)) {
panic!("{}", crate::exchange_errors::bad_request(feedback));
}
return Value::Null;
Value::Null
}
/*
* @ignore
* @method
* @name sxbet#sign
* @description builds the request url and attaches the x-sx-api-key header; every private v3 route authenticates with the apiKey credential, so its absence fails fast instead of surfacing a raw 401
* @param {string} path the endpoint path
* @param {string[]} api the api group and access level
* @param {string} method the http method
* @param {object} params the request parameters
* @returns {object} a dict with url, method, body and headers
*/
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("sxbet".into())]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiGroup: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut accessLevel: Option<String> = api.get(1).and_then(Value::as_str).map(str::to_owned);
if (accessLevel.as_deref() == Some("private")) && (self.apiKey.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), path).into()), Value::Str(" is a private endpoint and requires the apiKey credential (the x-sx-api-key header)".into()))));
}
let mut baseUrls: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null);
let mut baseUrl: Value = self.safe_string(baseUrls.clone(), apiGroup, &[baseUrls.as_map().and_then(|__m| __m.get("sxbet")).cloned().unwrap_or(Value::Null)]);
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseUrl, Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
let mut query: Value = self.omit(params, self.extract_params(path), &[]);
let mut existingHeaders: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut headersExtended: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Accept".to_string(), Value::Str("application/json".into()));
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m
}), &[Value::Map(existingHeaders)]);
if (self.apiKey.clone() != Value::Null) {
add_element_to_object(&mut headersExtended, &Value::Str("x-sx-api-key".into()), self.apiKey.clone());
}
// DELETE /orders-v3 carries its order ids in a JSON body; the other DELETE routes -
// /orders-v3/all and /orders-v3/event - take query parameters, like every GET
let mut sendAsQuery: bool = method.as_str() == Some("GET");
if (method.as_str() == Some("DELETE")) {
sendAsQuery = !(matches!(&query, Value::Dict(__d) if __d.contains_key("orders")));
}
let mut bodyValue: Value = Value::Null;
if sendAsQuery {
let mut querystring: Value = self.urlencode(query.clone(), &[]);
if (querystring.as_str() != Some("")) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), querystring).into())).into());
}
} else {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
bodyValue = json_stringify(&query);
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), bodyValue);
m.insert("headers".to_string(), headersExtended);
m
});
Value::Null
}
}