// 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::*;
pub struct PolymarketCore {
pub parent: crate::exchanges::polymarket::PolymarketCore,
}
impl PolymarketCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::polymarket::PolymarketCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = PolymarketCore::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 PolymarketCore {
fn nonce(&self, ) -> crate::Value {
crate::exchange::DerivedExchange::nonce(&self.parent)
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ticker(&self.parent, ticker, market)
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_trade(&self.parent, trade, market)
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_order(&self.parent, order, market)
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_market(&self.parent, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ohlcv(&self.parent, ohlcv, market)
}
fn parse_order_book(&self, ob: crate::Value, symbol: crate::Value, ts: crate::Value, bk: crate::Value, ak: crate::Value, pk: crate::Value, ak2: crate::Value, ck: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_order_book(&self.parent, ob, symbol, ts, bk, ak, pk, ak2, ck)
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_balance(&self.parent, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_position(&self.parent, position, market)
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_funding_rate(&self.parent, rate, market)
}
fn parse_deposit(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit(&self.parent, tx, currency)
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit_address(&self.parent, depositAddress, currency)
}
fn parse_last_price(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_last_price(&self.parent, entry, market)
}
fn parse_withdrawal(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_withdrawal(&self.parent, tx, currency)
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ledger_entry(&self.parent, entry, currency)
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_transfer(&self.parent, transfer, currency)
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_currency(&self.parent, currency)
}
fn parse_bid_ask(&self, bidask: crate::Value, price_key: crate::Value, amount_key: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_bid_ask(&self.parent, bidask, price_key, amount_key, market)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_open_interest(&self.parent, interest, market)
}
fn parse_liquidation(&self, liquidation: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_liquidation(&self.parent, liquidation, market)
}
fn parse_funding_rate_history(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_funding_rate_history(&self.parent, entry, market)
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_margin_modification(&self.parent, data, market)
}
fn parse_account(&self, account: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_account(&self.parent, account)
}
fn parse_my_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_my_trade(&self.parent, trade, market)
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_transaction(&self.parent, transaction, currency)
}
fn parse_borrow_interest(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_borrow_interest(&self.parent, info, market)
}
fn parse_adl_rank(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_adl_rank(&self.parent, info, market)
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_income(&self.parent, info, market)
}
fn parse_greeks(&self, greeks: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_greeks(&self.parent, greeks, market)
}
fn parse_margin_mode(&self, margin_mode: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_margin_mode(&self.parent, margin_mode, market)
}
fn parse_conversion(&self, conversion: crate::Value, from_currency: crate::Value, to_currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_conversion(&self.parent, conversion, from_currency, to_currency)
}
fn parse_borrow_rate(&self, info: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_borrow_rate(&self.parent, info, currency)
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_leverage(&self.parent, leverage, market)
}
fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_market_leverage_tiers(&self.parent, info, market)
}
fn parse_deposit_withdraw_fee(&self, fee: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit_withdraw_fee(&self.parent, fee, currency)
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_trade(&self.parent, trade, market)
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_order(&self.parent, order, market)
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_position(&self.parent, position, market)
}
fn create_expired_option_market(&self, symbol: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::create_expired_option_market(&self.parent, symbol)
}
fn market(&self, symbol: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::market(&self.parent, symbol)
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::sign(&self.parent, 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 {
crate::exchange::DerivedExchange::handle_errors(&self.parent, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for PolymarketCore {
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 {
"authenticate" => self.authenticate(&args[..]).await,
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"load_balance_snapshot" => self.load_balance_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"load_positions_snapshot" => self.load_positions_snapshot(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"request_id" => self.request_id(),
"send_subscription" => self.send_subscription(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())..]),
"un_watch_ohlcv" => self.un_watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_order_book" => self.un_watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_ticker" => self.un_watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_trades" => self.un_watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_balance" => self.watch_balance(&args[..]).await,
"watch_bids_asks" => self.watch_bids_asks(&args[..]).await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_ohlcv" => self.watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_positions" => self.watch_positions(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_tickers" => self.watch_tickers(&args[..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// Go-style inheritance: an un-overridden method dispatches to the parent core.
_ => crate::exchange_generated::ExchangeBase::call_dynamic(&mut self.parent, method, args).await,
}
})
}
}
impl PolymarketCore {
/// Synchronous WS handler dispatch — routes a handler-name string (from the
/// venue's handle_message dispatch table) to the real handler method.
#[allow(dead_code, unreachable_patterns, clippy::all)]
pub fn dispatch_ws_handler(&mut self, __name: &crate::Value, args: &[crate::Value]) -> crate::Value {
let __n = match __name { crate::Value::Str(s) => s.as_ref(), _ => return crate::Value::Null };
match __n {
"authenticate" => { crate::exchange_stubs::enqueue_spawn("authenticate", args.to_vec()); crate::Value::Null },
"handle_ack" => { self.handle_ack(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_bid_ask" => { self.handle_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_my_trades" => { self.handle_my_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ohlcv" => { self.handle_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order" => { self.handle_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book" => { self.handle_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_portfolio" => { self.handle_portfolio(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ticker" => { self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trades" => { self.handle_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"load_balance_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_balance_snapshot", args.to_vec()); crate::Value::Null },
"load_positions_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_positions_snapshot", args.to_vec()); crate::Value::Null },
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"request_id" => self.request_id(),
"send_subscription" => self.send_subscription(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())..]),
"set_balance_cache" => { self.set_balance_cache(args.get(0).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"set_positions_cache" => { self.set_positions_cache(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]); crate::Value::Null },
"un_watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("un_watch_ohlcv", args.to_vec()); crate::Value::Null },
"un_watch_order_book" => { crate::exchange_stubs::enqueue_spawn("un_watch_order_book", args.to_vec()); crate::Value::Null },
"un_watch_ticker" => { crate::exchange_stubs::enqueue_spawn("un_watch_ticker", args.to_vec()); crate::Value::Null },
"un_watch_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades", args.to_vec()); crate::Value::Null },
"watch_balance" => { crate::exchange_stubs::enqueue_spawn("watch_balance", args.to_vec()); crate::Value::Null },
"watch_bids_asks" => { crate::exchange_stubs::enqueue_spawn("watch_bids_asks", args.to_vec()); crate::Value::Null },
"watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("watch_my_trades", args.to_vec()); crate::Value::Null },
"watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_orders" => { crate::exchange_stubs::enqueue_spawn("watch_orders", args.to_vec()); crate::Value::Null },
"watch_positions" => { crate::exchange_stubs::enqueue_spawn("watch_positions", args.to_vec()); crate::Value::Null },
"watch_ticker" => { crate::exchange_stubs::enqueue_spawn("watch_ticker", args.to_vec()); crate::Value::Null },
"watch_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_tickers", args.to_vec()); crate::Value::Null },
"watch_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for PolymarketCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for PolymarketCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl PolymarketCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.parent.describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Bool(true));
m.insert("watchBalance".to_string(), Value::Bool(true));
m.insert("watchBidsAsks".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchPositions".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(false));
m.insert("unWatchOHLCV".to_string(), Value::Bool(true));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m.insert("unWatchTicker".to_string(), Value::Bool(true));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Str("wss://ws.perpetuals.polymarket.com/v1/ws".into()));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("watchPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fetchPositionsSnapshot".to_string(), Value::Bool(true));
m.insert("awaitPositionsSnapshot".to_string(), Value::Bool(true));
m
}));
m.insert("watchBalance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fetchBalanceSnapshot".to_string(), Value::Bool(true));
m.insert("awaitBalanceSnapshot".to_string(), Value::Bool(true));
m
}));
m.insert("wsTimeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15m".to_string(), Value::Str("15m".into()));
m.insert("30m".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("6h".to_string(), Value::Str("6h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m
}));
m
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ping".to_string(), Value::Str("ping".into()).clone());
m.insert("keepAlive".to_string(), Value::Int(20000));
m
}));
m
})]);
Value::Null
}
pub fn request_id(&mut self) -> Value {
let mut requestId: Value = self.sum(&[self.safe_integer_k(self.options.clone(), "requestId", &[Value::Int(0)]), Value::Int(1)]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("requestId".into(), requestId.clone()); }
return requestId;
Value::Null
}
/*
* @method
* @ignore
* @name polymarket#sendSubscription
* @description sends a subscribe or unsubscribe request and records the request id so the ack can be matched back
* @param {string} action either 'sub' or 'unsub'
* @param {string[]} channels venue channel names to subscribe to
* @param {string[]} messageHashes message hashes the caller awaits
* @param {string[]} subMessageHashes the underlying subscription hashes, used to reject or clean them when the ack fails
* @param {object} [context] extra fields stored with the pending request, e.g. the symbol and topic for cache cleanup
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the raw request frame to send
*/
pub fn send_subscription(&mut self, mut action: Value, mut channels: Value, mut messageHashes: Value, mut subMessageHashes: Value, optional_args: &[Value]) -> Value {
let mut context = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut checkHashes = get_arg(optional_args, 2, Value::Null);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut client: Value = self.client(&[url]);
// the base watch only sends the request when one of the hashes is not
// subscribed yet, so a pending entry is registered under the same
// condition - otherwise no ack would ever arrive to consume it, the
// private channels register a shared hash next to narrowed ones
let mut hashesToCheck: Value = (if (checkHashes == Value::Null) { messageHashes.clone() } else { checkHashes });
let mut willSend: bool = false;
{
let mut i: Value = Value::Int(0);
let mut __for_first_624: bool = true;
while { if !__for_first_624 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_624 = false; i.as_f64().unwrap_or(f64::NAN) < ((hashesToCheck.len() as i64) as f64) } {
if !(in_op(&get_value(&client, &Value::Str("subscriptions".into())), &hashesToCheck.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))) {
willSend = true;
}
}
}
if !willSend {
let mut emptyRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
return self.extend(emptyRequest, &[params.clone()]);
}
let mut id: Value = self.request_id();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("req".to_string(), action.clone());
m.insert("chs".to_string(), channels);
m
});
let mut basePending: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), action);
m.insert("messageHashes".to_string(), messageHashes);
m.insert("subMessageHashes".to_string(), subMessageHashes);
m
});
let mut pending: Value = self.extend(basePending, &[context]);
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &Value::Str(format!("{}{}", Value::Str("req:".into()), Value::Str(format!("{}", id).into())).into()), pending);
return self.extend(request, &[params]);
Value::Null
}
/*
* @method
* @name polymarket#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] not used by polymarket watchOrderBook, the channel always carries the top twenty levels
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/#/?id=order-book-structure}
*/
pub async fn watch_order_book(&mut self, mut symbol: 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_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbolResolved).into());
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("book::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(vec![channel]), Value::from(vec![messageHash.clone()]), Value::from(vec![messageHash.clone()]), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut orderbook: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name polymarket#unWatchOrderBook
* @description unWatches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} symbol unified symbol of the market to unwatch the order book for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} status of the unwatch request
*/
pub async fn un_watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbolResolved).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("book::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut context: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("topic".to_string(), Value::Str("orderbook".into()));
m.insert("symbol".to_string(), symbolResolved);
m
});
let mut request: Value = self.send_subscription(Value::Str("unsub".into()), Value::from(vec![channel]), Value::from(vec![messageHash.clone()]), Value::from(vec![subMessageHash]), &[context, params]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
return self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "ch": "book::1",
// "ts": 1788546815589,
// "ets": 1788546815543,
// "sq": 35879871598,
// "data": {
// "a": [ [ "7715.7", "0.31631" ] ],
// "b": [ [ "7715.6", "7.43477" ] ]
// }
// }
//
// every frame is a full snapshot of the top twenty levels, deltas are never sent
//
let mut ch: Value = (match message.get("ch") { 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("".into()) });
let mut parts: Value = Value::Array(ch.as_str().map(|__s| __s.split("::").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
let mut marketId: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut timestamp: Value = (match message.get("ts") { 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 snapshot: Value = self.parse_order_book(data, symbol.clone(), &[timestamp, Value::Str("b".into()), Value::Str("a".into())]);
add_element_to_object(&mut snapshot, &Value::Str("nonce".into()), (match message.get("sq") { 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 }));
if !(matches!((&self.orderbooks, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
let mut ob: Value = self.order_book(&[snapshot.clone()]);
if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ob); }
}
let mut orderbook: Value = self.orderbooks.as_map().and_then(|__m| symbol.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
orderbook.reset(snapshot);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook:".into()), symbol).into());
client.resolve(&[orderbook, messageHash]);
}
/*
* @method
* @name polymarket#watchTicker
* @description watches a price ticker, which carries the last, mark and index prices, the mid price, the open interest and the funding rate stay available on the raw frame under the info field
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbolResolved).into());
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("tickers::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(vec![channel]), Value::from(vec![messageHash.clone()]), Value::from(vec![messageHash.clone()]), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
return self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
Value::Null
}
/*
* @method
* @name polymarket#unWatchTicker
* @description unWatches the price ticker
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} symbol unified symbol of the market to unwatch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} status of the unwatch request
*/
pub async fn un_watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbolResolved).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("tickers::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut context: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("topic".to_string(), Value::Str("ticker".into()));
m.insert("symbol".to_string(), symbolResolved);
m
});
let mut request: Value = self.send_subscription(Value::Str("unsub".into()), Value::from(vec![channel]), Value::from(vec![messageHash.clone()]), Value::from(vec![subMessageHash]), &[context, params]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
return self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
Value::Null
}
/*
* @method
* @name polymarket#watchTickers
* @description watches price tickers for multiple markets, the venue fans the all-instruments channel out into one frame per instrument
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, all market tickers are streamed if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
pub async fn watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = 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_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut messageHashes: Value = Value::from(vec![]);
let mut channels: Vec<Value> = Vec::new();
if (symbolsNormalized == Value::Null) {
if let Value::Arr(__a) = &mut messageHashes { std::sync::Arc::make_mut(__a).push(Value::Str("tickers".into())); }
channels.push(Value::Str("tickers::all".into()));
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_625: bool = true;
while { if !__for_first_625 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_625 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsNormalized.len() as i64) as f64) } {
let mut market: Value = self.market(symbolsNormalized.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::Arr(__a) = &mut messageHashes { std::sync::Arc::make_mut(__a).push(Value::Str(format!("{}{}", Value::Str("ticker:".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into())); }
channels.push(Value::Str(format!("{}{}", Value::Str("tickers::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
}
}
}
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(channels), messageHashes.clone(), messageHashes.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params]);
let mut newTicker: Value = self.watch_multiple(url, messageHashes.clone(), &[request, messageHashes.clone()]).await;
if self.newUpdates.as_bool() == Some(true) {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut result, &crate::value::get_value_k(&newTicker, "symbol"), newTicker.clone());
return result;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
pub fn handle_ticker(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "ch": "tickers::1",
// "ts": 1788546815743,
// "ets": 1788546815693,
// "sq": 35879872600,
// "data": {
// "iid": 1,
// "idx": "7713.6",
// "mark": "7715.6",
// "last": "7714",
// "mid": "7715.6",
// "oi": "1101.82729",
// "fr": "0.00000625",
// "nxf": 1788548400000
// }
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "iid", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = (match message.get("ts") { 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 ticker: Value = self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("close".to_string(), self.safe_string_k(data.clone(), "last", &[]));
m.insert("last".to_string(), self.safe_string_k(data.clone(), "last", &[]));
m.insert("markPrice".to_string(), self.safe_string_k(data.clone(), "mark", &[]));
m.insert("indexPrice".to_string(), self.safe_string_k(data.clone(), "idx", &[]));
m.insert("info".to_string(), data);
m
}), &[market]);
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker.clone()); }
client.resolve(&[ticker.clone(), Value::Str(format!("{}{}", Value::Str("ticker:".into()), symbol).into())]);
client.resolve(&[ticker, Value::Str("tickers".into())]);
}
/*
* @method
* @name polymarket#watchBidsAsks
* @description watches best bids and asks for multiple markets
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string[]} symbols unified symbols of the markets to fetch the best bids and asks for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
pub async fn watch_bids_asks(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = 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_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(false)]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut messageHashes: Value = Value::from(vec![]);
let mut channels: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_626: bool = true;
while { if !__for_first_626 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_626 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsNormalized.len() as i64) as f64) } {
let mut market: Value = self.market(symbolsNormalized.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::Arr(__a) = &mut messageHashes { std::sync::Arc::make_mut(__a).push(Value::Str(format!("{}{}", Value::Str("bidask:".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into())); }
channels.push(Value::Str(format!("{}{}", Value::Str("bbo::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
}
}
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(channels), messageHashes.clone(), messageHashes.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params]);
let mut ticker: Value = self.watch_multiple(url, messageHashes.clone(), &[request, messageHashes.clone()]).await;
if self.newUpdates.as_bool() == Some(true) {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut result, &crate::value::get_value_k(&ticker, "symbol"), ticker.clone());
return result;
}
return self.filter_by_array(self.bidsasks.clone(), Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
pub fn handle_bid_ask(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "ch": "bbo::1",
// "ts": 1788546815589,
// "ets": 1788546815543,
// "sq": 35879871599,
// "data": {
// "iid": 1,
// "bp": "7714.9",
// "bq": "22.96595",
// "ap": "7715.8",
// "aq": "12.9618"
// }
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Value = self.safe_string_k(data.clone(), "iid", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = (match message.get("ts") { 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 ticker: Value = self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("bid".to_string(), self.safe_string_k(data.clone(), "bp", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(data.clone(), "bq", &[]));
m.insert("ask".to_string(), self.safe_string_k(data.clone(), "ap", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(data.clone(), "aq", &[]));
m.insert("info".to_string(), data);
m
}), &[market]);
if let Value::Dict(__d) = &mut self.bidsasks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker.clone()); }
client.resolve(&[ticker, Value::Str(format!("{}{}", Value::Str("bidask:".into()), symbol).into())]);
}
/*
* @method
* @name polymarket#watchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades}
*/
pub async fn watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trade:".into()), symbolResolved).into());
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("trades::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(vec![channel]), Value::from(vec![messageHash.clone()]), Value::from(vec![messageHash.clone()]), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut trades: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
let mut limitResolved: Value = limit;
if self.newUpdates.as_bool() == Some(true) {
limitResolved = trades.get_limit(symbolResolved, limitResolved.clone());
}
return self.filter_by_since_limit(trades, &[since, limitResolved, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name polymarket#unWatchTrades
* @description unWatches the trades stream
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} symbol unified symbol of the market to unwatch the trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} status of the unwatch request
*/
pub async fn un_watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str("trade:".into()), symbolResolved).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut channel: Value = Value::Str(format!("{}{}", Value::Str("trades::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
let mut context: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("topic".to_string(), Value::Str("trades".into()));
m.insert("symbol".to_string(), symbolResolved);
m
});
let mut request: Value = self.send_subscription(Value::Str("unsub".into()), Value::from(vec![channel]), Value::from(vec![messageHash.clone()]), Value::from(vec![subMessageHash]), &[context, params]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
return self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
Value::Null
}
pub fn handle_trades(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "ch": "trades::1",
// "ts": 1788546815589,
// "ets": 1788546815543,
// "sq": 35879871600,
// "data": {
// "tid": 3738280849593744,
// "iid": 1,
// "side": "long",
// "p": "7714",
// "qty": "0.00136",
// "ts": 1788546565789,
// "hash": "0x"
// }
// }
//
// the asyncapi spec describes the data field as an array of trade objects while typing it
// as a single object, so both shapes are handled here
//
let mut data: Value = (match message.get("data") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Null });
let mut rows: Value = Value::from(vec![]);
if (matches!(&data, Value::Arr(_))) {
rows = data.clone();
} else {
append_to_array(&mut rows, data);
}
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
if (rowsLength == 0.0) {
return;
}
let mut first: Value = self.safe_dict(rows.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string_k(first, "iid", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if !(matches!((&self.trades, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
let mut stored = ArrayCache::new(limit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored); }
}
let mut trades: Value = self.trades.as_map().and_then(|__m| symbol.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
{
let mut i: Value = Value::Int(0);
let mut __for_first_627: bool = true;
while { if !__for_first_627 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_627 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut row: Value = self.safe_dict(rows.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut trade: Value = self.parse_ws_trade(row, &[market.clone()]);
trades.append(trade);
}
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trade:".into()), symbol).into());
client.resolve(&[trades, messageHash]);
}
pub fn parse_ws_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "tid": 3738280849593744,
// "iid": 1,
// "side": "long",
// "p": "7714",
// "qty": "0.00136",
// "ts": 1788546565789,
// "hash": "0x"
// }
//
let mut marketId: Value = self.safe_string_k(trade.clone(), "iid", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "ts", &[]);
let mut side: Value = self.safe_string_lower_k(trade.clone(), "side", &[]);
if (side.as_str() == Some("long")) {
side = Value::Str("buy".into());
} else if (side.as_str() == Some("short")) {
side = Value::Str("sell".into());
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "tid", &[]));
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("price".to_string(), self.safe_string_k(trade.clone(), "p", &[]));
m.insert("amount".to_string(), self.safe_string_k(trade, "qty", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name polymarket#watchOHLCV
* @description watches historical candlestick data containing the open, high, low, close price, and the volume of a market
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents, the 1s timeframe is not available over the websocket
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut wsTimeframes: Value = self.safe_dict_k(self.options.clone(), "wsTimeframes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut interval: Value = self.safe_string(wsTimeframes, timeframe.clone(), &[]);
if (interval == Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" watchOHLCV() does not support the ".into())).into()), timeframe).into()), Value::Str(" timeframe over the websocket".into()))));
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("candles:".into()), timeframe).into()), Value::Str(":".into())).into()), symbolResolved).into());
let mut channel: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("klines::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str("::".into())).into()), interval).into());
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(vec![channel]), Value::from(vec![messageHash.clone()]), Value::from(vec![messageHash.clone()]), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut ohlcv: Value = self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
let mut limitResolved: Value = limit;
if self.newUpdates.as_bool() == Some(true) {
limitResolved = ohlcv.get_limit(symbolResolved, limitResolved.clone());
}
return self.filter_by_since_limit(ohlcv, &[since, limitResolved, Value::Int(0), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name polymarket#unWatchOHLCV
* @description unWatches the candlestick stream
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} symbol unified symbol of the market to unwatch the candles for
* @param {string} timeframe the length of time each candle represents
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} status of the unwatch request
*/
pub async fn un_watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut wsTimeframes: Value = self.safe_dict_k(self.options.clone(), "wsTimeframes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut interval: Value = self.safe_string(wsTimeframes, timeframe.clone(), &[timeframe.clone()]);
let mut subMessageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("candles:".into()), timeframe).into()), Value::Str(":".into())).into()), symbolResolved).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut channel: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("klines::".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str("::".into())).into()), interval).into());
let mut context: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("topic".to_string(), Value::Str("ohlcv".into()));
m.insert("symbol".to_string(), symbolResolved);
m.insert("timeframe".to_string(), timeframe);
m
});
let mut request: Value = self.send_subscription(Value::Str("unsub".into()), Value::from(vec![channel]), Value::from(vec![messageHash.clone()]), Value::from(vec![subMessageHash]), &[context, params]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
return self.watch(url, messageHash.clone(), &[request, messageHash.clone()]).await;
Value::Null
}
pub fn handle_ohlcv(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "ch": "klines::1::1h",
// "ts": 1788547135685,
// "ets": 1788547135685,
// "sq": 35880657084,
// "data": [
// [ 1788537600000, "7724.9", "7724.9", "7724.2", "7724.2", "0.02872", 5 ]
// ]
// }
//
// only the candles touched by fresh trades are included, the array can be empty
//
let mut ch: Value = (match message.get("ch") { 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("".into()) });
let mut parts: Value = Value::Array(ch.as_str().map(|__s| __s.split("::").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
let mut marketId: Value = self.safe_string(parts.clone(), Value::Int(1), &[]);
let mut interval: Value = self.safe_string(parts, Value::Int(2), &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timeframe: Value = self.find_timeframe(interval, &[]);
if (timeframe == Value::Null) {
return;
}
let mut rows: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
if (rowsLength == 0.0) {
return;
}
if !(matches!((&self.ohlcvs, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut self.ohlcvs { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }
}
if !(in_op(&self.ohlcvs.as_map().and_then(|__m| symbol.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null), &timeframe)) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
let mut stored = ArrayCacheByTimestamp::new(limit);
add_element_to_object(get_value_mut(&mut self.ohlcvs, &symbol), &timeframe, stored);
}
let mut ohlcv: Value = self.ohlcvs.as_map().and_then(|__m| symbol.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| timeframe.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
{
let mut i: Value = Value::Int(0);
let mut __for_first_628: bool = true;
while { if !__for_first_628 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_628 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut parsed: Value = self.parse_ohlcv(rows.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), &[market.clone()]);
ohlcv.append(parsed);
}
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("candles:".into()), timeframe).into()), Value::Str(":".into())).into()), symbol).into());
client.resolve(&[ohlcv, messageHash]);
}
/*
* @method
* @ignore
* @name polymarket#authenticate
* @description authenticates the websocket connection with the session proxy credentials, provisioning them first when needed
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} resolves once the connection is authenticated
*/
pub async fn authenticate(&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 credentials: Value = self.parent.load_proxy_credentials(&[]).await;
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut client: Value = self.client(&[url.clone()]);
let mut messageHash: Value = Value::Str("authenticated".into());
let mut future: Value = client.reusable_future(messageHash.clone());
let mut authenticated: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".into())), messageHash.clone(), &[]);
if (authenticated == Value::Null) {
let mut id: Value = self.request_id();
let mut pending: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("auth".into()));
m.insert("messageHashes".to_string(), Value::from(vec![messageHash.clone()]));
m.insert("subMessageHashes".to_string(), Value::from(vec![messageHash.clone()]));
m
});
add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".into())), &Value::Str(format!("{}{}", Value::Str("req:".into()), Value::Str(format!("{}", id).into())).into()), pending);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("req".to_string(), Value::Str("post".into()));
m.insert("op".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("auth".into()));
m.insert("args".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("proxy".to_string(), self.safe_string_k(credentials.clone(), "proxy", &[]));
m.insert("secret".to_string(), self.safe_string_k(credentials, "secret", &[]));
m
}));
m
}));
m
});
let __ws_arg_0 = self.extend(request, &[params]);
self.watch(url, messageHash.clone(), &[__ws_arg_0, messageHash.clone()]).await;
}
return crate::exchange_stubs::ws_await_flight(&future).await;
Value::Null
}
/*
* @method
* @name polymarket#watchOrders
* @description watches information on the orders made by the user
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} [symbol] unified market symbol of the market the orders were made in
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of order structures to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.authenticate(&[]).await;
let mut messageHash: Value = Value::Str("orders".into());
let mut symbolResolved: Value = symbol;
if (symbolResolved != Value::Null) {
let mut market: Value = self.market(symbolResolved.clone());
symbolResolved = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
messageHash = Value::Str(format!("{}{}", Value::Str("orders:".into()), symbolResolved).into());
}
let mut subscribeHashes: Value = Value::from(vec![Value::Str("orders".into())]);
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(vec![Value::Str("orders".into())]), Value::from(vec![messageHash.clone()]), subscribeHashes.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params, subscribeHashes]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut orders: Value = self.watch(url, messageHash, &[request, Value::Str("orders".into())]).await;
let mut limitResolved: Value = limit;
if self.newUpdates.as_bool() == Some(true) {
limitResolved = orders.get_limit(symbolResolved.clone(), limitResolved.clone());
}
return self.filter_by_symbol_since_limit(orders, &[symbolResolved, since, limitResolved, Value::Bool(true)]);
Value::Null
}
pub fn handle_order(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "ch": "orders",
// "ts": 1788546565800,
// "sq": 35879860000,
// "data": {
// "oid": 1234567890,
// "iid": 6,
// "buy": true,
// "p": "79000.0",
// "qty": "0.001",
// "tif": "gtc",
// "po": false,
// "ro": false,
// "rest": "0.001",
// "fill": "0",
// "cts": 1788546565789,
// "uts": 1788546565789,
// "status": "open"
// }
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Null });
let mut rows: Value = Value::from(vec![]);
if (matches!(&data, Value::Arr(_))) {
rows = data.clone();
} else {
append_to_array(&mut rows, data);
}
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
if (rowsLength == 0.0) {
return;
}
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheBySymbolById::new(limit);
}
let mut stored: Value = self.orders.clone();
let mut symbols: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_629: bool = true;
while { if !__for_first_629 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_629 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut row: Value = self.safe_dict(rows.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut parsed: Value = self.parse_order(row, &[]);
stored.append(parsed.clone());
let mut symbol: Value = self.safe_string_k(parsed, "symbol", &[]);
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut symbols { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Bool(true)); }
}
}
}
client.resolve(&[stored.clone(), Value::Str("orders".into())]);
let mut symbolKeys: Value = object_keys(&symbols);
{
let mut i: Value = Value::Int(0);
let mut __for_first_630: bool = true;
while { if !__for_first_630 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_630 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolKeys.len() as i64) as f64) } {
let mut symbol: Value = symbolKeys.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);
client.resolve(&[stored.clone(), Value::Str(format!("{}{}", Value::Str("orders:".into()), symbol).into())]);
}
}
}
/*
* @method
* @name polymarket#watchMyTrades
* @description watches information on the trades made by the user
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string} [symbol] unified market symbol of the market the trades were made in
* @param {int} [since] timestamp in ms of the earliest trade
* @param {int} [limit] the maximum number of trade structures to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure}
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.authenticate(&[]).await;
let mut messageHash: Value = Value::Str("myTrades".into());
let mut symbolResolved: Value = symbol;
if (symbolResolved != Value::Null) {
let mut market: Value = self.market(symbolResolved.clone());
symbolResolved = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
messageHash = Value::Str(format!("{}{}", Value::Str("myTrades:".into()), symbolResolved).into());
}
let mut subscribeHashes: Value = Value::from(vec![Value::Str("fills".into())]);
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(vec![Value::Str("fills".into())]), Value::from(vec![messageHash.clone()]), subscribeHashes.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params, subscribeHashes]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut trades: Value = self.watch(url, messageHash, &[request, Value::Str("fills".into())]).await;
let mut limitResolved: Value = limit;
if self.newUpdates.as_bool() == Some(true) {
limitResolved = trades.get_limit(symbolResolved.clone(), limitResolved.clone());
}
return self.filter_by_symbol_since_limit(trades, &[symbolResolved, since, limitResolved, Value::Bool(true)]);
Value::Null
}
pub fn handle_my_trades(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "ch": "fills",
// "ts": 1788546571800,
// "sq": 35879861000,
// "data": [
// {
// "tid": 3738280849593744,
// "oid": 1234567891,
// "iid": 6,
// "side": "short",
// "p": "80100.0",
// "qty": "0.002",
// "taker": true,
// "fee": "0.064",
// "fea": "pUSD",
// "psz": "0.003",
// "pep": "79650.0",
// "pnl": "0.9",
// "liq": false,
// "adl": false,
// "ts": 1788546571789
// }
// ]
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Null });
let mut rows: Value = Value::from(vec![]);
if (matches!(&data, Value::Arr(_))) {
rows = data.clone();
} else {
append_to_array(&mut rows, data);
}
let mut rowsLength: f64 = ((rows.len() as i64) as f64);
if (rowsLength == 0.0) {
return;
}
if (self.myTrades.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "myTradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheBySymbolById::new(limit);
}
let mut stored: Value = self.myTrades.clone();
let mut symbols: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_631: bool = true;
while { if !__for_first_631 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_631 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut row: Value = self.safe_dict(rows.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut parsed: Value = self.parse_trade(row, &[]);
stored.append(parsed.clone());
let mut symbol: Value = self.safe_string_k(parsed, "symbol", &[]);
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut symbols { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Bool(true)); }
}
}
}
client.resolve(&[stored.clone(), Value::Str("myTrades".into())]);
let mut symbolKeys: Value = object_keys(&symbols);
{
let mut i: Value = Value::Int(0);
let mut __for_first_632: bool = true;
while { if !__for_first_632 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_632 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolKeys.len() as i64) as f64) } {
let mut symbol: Value = symbolKeys.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);
client.resolve(&[stored.clone(), Value::Str(format!("{}{}", Value::Str("myTrades:".into()), symbol).into())]);
}
}
}
/*
* @method
* @name polymarket#watchPositions
* @description watches information on the open positions of the account, the venue pushes a full portfolio snapshot roughly every five seconds
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {string[]} [symbols] list of unified market symbols
* @param {int} [since] not used by polymarket watchPositions
* @param {int} [limit] not used by polymarket watchPositions
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
pub async fn watch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.authenticate(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut client: Value = self.client(&[url.clone()]);
self.set_positions_cache(client.clone(), &[symbolsNormalized.clone()]);
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("fetchPositionsSnapshot".into()), &[Value::Bool(true)]);
let mut awaitPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("awaitPositionsSnapshot".into()), &[Value::Bool(true)]);
let mut cache: Value = self.positions.clone();
if ((match &(fetchPositionsSnapshot) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) })) && ((match &(awaitPositionsSnapshot) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) })) && (cache == Value::Null) {
// the portfolio channel pushes one snapshot at subscribe time and
// then only on changes, so the first call hydrates over rest
let mut snapshot: Value = crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str("fetchPositionsSnapshot".into())])).await;
return self.filter_by_symbols_since_limit(snapshot, &[symbolsNormalized.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
}
let mut subscribeHashes: Value = Value::from(vec![Value::Str("portfolio".into())]);
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(vec![Value::Str("portfolio".into())]), Value::from(vec![Value::Str("positions".into())]), subscribeHashes.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params, subscribeHashes]);
let mut newPositions: Value = self.watch(url, Value::Str("positions".into()), &[request, Value::Str("portfolio".into())]).await;
if self.newUpdates.as_bool() == Some(true) {
return self.filter_by_symbols_since_limit(newPositions, &[symbolsNormalized.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
}
return self.filter_by_symbols_since_limit(self.positions.clone(), &[symbolsNormalized, since, limit, Value::Bool(true)]);
Value::Null
}
pub fn set_positions_cache(&mut self, mut client: Value, optional_args: &[Value]) {
let mut symbols = get_arg(optional_args, 0, Value::Null);
if (self.positions.clone() != Value::Null) {
return;
}
let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".into()), Value::Str("fetchPositionsSnapshot".into()), &[Value::Bool(true)]);
if (match &(fetchPositionsSnapshot) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) }) {
let mut messageHash: Value = Value::Str("fetchPositionsSnapshot".into());
if !(in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
client.future(&[messageHash.clone()]);
self.spawn(&[Value::Str("load_positions_snapshot".into()).clone(), client.clone(), messageHash.clone()]);
}
} else {
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
}
}
pub async fn load_positions_snapshot(&mut self, mut client: Value, mut messageHash: Value) -> Value {
let mut positions: Value = self.fetch_positions(&[]).await;
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
let mut cache: Value = self.positions.clone();
{
let mut i: Value = Value::Int(0);
let mut __for_first_633: bool = true;
while { if !__for_first_633 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_633 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
cache.append(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));
}
}
// don't remove the future from the .futures cache
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".into())), &messageHash);
future.resolve(&[cache.clone()]);
}
client.resolve(&[cache, Value::Str("positions".into())]);
Value::Null
}
/*
* @method
* @name polymarket#watchBalance
* @description watches the account margin summary, the venue pushes a full portfolio snapshot roughly every five seconds
* @see https://docs.polymarket.com/perps/realtime-updates
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/#/?id=balance-structure}
*/
pub async fn watch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.authenticate(&[]).await;
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut client: Value = self.client(&[url.clone()]);
self.set_balance_cache(client.clone());
let mut fetchBalanceSnapshot: Value = self.handle_option(Value::Str("watchBalance".into()), Value::Str("fetchBalanceSnapshot".into()), &[Value::Bool(true)]);
let mut awaitBalanceSnapshot: Value = self.handle_option(Value::Str("watchBalance".into()), Value::Str("awaitBalanceSnapshot".into()), &[Value::Bool(true)]);
let mut balanceLoaded: bool = matches!(&self.balance, Value::Dict(__d) if __d.contains_key("info"));
if ((match &(fetchBalanceSnapshot) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) })) && ((match &(awaitBalanceSnapshot) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) })) && (!balanceLoaded) {
// the portfolio channel pushes one snapshot at subscribe time and
// then only on changes, so the first call hydrates over rest
let mut snapshot: Value = crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str("fetchBalanceSnapshot".into())])).await;
return snapshot;
}
let mut subscribeHashes: Value = Value::from(vec![Value::Str("portfolio".into())]);
let mut request: Value = self.send_subscription(Value::Str("sub".into()), Value::from(vec![Value::Str("portfolio".into())]), Value::from(vec![Value::Str("balance".into())]), subscribeHashes.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), params, subscribeHashes]);
return self.watch(url, Value::Str("balance".into()), &[request, Value::Str("portfolio".into())]).await;
Value::Null
}
pub fn set_balance_cache(&mut self, mut client: Value) {
let mut balanceLoaded: bool = matches!(&self.balance, Value::Dict(__d) if __d.contains_key("info"));
if balanceLoaded {
return;
}
let mut fetchBalanceSnapshot: Value = self.handle_option(Value::Str("watchBalance".into()), Value::Str("fetchBalanceSnapshot".into()), &[Value::Bool(true)]);
if (match &(fetchBalanceSnapshot) { Value::Bool(__x) => *__x == true, __v => matches!((match __v { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), Some(__y) if __y == 1.0) }) {
let mut messageHash: Value = Value::Str("fetchBalanceSnapshot".into());
if !(in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
client.future(&[messageHash.clone()]);
self.spawn(&[Value::Str("load_balance_snapshot".into()).clone(), client.clone(), messageHash.clone()]);
}
}
}
pub async fn load_balance_snapshot(&mut self, mut client: Value, mut messageHash: Value) -> Value {
let mut balance: Value = self.fetch_balance(&[]).await;
{ let __t = self.extend(self.balance.clone(), &[balance.clone()]); self.balance = __t; }
// don't remove the future from the .futures cache
if (in_op(&get_value(&client, &Value::Str("futures".into())), &messageHash)) {
let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".into())), &messageHash);
future.resolve(&[self.balance.clone()]);
}
client.resolve(&[self.balance.clone(), Value::Str("balance".into())]);
Value::Null
}
pub fn handle_portfolio(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "ch": "portfolio",
// "ts": 1788546565789,
// "sq": 35879860000,
// "data": {
// "positions": [
// {
// "instrument_id": 6,
// "symbol": "BTC-USD",
// "size": "0.001",
// "entry_price": "79650.0",
// "leverage": 10,
// "cross": true,
// "initial_margin": "7.97",
// "maintenance_margin": "3.99",
// "position_value": "79.65",
// "liquidation_price": "72000.0",
// "unrealized_pnl": "-0.10",
// "return_on_equity": "-0.0125",
// "cumulative_funding": "0.01",
// "adl_index": 0
// }
// ],
// "margin": {
// "total_account_value": "100.00",
// "available_order_margin": "90.00",
// "total_initial_margin": "10.00",
// "total_maintenance_margin": "5.00",
// "total_position_value": "50.00"
// },
// "withdrawable": "90.00",
// "in_liquidation": false,
// "timestamp": 1788546565789
// }
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut timestamp: Value = self.safe_integer_k(data.clone(), "timestamp", &[]);
if (self.positions.clone() == Value::Null) {
self.positions = ArrayCacheBySymbolBySide::new(Value::Null);
}
let mut cache: Value = self.positions.clone();
let mut rows: Value = self.safe_list_k(data.clone(), "positions", &[Value::from(vec![])]);
let mut newPositions: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_634: bool = true;
while { if !__for_first_634 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_634 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut row: Value = self.safe_dict(rows.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut extended: Value = self.extend(row, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timestamp".to_string(), timestamp.clone());
m
})]);
let mut position: Value = self.parse_position(extended, &[]);
if let Value::Arr(__a) = &mut newPositions { std::sync::Arc::make_mut(__a).push(position.clone()); }
cache.append(position);
}
}
client.resolve(&[newPositions, Value::Str("positions".into())]);
let mut margin: Value = self.safe_dict_k(data.clone(), "margin", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
});
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(margin.clone(), "total_account_value", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(margin.clone(), "available_order_margin", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(margin, "total_initial_margin", &[])); }
// pUSD is the only collateral asset on the venue
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("PUSD".into(), account); }
{ let __t = self.safe_balance(result); self.balance = __t; }
client.resolve(&[self.balance.clone(), Value::Str("balance".into())]);
}
pub fn handle_ack(&mut self, mut client: Value, mut message: Value) {
//
// subscribe or unsubscribe acknowledgement
//
// { "id": 1, "data": [ { "status": "ok" } ] }
// { "id": 2, "data": [ { "status": "err", "error": "invalid channel" } ] }
//
// ping reply
//
// { "id": 99, "ts": 1788546831854, "data": { "status": "ok", "ts": 1788546831854, "sq": 35879934302 } }
//
let mut id: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut data: Value = self.safe_value_k(message.clone(), "data", &[]);
if !(matches!(&data, Value::Arr(_))) {
// post replies carry a data object - the auth op is matched back
// through its pending entry, anything else counts like a pong
if (id != Value::Null) {
let mut postKey: Value = Value::Str(format!("{}{}", Value::Str("req:".into()), id).into());
let mut postPending: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), postKey.clone(), &[]);
if (postPending != Value::Null) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &postKey);
let mut postAction: Option<String> = self.safe_string_k(postPending, "method", &[]).as_str().map(str::to_owned);
if (postAction.as_deref() == Some("auth")) {
let mut authStatus: Option<String> = self.safe_string_k(data.clone(), "status", &[]).as_str().map(str::to_owned);
if (authStatus.as_deref() == Some("ok")) {
// resolve the future object directly so it stays
// cached and later authenticate calls reuse it
let mut future: Value = self.safe_value(get_value(&client, &Value::Str("futures".into())), Value::Str("authenticated".into()), &[]);
if (future != Value::Null) {
future.resolve(&[Value::Bool(true)]);
}
} else {
let mut authError = Value::from(crate::exchange_errors::authentication_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" authentication failed ".into())).into()), json_stringify(&data))));
client.reject(&[authError, Value::Str("authenticated".into())]);
if (matches!(&get_value(&client, &Value::Str("subscriptions".into())), Value::Dict(__d) if __d.contains_key("authenticated"))) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &Value::Str("authenticated".into()));
}
}
return;
}
}
}
let __ws_arg_1 = self.milliseconds();
crate::set_value(&mut client, &Value::Str("lastPong".into()), self.safe_integer_k(message, "ts", &[__ws_arg_1]));
return;
}
if (id == Value::Null) {
return;
}
let mut key: Value = Value::Str(format!("{}{}", Value::Str("req:".into()), id).into());
let mut pending: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), key.clone(), &[]);
if (pending == Value::Null) {
return;
}
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &key);
let mut messageHashes: Value = self.safe_list_k(pending.clone(), "messageHashes", &[Value::from(vec![])]);
let mut subMessageHashes: Value = self.safe_list_k(pending.clone(), "subMessageHashes", &[Value::from(vec![])]);
let mut action: Option<String> = self.safe_string_k(pending.clone(), "method", &[]).as_str().map(str::to_owned);
let mut errorMessage: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_635: bool = true;
while { if !__for_first_635 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_635 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut entry: Value = self.safe_dict(data.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Option<String> = self.safe_string_k(entry.clone(), "status", &[]).as_str().map(str::to_owned);
if (status.as_deref() == Some("err")) {
errorMessage = self.safe_string_k(entry, "error", &[]);
}
}
}
if (errorMessage != Value::Null) {
let mut error = Value::from(crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), errorMessage)));
{
let mut i: Value = Value::Int(0);
let mut __for_first_636: bool = true;
while { if !__for_first_636 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_636 = false; i.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
client.reject(&[Value::from(error.clone()), messageHashes.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)]);
// clearing the awaited hash lets a later call resend, and a
// failed subscribe must also clear the shared hash the base
// watch registered - a failed unsubscribe keeps the live
// subscription untouched instead
let mut messageHash: Value = messageHashes.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 (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &messageHash)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &messageHash);
}
if (action.as_deref() == Some("sub")) {
let mut subMessageHash: Value = subMessageHashes.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 (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &subMessageHash)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &subMessageHash);
}
}
}
}
return;
}
if (action.as_deref() == Some("unsub")) {
let mut topic: Option<String> = self.safe_string_k(pending.clone(), "topic", &[]).as_str().map(str::to_owned);
let mut symbol: Value = self.safe_string_k(pending.clone(), "symbol", &[]);
if (symbol != Value::Null) {
if (topic.as_deref() == Some("orderbook")) {
if (matches!((&self.orderbooks, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let (Value::Dict(__d), Value::Str(__k)) = (&mut self.orderbooks, &symbol) { std::sync::Arc::make_mut(__d).shift_remove(__k.as_ref()); }
}
} else if (topic.as_deref() == Some("trades")) {
if (matches!((&self.trades, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let (Value::Dict(__d), Value::Str(__k)) = (&mut self.trades, &symbol) { std::sync::Arc::make_mut(__d).shift_remove(__k.as_ref()); }
}
} else if (topic.as_deref() == Some("ticker")) {
if (matches!((&self.tickers, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let (Value::Dict(__d), Value::Str(__k)) = (&mut self.tickers, &symbol) { std::sync::Arc::make_mut(__d).shift_remove(__k.as_ref()); }
}
} else if (topic.as_deref() == Some("ohlcv")) {
let mut timeframe: Value = self.safe_string_k(pending, "timeframe", &[]);
if (timeframe != Value::Null) && (matches!((&self.ohlcvs, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if (in_op(&self.ohlcvs.as_map().and_then(|__m| symbol.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null), &timeframe)) {
remove(&mut get_value(&self.ohlcvs, &symbol), &timeframe);
}
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_637: bool = true;
while { if !__for_first_637 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_637 = false; i.as_f64().unwrap_or(f64::NAN) < ((messageHashes.len() as i64) as f64) } {
self.clean_unsubscription(client.clone(), subMessageHashes.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), messageHashes.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), &[]);
}
}
}
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let mut ch: Value = self.safe_string_k(message.clone(), "ch", &[]);
if (ch == Value::Null) {
self.handle_ack(client.clone(), message.clone());
return;
}
let mut parts: Value = Value::Array(ch.as_str().map(|__s| __s.split("::").map(|__p| Value::Str(__p.to_string().into())).collect()).unwrap_or_default());
let mut family: Value = self.safe_string(parts, Value::Int(0), &[Value::Str("".into())]);
let mut methods: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("book".to_string(), Value::Str("handle_order_book".into()).clone());
m.insert("bbo".to_string(), Value::Str("handle_bid_ask".into()).clone());
m.insert("trades".to_string(), Value::Str("handle_trades".into()).clone());
m.insert("tickers".to_string(), Value::Str("handle_ticker".into()).clone());
m.insert("klines".to_string(), Value::Str("handle_ohlcv".into()).clone());
m.insert("orders".to_string(), Value::Str("handle_order".into()).clone());
m.insert("fills".to_string(), Value::Str("handle_my_trades".into()).clone());
m.insert("portfolio".to_string(), Value::Str("handle_portfolio".into()).clone());
m
});
let mut method: Value = self.safe_value(methods, family, &[]);
if (method != Value::Null) {
self.dispatch_ws_handler(&method, &[client, message]);
}
}
pub fn ping(&mut self, mut client: Value) -> Value {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.request_id());
m.insert("req".to_string(), Value::Str("post".into()));
m.insert("op".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("ping".into()));
m
}));
m
});
Value::Null
}
}