// 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 BinanceCore {
pub exchange: crate::prediction_exchange::PredictionExchange,
}
impl BinanceCore {
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 = BinanceCore::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 BinanceCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on BinanceCore.
BinanceCore::nonce(self, )
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BinanceCore.
BinanceCore::parse_prediction_trade(self, trade, &[market])
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BinanceCore.
BinanceCore::parse_prediction_order(self, order, &[market])
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BinanceCore.
BinanceCore::parse_prediction_position(self, position, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on BinanceCore.
BinanceCore::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 BinanceCore.
BinanceCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for BinanceCore {
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 {
"amount_to_precision" => self.amount_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"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,
"complete_raw_topics" => self.complete_raw_topics(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"create_market_order_with_cost" => self.create_market_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"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_event" => self.fetch_event(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_events" => self.fetch_events(&args[..]).await,
"fetch_events_by_query" => self.fetch_events_by_query(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).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_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_quote" => self.fetch_quote(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_raw_topic_detail" => self.fetch_raw_topic_detail(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_raw_topics" => self.fetch_raw_topics(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_wallet" => self.fetch_wallet(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"nonce" => self.nonce(),
"parse_event" => self.parse_event(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_position" => self.parse_prediction_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_trade" => self.parse_prediction_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_topic_market" => self.parse_topic_market(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"price_to_precision" => self.price_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
// 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 BinanceCore {
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 BinanceCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}
impl std::ops::DerefMut for BinanceCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.exchange) }
}
impl BinanceCore {
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("binance".into()));
m.insert("name".to_string(), Value::Str("Binance".into()));
m.insert("countries".to_string(), Value::from(vec![]));
m.insert("rateLimit".to_string(), Value::Int(5));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(false));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
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("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("prediction".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/e9419b93-ccb0-46aa-9bff-c883f096274b".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sapi".to_string(), Value::Str("https://api.binance.com/sapi/v1/w3w/wallet/prediction".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.binance.com/en/markets/prediction".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading".into())]));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sapi".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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("category/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("market/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("market/search".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("market/detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("order-book".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("order-book/last-trade-price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("wallet/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("balance/payment-options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("quota/limit/status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("pnl/portfolio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("pnl/query".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("position/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("position/filter".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("position/token".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("position/settled-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("order/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("order/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/get-quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("trade/place-order-bundle".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("trade/batch-cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(true));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("maker".to_string(), Value::Int(0));
m.insert("taker".to_string(), Value::Float(0.02));
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("-1003".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("-1021".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("-1022".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-1102".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1121".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("-2008".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-2014".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-2015".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-2010".to_string(), Value::Str("InsufficientFunds".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("insufficient balance".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("Order does not exist".to_string(), Value::Str("InvalidOrder".into()).clone());
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultVendor".to_string(), Value::Str("PREDICT_FUN".into()));
m.insert("fetchOutcomeSearchLimit".to_string(), Value::Int(10));
m.insert("maxFetchEventsResults".to_string(), Value::Int(25));
m.insert("marketsPageLimit".to_string(), Value::Int(100));
m.insert("maxFetchMarketsLimit".to_string(), Value::Int(200));
m.insert("loadAllOutcomes".to_string(), Value::Bool(false));
m.insert("allowUnscopedFetchEvents".to_string(), Value::Bool(true));
m.insert("eventScopeParams".to_string(), Value::from(vec![Value::Str("l1Category".into()), Value::Str("l2Category".into())]));
m
}));
m
})]);
Value::Null
}
pub fn nonce(&self) -> Value {
return self.milliseconds();
Value::Null
}
/*
* @method
* @name binance#fetchMarkets
* @description fetches binance prediction markets; with a query it resolves the query via the search endpoint and returns the matched topics' markets, otherwise it pages the market listing
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.query] a single search query resolved against the market search endpoint
* @param {string[]} [params.queries] multiple search queries (alternative to query)
* @param {string} [params.l1Category] filter the listing by a level-1 category id (see the category/list endpoint)
* @param {string} [params.l2Category] filter the listing by a level-2 category id
* @param {int} [params.limit] for an unscoped listing (no query), the max number of topics to collect (defaults to options.maxFetchMarketsLimit, 200)
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
if queriesLength > ((0i64) as f64) {
let mut eventParams: Value = self.omit(params.clone(), Value::from(vec![Value::Str("limit".into())]), &[]);
let mut events: Value = self.fetch_events(&[eventParams]).await;
let mut eventsLength: f64 = ((events.len() as i64) as f64);
let mut queryMarkets: Value = Value::from(vec![]);
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1160: bool = true;
while { if !__for_first_1160 { ei = (match (&(ei), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1160 = false; ei.as_f64().unwrap_or(f64::NAN) < eventsLength } {
let mut eventMarkets: Value = self.safe_list(events.as_array().and_then(|__arr| match &ei { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), Value::Str("markets".into()), &[Value::from(vec![])]);
let mut eventMarketsLength: f64 = ((eventMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1159: bool = true;
while { if !__for_first_1159 { mi = (match (&(mi), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1159 = false; mi.as_f64().unwrap_or(f64::NAN) < eventMarketsLength } {
append_to_array(&mut queryMarkets, eventMarkets.as_array().and_then(|__arr| match &mi { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
}
}
}
}
return queryMarkets;
}
let mut maxMarkets: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("maxFetchMarketsLimit".into()), &[Value::Int(200)])]);
let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("query".into()), Value::Str("queries".into()), Value::Str("limit".into())]), &[]);
let mut rawTopics: Value = self.fetch_raw_topics(maxMarkets, &[rest]).await;
let mut parsedEvents: Value = Value::from(vec![]);
let mut flatMarkets: Value = Value::from(vec![]);
let mut rawTopicsLength: f64 = ((rawTopics.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1162: bool = true;
while { if !__for_first_1162 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1162 = false; i.as_f64().unwrap_or(f64::NAN) < rawTopicsLength } {
let mut parsedEvent: Value = self.parse_event(rawTopics.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));
append_to_array(&mut parsedEvents, parsedEvent.clone());
let mut eventMarkets: Value = self.safe_list_k(parsedEvent, "markets", &[Value::from(vec![])]);
let mut eventMarketsLength: f64 = ((eventMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1161: bool = true;
while { if !__for_first_1161 { mi = (match (&(mi), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1161 = false; mi.as_f64().unwrap_or(f64::NAN) < eventMarketsLength } {
append_to_array(&mut flatMarkets, eventMarkets.as_array().and_then(|__arr| match &mi { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
}
}
}
}
self.set_events(parsedEvents);
return flatMarkets;
Value::Null
}
/*
* @ignore
* @method
* @name binance#fetchRawTopics
* @description pages the market/list endpoint and returns up to `maxTopics` raw market topics
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#list-prediction-markets
* @param {int} maxTopics stop collecting once this many topics are gathered
* @param {object} [rest] extra params forwarded verbatim to the listing endpoint (l1Category, l2Category, sortBy, orderBy)
* @returns {object[]} raw market topic objects
*/
pub async fn fetch_raw_topics(&mut self, mut maxTopics: Value, optional_args: &[Value]) -> Value {
let mut rest = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut maxTopicsResolved: Value = (if (maxTopics == Value::Null) { self.safe_integer_k(self.options.clone(), "maxFetchMarketsLimit", &[Value::Int(200)]) } else { maxTopics });
let mut pageLimit: Value = self.safe_integer_k(self.options.clone(), "marketsPageLimit", &[Value::Int(100)]);
if pageLimit.as_f64().unwrap_or(f64::NAN) > ((100i64) as f64) {
pageLimit = Value::Int(100);
}
let mut collected: Value = Value::from(vec![]);
let mut offset: Value = Value::Int(0);
loop {
let mut reqLimit: Value = pageLimit.clone();
let mut collectedLength: Value = Value::Int(collected.len() as i64);
let mut remaining: Value = (match (&(maxTopicsResolved), &(collectedLength)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
if remaining.as_f64().unwrap_or(f64::NAN) < reqLimit.as_f64().unwrap_or(f64::NAN) {
reqLimit = remaining;
}
if reqLimit.as_f64().unwrap_or(f64::NAN) <= ((0i64) as f64) {
break;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("offset".to_string(), offset.clone());
m.insert("limit".to_string(), reqLimit.clone());
m
});
let __ws_arg_0 = self.extend(request, &[rest.clone()]);
let mut response: Value = self.sapi_private_get_market_list(&[__ws_arg_0]).await;
//
// {
// "marketTopics": [
// {
// "marketTopicId": 4229564,
// "vendor": "PREDICT_FUN",
// "chainId": "56",
// "slug": "btc-price-1h-up-or-down",
// "title": "BTC Price 1h Up or Down?",
// "question": "Will BTC price go UP?",
// "topicType": "FLAT",
// "chartType": "CRYPTO_UP_DOWN",
// "symbol": "BTCUSDT",
// "participantCount": 3420,
// "collateral": "USDT",
// "feeRateBps": 200,
// "slippageBps": 1200,
// "tradeVolume": "158234.56",
// "liquidity": "45000.00",
// "publishedAt": 1748100000000,
// "startDate": 1748131200000,
// "endDate": 1748134800000,
// "status": "REGISTERED",
// "markets": []
// }
// ],
// "total": 128,
// "offset": 0,
// "limit": 20,
// "hasMore": true
// }
//
let mut pageTopics: Value = self.safe_list_k(response.clone(), "marketTopics", &[Value::from(vec![])]);
let mut pageTopicsLength: Value = Value::Int(pageTopics.len() as i64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1163: bool = true;
while { if !__for_first_1163 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1163 = false; i.as_f64().unwrap_or(f64::NAN) < pageTopicsLength.as_f64().unwrap_or(f64::NAN) } {
append_to_array(&mut collected, pageTopics.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 hasMore: Value = self.safe_bool_k(response, "hasMore", &[Value::Bool(false)]);
if (hasMore.as_bool() != Some(true)) || (pageTopicsLength.as_f64().unwrap_or(f64::NAN) < reqLimit.as_f64().unwrap_or(f64::NAN)) {
break;
}
offset = self.sum(&[offset.clone(), pageTopicsLength]);
}
return collected;
Value::Null
}
/*
* @ignore
* @method
* @name binance#fetchRawTopicDetail
* @description fetches a single raw market topic (with nested markets and outcome tokens) by its id
* @param {string} topicId the marketTopicId
* @param {object} [params] extra params forwarded verbatim to the detail endpoint
* @returns {object} the raw market topic object
*/
pub async fn fetch_raw_topic_detail(&mut self, mut topicId: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketTopicId".to_string(), topicId);
m
});
let __ws_arg_1 = self.extend(request, &[params]);
return self.sapi_private_get_market_detail(&[__ws_arg_1]).await;
Value::Null
}
/*
* @ignore
* @method
* @name binance#completeRawTopics
* @description ensures each raw topic carries fully-populated nested markets (with outcome token ids), fetching the topic detail when the listing/search payload omitted them
* @param {object[]} rawTopics raw market topic objects
* @returns {object[]} raw market topic objects with usable nested markets
*/
pub async fn complete_raw_topics(&mut self, mut rawTopics: Value) -> Value {
let mut result: Value = Value::from(vec![]);
let mut rawTopicsLength: f64 = ((rawTopics.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1164: bool = true;
while { if !__for_first_1164 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1164 = false; i.as_f64().unwrap_or(f64::NAN) < rawTopicsLength } {
let mut rawTopic: Value = rawTopics.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 rawMarkets: Value = self.safe_list_k(rawTopic.clone(), "markets", &[Value::from(vec![])]);
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
let mut hasOutcomes: bool = false;
if rawMarketsLength > ((0i64) as f64) {
let mut firstMarket: Value = self.safe_dict(rawMarkets, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut firstOutcomes: Value = self.safe_list_k(firstMarket, "outcomes", &[Value::from(vec![])]);
let mut firstOutcomesLength: f64 = ((firstOutcomes.len() as i64) as f64);
hasOutcomes = firstOutcomesLength > ((0i64) as f64);
}
if hasOutcomes {
append_to_array(&mut result, rawTopic.clone());
} else {
let mut topicId: Value = self.safe_string_k(rawTopic, "marketTopicId", &[]);
if (topicId != Value::Null) {
let mut detail: Value = self.fetch_raw_topic_detail(topicId, &[]).await;
append_to_array(&mut result, detail);
}
}
}
}
return result;
Value::Null
}
/*
* @method
* @name binance#fetchEvents
* @description fetches prediction-market events (market topics); the call must be scoped by query/queries/tags, eventId, or an l1Category/l2Category listing filter
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.query] a free-text search resolved against the semantic market search endpoint
* @param {string[]} [params.queries] multiple free-text searches (alternative to query)
* @param {string[]} [params.tags] treated as additional free-text searches (binance has no tag taxonomy)
* @param {string} [params.eventId] a marketTopicId, fetched directly via the detail endpoint
* @param {string} [params.l1Category] scope the listing server-side by a level-1 category id
* @param {string} [params.l2Category] scope the listing server-side by a level-2 category id
* @param {int} [params.limit] the maximum number of events to return
* @param {string} [params.sort] 'volume' | 'liquidity' | 'newest' (client-side)
* @param {string} [params.status] 'active' | 'closed' | 'all' (client-side)
* @param {string} [params.sortBy] sort events by server side ('RECOMMENDED' | 'VOLUME' | 'PARTICIPANTS' | 'CREATED_TIME' | 'END_DATE'), works when no queries and eventId provided
* @param {string} [params.orderBy] order events by server side ('ASC' | 'DESC'), works when no queries and eveitId provided
* @returns {object[]} a list of [prediction event structures](https://docs.ccxt.com/#/?id=prediction-event-structure)
*/
pub async fn fetch_events(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut allowUnscopedFetchEvents: Value = self.safe_bool_k(self.options.clone(), "allowUnscopedFetchEvents", &[Value::Bool(false)]);
if (allowUnscopedFetchEvents.as_bool() != Some(true)) {
self.require_event_query(&[params.clone()]);
}
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
// binance has no tag taxonomy — resolve requested tags through the semantic search too
let mut tags: Value = self.safe_list_k(params.clone(), "tags", &[Value::from(vec![])]);
let mut tagsLength: f64 = ((tags.len() as i64) as f64);
let mut allQueries: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1165: bool = true;
while { if !__for_first_1165 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1165 = false; i.as_f64().unwrap_or(f64::NAN) < ((queries.len() as i64) as f64) } {
append_to_array(&mut allQueries, queries.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 i: Value = Value::Int(0);
let mut __for_first_1166: bool = true;
while { if !__for_first_1166 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1166 = false; i.as_f64().unwrap_or(f64::NAN) < tagsLength } {
append_to_array(&mut allQueries, tags.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 allQueriesLength: f64 = ((allQueries.len() as i64) as f64);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("query".into()), Value::Str("queries".into())]), &[]);
// keys dropped before the client-side pass; a server-side sort also drops its own keys
let mut postOmitKeys: Value = Value::from(vec![Value::Str("tags".into()), Value::Str("l1Category".into()), Value::Str("l2Category".into())]);
let mut userLimit: Value = self.safe_integer_k(paramsOmitted.clone(), "limit", &[]);
let mut fetchCap: Value = self.safe_integer_k(self.options.clone(), "maxFetchEventsResults", &[Value::Int(100)]);
if (userLimit != Value::Null) {
fetchCap = userLimit;
}
let mut rest: Value = self.omit(paramsOmitted.clone(), Value::from(vec![Value::Str("status".into()), Value::Str("limit".into()), Value::Str("sort".into()), Value::Str("searchIn".into()), Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("tags".into()), Value::Str("l1Category".into()), Value::Str("l2Category".into())]), &[]);
let mut eventId: Value = self.safe_string_k(paramsOmitted.clone(), "eventId", &[]);
let mut l1Category: Value = self.safe_string_k(paramsOmitted.clone(), "l1Category", &[]);
let mut l2Category: Value = self.safe_string_k(paramsOmitted.clone(), "l2Category", &[]);
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut rawTopics: Value = Value::from(vec![]);
if allQueriesLength > ((0i64) as f64) {
rawTopics = self.fetch_events_by_query(allQueries, fetchCap.clone(), &[rest.clone()]).await;
} else if (eventId != Value::Null) {
let mut detail: Value = self.fetch_raw_topic_detail(eventId, &[rest.clone()]).await;
rawTopics = Value::from(vec![detail]);
} else {
let mut listingRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (l1Category != Value::Null) {
if let Value::Dict(__d) = &mut listingRequest { std::sync::Arc::make_mut(__d).insert("l1Category".into(), l1Category); }
}
if (l2Category != Value::Null) {
if let Value::Dict(__d) = &mut listingRequest { std::sync::Arc::make_mut(__d).insert("l2Category".into(), l2Category); }
}
let mut sortBy: Value = self.safe_string_upper2(paramsOmitted.clone(), Value::Str("sortBy".into()), Value::Str("sort".into()), &[]);
if (sortBy != Value::Null) {
// map the unified sort values onto the server enum, one of RECOMMENDED,
// VOLUME, PARTICIPANTS, CREATED_TIME or END_DATE — 'liquidity' has no
// server-side equivalent and stays in params so the base
// applyEventFetchParams sorts it client-side instead
if (sortBy.as_str() == Some("NEWEST")) {
sortBy = Value::Str("CREATED_TIME".into());
} else if (sortBy.as_str() == Some("LIQUIDITY")) {
sortBy = Value::Null;
}
if (sortBy != Value::Null) {
if let Value::Dict(__d) = &mut listingRequest { std::sync::Arc::make_mut(__d).insert("sortBy".into(), sortBy); }
append_to_array(&mut postOmitKeys, Value::Str("sort".into()));
append_to_array(&mut postOmitKeys, Value::Str("sortBy".into()));
}
}
let __ws_arg_2 = self.extend(listingRequest, &[rest]);
let mut listed: Value = self.fetch_raw_topics(fetchCap, &[__ws_arg_2]).await;
rawTopics = self.complete_raw_topics(listed).await;
}
let mut rawTopicsLength: f64 = ((rawTopics.len() as i64) as f64);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1168: bool = true;
while { if !__for_first_1168 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1168 = false; i.as_f64().unwrap_or(f64::NAN) < rawTopicsLength } {
let mut parsedEvent: Value = self.parse_event(rawTopics.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));
append_to_array(&mut result, parsedEvent.clone());
let mut parsedMarkets: Value = self.safe_list_k(parsedEvent, "markets", &[Value::from(vec![])]);
let mut parsedMarketsLength: f64 = ((parsedMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1167: bool = true;
while { if !__for_first_1167 { mi = (match (&(mi), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1167 = false; mi.as_f64().unwrap_or(f64::NAN) < parsedMarketsLength } {
let mut m: Value = parsedMarkets.as_array().and_then(|__arr| match &mi { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
// prediction market rows are keyed by the unified 'market' handle
let mut handle: Value = self.safe_string_k(m.clone(), "market", &[]);
if (handle != Value::Null) {
if let Value::Dict(__d) = &mut self.markets { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&handle), m); }
}
}
}
}
}
self.populate_outcomes();
// scoping already happened server-side: the tag filter needs an event-level tags field
// binance topics lack, and the query filter would drop semantic-search matches whose
// title uses different words than the query
let mut postParams: Value = self.omit(paramsOmitted, postOmitKeys, &[]);
return self.apply_event_fetch_params(result, &[postParams, Value::from(vec![])]);
Value::Null
}
/*
* @ignore
* @method
* @name binance#fetchEventsByQuery
* @description resolves free-text queries through the semantic market search endpoint, then completes the matched topics with their outcome tokens
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#market-search
* @param {string[]} queries free-text search strings
* @param {int} [limit] max number of topics to fetch
* @param {object} [rest] extra params forwarded verbatim to the search endpoint
* @returns {object[]} raw market topic objects with usable nested markets
*/
pub async fn fetch_events_by_query(&mut self, mut queries: Value, mut limit: Value, optional_args: &[Value]) -> Value {
let mut rest = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut collected: Value = Value::from(vec![]);
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
let mut limitResolved: Value = limit.clone();
if (limit == Value::Null) {
limitResolved = Value::Int(20);
} else if limit.as_f64().unwrap_or(f64::NAN) > ((50i64) as f64) {
limitResolved = Value::Int(50);
}
{
let mut qi: Value = Value::Int(0);
let mut __for_first_1170: bool = true;
while { if !__for_first_1170 { qi = (match (&(qi), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1170 = false; qi.as_f64().unwrap_or(f64::NAN) < queriesLength } {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("query".to_string(), queries.as_array().and_then(|__arr| match &qi { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
m
});
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("topK".into(), limitResolved.clone()); }
let __ws_arg_3 = self.extend(request, &[rest.clone()]);
let mut response: Value = self.sapi_private_get_market_search(&[__ws_arg_3]).await;
//
// [
// {
// "marketTopicId": 4229564,
// "vendor": "PREDICT_FUN",
// "slug": "btc-price-1h-up-or-down",
// "title": "BTC Price 1h Up or Down?",
// ...
// "markets": []
// }
// ]
//
let mut responseLength: f64 = ((response.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1169: bool = true;
while { if !__for_first_1169 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1169 = false; i.as_f64().unwrap_or(f64::NAN) < responseLength } {
let mut rawTopic: Value = self.safe_dict(response.clone(), i.clone(), &[]);
let mut topicId: Value = self.safe_string_k(rawTopic.clone(), "marketTopicId", &[]);
if (topicId != Value::Null) {
let mut already: Option<String> = self.safe_string(seen.clone(), topicId.clone(), &[]).as_str().map(str::to_owned);
if (already.is_none()) {
if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&topicId), topicId.clone()); }
append_to_array(&mut collected, rawTopic);
}
}
}
}
}
}
let mut capped: Value = collected.clone();
let mut collectedLength: f64 = ((collected.len() as i64) as f64);
if (limitResolved != Value::Null) && (collectedLength > limitResolved.as_f64().unwrap_or(f64::NAN)) {
capped = self.array_slice(collected, Value::Int(0), &[limitResolved]);
}
return self.complete_raw_topics(capped).await;
Value::Null
}
/*
* @method
* @name binance#fetchEvent
* @description fetches a single prediction-market event (market topic) by its marketTopicId
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data
* @param {string} id the marketTopicId
* @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("eventId".to_string(), id);
m
}), &[params]);
let mut events: Value = self.fetch_events(&[__ws_arg_4]).await;
return self.safe_dict(events, Value::Int(0), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name binance#parseEvent
* @description parses a raw binance market topic (with nested markets) into the unified event shape
* @param {object} rawTopic the raw market topic object
* @returns {object} an event structure
*/
pub fn parse_event(&self, mut rawTopic: Value) -> Value {
//
// {
// "marketTopicId": 4229564,
// "vendor": "PREDICT_FUN",
// "chainId": "56",
// "slug": "btc-price-1h-up-or-down",
// "title": "BTC Price 1h Up or Down?",
// "question": "Will BTC price go UP?",
// "description": "Resolves YES if BTC spot price is higher than the starting price.",
// "imageUrl": "https://...",
// "topicType": "FLAT",
// "chartType": "CRYPTO_UP_DOWN",
// "symbol": "BTCUSDT",
// "variantData": { "type": "CRYPTO_UP_DOWN", "startPrice": "67890.12", "endPrice": null },
// "participantCount": 3420,
// "collateral": "USDT",
// "feeRateBps": 200,
// "slippageBps": 1200,
// "tradeVolume": "158234.56",
// "liquidity": "45000.00",
// "publishedAt": 1748100000000,
// "startDate": 1748131200000,
// "endDate": 1748134800000,
// "status": "REGISTERED",
// "timeline": [ ... ],
// "markets": [ { "marketId": 5567895, "title": "UP", "outcomes": [ ... ] } ]
// }
//
let mut rawMarkets: Value = self.safe_list_k(rawTopic.clone(), "markets", &[Value::from(vec![])]);
let mut marketsList: Value = Value::from(vec![]);
let mut anyActive: Value = Value::Bool(false);
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1171: bool = true;
while { if !__for_first_1171 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1171 = false; i.as_f64().unwrap_or(f64::NAN) < rawMarketsLength } {
let mut parsed: Value = self.parse_topic_market(rawMarkets.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), rawTopic.clone());
append_to_array(&mut marketsList, parsed.clone());
if matches!(self.safe_bool_k(parsed, "active", &[Value::Bool(false)]), Value::Bool(true)) {
anyActive = Value::Bool(true);
}
}
}
let mut topicId: Value = self.safe_string_k(rawTopic.clone(), "marketTopicId", &[]);
let mut slug: Value = self.safe_string_k(rawTopic.clone(), "slug", &[]);
let mut title: Value = self.safe_string_k(rawTopic.clone(), "title", &[]);
let mut endDate: Value = self.safe_integer_k(rawTopic.clone(), "endDate", &[]);
let mut created: Value = self.safe_integer2(rawTopic.clone(), Value::Str("publishedAt".into()), Value::Str("startDate".into()), &[]);
let mut status: Option<String> = self.safe_string_k(rawTopic.clone(), "status", &[]).as_str().map(str::to_owned);
let mut active: Value = anyActive;
if (rawMarketsLength == 0.0) {
active = Value::Bool((status.as_deref() == Some("REGISTERED")) || (status.as_deref() == Some("OPEN")));
}
let mut resolved: Value = Value::Null;
if (status.is_some()) {
resolved = Value::Bool((status.as_deref() == Some("RESOLVED")) || (status.as_deref() == Some("SETTLED")));
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), topicId);
m.insert("slug".to_string(), slug.clone());
m.insert("event".to_string(), (if (slug != Value::Null) { self.shorten_slug(slug) } else { Value::Null }));
m.insert("title".to_string(), title);
m.insert("description".to_string(), self.safe_string_k(rawTopic.clone(), "description", &[]));
m.insert("markets".to_string(), marketsList);
m.insert("active".to_string(), active);
m.insert("volume".to_string(), self.safe_number_k(rawTopic.clone(), "tradeVolume", &[]));
m.insert("liquidity".to_string(), self.safe_number_k(rawTopic.clone(), "liquidity", &[]));
m.insert("url".to_string(), Value::Null);
m.insert("image".to_string(), self.safe_string_k(rawTopic.clone(), "imageUrl", &[]));
m.insert("created".to_string(), created.clone());
m.insert("createdDatetime".to_string(), self.iso8601(created));
m.insert("end".to_string(), endDate.clone());
m.insert("endDatetime".to_string(), self.iso8601(endDate));
m.insert("category".to_string(), self.safe_string_k(rawTopic.clone(), "chartType", &[]));
m.insert("resolved".to_string(), resolved);
m.insert("info".to_string(), rawTopic);
m
});
Value::Null
}
/*
* @ignore
* @method
* @name binance#parseTopicMarket
* @description parses one nested market of a market topic into the unified market shape, building its outcome tokens
* @param {object} rawMarket the nested market object
* @param {object} rawTopic the enclosing raw market topic (carries slug/vendor/fees/dates)
* @returns {object} a market structure
*/
pub fn parse_topic_market(&self, mut rawMarket: Value, mut rawTopic: Value) -> Value {
let __rawTopic_empty = indexmap::IndexMap::new();
let rawTopic = rawTopic.as_map().unwrap_or(&__rawTopic_empty);
//
// {
// "marketId": 5567895,
// "externalId": "ext_001",
// "title": "UP",
// "question": "Will BTC go UP?",
// "description": "Resolves YES if BTC price increases.",
// "conditionId": "0xabc123",
// "status": "REGISTERED",
// "tradingStatus": "OPEN",
// "tradeVolume": "90000.00",
// "liquidity": "25000.00",
// "decimalPrecision": 2,
// "outcomes": [
// { "name": "YES", "price": "0.52", "chance": "0.52", "index": 0, "tokenId": "112233" }
// ]
// }
//
let mut marketId: Value = self.safe_string_k(rawMarket.clone(), "marketId", &[]);
let mut topicId: Value = (match rawTopic.get("marketTopicId") { 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 topicSlug: Value = (match rawTopic.get("slug") { 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 vendor: Value = (match rawTopic.get("vendor") { 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 collateral: Value = (match rawTopic.get("collateral") { 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::Str("USDT".into()) });
let mut title: Value = self.safe_string_k(rawMarket.clone(), "title", &[marketId.clone()]);
let mut marketSymbol: Value = self.slug_to_market_symbol(topicSlug.clone(), title.clone());
let mut tradingStatus: Option<String> = self.safe_string_k(rawMarket.clone(), "tradingStatus", &[]).as_str().map(str::to_owned);
let mut status: Option<String> = self.safe_string_k(rawMarket.clone(), "status", &[]).as_str().map(str::to_owned);
let mut active: Value = (Value::Bool(tradingStatus.as_deref() == Some("OPEN")));
if (tradingStatus.is_none()) {
active = Value::Bool((status.as_deref() == Some("REGISTERED")) || (status.as_deref() == Some("OPEN")));
}
let mut resolved: Value = Value::Bool((status.as_deref() == Some("RESOLVED")) || (status.as_deref() == Some("SETTLED")));
let mut endDate: Value = (match rawTopic.get("endDate") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
let mut feeRateBps: Value = (match rawTopic.get("feeRateBps") { 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::Str("200".into()) });
let mut feeRate: Value = self.parse_number(crate::precise::Precise::stringDiv(&feeRateBps, &Value::Str("10000".into())), &[]);
let mut decimalPrecision: Value = self.safe_string_k(rawMarket.clone(), "decimalPrecision", &[Value::Str("2".into())]);
let mut pricePrecision: Value = self.parse_number(self.parse_precision(&[decimalPrecision]), &[]);
let mut precision: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Float(0.01));
m.insert("price".to_string(), pricePrecision);
m
});
let mut volume: Value = self.safe_number_k(rawMarket.clone(), "tradeVolume", &[]);
let mut liquidity: Value = self.safe_number_k(rawMarket.clone(), "liquidity", &[]);
let mut rawOutcomes: Value = self.safe_list_k(rawMarket.clone(), "outcomes", &[Value::from(vec![])]);
let mut outcomes: Value = Value::from(vec![]);
let mut resolvedOutcomeRaw: Value = Value::Null;
let mut rawOutcomesLength: f64 = ((rawOutcomes.len() as i64) as f64);
{
let mut oi: Value = Value::Int(0);
let mut __for_first_1172: bool = true;
while { if !__for_first_1172 { oi = (match (&(oi), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1172 = false; oi.as_f64().unwrap_or(f64::NAN) < rawOutcomesLength } {
let mut rawOutcome: Value = self.safe_dict(rawOutcomes.clone(), oi.clone(), &[]);
let mut label: Value = self.safe_string_upper_k(rawOutcome.clone(), "name", &[]);
let mut tokenId: Value = self.safe_string_k(rawOutcome.clone(), "tokenId", &[]);
let mut outcomeHandle: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", marketSymbol, Value::Str(":".into())).into()), label).into());
let mut price: Value = self.safe_string_k(rawOutcome.clone(), "price", &[]);
let mut winnerRaw: Value = Value::Null;
let mut settleFractionRaw: Value = Value::Null;
if matches!(&resolved, Value::Bool(true)) && (price != Value::Null) {
winnerRaw = crate::precise::Precise::stringEq(&price, &Value::Str("1".into()));
settleFractionRaw = (if is_true(&(winnerRaw)) { Value::Int(1) } else { Value::Int(0) });
if is_true(&winnerRaw) {
resolvedOutcomeRaw = outcomeHandle.clone();
}
}
let mut winner: Value = winnerRaw;
let mut settleFraction: Value = settleFractionRaw;
append_to_array(&mut outcomes, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), tokenId.clone());
m.insert("outcomeId".to_string(), tokenId.clone());
m.insert("outcome".to_string(), outcomeHandle);
m.insert("market".to_string(), marketSymbol.clone());
m.insert("label".to_string(), label.clone());
m.insert("price".to_string(), self.parse_number(price.clone(), &[]));
m.insert("active".to_string(), active.clone());
m.insert("winner".to_string(), winner);
m.insert("settleFraction".to_string(), settleFraction);
m.insert("precision".to_string(), precision.clone());
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tokenId".to_string(), tokenId);
m.insert("marketId".to_string(), marketId.clone());
m.insert("marketTopicId".to_string(), topicId.clone());
m.insert("vendor".to_string(), vendor.clone());
m.insert("chainId".to_string(), (match rawTopic.get("chainId") { 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("slug".to_string(), topicSlug.clone());
m.insert("marketTitle".to_string(), title.clone());
m.insert("outcomeLabel".to_string(), label);
m.insert("index".to_string(), self.safe_string_k(rawOutcome.clone(), "index", &[]));
m.insert("price".to_string(), price);
m.insert("chance".to_string(), self.safe_string_k(rawOutcome, "chance", &[]));
m.insert("collateral".to_string(), collateral.clone());
m.insert("feeRateBps".to_string(), feeRateBps.clone());
m.insert("slippageBps".to_string(), (match rawTopic.get("slippageBps") { 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("conditionId".to_string(), self.safe_string_k(rawMarket.clone(), "conditionId", &[]));
m.insert("externalId".to_string(), self.safe_string_k(rawMarket.clone(), "externalId", &[]));
m
}));
m
}));
}
}
let mut resolvedOutcome: Value = resolvedOutcomeRaw;
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId.clone());
m.insert("market".to_string(), marketSymbol);
m.insert("base".to_string(), collateral.clone());
m.insert("quote".to_string(), collateral.clone());
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), marketId);
m.insert("quoteId".to_string(), collateral.clone());
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("collateral".to_string(), collateral);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("active".to_string(), active);
m.insert("resolved".to_string(), resolved);
m.insert("resolvedOutcome".to_string(), resolvedOutcome);
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(), endDate.clone());
m.insert("expiryDatetime".to_string(), self.iso8601(endDate));
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("taker".to_string(), feeRate);
m.insert("maker".to_string(), Value::Int(0));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("feeSide".to_string(), Value::Str("get".into()));
m.insert("precision".to_string(), precision);
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(1));
m.insert("max".to_string(), Value::Int(1));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Float(0.01));
m.insert("max".to_string(), Value::Float(0.99));
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Float(1.5));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("outcomes".to_string(), outcomes);
m.insert("info".to_string(), self.extend(rawMarket, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketTopicId".to_string(), topicId);
m.insert("vendor".to_string(), vendor);
m.insert("slug".to_string(), topicSlug);
m.insert("volume".to_string(), volume);
m.insert("liquidity".to_string(), liquidity);
m
})]));
m.insert("created".to_string(), (match rawTopic.get("publishedAt") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null }));
m
});
Value::Null
}
/*
* @method
* @name binance#fetchTicker
* @description fetches the last trade price for a single prediction outcome
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#query-last-trade-price
* @param {string} outcome unified outcome handle like BTC_PRICE_1H_UP_DOWN_UP:YES, or an outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a prediction [ticker structure](https://docs.ccxt.com/#/?id=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 info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), self.safe_string_k(info, "marketId", &[]));
m
});
let __ws_arg_5 = self.extend(request, &[params]);
let mut response: Value = self.sapi_private_get_order_book_last_trade_price(&[__ws_arg_5]).await;
return self.parse_prediction_ticker(response, &[outcomeObj]);
Value::Null
}
/*
* @ignore
* @method
* @name binance#parsePredictionTicker
* @description parses a last-trade-price response into a unified ticker object; the venue quotes the market's primary (YES) token, so a NO outcome mirrors as 1 - price
* @param {object} raw the raw last-trade-price object
* @param {object} [market] the outcome object the ticker belongs to
* @returns {object} a [ticker structure](https://docs.ccxt.com/#/?id=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);
//
// { "marketId": 5567895, "lastTradePrice": "0.52" }
//
let mut marketAny: Value = market.clone();
let mut outcomeObj: Value = self.safe_outcome(self.safe_string_k(marketAny.clone(), "outcome", &[]), &[marketAny]);
// the venue quotes the market's primary token (outcome index 0, e.g. YES or UP),
// any other outcome of a binary market mirrors as 1 - price
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut outcomeIndex: Option<String> = self.safe_string_k(outcomeInfo, "index", &[]).as_str().map(str::to_owned);
let mut isMirrored: bool = false;
if (outcomeIndex.is_some()) {
isMirrored = outcomeIndex.as_deref() != Some("0");
} else {
let mut label: Option<String> = self.safe_string_upper_k(outcomeObj.clone(), "label", &[Value::Str("YES".into())]).as_str().map(str::to_owned);
isMirrored = (label.as_deref() == Some("NO")) || (label.as_deref() == Some("DOWN"));
}
let mut lastString: Value = self.safe_string_k(raw.clone(), "lastTradePrice", &[]);
let mut last: Value = Value::Null;
if (lastString != Value::Null) {
if isMirrored {
last = self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &lastString), &[]);
} else {
last = self.parse_number(lastString, &[]);
}
}
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(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), Value::Null);
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), Value::Null);
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
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 binance#fetchTickers
* @description fetches last trade prices for multiple outcomes, one request per distinct underlying market
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#query-last-trade-price
* @param {string[]} outcomes unified outcomes — required: the venue has no all-tickers endpoint
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of prediction [ticker structures](https://docs.ccxt.com/#/?id=ticker-structure)
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcomes == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles to fetch (discover them via fetchEvents ())".into()))));
}
self.load_outcomes(&[outcomes.clone()]).await;
let mut responsesByMarketId: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomesLength: f64 = ((outcomes.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1173: bool = true;
while { if !__for_first_1173 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1173 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
let mut outcomeObj: Value = self.outcome(outcomes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string_k(info, "marketId", &[]);
if (marketId == Value::Null) {
continue;
}
let mut response: Value = self.safe_dict(responsesByMarketId.clone(), marketId.clone(), &[]);
if (response == Value::Null) {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), marketId.clone());
m
});
let __ws_arg_6 = self.extend(request, &[params.clone()]);
response = self.sapi_private_get_order_book_last_trade_price(&[__ws_arg_6]).await;
if let Value::Dict(__d) = &mut responsesByMarketId { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketId), response.clone()); }
}
let mut ticker: Value = self.parse_prediction_ticker(response, &[outcomeObj]);
let mut symbolKey: Value = self.safe_string_k(ticker.clone(), "outcome", &[outcomes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)]);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbolKey), ticker); }
}
}
return result;
Value::Null
}
/*
* @method
* @name binance#fetchOrderBook
* @description fetches the order book for a single prediction outcome token
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#query-order-book
* @param {string} outcome unified outcome handle, or an outcome token id
* @param {int} [limit] not used by binance fetchOrderBook
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a prediction [order book structure](https://docs.ccxt.com/#/?id=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 info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("vendor".to_string(), self.safe_string_k(info.clone(), "vendor", &[self.safe_string(self.options.clone(), Value::Str("defaultVendor".into()), &[])]));
m.insert("marketId".to_string(), self.safe_string_k(info, "marketId", &[]));
m.insert("tokenId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m
});
let __ws_arg_7 = self.extend(request, &[params]);
let mut response: Value = self.sapi_private_get_order_book(&[__ws_arg_7]).await;
//
// {
// "outcome": "YES",
// "tokenId": "112233",
// "timestamp": 1748131800000,
// "bids": [ { "price": "0.51", "size": "5000.00" } ],
// "asks": [ { "price": "0.52", "size": "3000.00" } ]
// }
//
let mut timestamp: Value = self.safe_integer_k(response.clone(), "timestamp", &[]);
let mut orderbook: Value = self.parse_order_book(response, self.safe_outcome_symbol(outcome, &[outcomeObj.clone()]), &[timestamp, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("size".into())]);
return self.safe_prediction_order_book(orderbook, &[outcomeObj]);
Value::Null
}
/*
* @method
* @name binance#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/wallet#query-payment-option-balances
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'CeDefi', 'FUNDING', or 'SPOT'
* @returns {object} a [balance structure]{@link 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 type_varparamsTypeVariable = self.handle_option_string_and_params(params, Value::Str("fetchBalance".into()), Value::Str("type".into()), &[Value::Str("SPOT".into())]);
let mut type_var: Value = type_varparamsTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsType: Value = type_varparamsTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = self.sapi_private_get_balance_payment_options(&[paramsType]).await;
//
// {
// "items": [
// {
// "accountType": "SPOT",
// "availableBalanceDisplay": "1000.00",
// "enabled": true
// }
// ]
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut balances: Value = self.safe_list_k(response, "items", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1174: bool = true;
while { if !__for_first_1174 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1174 = false; i.as_f64().unwrap_or(f64::NAN) < ((balances.len() as i64) as f64) } {
let mut balance: Value = self.safe_dict(balances.clone(), i.clone(), &[]);
let mut accountType: Value = self.safe_string_k(balance.clone(), "accountType", &[]);
if (accountType.as_str() == type_var.as_str()) {
let mut free: Value = self.safe_string_k(balance, "availableBalanceDisplay", &[]);
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), free); }
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("USDT".into(), account); }
}
}
}
return self.safe_balance(result);
Value::Null
}
/*
* @ignore
* @method
* @name binance#parsePredictionOrder
* @description parses a raw binance prediction order object into a unified order object
* @param {object} order the raw order object
* @param {object} [outcomeObj] the ourtome the order belongs to
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub fn parse_prediction_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = get_arg(optional_args, 0, Value::Null);
//
// {
// "orderId": "54124",
// "vendorOrderId": "0x1234abcd...",
// "vendor": "PREDICT_FUN",
// "marketTopicId": 4229564,
// "slug": "btc-price-1h-up-or-down",
// "marketTopicTitle": "BTC Price 1h Up or Down?",
// "marketId": 5567895,
// "marketTitle": "UP",
// "outcome": "YES",
// "outcomeIndex": 0,
// "status": "OPENING",
// "side": "BUY",
// "orderType": "LIMIT",
// "createTime": 1748131500000,
// "modifyTime": 1748131500000,
// "makerUsdtAmount": "1.00",
// "makerShareQty": "2000.00",
// "filledUsdtAmount": "0.00",
// "filledShareQty": "0.00",
// "fillPercentage": "0.00",
// "price": "0.50",
// "marketProviderFee": "0.02",
// "networkFee": "0.000001"
// }
//
let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "status", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut outcomeObjResolved: Value = outcomeObj;
if (outcomeObjResolved == Value::Null) {
let mut marketId: Value = self.safe_string_k(order.clone(), "marketId", &[]);
let mut outcome: Value = self.safe_string_upper_k(order.clone(), "outcome", &[]);
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut outcomeName: Value = self.safe_string_k(market, "market", &[]);
if (outcomeName == Value::Null) {
outcomeName = marketId;
}
outcomeName = Value::Str(format!("{}{}", outcomeName, Value::Str(format!("{}{}", Value::Str(":".into()), outcome).into())).into());
outcomeObjResolved = self.safe_outcome(outcomeName, &[]);
}
let mut side: Value = self.safe_string_lower_k(order.clone(), "side", &[]);
let mut timestamp: Value = self.safe_integer_k(order.clone(), "createTime", &[]);
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(order.clone(), "orderId", &[]));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), order.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("outcome".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "market", &[]));
m.insert("type".to_string(), self.safe_string_lower_k(order.clone(), "orderType", &[]));
m.insert("timeInForce".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.safe_number_k(order, "price", &[]));
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("amount".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("filled".to_string(), Value::Null);
m.insert("remaining".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m
}), &[outcomeObjResolved]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("OPENING".to_string(), Value::Str("open".into()));
m.insert("FILLED".to_string(), Value::Str("closed".into()));
m
});
if (status == Value::Null) {
return None;
}
if (ends_with(&status, &Value::Str("Rejected".into()))) {
return Value::Str("rejected".into()).as_str().map(str::to_owned);
}
if (ends_with(&status, &Value::Str("Canceled".into()))) {
return Value::Str("canceled".into()).as_str().map(str::to_owned);
}
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name binance#fetchOpenOrders
* @description fetches currently open orders for the user
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#query-active-orders
* @param {string} [outcome] filter by outcome
* @param {int} [since] only return orders updated since this timestamp in ms
* @param {int} [limit] max number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.tradeSide] Filter by trade side. Enum: BUY, SELL
* @param {string} [params.l1Category] Filter by level-1 category
* @param {boolean} [params.paginate] *spot only* default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @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 paginate: Value = Value::Bool(false);
let mut paramsPaginate: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{ let __destr_tmp = self.handle_option_bool_and_params(params, Value::Str("fetchOpenOrders".into()), Value::Str("paginate".into()), &[Value::Bool(false)]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsPaginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut maxEntriesPerRequestparamsMaxEntriesPerRequestVariable = self.handle_option_integer_and_params(paramsPaginate, Value::Str("fetchOpenOrders".into()), Value::Str("maxEntriesPerRequest".into()), &[Value::Int(100)]);
let mut maxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMaxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut pageKey: Value = Value::Str("ccxtPageKey".into());
if is_true(&paginate) {
return self.fetch_paginated_call_incremental(Value::Str("fetchOpenOrders".into()), &[outcome.clone(), since.clone(), limit.clone(), paramsMaxEntriesPerRequest.clone(), pageKey.clone(), maxEntriesPerRequest.clone()]).await;
}
let mut page: Value = (match (&(self.safe_integer(paramsMaxEntriesPerRequest.clone(), pageKey, &[Value::Int(1)])), &(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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut offSet: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "offset", &[(match (&(page), &(maxEntriesPerRequest)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
if offSet.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("offset".into(), offSet); }
}
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
let mut market: Value = self.market(outcomeObj.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("marketId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut wallet: Value = self.fetch_wallet(Value::Str("fetchOpenOrders".into()), &[paramsMaxEntriesPerRequest.clone()]).await;
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("walletAddress".into(), crate::value::get_value_k(&wallet, "walletAddress")); }
let __ws_arg_8 = self.extend(request, &[paramsMaxEntriesPerRequest]);
let mut response: Value = self.sapi_private_get_order_list(&[__ws_arg_8]).await;
//
// {
// "total": 2,
// "offset": 0,
// "limit": 20,
// "orders": [
// {
// "orderId": "54124",
// "vendorOrderId": "0x1234abcd...",
// "vendor": "PREDICT_FUN",
// "marketTopicId": 4229564,
// "slug": "btc-price-1h-up-or-down",
// "marketTopicTitle": "BTC Price 1h Up or Down?",
// "marketId": 5567895,
// "marketTitle": "UP",
// "outcome": "YES",
// "outcomeIndex": 0,
// "status": "OPENING",
// "side": "BUY",
// "orderType": "LIMIT",
// "createTime": 1748131500000,
// "modifyTime": 1748131500000,
// "makerUsdtAmount": "1.00",
// "makerShareQty": "2000.00",
// "filledUsdtAmount": "0.00",
// "filledShareQty": "0.00",
// "fillPercentage": "0.00",
// "price": "0.50",
// "marketProviderFee": "0.02",
// "networkFee": "0.000001"
// }
// ]
// }
//
let mut orders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
let mut parsedOrders: Value = self.parse_prediction_orders(orders, &[outcomeObj, since.clone()]);
return self.filter_by_outcome_since_limit(parsedOrders, &[outcome, since, limit]);
Value::Null
}
/*
* @method
* @name binance#fetchOrders
* @description fetches all historical orders for the user
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#query-order-history
* @param {string} [outcome] filter by outcome
* @param {int} [since] only return orders updated since this timestamp in ms
* @param {int} [limit] max number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.orderType] Filter by order type. Enum: MARKET, LIMIT
* @param {string} [params.l1Category] Filter by level-1 category
* @param {string} [params.status] Filter by order status
* @param {string} [params.until] end timestamp in ms
* @param {boolean} [params.paginate] *spot only* default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @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
}));
let mut paginate: Value = Value::Bool(false);
let mut paramsPaginate: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{ let __destr_tmp = self.handle_option_bool_and_params(params, Value::Str("fetchOrders".into()), Value::Str("paginate".into()), &[Value::Bool(false)]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsPaginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut maxEntriesPerRequestparamsMaxEntriesPerRequestVariable = self.handle_option_integer_and_params(paramsPaginate, Value::Str("fetchOrders".into()), Value::Str("maxEntriesPerRequest".into()), &[Value::Int(100)]);
let mut maxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMaxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut pageKey: Value = Value::Str("ccxtPageKey".into());
if is_true(&paginate) {
return self.fetch_paginated_call_incremental(Value::Str("fetchOrders".into()), &[outcome.clone(), since.clone(), limit.clone(), paramsMaxEntriesPerRequest.clone(), pageKey.clone(), maxEntriesPerRequest.clone()]).await;
}
let mut page: Value = (match (&(self.safe_integer(paramsMaxEntriesPerRequest.clone(), pageKey, &[Value::Int(1)])), &(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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut offSet: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "offset", &[(match (&(page), &(maxEntriesPerRequest)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
if offSet.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("offset".into(), offSet); }
}
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startDate".into(), self.yyyymmdd(since.clone(), &[])); }
}
let mut until: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(paramsMaxEntriesPerRequest, Value::Str("until".into()), &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endDate".into(), self.yyyymmdd(until, &[])); }
}
let mut wallet: Value = self.fetch_wallet(Value::Str("fetchOrders".into()), &[paramsOmitted.clone()]).await;
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("walletAddress".into(), crate::value::get_value_k(&wallet, "walletAddress")); }
let __ws_arg_9 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.sapi_private_get_order_history(&[__ws_arg_9]).await;
//
// {
// "total": 15,
// "offset": 0,
// "limit": 20,
// "orders": [
// {
// "orderId": "54100",
// "vendorOrderId": "0xabcd5678...",
// "vendor": "PREDICT_FUN",
// "marketTopicId": 4229500,
// "slug": "btc-price-1h-up-or-down-prev",
// "marketTopicTitle": "BTC Price 1h Up or Down?",
// "marketId": 5567800,
// "marketTitle": "UP",
// "outcome": "YES",
// "outcomeIndex": 0,
// "status": "CLOSED",
// "side": "BUY",
// "orderType": "MARKET",
// "createTime": 1748045100000,
// "modifyTime": 1748045101000,
// "terminalTime": 1748045101000,
// "makerUsdtAmount": "1.00",
// "makerShareQty": "1923.07",
// "filledUsdtAmount": "1.00",
// "filledShareQty": "1923.07",
// "fillPercentage": "1.00",
// "price": "0.52",
// "marketProviderFee": "0.02",
// "networkFee": "0.000001"
// }
// ]
// }
//
let mut orders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
let mut parsedOrders: Value = self.parse_prediction_orders(orders, &[outcomeObj, since.clone()]);
return self.filter_by_outcome_since_limit(parsedOrders, &[outcome, since, limit]);
Value::Null
}
/*
* @method
* @name binance#fetchPositions
* @description fetches the user's outcome positions; outcome positions are spot token balances under the "+<encoding>" coin form (size and entry notional), the value/entry/mark price/pnl are computed from the current mid prices
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/position#query-positions
* @param {string[]} [outcomes] filter by outcome ids or outcomes
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.tab] Position status tab. Values from PositionQueryType. Default ONGOING
* @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.load_outcomes(&[]).await;
let mut requestedOutcomeSymbols: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (outcomes != Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_1175: bool = true;
while { if !__for_first_1175 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1175 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomes.len() as i64) as f64) } {
let mut requested: Value = outcomes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut requestedOutcomeObj: Value = self.safe_outcome(requested.clone(), &[]);
let mut requestedOutcome: Value = self.safe_string_k(requestedOutcomeObj, "outcome", &[requested]);
if let Value::Dict(__d) = &mut requestedOutcomeSymbols { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&requestedOutcome), Value::Bool(true)); }
}
}
}
let mut wallet: Value = self.fetch_wallet(Value::Str("fetchPositions".into()), &[params.clone()]).await;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("walletAddress".to_string(), crate::value::get_value_k(&wallet, "walletAddress"));
m
});
let __ws_arg_10 = self.extend(request, &[params]);
let mut response: Value = self.sapi_private_get_position_list(&[__ws_arg_10]).await;
//
// {
// "summary": {
// "totalValue": "1523.45",
// "positionValue": "523.45",
// "walletBalance": "1000.00",
// "totalClaimableAmount": "50.00",
// "todayRealizedPnl": "15.30",
// "todayRealizedPnlPercent": "3.10",
// "todayTotalCost": "493.55"
// },
// "counts": {
// "ongoingCount": 3,
// "endedCount": 12,
// "pendingClaimCount": 1
// },
// "positions": [
// {
// "positionId": 1001,
// "vendor": "PREDICT_FUN",
// "chainId": "56",
// "tokenId": "112233",
// "collateralSymbol": "USDT",
// "topicType": "FLAT",
// "marketTopicId": 4229564,
// "marketId": 5567895,
// "marketTopicTitle": "BTC Price 1h Up or Down?",
// "marketTitle": "UP",
// "outcomeName": "YES",
// "outcomeIndex": 0,
// "shares": "1923.07",
// "avgPrice": "0.52",
// "totalCost": "1.00",
// "value": "1.06",
// "currentPrice": "0.55",
// "toWin": "1923.07",
// "positionStatus": "OPEN",
// "canClaim": false,
// "endDate": 1748134800000,
// "unrealizedPnl": "0.06",
// "unrealizedPnlPercent": "6.00",
// "realizedPnl": "0.00",
// "pnl": "0.06",
// "createdTime": 1748131500000,
// "updatedTime": 1748132000000
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "positions", &[Value::from(vec![])]);
let mut positions: Value = self.parse_prediction_positions(data, &[]);
if (outcomes == Value::Null) {
return positions;
}
let mut filtered: Value = Value::from(vec![]);
let mut positionsLength: f64 = ((positions.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1176: bool = true;
while { if !__for_first_1176 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1176 = false; i.as_f64().unwrap_or(f64::NAN) < positionsLength } {
let mut position: Value = positions.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 positionOutcome: Value = self.safe_string_k(position.clone(), "outcome", &[]);
if (positionOutcome != Value::Null) && (in_op(&requestedOutcomeSymbols, &positionOutcome)) {
append_to_array(&mut filtered, position);
}
}
}
return filtered;
Value::Null
}
/*
* @method
* @name binance#fetchPosition
* @description fetch data on an open position
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/position#query-positions-by-filter
* @param {string} [outcome] filter by outcome
* @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_position(&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
}));
let mut request: Value = Value::Map({
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());
let mut market: Value = self.market(outcomeObj.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("marketTopicId".into(), crate::value::get_value_k(&market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), "marketTopicId")); }
}
let mut wallet: Value = self.fetch_wallet(Value::Str("fetchOrders".into()), &[params.clone()]).await;
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("walletAddress".into(), crate::value::get_value_k(&wallet, "walletAddress")); }
let __ws_arg_11 = self.extend(request, &[params]);
let mut response: Value = self.sapi_private_get_position_filter(&[__ws_arg_11]).await;
//
//
let mut positions: Value = self.safe_list_k(response, "positions", &[Value::from(vec![])]);
let mut parsedPositions: Value = self.parse_prediction_positions(positions, &[]);
let mut filteredPositions: Value = self.filter_by_outcome_since_limit(parsedPositions, &[outcome, Value::Null, Value::Null]);
return self.safe_dict(filteredPositions, Value::Int(0), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name binance#parsePredictionPosition
* @description parses a spot balance entry for an outcome token into a unified position object
* @param {object} position the raw balance entry
* @param {object} [outcomeObj] the ourtome the position belongs to
* @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub fn parse_prediction_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = get_arg(optional_args, 0, Value::Null);
let mut outcomeObjResolved: Value = outcomeObj;
if (outcomeObjResolved == Value::Null) {
let mut marketId: Value = self.safe_string_k(position.clone(), "marketId", &[]);
let mut outcome: Value = self.safe_string_upper_k(position.clone(), "outcomeName", &[]);
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut outcomeName: Value = self.safe_string_k(market, "market", &[]);
if (outcomeName == Value::Null) {
outcomeName = marketId;
}
outcomeName = Value::Str(format!("{}{}", outcomeName, Value::Str(format!("{}{}", Value::Str(":".into()), outcome).into())).into());
outcomeObjResolved = self.safe_outcome(outcomeName, &[]);
}
let mut timestamp: Value = self.safe_integer_k(position.clone(), "createdTime", &[]);
let mut totalCost: Value = self.parse_number(self.safe_string_k(position.clone(), "totalCost", &[]), &[]);
return self.safe_prediction_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_integer_k(position.clone(), "positionId", &[]));
m.insert("outcome".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObjResolved.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObjResolved, "market", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("isolated".to_string(), Value::Bool(false));
m.insert("hedged".to_string(), Value::Null);
m.insert("side".to_string(), Value::Str("long".into()));
m.insert("contracts".to_string(), Value::Null);
m.insert("contractSize".to_string(), self.parse_number(self.safe_string_k(position.clone(), "shares", &[]), &[]));
m.insert("entryPrice".to_string(), self.parse_number(self.safe_string_k(position.clone(), "avgPrice", &[]), &[]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("notional".to_string(), self.parse_number(self.safe_string_k(position.clone(), "value", &[]), &[]));
m.insert("leverage".to_string(), Value::Null);
m.insert("collateral".to_string(), totalCost.clone());
m.insert("initialMargin".to_string(), totalCost);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), self.parse_number(self.safe_string_k(position.clone(), "unrealizedPnl", &[]), &[]));
m.insert("realizedPnl".to_string(), self.parse_number(self.safe_string_k(position.clone(), "realizedPnl", &[]), &[]));
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Str("cross".into()));
m.insert("percentage".to_string(), self.parse_number(self.safe_string_k(position.clone(), "unrealizedPnlPercent", &[]), &[]));
m.insert("info".to_string(), position);
m
}));
Value::Null
}
/*
* @method
* @name binance#fetchMyTrades
* @description fetch all trades made by the user
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#query-order-history
* @param {string} [outcome] filter by outcome
* @param {int} [since] only return orders updated since this timestamp in ms
* @param {int} [limit] max number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.orderType] Filter by order type. Enum: MARKET, LIMIT
* @param {string} [params.l1Category] Filter by level-1 category
* @param {string} [params.status] Filter by order status
* @param {string} [params.until] end timestamp in ms
* @param {boolean} [params.paginate] *spot only* default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-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
}));
let mut paginate: Value = Value::Bool(false);
let mut paramsPaginate: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{ let __destr_tmp = self.handle_option_bool_and_params(params, Value::Str("fetchMyTrades".into()), Value::Str("paginate".into()), &[Value::Bool(false)]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsPaginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut maxEntriesPerRequestparamsMaxEntriesPerRequestVariable = self.handle_option_integer_and_params(paramsPaginate, Value::Str("fetchMyTrades".into()), Value::Str("maxEntriesPerRequest".into()), &[Value::Int(100)]);
let mut maxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMaxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut pageKey: Value = Value::Str("ccxtPageKey".into());
if is_true(&paginate) {
return self.fetch_paginated_call_incremental(Value::Str("fetchMyTrades".into()), &[outcome.clone(), since.clone(), limit.clone(), paramsMaxEntriesPerRequest.clone(), pageKey.clone(), maxEntriesPerRequest.clone()]).await;
}
let mut page: Value = (match (&(self.safe_integer(paramsMaxEntriesPerRequest.clone(), pageKey, &[Value::Int(1)])), &(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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("FILLED".into()));
m
});
let mut offSet: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "offset", &[(match (&(page), &(maxEntriesPerRequest)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
if offSet.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("offset".into(), offSet); }
}
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startDate".into(), self.yyyymmdd(since.clone(), &[])); }
}
let mut until: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(paramsMaxEntriesPerRequest, Value::Str("until".into()), &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endDate".into(), self.yyyymmdd(until, &[])); }
}
let mut wallet: Value = self.fetch_wallet(Value::Str("fetchMyTrades".into()), &[paramsOmitted.clone()]).await;
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("walletAddress".into(), crate::value::get_value_k(&wallet, "walletAddress")); }
let __ws_arg_12 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.sapi_private_get_order_history(&[__ws_arg_12]).await;
//
// {
// "total": 15,
// "offset": 0,
// "limit": 20,
// "orders": [
// {
// "orderId": "54100",
// "vendorOrderId": "0xabcd5678...",
// "vendor": "PREDICT_FUN",
// "marketTopicId": 4229500,
// "slug": "btc-price-1h-up-or-down-prev",
// "marketTopicTitle": "BTC Price 1h Up or Down?",
// "marketId": 5567800,
// "marketTitle": "UP",
// "outcome": "YES",
// "outcomeIndex": 0,
// "status": "CLOSED",
// "side": "BUY",
// "orderType": "MARKET",
// "createTime": 1748045100000,
// "modifyTime": 1748045101000,
// "terminalTime": 1748045101000,
// "makerUsdtAmount": "1.00",
// "makerShareQty": "1923.07",
// "filledUsdtAmount": "1.00",
// "filledShareQty": "1923.07",
// "fillPercentage": "1.00",
// "price": "0.52",
// "marketProviderFee": "0.02",
// "networkFee": "0.000001"
// }
// ]
// }
//
let mut trades: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
let mut parsedTrades: Value = self.parse_prediction_trades(trades, &[outcomeObj]);
return self.filter_by_outcome_since_limit(parsedTrades, &[outcome, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name binance#parsePredictionTrade
* @description parses a single binance fill into a unified trade object
* @param {object} trade the raw fill object
* @param {object} [outcomeObj] the outcome the trade belongs to
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = get_arg(optional_args, 0, Value::Null);
//
// {
// "orderId": "54124",
// "vendorOrderId": "0x1234abcd...",
// "vendor": "PREDICT_FUN",
// "marketTopicId": 4229564,
// "slug": "btc-price-1h-up-or-down",
// "marketTopicTitle": "BTC Price 1h Up or Down?",
// "marketId": 5567895,
// "marketTitle": "UP",
// "outcome": "YES",
// "outcomeIndex": 0,
// "status": "OPENING",
// "side": "BUY",
// "orderType": "LIMIT",
// "createTime": 1748131500000,
// "modifyTime": 1748131500000,
// "makerUsdtAmount": "1.00",
// "makerShareQty": "2000.00",
// "filledUsdtAmount": "0.00",
// "filledShareQty": "0.00",
// "fillPercentage": "0.00",
// "price": "0.50",
// "marketProviderFee": "0.02",
// "networkFee": "0.000001"
// }
//
let mut outcomeObjResolved: Value = outcomeObj;
if (outcomeObjResolved == Value::Null) {
let mut marketId: Value = self.safe_string_k(trade.clone(), "marketId", &[]);
let mut outcome: Value = self.safe_string_upper_k(trade.clone(), "outcome", &[]);
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut outcomeName: Value = self.safe_string_k(market, "market", &[]);
if (outcomeName == Value::Null) {
outcomeName = marketId;
}
outcomeName = Value::Str(format!("{}{}", outcomeName, Value::Str(format!("{}{}", Value::Str(":".into()), outcome).into())).into());
outcomeObjResolved = self.safe_outcome(outcomeName, &[]);
}
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "createTime", &[]);
let mut filled: Value = self.safe_string_k(trade.clone(), "filledShareQty", &[]);
let mut cost: Value = self.safe_string_k(trade.clone(), "filledUsdtAmount", &[]);
let mut price: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut orderType: Value = self.safe_string_lower_k(trade.clone(), "orderType", &[]);
let mut fee: Value = Value::Null;
if (orderType.as_str() == Some("market")) && (cost != Value::Null) && (price != Value::Null) && (filled != Value::Null) {
// buys pay cost above price*filled, sells receive proceeds net of the fee —
// either way the fee is the absolute difference
let mut feeCost: Value = crate::precise::Precise::stringAbs(&crate::precise::Precise::stringSub(&cost, &crate::precise::Precise::stringMul(&price, &filled)));
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDT".into()));
m.insert("cost".to_string(), self.parse_number(feeCost, &[]));
m
});
}
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Null);
m.insert("info".to_string(), trade.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(outcomeObjResolved.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "market", &[]));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "orderId", &[]));
m.insert("type".to_string(), orderType);
m.insert("side".to_string(), self.safe_string_lower_k(trade.clone(), "side", &[]));
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), self.safe_string_k(trade, "makerShareQty", &[]));
m.insert("cost".to_string(), cost);
m.insert("fee".to_string(), fee);
m
}), &[outcomeObjResolved]);
Value::Null
}
/*
* @method
* @name binance#fetchWallet
* @description fetch wallet for user and save the one match the walletAddress user provided
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/wallet#list-prediction-wallets
* @param {string} [methodName] method name
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a wallet
*/
pub async fn fetch_wallet(&mut self, mut methodName: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut cachedWallet: Value = self.safe_dict_k(self.options.clone(), "wallet", &[]);
if (cachedWallet != Value::Null) {
return cachedWallet;
}
let mut walletAddress: Value = self.handle_option_string_and_params(params, methodName, Value::Str("walletAddress".into()), &[self.walletAddress.clone()]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut response: Value = self.sapi_private_get_wallet_list(&[]).await;
//
// {
// "wallets": [
// {
// "walletAddress": "0x12e32db8817e292508c34111cbc4b23340df542c",
// "walletId": "5b5c1ec3be4e4416a5872b21c1ca5d20",
// "registeredTime": 1748000000000
// }
// ]
// }
//
let mut wallets: Value = self.safe_list_k(response, "wallets", &[Value::from(vec![])]);
if (walletAddress == Value::Null) {
cachedWallet = self.safe_dict(wallets.clone(), Value::Int(0), &[]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wallet".into(), cachedWallet.clone()); }
return cachedWallet;
}
let mut walletLength: f64 = ((wallets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1177: bool = true;
while { if !__for_first_1177 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1177 = false; i.as_f64().unwrap_or(f64::NAN) < walletLength } {
let mut w: Value = self.safe_string(wallets.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("walletAddress".into()), &[Value::Str("".into())]);
if (w.as_str() == walletAddress.as_str()) {
cachedWallet = wallets.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);
break;
}
}
}
if (cachedWallet == Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str("fetchWallet could'n find wallet ".into())).into()), walletAddress)));
}
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wallet".into(), cachedWallet.clone()); }
return cachedWallet;
Value::Null
}
/*
* @method
* @name binance#fetchQuote
* @description request for quote from binance server
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#get-quote
* @param {object} [request] request to the exchange API endpoint
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.chainId] Chain ID. Default 56 (BSC)
* @param {integer} [params.feeRateBps] Fee rate in basis points. Default 200, range 1–10000
* @param {string} [params.fundingSource] Funding source. Enum: MPC, CEX. Default MPC
* @param {string} [params.fundTransferAmount] Auto-transfer amount before order (wei). Must be > 0 if provided
* @returns {object} a quote
*/
pub async fn fetch_quote(&mut self, mut request: 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_13 = self.extend(request, &[params]);
let mut response: Value = self.sapi_private_post_trade_get_quote(&[__ws_arg_13]).await;
return response;
Value::Null
}
pub fn price_to_precision(&self, mut outcome: Value, mut price: Value) -> Value {
let mut market: Value = self.market(outcome);
let mut prec: Value = self.safe_number(self.safe_dict_k(market, "precision", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("price".into()), &[Value::Float(0.0001)]);
let mut decimals: Value = Value::Int(4);
if (prec != Value::Null) && (prec.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
decimals = self.precision_from_string(self.number_to_string(prec));
}
return self.decimal_to_precision(price, Value::Int(crate::runtime::ROUND), decimals, &[Value::Int(crate::runtime::DECIMAL_PLACES), self.paddingMode.clone()]);
Value::Null
}
pub fn amount_to_precision(&self, mut outcome: Value, mut amount: Value) -> Value {
let mut market: Value = self.market(outcome);
let mut prec: Value = self.safe_number(self.safe_dict_k(market, "precision", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("amount".into()), &[Value::Float(0.01)]);
let mut decimals: Value = Value::Int(2);
if (prec != Value::Null) && (prec.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
decimals = self.precision_from_string(self.number_to_string(prec));
}
return self.decimal_to_precision(amount, Value::Int(crate::runtime::TRUNCATE), decimals, &[Value::Int(crate::runtime::DECIMAL_PLACES), self.paddingMode.clone()]);
Value::Null
}
/*
* @method
* @name binance#createOrder
* @description creates a limit or market order for an outcome market
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#place-order
* @param {string} outcome unified outcome
* @param {string} type 'limit' or 'market'
* @param {string} side 'buy' or 'sell'
* @param {float} amount quantity of outcome tokens
* @param {float} [price] limit price (0–1 range for prediction markets)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.timeInForce] Must match orderType: FOK for MARKET, GTC for LIMIT
* @param {string} [params.slippage] slippage for market orders (default 5%)
* @param {string} [params.fundingSource] Funding source. Enum: MPC, CEX. Default MPC
* @param {string} [params.fundTransferAmount] Auto-transfer amount before order (wei). Must be > 0 if provided
* @param {string} [params.accountType] Payment account type. Enum: SPOT, FUNDING
* @param {string} [params.feeRateBps] Payment account type. Enum: SPOT, FUNDING
* @param {string} [params.cost] Buy prediction market with USDT cost, only for buy side
* @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.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
// markets are keyed by the parent market outcome; the outcome handle ("MARKET:LABEL")
// is not a market id, so resolve the market and price/amount precision via outcomeObj['market']
let mut marketSymbol: Value = self.safe_string_k(outcomeObj.clone(), "market", &[]);
let mut market: Value = self.market(marketSymbol.clone());
let mut typeUpper: Value = to_upper(&type_var);
let mut sideUpper: Value = to_upper(&side);
let mut wallet: Value = self.fetch_wallet(Value::Str("createOrder".into()), &[params.clone()]).await;
let mut defaultSlippage: Value = self.safe_string_k(self.options.clone(), "defaultSlippage", &[Value::Str("0.05".into())]);
let mut slippage: Value = self.safe_string_k(params.clone(), "slippage", &[defaultSlippage]);
let mut cost: Value = self.safe_string_k(params.clone(), "cost", &[]);
let mut slippageBps: Value = self.parse_to_int(crate::precise::Precise::stringMul(&slippage, &Value::Str("10000".into())));
let mut commonRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("walletAddress".to_string(), crate::value::get_value_k(&wallet, "walletAddress"));
m.insert("orderType".to_string(), typeUpper.clone());
m.insert("slippageBps".to_string(), slippageBps);
m
});
let mut amountStr: Value = self.number_to_string(amount.clone());
let mut priceStr: Value = self.number_to_string(price.clone());
let mut defaultTif: Value = Value::Str("FOK".into());
if (typeUpper.as_str() == Some("LIMIT")) {
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str("createOrder requires price for limit order".into()))));
}
if let Value::Dict(__d) = &mut commonRequest { std::sync::Arc::make_mut(__d).insert("priceLimit".into(), self.price_to_precision(marketSymbol.clone(), price.clone())); }
defaultTif = Value::Str("GTC".into());
}
if (sideUpper.as_str() == Some("BUY")) {
if (cost != Value::Null) {
amountStr = cost;
} else {
// the amountIn represents USDT for buy order
let mut feeRateBps: Value = self.safe_string_k(params.clone(), "feeRateBps", &[Value::Str("200".into())]);
if (typeUpper.as_str() == Some("LIMIT")) {
feeRateBps = Value::Str("0".into());
} else {
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder requires price for ".into())).into()), side).into()), Value::Str(" order".into()))));
}
}
let mut feeRate: Value = crate::precise::Precise::stringDiv(&feeRateBps, &Value::Str("10000".into()));
let mut minPrice: Value = crate::precise::Precise::stringMin(&priceStr, &crate::precise::Precise::stringSub(&Value::Str("1".into()), &priceStr));
let mut fee: Value = crate::precise::Precise::stringMul(&crate::precise::Precise::stringMul(&feeRate, &minPrice), &amountStr);
amountStr = crate::precise::Precise::stringAdd(&crate::precise::Precise::stringMul(&amountStr, &priceStr), &fee);
}
}
let mut timeInForce: Value = self.safe_string_upper_k(params.clone(), "timeInForce", &[defaultTif]);
let mut accountType: Value = self.safe_string_k(params.clone(), "accountType", &[]);
if (accountType == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder requires accountType (SPOT, FUNDING)".into()))));
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("timeInForce".into()), Value::Str("accountType".into()), Value::Str("cost".into())]), &[]);
let __ws_arg_14 = self.amount_to_precision(marketSymbol, amountStr);
let mut quoteRequest: Value = self.extend(commonRequest.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tokenId".to_string(), outcomeObj.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("side".to_string(), sideUpper);
m.insert("amountIn".to_string(), crate::precise::Precise::stringMul(&__ws_arg_14, &Value::Str("1000000000000000000".into())));
m
})]);
let mut quote: Value = self.fetch_quote(quoteRequest, &[paramsOmitted.clone()]).await;
let mut quoteId: Value = self.safe_string_k(quote, "quoteId", &[]);
let mut orderRequest: Value = self.extend(commonRequest, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("walletId".to_string(), crate::value::get_value_k(&wallet, "walletId"));
m.insert("quoteId".to_string(), quoteId);
m.insert("timeInForce".to_string(), timeInForce);
m.insert("accountType".to_string(), accountType);
m
})]);
let __ws_arg_15 = self.extend(orderRequest, &[paramsOmitted]);
let mut response: Value = self.sapi_private_post_trade_place_order_bundle(&[__ws_arg_15]).await;
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(response.clone(), "orderId", &[]));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), response);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("status".to_string(), Value::Null);
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "id", &[]));
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("type".to_string(), type_var);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), Value::Null);
m.insert("remaining".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m
}), &[market]);
Value::Null
}
/*
* @method
* @name binance#createMarketOrderWithCost
* @description create a market order by providing the symbol, side and cost
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#place-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} side 'buy' or 'sell'
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_market_order_with_cost(&mut self, mut symbol: Value, mut side: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut req: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), cost.clone());
m
});
let __ws_arg_16 = self.extend(req, &[params]);
return self.create_order(symbol, Value::Str("market".into()), side, cost, &[Value::Null, __ws_arg_16]).await;
Value::Null
}
/*
* @method
* @name binance#cancelOrder
* @description cancels a single open order
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#batch-cancel-orders
* @param {string} id order id
* @param {string} [outcome] unified outcome
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut orders: Value = self.cancel_orders(Value::from(vec![id]), &[outcome, params]).await;
let mut first: Value = self.safe_dict(orders, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return first;
Value::Null
}
/*
* @method
* @name binance#cancelOrders
* @description cancels multiple open orders
* @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#batch-cancel-orders
* @param {string[]} ids order ids
* @param {string} [outcome] unified outcome (required)
* @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
}));
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
}
let mut wallet: Value = self.fetch_wallet(Value::Str("cancelOrders".into()), &[params.clone()]).await;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("walletAddress".to_string(), crate::value::get_value_k(&wallet, "walletAddress"));
m.insert("walletId".to_string(), crate::value::get_value_k(&wallet, "walletId"));
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1178: bool = true;
while { if !__for_first_1178 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1178 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
let mut key: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("cancelInfoList[".into()), self.number_to_string(i.clone())).into()), Value::Str("].orderId".into())).into());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&key), ids.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 __ws_arg_17 = self.extend(request, &[params]);
let mut response: Value = self.sapi_private_post_trade_batch_cancel(&[__ws_arg_17]).await;
//
// {
// "canceled": [
// "54124"
// ],
// "failed": [
// {
// "orderId": "54126",
// "reason": "ORDER_NOT_FOUND"
// }
// ]
// }
//
let mut canceledOrders: Value = self.safe_list_k(response.clone(), "canceled", &[Value::from(vec![])]);
let mut outcomeSymbol: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome]);
let mut failedOrders: Value = self.safe_list_k(response, "failed", &[Value::from(vec![])]);
let mut failedOrdersLength: f64 = ((failedOrders.len() as i64) as f64);
if failedOrdersLength > ((0i64) as f64) {
let mut failedDetails: Value = Value::Str("".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_1179: bool = true;
while { if !__for_first_1179 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1179 = false; i.as_f64().unwrap_or(f64::NAN) < failedOrdersLength } {
let mut failedOrder: Value = self.safe_dict(failedOrders.clone(), i.clone(), &[]);
let mut failedOrderId: Value = self.safe_string_k(failedOrder.clone(), "orderId", &[]);
let mut failedReason: Value = self.safe_string_k(failedOrder, "reason", &[]);
if i.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
failedDetails = Value::Str(format!("{}{}", failedDetails, Value::Str(", ".into())).into());
}
failedDetails = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", failedDetails, failedOrderId).into()), Value::Str(": ".into())).into()), failedReason).into());
}
}
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() failed for ".into())).into()), failedDetails)));
}
let mut orders: Value = Value::from(vec![]);
let mut canceledOrdersLength: f64 = ((canceledOrders.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1180: bool = true;
while { if !__for_first_1180 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1180 = false; i.as_f64().unwrap_or(f64::NAN) < canceledOrdersLength } {
let mut status: Value = canceledOrders.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 order: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), status.clone());
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), status);
m.insert("status".to_string(), Value::Str("canceled".into()));
m.insert("outcome".to_string(), outcomeSymbol.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "id", &[]));
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("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
append_to_array(&mut orders, self.safe_prediction_order(order, &[]));
}
}
return orders;
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
let mut errorCode: Value = self.safe_string_k(response.clone(), "code", &[]);
if (errorCode != Value::Null) && is_true(&crate::precise::Precise::stringLt(&errorCode, &Value::Str("0".into()))) {
let mut message: Value = self.safe_string_k(response, "msg", &[Value::Str("".into())]);
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorCode.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
/*
* @ignore
* @method
* @name binance#sign
* @description builds the request URL and attaches the standard binance SAPI HMAC-SHA256 signature — every prediction endpoint is signed
* @param {string} path the endpoint path
* @param {string|string[]} [api] the api group and access level
* @param {string} [method] HTTP method
* @param {object} [params] request parameters
* @param {object} [headers] request headers
* @param {object} [body] request body
* @returns {object} a dictionary with url, method, body and headers
*/
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("sapi".into()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut apiGroup: Value = (if matches!(&api, Value::Str(_)) { api.clone() } else { get_value(&api, &Value::Int(0)) });
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("sapi")).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), &[]);
self.check_required_credentials(&[]);
let __ws_arg_18 = self.nonce();
let mut extendedParams: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timestamp".to_string(), __ws_arg_18);
m
}), &[query]);
let mut defaultRecvWindow: Value = self.safe_integer_k(self.options.clone(), "recvWindow", &[]);
if (defaultRecvWindow != Value::Null) {
add_element_to_object(&mut extendedParams, &Value::Str("recvWindow".into()), defaultRecvWindow);
}
let mut querystring: Value = self.urlencode_nested(extendedParams, &[]);
querystring = replace_all_str(&querystring, &Value::Str("%5B".into()), &Value::Str("[".into()));
querystring = replace_all_str(&querystring, &Value::Str("%5D".into()), &Value::Str("]".into()));
let mut signature: Value = self.hmac(self.encode(querystring.clone()), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[]);
querystring = Value::Str(format!("{}{}", Value::Str(format!("{}{}", querystring, Value::Str("&signature=".into())).into()), signature).into());
let mut headersValue: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("X-MBX-APIKEY".to_string(), self.apiKey.clone());
m
});
let mut bodyValue: Value = body;
if (method.as_str() == Some("GET")) || (method.as_str() == Some("DELETE")) {
url = Value::Str(format!("{}{}", Value::Str(format!("{}{}", url, Value::Str("?".into())).into()), querystring).into());
} else {
bodyValue = querystring;
if let Value::Dict(__d) = &mut headersValue { std::sync::Arc::make_mut(__d).insert("Content-Type".into(), Value::Str("application/x-www-form-urlencoded".into())); }
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), bodyValue);
m.insert("headers".to_string(), headersValue);
m
});
Value::Null
}
}