// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
use crate::pro::*;
use crate::prediction_exchange_generated::PredictionBase;
use crate::prediction_exchange::PredictionRuntime;
pub struct PolymarketCore {
pub exchange: crate::prediction_exchange::PredictionExchange,
}
impl PolymarketCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::prediction_exchange::PredictionExchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = 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 {
// Forward to the inherent method on PolymarketCore.
PolymarketCore::nonce(self, )
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PolymarketCore.
PolymarketCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on PolymarketCore.
PolymarketCore::parse_balance(self, response)
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PolymarketCore.
PolymarketCore::parse_prediction_trade(self, trade, &[market])
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PolymarketCore.
PolymarketCore::parse_prediction_order(self, order, &[market])
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PolymarketCore.
PolymarketCore::parse_prediction_position(self, position, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on PolymarketCore.
PolymarketCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on PolymarketCore.
PolymarketCore::handle_errors(self, 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 {
"build_clob_order_body" => self.build_clob_order_body(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())..]),
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_api_key" => self.create_api_key(&args[..]).await,
"create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_or_derive_api_key" => self.create_or_derive_api_key(&args[..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"derive_api_key" => self.derive_api_key(&args[..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_event" => self.fetch_event(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_events" => self.fetch_events(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_trades" => self.fetch_order_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_outcome" => self.fetch_outcome(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_outcomes" => self.fetch_outcomes(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_raw_events_by_search" => self.fetch_raw_events_by_search(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_raw_events_list" => self.fetch_raw_events_list(&args[..]).await,
"fetch_status" => self.fetch_status(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null),
args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"handle_list_message" => { self.handle_list_message(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_text_message" => { self.handle_text_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"load_api_credentials" => self.load_api_credentials().await,
"nonce" => self.nonce(),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_event" => self.parse_event(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_event_to_markets" => self.parse_event_to_markets(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_events" => self.parse_events(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_poly_timestamp" => self.parse_poly_timestamp(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_prediction_open_interest" => self.parse_prediction_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_position" => self.parse_prediction_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_trade" => self.parse_prediction_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"polymarket_order_raw_amounts" => self.polymarket_order_raw_amounts(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_api_credentials" => self.set_api_credentials(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"sign_hash" => self.sign_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_message" => self.sign_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"subscribe_user_channel" => self.subscribe_user_channel(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// Prediction Core: fall through to prediction base methods (then Exchange base).
_ => self.call_dynamic_prediction_base(method, args).await,
}
})
}
}
impl crate::prediction_exchange_generated::PredictionBase for PolymarketCore {
fn pred(&self) -> &crate::prediction_exchange::PredictionExchange { &self.exchange }
fn pred_mut(&mut self) -> &mut crate::prediction_exchange::PredictionExchange { &mut self.exchange }
}
impl std::ops::Deref for PolymarketCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}
impl std::ops::DerefMut for PolymarketCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.exchange) }
}
impl PolymarketCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.super_describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("polymarket".into()));
m.insert("name".to_string(), Value::Str("Polymarket".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
m.insert("rateLimit".to_string(), Value::Int(100));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ping".to_string(), Value::Null.clone());
m.insert("keepAlive".to_string(), Value::Int(10000));
m
}));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(false));
m.insert("fetchEvent".to_string(), Value::Bool(true));
m.insert("fetchEvents".to_string(), Value::Bool(true));
m.insert("fetchLedger".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrderTrades".to_string(), Value::Bool(true));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(true));
m.insert("fetchWithdrawals".to_string(), Value::Bool(false));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1".into()));
m.insert("5m".to_string(), Value::Str("5".into()));
m.insert("1h".to_string(), Value::Str("60".into()));
m.insert("6h".to_string(), Value::Str("360".into()));
m.insert("1d".to_string(), Value::Str("1440".into()));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/89e1a2c4-a682-44e7-ad50-9fb15b534437".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("gamma".to_string(), Value::Str("https://gamma-api.polymarket.com".into()));
m.insert("clob".to_string(), Value::Str("https://clob.polymarket.com".into()));
m.insert("data".to_string(), Value::Str("https://data-api.polymarket.com".into()));
m.insert("ws".to_string(), Value::Str("wss://ws-subscriptions-clob.polymarket.com/ws/market".into()));
m.insert("wsUser".to_string(), Value::Str("wss://ws-subscriptions-clob.polymarket.com/ws/user".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://polymarket.com".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.polymarket.com".into())]));
m.insert("fees".to_string(), Value::Str("https://docs.polymarket.com/#fees".into()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("gamma".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("comments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("comments/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("comments/user_address/{user_address}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/creators".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/creators/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/keyset".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/pagination".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/results".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/slug/{slug}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/{id}/comments/count".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/{id}/tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events/{id}/tweet-count".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/keyset".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/slug/{slug}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{id}/description".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{id}/tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("profiles/user_address/{user_address}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public-profile".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public-search".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series-summary/slug/{slug}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series-summary/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("series/{id}/comments/count".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sports".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sports/market-types".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tags/slug/{slug}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tags/slug/{slug}/related-tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tags/slug/{slug}/related-tags/tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tags/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tags/{id}/related-tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tags/{id}/related-tags/tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("teams".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("teams/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("markets/abridged".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/information".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("clob".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("book".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("books".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("builder/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("clob-markets/{condition_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fee-rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fee-rate/{token_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("last-trade-price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("last-trades-prices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets-by-token/{token_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/live-activity/{condition_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("midpoint".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("midpoints".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("neg-risk".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("neg-risk/{token_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("prices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("prices-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rebates/current".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rewards/markets/current".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rewards/markets/multi".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rewards/markets/{condition_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sampling-markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sampling-simplified-markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("simplified-markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spread".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tick-size".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tick-size/{token_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("batch-prices-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("books".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("last-trades-prices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/live-activity".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("midpoints".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("prices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spreads".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("auth/api-keys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/ban-status/closed-only".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/builder-api-key".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/derive-api-key".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("balance-allowance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("balance-allowance/update".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("data/order/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("data/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("data/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("notifications".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("order-scoring".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders-scoring".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rewards/user".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rewards/user/markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rewards/user/percentages".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rewards/user/total".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("auth/api-key".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/builder-api-key".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("heartbeats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/heartbeats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("auth/api-key".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/builder-api-key".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("cancel-all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("cancel-market-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("notifications".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("activity".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("closed-positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("holders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("live-volume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("oi".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("other".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("revisions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("traded".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/accounting/snapshot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/activity/combos".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/builders/leaderboard".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/builders/volume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/leaderboard".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/market-positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/positions/combos".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("value".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("combos".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1/rfq/combo-markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1/maker/confirmations".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/maker/quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/maker/quotes/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("not enough balance / allowance".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("invalid signature".to_string(), Value::Str("AuthenticationError".into()));
m.insert("api key not found".to_string(), Value::Str("AuthenticationError".into()));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("No orderbook exists".to_string(), Value::Str("BadSymbol".into()));
m.insert("invalid clob token ids".to_string(), Value::Str("BadSymbol".into()));
m.insert("not enough balance".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("allowance".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("invalid amount".to_string(), Value::Str("InvalidOrder".into()));
m.insert("invalid price".to_string(), Value::Str("InvalidOrder".into()));
m.insert("minimum tick size".to_string(), Value::Str("InvalidOrder".into()));
m.insert("no orders found to match".to_string(), Value::Str("OrderNotFillable".into()));
m.insert("could not be fully filled".to_string(), Value::Str("OrderNotFillable".into()));
m.insert("geoblocked".to_string(), Value::Str("PermissionDenied".into()));
m.insert("restricted jurisdiction".to_string(), Value::Str("PermissionDenied".into()));
m.insert("Unauthorized".to_string(), Value::Str("AuthenticationError".into()));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(false));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("password".to_string(), Value::Bool(false));
m.insert("privateKey".to_string(), Value::Bool(false));
m.insert("walletAddress".to_string(), Value::Bool(false));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("maker".to_string(), Value::Int(0));
m.insert("taker".to_string(), Value::Int(0));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultFetchEventsLimit".to_string(), Value::Int(100));
m.insert("eventsPageSize".to_string(), Value::Int(100));
m.insert("fetchMarketsLimit".to_string(), Value::Int(200));
m.insert("maxFetchEventsLimit".to_string(), Value::Int(500));
m.insert("defaultEventStatus".to_string(), Value::Str("active".into()));
m.insert("maxPricesHistoryWindow".to_string(), Value::Int(1296000));
m.insert("chainId".to_string(), Value::Int(137));
m.insert("ctfExchangeName".to_string(), Value::Str("Polymarket CTF Exchange".into()));
m.insert("ctfExchangeVersion".to_string(), Value::Str("2".into()));
m.insert("exchangeAddress".to_string(), Value::Str("0xE111180000d2663C0091e4f400237545B87B996B".into()));
m.insert("negRiskExchangeAddress".to_string(), Value::Str("0xe2222d279d744050d28e00520010520000310F59".into()));
m.insert("builder".to_string(), Value::Str("0xea409de8b037bb6ac664b6d12d6831b03cb04a37".into()));
m.insert("builderFee".to_string(), Value::Bool(true));
m.insert("feeRate".to_string(), Value::Int(0));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name polymarket#fetchMarkets
* @description retrieves data on all markets for polymarket, each prediction market becomes one market with its outcome tokens listed under the outcomes key
* @see https://docs.polymarket.com/api-reference/events/list-events
* @see https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles
* @param {object} [params] extra exchange-specific parameters
* @param {string} [params.query] a single search term used to filter the fetched events
* @param {string[]} [params.queries] multiple search terms (alternative to query)
* @param {string[]} [params.tags] filter events by tag — human-readable labels ("Fed Rates") or slugs ("fed-rates") both work; multiple tags match ANY (one gamma listing per tag, unioned)
* @param {string} [params.status] 'active', 'closed' or 'all', the status of the events to fetch, defaults to 'active'
* @param {int} [params.limit] max number of events to fetch when no query is given (defaults to options.fetchMarketsLimit, 200); the listing is ordered by 24h volume so the most active markets come first — outcomes on lower-volume markets are resolvable on demand by their token id (fetchOutcome)
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("query".into()), Value::Str("queries".into())]), &[]);
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
let mut rawEvents: Value = Value::from(vec![]);
if queriesLength > ((0i64) as f64) {
rawEvents = self.fetch_raw_events_by_search(queries, &[rest.clone()]).await;
} else {
rawEvents = self.fetch_raw_events_list(&[rest]).await;
}
let mut flatMarkets: Vec<Value> = Vec::new();
let mut eventsDict: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut rei: i64 = 0;
let mut __for_first_1407: bool = true;
while { if !__for_first_1407 { rei += 1; } __for_first_1407 = false; rei < (rawEvents.len() as i64) } {
let mut rawEvent: Value = rawEvents.as_array().map(Vec::as_slice).unwrap_or_default().get(rei as usize).cloned().unwrap_or(Value::Null);
let mut ccxtMarkets: Vec<Value> = self.parse_event_to_markets(rawEvent.clone()).as_array().cloned().unwrap_or_default();
{
let mut mi: i64 = 0;
let mut __for_first_1406: bool = true;
while { if !__for_first_1406 { mi += 1; } __for_first_1406 = false; mi < (ccxtMarkets.len() as i64) } {
flatMarkets.push(ccxtMarkets.get(mi as usize).cloned().unwrap_or(Value::Null));
}
}
let mut parsedEvent: indexmap::IndexMap<String, Value> = self.parse_event(rawEvent.clone()).as_map().cloned().unwrap_or_default();
let mut eventSlug: Option<String> = self.safe_string_k_opt(rawEvent, "slug", &[]);
if (eventSlug.is_some()) && (eventSlug.as_deref() != Some("")) {
let mut eventKey: Value = self.shorten_slug(eventSlug.map(Value::from).unwrap_or(Value::Null));
if let Value::Dict(__d) = &mut eventsDict { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&eventKey), Value::Map(parsedEvent)); }
}
}
}
self.exchange.events = eventsDict.clone();
return Value::from(flatMarkets);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#fetchRawEventsBySearch
* @description fetches raw gamma event objects matching the given search terms, paginating through all result pages
* @see https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles
* @param {string[]} queries search terms
* @param {object} [params] extra exchange-specific parameters
* @param {int} [params.limit] page size per search query, defaults to 50
* @returns {object[]} an array of raw gamma event objects
*/
pub async fn fetch_raw_events_by_search(&mut self, mut queries: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __queries_empty = Vec::new();
let queries = queries.as_array().unwrap_or(&__queries_empty);
let mut resultLimit: Value = self.safe_integer_k(params.clone(), "limit", &[]);
// fixed page size (gamma's limit_per_type). do NOT tie it to `limit`: that made a small
// limit fan out into many tiny-page requests (limit:1 -> ~one request per matching event).
// tunable per-call via params.searchPageSize, else the exchange option, else 100
let mut optionPageSize: Value = self.safe_integer_k(self.options.clone(), "searchPageSize", &[Value::Int(100)]);
let mut pageSize: Value = self.safe_integer_k(params.clone(), "searchPageSize", &[optionPageSize]);
// map the unified sort/status onto the gamma search params
let mut sort: Option<String> = self.safe_string_k(params.clone(), "sort", &[]).as_str().map(str::to_owned);
let mut sortParam: String = "volume".to_string();
if (sort.as_deref() == Some("liquidity")) {
sortParam = "liquidity".to_string();
} else if (sort.as_deref() == Some("newest")) {
sortParam = "startDate".to_string();
}
let mut status: Option<String> = self.safe_string_k(params.clone(), "status", &[Value::Str("active".into())]).as_str().map(str::to_owned);
let mut eventsStatus: Value = Value::Str("active".into());
if (status.as_deref() == Some("closed")) || (status.as_deref() == Some("inactive")) {
eventsStatus = Value::Str("closed".into());
} else if (status.as_deref() == Some("all")) {
eventsStatus = Value::Null;
}
let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("limit".into()), Value::Str("sort".into()), Value::Str("status".into()), Value::Str("searchIn".into()), Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("query".into()), Value::Str("queries".into()), Value::Str("searchPageSize".into()), Value::Str("maxSearchPages".into())]), &[]);
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut rawEvents: Vec<Value> = Vec::new();
{
let mut qi: Value = Value::Int(0);
let mut __for_first_1414: bool = true;
while { if !__for_first_1414 { if let Value::Int(n) = &mut qi { *n += 1; } } __for_first_1414 = false; qi.as_f64().unwrap_or(f64::NAN) < ((queries.len() as i64) as f64) } {
let mut q: Value = queries.get((qi).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut baseRequest: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("q".to_string(), q);
m.insert("limit_per_type".to_string(), pageSize.clone());
m.insert("sort".to_string(), Value::from(sortParam.clone()));
m.insert("ascending".to_string(), Value::Bool(false));
m
});
if (eventsStatus != Value::Null) {
baseRequest.insert("events_status".into(), eventsStatus.clone());
}
let mut firstRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("page".to_string(), Value::Int(1));
m
});
let __ws_arg_0 = self.extend(firstRequest.clone(), &[Value::Map(baseRequest.clone())]);
firstRequest = self.extend(__ws_arg_0, &[rest.clone()]);
let mut first: Value = self.gamma_public_get_public_search(&[firstRequest]).await;
let mut firstEvents: Vec<Value> = self.safe_list_k(first.clone(), "events", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut firstEventsLength: Value = Value::Int(firstEvents.len() as i64);
let mut pagination: Value = self.safe_dict_k(first, "pagination", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut totalResults: Value = self.safe_integer_k(pagination, "totalResults", &[firstEventsLength]);
let mut totalPages: Value = self.parse_to_int(((match ((totalResults).as_f64(), (pageSize).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64().map(|__x| Value::Float(__x.ceil())).unwrap_or(Value::Null));
// only page as far as `limit` needs (applyEventFetchParams slices to it afterwards);
// with no limit, cap the fan-out at options.maxSearchPages so a broad query stays bounded
if (resultLimit != Value::Null) {
let mut limitPages: Value = self.parse_to_int(((match ((resultLimit).as_f64(), (pageSize).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64().map(|__x| Value::Float(__x.ceil())).unwrap_or(Value::Null));
if limitPages.as_f64().unwrap_or(f64::NAN) < totalPages.as_f64().unwrap_or(f64::NAN) {
totalPages = limitPages;
}
} else {
let mut optionMaxPages: Value = self.safe_integer_k(self.options.clone(), "maxSearchPages", &[Value::Int(5)]);
let mut maxSearchPages: Value = self.safe_integer_k(params.clone(), "maxSearchPages", &[optionMaxPages]);
if maxSearchPages.as_f64().unwrap_or(f64::NAN) < totalPages.as_f64().unwrap_or(f64::NAN) {
totalPages = maxSearchPages;
}
}
let mut remainingPages: Vec<Value> = Vec::new();
{
let mut p: Value = Value::Int(2);
let mut __for_first_1408: bool = true;
while { if !__for_first_1408 { if let Value::Int(n) = &mut p { *n += 1; } } __for_first_1408 = false; p.as_f64().unwrap_or(f64::NAN) <= totalPages.as_f64().unwrap_or(f64::NAN) } {
remainingPages.push(p.clone());
}
}
let mut restPromises: Value = Value::from(vec![]);
{
let mut pi: Value = Value::Int(0);
let mut __for_first_1409: bool = true;
while { if !__for_first_1409 { if let Value::Int(n) = &mut pi { *n += 1; } } __for_first_1409 = false; pi.as_f64().unwrap_or(f64::NAN) < ((remainingPages.len() as i64) as f64) } {
let mut pageRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("page".to_string(), remainingPages.get((pi).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_1 = self.extend(pageRequest.clone(), &[Value::Map(baseRequest.clone())]);
pageRequest = self.extend(__ws_arg_1, &[rest.clone()]);
if let Value::Arr(__a) = &mut restPromises { std::sync::Arc::make_mut(__a).push(self.gamma_public_get_public_search(&[pageRequest]).await); }
}
}
let mut restResponses: Vec<Value> = promise_all(&restPromises).await.as_array().cloned().unwrap_or_default();
let mut allEvents: Vec<Value> = Vec::new();
{
let mut fi: i64 = 0;
let mut __for_first_1410: bool = true;
while { if !__for_first_1410 { fi += 1; } __for_first_1410 = false; fi < (firstEvents.len() as i64) } {
allEvents.push(firstEvents.get(fi as usize).cloned().unwrap_or(Value::Null));
}
}
{
let mut ri: i64 = 0;
let mut __for_first_1412: bool = true;
while { if !__for_first_1412 { ri += 1; } __for_first_1412 = false; ri < (restResponses.len() as i64) } {
let mut pageEvents: Vec<Value> = self.safe_list_k(restResponses.get(ri as usize).cloned().unwrap_or(Value::Null), "events", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
{
let mut ei: i64 = 0;
let mut __for_first_1411: bool = true;
while { if !__for_first_1411 { ei += 1; } __for_first_1411 = false; ei < (pageEvents.len() as i64) } {
allEvents.push(pageEvents.get(ei as usize).cloned().unwrap_or(Value::Null));
}
}
}
}
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1413: bool = true;
while { if !__for_first_1413 { if let Value::Int(n) = &mut ei { *n += 1; } } __for_first_1413 = false; ei.as_f64().unwrap_or(f64::NAN) < ((allEvents.len() as i64) as f64) } {
let mut rawEvent: Value = allEvents.get((ei).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut eventId: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "id", &[]);
if ((eventId.is_some()) && (eventId.as_deref() != Some(""))) && !(matches!((&seen, &eventId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(eventId.as_deref().unwrap_or("null").to_string(), Value::Bool(true)); }
rawEvents.push(rawEvent);
}
}
}
}
}
return Value::from(rawEvents);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#tagToSlug
* @description converts a human-readable tag label into gamma's slug form, "Fed Rates" -> "fed-rates"; lowercase alphanumeric runs joined by single dashes, so a tag already in slug form passes through unchanged
* @param {string} tag the tag label or slug
* @returns {string} the gamma tag slug
*/
pub fn tag_to_slug(&self, mut tag: Value) -> Option<String> {
let mut lower: String = tag.as_str().map(str::to_lowercase).unwrap_or_default();
let mut allowed: String = "abcdefghijklmnopqrstuvwxyz0123456789".to_string();
let mut chars: Vec<Value> = self.string_to_chars_array(Value::from(lower.clone())).as_array().cloned().unwrap_or_default();
let mut slug: Value = Value::Str("".into());
let mut pendingSep: bool = false;
{
let mut i: i64 = 0;
let mut __for_first_1415: bool = true;
while { if !__for_first_1415 { i += 1; } __for_first_1415 = false; i < (chars.len() as i64) } {
let mut ch: Value = chars.get(i as usize).cloned().unwrap_or(Value::Null);
if Value::Int(Some(allowed.as_str()).zip(ch.as_str()).and_then(|(__s, __n)| __s.find(__n)).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
if pendingSep && (slug.as_str() != Some("")) {
slug = Value::Str(format!("{}{}", slug, Value::Str("-".into())).into());
}
slug = Value::Str(format!("{}{}", slug, ch).into());
pendingSep = false;
} else {
pendingSep = true;
}
}
}
if (slug.as_str() == Some("")) {
return Value::from(lower).as_str().map(str::to_owned);
}
return slug.as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name polymarket#fetchRawEventsList
* @description fetches raw gamma event objects from the events listing endpoint, paginating in parallel
* @see https://docs.polymarket.com/api-reference/events/list-events
* @param {object} [params] extra exchange-specific parameters
* @param {string} [params.status] 'active', 'closed' or 'all', defaults to options.defaultEventStatus
* @param {int} [params.limit] max number of events to fetch (default options.fetchMarketsLimit); the listing is ordered by 24h volume so the most active markets come first
* @returns {object[]} an array of raw gamma event objects
*/
pub async fn fetch_raw_events_list(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// gamma hard-caps each response at 100 events regardless of the requested limit, so the
// page size must be that cap or pagination never advances (the > check below stays false)
let mut pageSize: Value = self.safe_integer_k(self.options.clone(), "eventsPageSize", &[Value::Int(100)]);
// scope the listing: without a search query loadMarkets would otherwise dump every
// active event (tens of thousands of markets). Cap to `limit` events (most-traded first).
let mut limit: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("fetchMarketsLimit".into()), &[Value::Int(200)])]);
let mut maxPages: Value = ((match ((limit).as_f64(), (pageSize).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64().map(|__x| Value::Float(__x.ceil())).unwrap_or(Value::Null);
let mut status: Option<String> = self.safe_string_k(params.clone(), "status", &[self.safe_string(self.options.clone(), Value::Str("defaultEventStatus".into()), &[Value::Str("active".into())])]).as_str().map(str::to_owned);
// sort maps to the gamma `order` field; 'volume' is the default ranking
let mut sort: Option<String> = self.safe_string_k(params.clone(), "sort", &[]).as_str().map(str::to_owned);
let mut order: String = "volume".to_string();
if (sort.as_deref() == Some("liquidity")) {
order = "liquidity".to_string();
} else if (sort.as_deref() == Some("newest")) {
order = "startDate".to_string();
}
let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("status".into()), Value::Str("limit".into()), Value::Str("sort".into()), Value::Str("searchIn".into()), Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("query".into()), Value::Str("queries".into()), Value::Str("tags".into())]), &[]);
let mut baseRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), pageSize.clone());
m.insert("order".to_string(), Value::from(order.clone()));
m.insert("ascending".to_string(), Value::Bool(false));
m
});
baseRequest = self.extend(baseRequest.clone(), &[rest]);
// push requested tags server-side (gamma accepts one tag_slug per request) so a tags-only
// fetchEvents returns the tagged events rather than filtering the top-volume listing down
// to nothing; multiple tags run one listing per tag, unioned and deduped by event id
let mut requestedTags: Value = self.safe_list_k(params.clone(), "tags", &[Value::from(vec![])]);
let mut requestedTagsLength: f64 = ((requestedTags.len() as i64) as f64);
if requestedTagsLength > ((1i64) as f64) {
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut unioned: Vec<Value> = Vec::new();
{
let mut ti: Value = Value::Int(0);
let mut __for_first_1417: bool = true;
while { if !__for_first_1417 { if let Value::Int(n) = &mut ti { *n += 1; } } __for_first_1417 = false; ti.as_f64().unwrap_or(f64::NAN) < requestedTagsLength } {
let mut singleTagParams: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[params.clone()]);
add_element_to_object(&mut singleTagParams, &Value::Str("tags".into()), Value::from(vec![requestedTags.as_array().and_then(|__arr| match &ti { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)]));
let mut tagEvents: Value = Box::pin(self.fetch_raw_events_list(&[singleTagParams])).await;
{
let mut ei: i64 = 0;
let mut __for_first_1416: bool = true;
while { if !__for_first_1416 { ei += 1; } __for_first_1416 = false; ei < (tagEvents.len() as i64) } {
let mut rawEvent: Value = tagEvents.as_array().map(Vec::as_slice).unwrap_or_default().get(ei as usize).cloned().unwrap_or(Value::Null);
let mut eventId: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "id", &[]);
if (eventId.is_some()) && !(matches!((&seen, &eventId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(eventId.as_deref().unwrap_or("null").to_string(), Value::Bool(true)); }
unioned.push(rawEvent);
}
}
}
}
}
return Value::from(unioned);
}
if requestedTagsLength > ((0i64) as f64) {
// gamma matches tag_slug case-insensitively but only in slug form ("fed-rates"),
// so human-readable labels ("Fed Rates") must be slugified first
add_element_to_object(&mut baseRequest, &Value::Str("tag_slug".into()), self.tag_to_slug(self.safe_string(requestedTags, Value::Int(0), &[])).map(Value::from).unwrap_or(Value::Null));
}
if (status.as_deref() == Some("active")) {
add_element_to_object(&mut baseRequest, &Value::Str("active".into()), Value::Bool(true));
add_element_to_object(&mut baseRequest, &Value::Str("closed".into()), Value::Bool(false));
} else if (status.as_deref() == Some("closed")) || (status.as_deref() == Some("inactive")) {
add_element_to_object(&mut baseRequest, &Value::Str("active".into()), Value::Bool(false));
add_element_to_object(&mut baseRequest, &Value::Str("closed".into()), Value::Bool(true));
}
// 'all' — no active/closed filter
// fetch page 1 first; if full, fire remaining pages in parallel
let mut firstPageRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("offset".to_string(), Value::Int(0));
m
});
firstPageRequest = self.extend(firstPageRequest.clone(), &[baseRequest.clone()]);
let mut firstPageResponse: Value = self.gamma_public_get_events(&[firstPageRequest]).await;
let mut firstPageIsArray: bool = matches!(&firstPageResponse, Value::Arr(_));
let mut firstPage: Value = (if (firstPageIsArray) { firstPageResponse } else { Value::from(vec![]) });
let mut firstPageLength: f64 = ((firstPage.len() as i64) as f64);
let mut allRawEvents: Vec<Value> = Vec::new();
{
let mut fi: Value = Value::Int(0);
let mut __for_first_1418: bool = true;
while { if !__for_first_1418 { if let Value::Int(n) = &mut fi { *n += 1; } } __for_first_1418 = false; fi.as_f64().unwrap_or(f64::NAN) < firstPageLength } {
allRawEvents.push(firstPage.as_array().and_then(|__arr| match &fi { 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 firstPageLength >= pageSize.as_f64().unwrap_or(f64::NAN) {
let mut offsets: Vec<Value> = Vec::new();
{
let mut p: Value = Value::Int(1);
let mut __for_first_1419: bool = true;
while { if !__for_first_1419 { if let Value::Int(n) = &mut p { *n += 1; } } __for_first_1419 = false; maxPages.as_f64().unwrap_or(f64::NAN) > p.as_f64().unwrap_or(f64::NAN) } {
offsets.push((match (&(p), &(pageSize)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }));
}
}
let mut restPromises: Vec<Value> = Vec::new();
{
let mut oi: Value = Value::Int(0);
let mut __for_first_1420: bool = true;
while { if !__for_first_1420 { if let Value::Int(n) = &mut oi { *n += 1; } } __for_first_1420 = false; oi.as_f64().unwrap_or(f64::NAN) < ((offsets.len() as i64) as f64) } {
let mut pageRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("offset".to_string(), offsets.get((oi).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
m
});
pageRequest = self.extend(pageRequest.clone(), &[baseRequest.clone()]);
restPromises.push(self.gamma_public_get_events(&[pageRequest]).await);
}
}
let mut restPages: Value = promise_all(&Value::from(restPromises)).await;
{
let mut ri: i64 = 0;
let mut __for_first_1422: bool = true;
while { if !__for_first_1422 { ri += 1; } __for_first_1422 = false; ri < (restPages.len() as i64) } {
let mut page: Vec<Value> = self.safe_list(restPages.clone(), Value::Int(ri), &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut pageLength: f64 = ((page.len() as i64) as f64);
{
let mut pi: Value = Value::Int(0);
let mut __for_first_1421: bool = true;
while { if !__for_first_1421 { if let Value::Int(n) = &mut pi { *n += 1; } } __for_first_1421 = false; pi.as_f64().unwrap_or(f64::NAN) < pageLength } {
allRawEvents.push(page.get(pi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
}
}
}
}
}
let mut allRawEventsLength: f64 = ((allRawEvents.len() as i64) as f64);
if allRawEventsLength > limit.as_f64().unwrap_or(f64::NAN) {
return self.array_slice(Value::from(allRawEvents), Value::Int(0), &[limit]);
}
return Value::from(allRawEvents);
Value::Null
}
pub fn parse_event_to_markets(&self, mut event: Value) -> Value {
let __event_empty = indexmap::IndexMap::new();
let event = event.as_map().unwrap_or(&__event_empty);
let mut eventSlug: Value = (match event.get("slug") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => (match event.get("id") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()),
Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }) });
let mut rawMarkets: Vec<Value> = (match event.get("markets") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) }).as_array().cloned().unwrap_or_default();
let mut result: Vec<Value> = Vec::new();
{
let mut mi: i64 = 0;
let mut __for_first_1424: bool = true;
while { if !__for_first_1424 { mi += 1; } __for_first_1424 = false; mi < (rawMarkets.len() as i64) } {
let mut market: Value = rawMarkets.get(mi as usize).cloned().unwrap_or(Value::Null);
let mut conditionId: Value = self.safe_string_k(market.clone(), "conditionId", &[]);
let mut marketId: Value = self.safe_string_k(market.clone(), "id", &[]);
let mut marketSlug: Value = self.safe_string_k(market.clone(), "slug", &[conditionId.clone()]);
let mut active: bool = self.safe_bool_k_opt(market.clone(), "active", &[Value::Bool(false)]).unwrap_or(false);
let mut closed: bool = self.safe_bool_k_opt(market.clone(), "closed", &[Value::Bool(false)]).unwrap_or(false);
// resolution: a closed/uma-resolved market settles each outcome price to 0 or 1
let mut marketResolved: Value = Value::Bool(closed || (self.safe_string_lower_k(market.clone(), "umaResolutionStatus", &[]).as_str() == Some("resolved")));
let mut resolvedOutcome: Value = Value::Null;
// gamma exposes the order-book tick as orderPriceMinTickSize; minimumTickSize is the clob alias
let mut tickSize: Value = self.safe_number2(market.clone(), Value::Str("orderPriceMinTickSize".into()), Value::Str("minimumTickSize".into()), &[Value::Float(0.01)]);
// real per-market min order size (shares) and price tick — don't hardcode 1 / 0.01..0.99
let mut orderMinSize: Value = self.safe_number_k(market.clone(), "orderMinSize", &[Value::Int(1)]);
let mut priceMax: Value = self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &self.number_to_string(tickSize.clone())), &[]);
let mut negRisk: bool = self.safe_bool_k_opt(market.clone(), "negRisk", &[Value::Bool(false)]).unwrap_or(false);
let mut endDate: Value = self.safe_string_k(market.clone(), "endDate", &[self.safe_string(market.clone(), Value::Str("end_date_iso".into()), &[])]);
// Gamma API returns these arrays as JSON-encoded strings
let mut outcomeLabels: Value = Value::from(vec![]);
let mut clobTokenIds: Value = Value::from(vec![]);
let mut outcomePrices: Value = Value::from(vec![]);
let mut parsedOutcomes: Value = self.parse_json_value(self.safe_string(market.clone(), Value::Str("outcomes".into()), &[Value::Str("[]".into())]));
let mut parsedTokenIds: Value = self.parse_json_value(self.safe_string(market.clone(), Value::Str("clobTokenIds".into()), &[Value::Str("[]".into())]));
let mut parsedPrices: Value = self.parse_json_value(self.safe_string(market.clone(), Value::Str("outcomePrices".into()), &[Value::Str("[]".into())]));
let mut parsedOutcomesLength: Value = Value::Null;
if (parsedOutcomes != Value::Null) {
parsedOutcomesLength = Value::Int(parsedOutcomes.len() as i64);
}
let mut parsedTokenIdsLength: Value = Value::Null;
if (parsedTokenIds != Value::Null) {
parsedTokenIdsLength = Value::Int(parsedTokenIds.len() as i64);
}
let mut parsedPricesLength: Value = Value::Null;
if (parsedPrices != Value::Null) {
parsedPricesLength = Value::Int(parsedPrices.len() as i64);
}
if (parsedOutcomes != Value::Null) && (parsedOutcomesLength != Value::Null) {
outcomeLabels = parsedOutcomes;
}
if (parsedTokenIds != Value::Null) && (parsedTokenIdsLength != Value::Null) {
clobTokenIds = parsedTokenIds;
}
if (parsedPrices != Value::Null) && (parsedPricesLength != Value::Null) {
outcomePrices = parsedPrices;
}
let mut outcomeLabelsLength: f64 = ((outcomeLabels.len() as i64) as f64);
let mut clobTokenIdsLength: f64 = ((clobTokenIds.len() as i64) as f64);
if (outcomeLabelsLength == 0.0) || (clobTokenIdsLength == 0.0) {
continue;
}
// Market outcome (no outcome suffix)
let mut marketSymbol: Value = self.slug_to_market_symbol(eventSlug.clone(), marketSlug.clone());
// Build outcomes array
let mut outcomes: Vec<Value> = Vec::new();
{
let mut oi: i64 = 0;
let mut __for_first_1423: bool = true;
while { if !__for_first_1423 { oi += 1; } __for_first_1423 = false; oi < (outcomeLabels.len() as i64) } {
let mut outcomeLabel: Value = outcomeLabels.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null);
let mut clobTokenId: Value = clobTokenIds.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null);
let mut outcomePrice: Value = self.safe_number(outcomePrices.clone(), Value::Int(oi), &[]);
if (clobTokenId == Value::Null) || (clobTokenId.as_str() == Some("")) {
continue;
}
let mut outcomeHandle: Value = self.slug_to_outcome_symbol(eventSlug.clone(), marketSlug.clone(), outcomeLabel.clone());
let mut winnerRaw: Value = Value::Null;
let mut settleFractionRaw: Value = Value::Null;
if matches!(&marketResolved, Value::Bool(true)) && (outcomePrice != Value::Null) {
// a genuinely-settled polymarket outcome is at 1 (won) or 0 (lost). a market
// that is only closed-for-trading (not yet UMA-resolved) still has fractional
// prices — don't report a fractional mid as a final settleFraction; leave the
// outcome-level fields undefined until a decisive price exists
if outcomePrice.as_f64().unwrap_or(f64::NAN) >= (0.99) {
winnerRaw = Value::Bool(true);
settleFractionRaw = Value::Int(1);
resolvedOutcome = outcomeHandle.clone();
} else if (0.01) >= outcomePrice.as_f64().unwrap_or(f64::NAN) {
winnerRaw = Value::Bool(false);
settleFractionRaw = Value::Int(0);
}
}
// effectively-final copies: Java emits the object literal below as an anonymous
// inner class, which cannot capture a reassigned local
let mut winner: Value = winnerRaw;
let mut settleFraction: Value = settleFractionRaw;
outcomes.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcomeHandle);
m.insert("outcomeId".to_string(), clobTokenId);
m.insert("market".to_string(), marketSymbol.clone());
m.insert("label".to_string(), outcomeLabel);
m.insert("price".to_string(), outcomePrice);
m.insert("active".to_string(), Value::Bool(active && (!(closed))));
m.insert("winner".to_string(), winner);
m.insert("settleFraction".to_string(), settleFraction);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), tickSize.clone());
m.insert("price".to_string(), tickSize.clone());
m
}));
m.insert("negRisk".to_string(), Value::Bool(negRisk));
m.insert("info".to_string(), market.clone());
m
}));
}
}
let mut baseId: Value = (if (conditionId != Value::Null) { conditionId.clone() } else { marketId });
let mut marketType: Value = (if (outcomeLabelsLength > ((2i64) as f64)) { Value::Str("categorical".into()) } else { Value::Str("binary".into()) });
// effectively-final copy for the market object literal below (reassigned in the loop)
let mut marketResolvedOutcome: Value = resolvedOutcome;
result.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), conditionId);
m.insert("market".to_string(), marketSymbol);
m.insert("marketType".to_string(), marketType);
m.insert("executionModel".to_string(), Value::Str("clob".into()));
m.insert("collateral".to_string(), Value::Str("USDC".into()));
m.insert("base".to_string(), Value::Str("USDC".into()));
m.insert("quote".to_string(), Value::Str("USDC".into()));
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), Value::Str("USDC".into()));
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("prediction".into()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("active".to_string(), Value::Bool(active && (!(closed))));
m.insert("resolved".to_string(), marketResolved);
m.insert("resolvedOutcome".to_string(), marketResolvedOutcome);
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), (if ((endDate != Value::Null) && (endDate.as_str() != Some(""))) { self.parse8601(endDate.clone()) } else { Value::Null }));
m.insert("expiryDatetime".to_string(), endDate);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("taker".to_string(), Value::Int(0));
m.insert("maker".to_string(), Value::Int(0));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("feeSide".to_string(), Value::Str("get".into()));
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), tickSize.clone());
m.insert("price".to_string(), tickSize.clone());
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(1));
m.insert("max".to_string(), Value::Int(1));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), orderMinSize);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), tickSize);
m.insert("max".to_string(), priceMax);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("outcomes".to_string(), Value::from(outcomes));
m.insert("info".to_string(), market);
m.insert("created".to_string(), Value::Null);
m
}));
}
}
return Value::from(result);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#fetchOutcome
* @description resolves a single outcome by its CLOB token id in one request, so a cache miss
* (a bare token id, or a valid outcome on a market outside the top-volume cold cache) recovers
* instead of throwing BadSymbol. an outcome HANDLE ("MARKET:LABEL") carries no token id, so it
* falls back to the base bulk load
* @param {string} outcomeSymbol the outcome token id or handle
* @returns {object} the resolved outcome object
*/
pub async fn fetch_outcome(&mut self, mut outcomeSymbol: Value) -> Value {
// a bare CLOB token id has no ':' (an outcome handle is always "MARKET:LABEL") and no
// searchable words — outcomeSearchQuery returns undefined only for id-like inputs, so
// word-bearing junk like 'BTC/USDT' skips the gamma by-id lookup (which 422s on
// non-ids) and falls through to the search path and its local BadSymbol below.
// absence must be `< 0` — the php transpiler maps that to `=== false`, while a literal
// `=== -1` passes through and never matches mb_strpos's false return
if (!outcomeSymbol.as_str().unwrap_or("").contains(":")) && (self.outcome_search_query(outcomeSymbol.clone()) == Value::Null) {
let mut response: Value = self.gamma_public_get_markets(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("clob_token_ids".to_string(), outcomeSymbol.clone());
m
})]).await;
let mut rawMarkets: Value = (if (response != Value::Null) { response } else { Value::from(vec![]) });
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
if rawMarketsLength > ((0i64) as f64) {
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut ccxtMarkets: Vec<Value> = self.parse_event_to_markets(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("markets".to_string(), rawMarkets);
m
})).as_array().cloned().unwrap_or_default();
let mut ccxtMarketsLength: f64 = ((ccxtMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1425: bool = true;
while { if !__for_first_1425 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1425 = false; i.as_f64().unwrap_or(f64::NAN) < ccxtMarketsLength } {
let mut mkt: Value = ccxtMarkets.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if (mkt == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOutcome() could not resolve mkt".into()))));
}
add_element_to_object(&mut self.markets, &mkt.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null), mkt.clone());
}
}
self.populate_outcomes();
if (self.safe_dict(self.exchange.outcomes_by_id.clone(), outcomeSymbol.clone(), &[]) != Value::Null) {
return self.safe_dict(self.exchange.outcomes_by_id.clone(), outcomeSymbol.clone(), &[]);
}
}
}
return self.super_fetch_outcome(outcomeSymbol).await;
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#fetchOutcomes
* @description resolves several uncached outcomes at once — bare CLOB token ids are batched into gamma markets requests (repeated clob_token_ids params, 50 per request to keep the URL bounded); handle-shaped symbols fall back to the single fetch and its search path
* @see https://docs.polymarket.com/api-reference/markets/list-markets
* @param {string[]} outcomeSymbols outcome token ids or handles
* @returns {object} the outcome cache
*/
pub async fn fetch_outcomes(&mut self, mut outcomeSymbols: Value) -> Value {
let __outcomeSymbols_empty = Vec::new();
let outcomeSymbols = outcomeSymbols.as_array().unwrap_or(&__outcomeSymbols_empty);
let mut tokenIds: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1426: bool = true;
while { if !__for_first_1426 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1426 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomeSymbols.len() as i64) as f64) } {
let mut outcomeSymbol: Value = outcomeSymbols.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
// only id-like symbols (no ':', no searchable words) belong in the by-id batch —
// see the same gate in fetchOutcome. absence must be `< 0` — the php transpiler
// maps that to `=== false`, while a literal `=== -1` passes through and never
// matches mb_strpos's false return
if (!outcomeSymbol.as_str().unwrap_or("").contains(":")) && (self.outcome_search_query(outcomeSymbol.clone()) == Value::Null) {
if let Value::Arr(__a) = &mut tokenIds { std::sync::Arc::make_mut(__a).push(outcomeSymbol); }
}
}
}
let mut tokenIdsLength: Value = Value::Int(tokenIds.len() as i64);
if tokenIdsLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
// token ids are ~78 chars each, so cap the batch to keep the URL under common limits
let mut chunkSize: Option<i64> = self.safe_integer_k(self.options.clone(), "fetchOutcomesBatchSize", &[Value::Int(50)]).as_i64();
let mut startIndex: Value = Value::Int(0);
while startIndex.as_f64().unwrap_or(f64::NAN) < tokenIdsLength.as_f64().unwrap_or(f64::NAN) {
let mut endIndex: Value = self.sum(&[startIndex.clone(), Value::from(chunkSize)]);
if endIndex.as_f64().unwrap_or(f64::NAN) > tokenIdsLength.as_f64().unwrap_or(f64::NAN) {
endIndex = tokenIdsLength.clone();
}
let mut chunk: Vec<Value> = Vec::new();
{
let mut i: Value = startIndex.clone();
let mut __for_first_1427: bool = true;
while { if !__for_first_1427 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
} __for_first_1427 = false; i.as_f64().unwrap_or(f64::NAN) < endIndex.as_f64().unwrap_or(f64::NAN) } {
chunk.push(get_value(&tokenIds, &i));
}
}
// gamma matches repeated clob_token_ids params — comma-joined ids are rejected
// with a validation error, so the list rides through urlencodeWithArrayRepeat
let mut response: Value = self.gamma_public_get_markets(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("clob_token_ids".to_string(), Value::from(chunk));
m.insert("limit".to_string(), Value::from(chunkSize));
m
})]).await;
let mut rawMarkets: Value = (if (response != Value::Null) { response } else { Value::from(vec![]) });
let mut ccxtMarkets: Vec<Value> = self.parse_event_to_markets(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("markets".to_string(), rawMarkets);
m
})).as_array().cloned().unwrap_or_default();
{
let mut i: i64 = 0;
let mut __for_first_1428: bool = true;
while { if !__for_first_1428 { i += 1; } __for_first_1428 = false; i < (ccxtMarkets.len() as i64) } {
let mut mkt: Value = ccxtMarkets.get(i as usize).cloned().unwrap_or(Value::Null);
if (mkt == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOutcomes() could not resolve mkt".into()))));
}
add_element_to_object(&mut self.markets, &mkt.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null), mkt.clone());
}
}
startIndex = self.sum(&[startIndex.clone(), Value::from(chunkSize)]);
}
self.populate_outcomes();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1429: bool = true;
while { if !__for_first_1429 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1429 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomeSymbols.len() as i64) as f64) } {
if !(self.has_outcome(outcomeSymbols.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)).as_bool() == Some(true)) {
self.fetch_outcome(outcomeSymbols.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)).await;
}
}
}
return self.exchange.outcomes.clone();
Value::Null
}
/*
* @method
* @name polymarket#fetchTicker
* @description fetches the current mid-price and best bid/ask for a single outcome token
* @see https://docs.polymarket.com/api-reference/data/get-midpoint-price
* @see https://docs.polymarket.com/api-reference/market-data/get-order-book
* @see https://docs.polymarket.com/api-reference/data/get-last-trade-price
* @param {string} outcome unified outcome like TRUMP_DANCE_TODAY_997:YES or an outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub async fn fetch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
let mut promises: Value = Value::from(vec![self.clob_public_get_midpoint(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m
})]).await, self.clob_public_get_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m
})]).await, self.clob_public_get_last_trade_price(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m
})]).await]);
let midpointResponsebookResponselastTradeResponseVariable: Vec<Value> = promise_all(&promises).await.as_array().cloned().unwrap_or_default();
let mut midpointResponse: Value = midpointResponsebookResponselastTradeResponseVariable.get(0).cloned().unwrap_or(Value::Null);
let mut bookResponse: Value = midpointResponsebookResponselastTradeResponseVariable.get(1).cloned().unwrap_or(Value::Null);
let mut lastTradeResponse: Value = midpointResponsebookResponselastTradeResponseVariable.get(2).cloned().unwrap_or(Value::Null);
let mut response: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("midpoint".to_string(), midpointResponse);
m.insert("book".to_string(), bookResponse);
m.insert("lastTrade".to_string(), lastTradeResponse);
m
});
return self.parse_prediction_ticker(Value::Map(response), &[outcomeObj]);
Value::Null
}
/*
* @method
* @name polymarket#fetchTickers
* @description fetches tickers for multiple outcome tokens at once using the batched CLOB book, midpoint and last-trade-price endpoints (200 per request trio)
* @see https://docs.polymarket.com/api-reference/market-data/get-order-books-request-body
* @see https://docs.polymarket.com/api-reference/market-data/get-midpoint-prices-request-body
* @see https://docs.polymarket.com/api-reference/data/get-last-trades-prices
* @param {string[]} outcomes unified outcomes or outcome token ids — required: polymarket has no endpoint returning all tickers at once, so an unscoped call is not supported
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [prediction ticker structures](https://docs.ccxt.com/#/?id=prediction-ticker-structure) indexed by outcome
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcomes == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles or token ids to fetch (discover them via fetchEvents ())".into()))));
}
// batch-resolve the uncached outcomes (one gamma request per 50 token ids)
self.load_outcomes(&[outcomes.clone()]).await;
let mut targets: Vec<Value> = Vec::new();
{
let mut oi: i64 = 0;
let mut __for_first_1430: bool = true;
while { if !__for_first_1430 { oi += 1; } __for_first_1430 = false; oi < (outcomes.len() as i64) } {
targets.push(outcomes.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null));
}
}
let mut outcomesByTokenId: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut tokenIds: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1431: bool = true;
while { if !__for_first_1431 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1431 = false; i.as_f64().unwrap_or(f64::NAN) < ((targets.len() as i64) as f64) } {
let mut outcomeObj: Value = self.outcome(targets.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
if (tokenId.is_some()) && !(matches!((&outcomesByTokenId, &tokenId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut outcomesByTokenId { std::sync::Arc::make_mut(__d).insert(tokenId.as_deref().unwrap_or("null").to_string(), outcomeObj.clone()); }
if let Value::Arr(__a) = &mut tokenIds { std::sync::Arc::make_mut(__a).push(tokenId.map(Value::from).unwrap_or(Value::Null)); }
}
}
}
let mut chunkSize: Option<i64> = self.safe_integer_k(self.options.clone(), "fetchTickersBatchSize", &[Value::Int(200)]).as_i64();
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut tokenIdsLength: Value = Value::Int(tokenIds.len() as i64);
let mut startIndex: Value = Value::Int(0);
while startIndex.as_f64().unwrap_or(f64::NAN) < tokenIdsLength.as_f64().unwrap_or(f64::NAN) {
let mut endIndex: Value = self.sum(&[startIndex.clone(), Value::from(chunkSize)]);
if endIndex.as_f64().unwrap_or(f64::NAN) > tokenIdsLength.as_f64().unwrap_or(f64::NAN) {
endIndex = tokenIdsLength.clone();
}
let mut bookParams: Vec<Value> = Vec::new();
{
let mut i: Value = startIndex.clone();
let mut __for_first_1432: bool = true;
while { if !__for_first_1432 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
} __for_first_1432 = false; i.as_f64().unwrap_or(f64::NAN) < endIndex.as_f64().unwrap_or(f64::NAN) } {
bookParams.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), get_value(&tokenIds, &i));
m
}));
}
}
let mut promises: Value = Value::from(vec![self.clob_public_post_books(&[Value::from(bookParams.clone())]).await, self.clob_public_post_midpoints(&[Value::from(bookParams.clone())]).await, self.clob_public_post_last_trades_prices(&[Value::from(bookParams)]).await]);
let mut responses: Vec<Value> = promise_all(&promises).await.as_array().cloned().unwrap_or_default();
let mut booksResponse: Value = responses.get(0).cloned().unwrap_or(Value::Null);
let mut midpoints: Value = responses.get(1).cloned().unwrap_or(Value::Null);
let mut lastTradesResponse: Value = responses.get(2).cloned().unwrap_or(Value::Null);
let mut booksIsArray: bool = matches!(&booksResponse, Value::Arr(_));
let mut books: Value = (if (booksIsArray) { booksResponse } else { Value::from(vec![]) });
let mut lastTradesIsArray: bool = matches!(&lastTradesResponse, Value::Arr(_));
let mut lastTrades: Value = (if (lastTradesIsArray) { lastTradesResponse } else { Value::from(vec![]) });
let mut lastTradesByTokenId: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut lastTradesLength: f64 = ((lastTrades.len() as i64) as f64);
{
let mut li: Value = Value::Int(0);
let mut __for_first_1433: bool = true;
while { if !__for_first_1433 { if let Value::Int(n) = &mut li { *n += 1; } } __for_first_1433 = false; li.as_f64().unwrap_or(f64::NAN) < lastTradesLength } {
let mut lastTradeEntry: Value = lastTrades.as_array().and_then(|__arr| match &li { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut lastTradeTokenId: Option<String> = self.safe_string_k_opt(lastTradeEntry.clone(), "token_id", &[]);
if (lastTradeTokenId.is_some()) {
lastTradesByTokenId.insert(lastTradeTokenId.as_deref().unwrap_or("null").to_string(), lastTradeEntry);
}
}
}
let mut booksLength: f64 = ((books.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1434: bool = true;
while { if !__for_first_1434 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1434 = false; i.as_f64().unwrap_or(f64::NAN) < booksLength } {
let mut book: Value = books.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut tokenId: Value = self.safe_string_k(book.clone(), "asset_id", &[]);
if (tokenId == Value::Null) || !(matches!((&outcomesByTokenId, &tokenId), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
continue;
}
let mut outcomeObj: Value = (if let (Some(__m), Some(__k)) = (outcomesByTokenId.as_map(), tokenId.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
let mut mid: Option<String> = self.safe_string_opt(midpoints.clone(), tokenId.clone(), &[]);
let mut tickerInput: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("midpoint".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mid".to_string(), mid.map(Value::from).unwrap_or(Value::Null));
m
}));
m.insert("book".to_string(), book);
m.insert("lastTrade".to_string(), self.safe_dict(Value::Map(lastTradesByTokenId.clone()), tokenId.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]));
m
});
let mut ticker: Value = self.parse_prediction_ticker(Value::Map(tickerInput), &[outcomeObj]);
let mut symbolKey: Value = self.safe_string_k(ticker.clone(), "outcome", &[tokenId]);
result.insert(crate::runtime::stringify_param(&symbolKey), ticker);
}
}
startIndex = self.sum(&[startIndex.clone(), Value::from(chunkSize)]);
}
return Value::Map(result);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#parsePredictionTicker
* @description parses a combined midpoint + order book response into a unified ticker object
* @param {object} ticker a dict with midpoint and book entries
* @param {object} [market] the outcome object the ticker belongs to
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub fn parse_prediction_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "midpoint": {
// "mid": "0.9985"
// },
// "book": {
// "market": "0x2d55f622bc12e23dc1f1bb4db8360c28c92155f9376bf73953c0756ee1387b2f",
// "asset_id": "16718041887881762329859205887704087070587186248220606272297433440108449709696",
// "timestamp": "1777344471023",
// "hash": "11aa0feabec970de83b04a2c0d50a7639e144f43",
// "bids": [
// {
// "price": "0.45",
// "size": "100"
// },
// ],
// "asks": [
// {
// "price": "0.46",
// "size": "150"
// },
// ],
// "min_order_size": "5",
// "tick_size": "0.001",
// "neg_risk": false,
// "last_trade_price": "0.998"
// },
// "lastTrade": {
// "price": "0.46",
// "side": "BUY"
// }
// }
//
let mut midpointData: Value = self.safe_dict_k(ticker.clone(), "midpoint", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bookData: Value = self.safe_dict_k(ticker.clone(), "book", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut mid: Value = self.safe_number_k(midpointData, "mid", &[]);
let mut bids: Value = self.safe_list_k(bookData.clone(), "bids", &[Value::from(vec![])]);
let mut asks: Value = self.safe_list_k(bookData.clone(), "asks", &[Value::from(vec![])]);
let mut bidsLength: Value = Value::Int(bids.len() as i64);
let mut asksLength: Value = Value::Int(asks.len() as i64);
// the CLOB book endpoint returns levels sorted away from the touch (bids ascending, asks descending), so the best level is the last entry
let mut bestBid: Value = (if (bidsLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) { bids.as_array().and_then(|__arr| match &((match (&(bidsLength), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x),
Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })) { Value::Int(__n) if *__n >= 0 => __arr.get(*__n as usize), _ => None }).cloned().unwrap_or(Value::Null) } else { Value::Null });
let mut bestAsk: Value = (if (asksLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) { asks.as_array().and_then(|__arr| match &((match (&(asksLength), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x),
Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })) { Value::Int(__n) if *__n >= 0 => __arr.get(*__n as usize), _ => None }).cloned().unwrap_or(Value::Null) } else { Value::Null });
// book.last_trade_price is market-level and denominated in whichever token traded last —
// on the complementary token it is the OTHER side's price, so only the per-token
// last-trade-price endpoint value is usable here; that endpoint reports "0" for a
// never-traded token, which also falls back to the mid
let mut lastTradeData: Value = self.safe_dict_k(ticker.clone(), "lastTrade", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut last: Value = self.safe_number_k(lastTradeData, "price", &[]);
if (last == Value::Null) || (last.as_f64() == Some(0.0)) {
last = mid.clone();
}
let mut outcome: Value = self.safe_outcome_symbol(Value::Null, &[market.clone()]);
let mut timestamp: Option<i64> = self.safe_integer_k(bookData, "timestamp", &[]).as_i64();
let mut quoteVolume: Value = Value::Null;
if (market != Value::Null) {
quoteVolume = self.safe_number2(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("volume24hr".into()), Value::Str("volume".into()), &[]);
}
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcome);
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), self.safe_number_k(bestBid.clone(), "price", &[]));
m.insert("bidVolume".to_string(), self.safe_number_k(bestBid, "size", &[]));
m.insert("ask".to_string(), self.safe_number_k(bestAsk.clone(), "price", &[]));
m.insert("askVolume".to_string(), self.safe_number_k(bestAsk, "size", &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), mid);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), quoteVolume);
m.insert("info".to_string(), ticker);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name polymarket#fetchOrderBook
* @description fetches the CLOB order book for a single outcome token
* @see https://docs.polymarket.com/api-reference/market-data/get-order-book
* @param {string} outcome unified outcome or outcome token id
* @param {int} [limit] not used by polymarket fetchOrderBook
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
*/
pub async fn fetch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_2 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.clob_public_get_book(&[__ws_arg_2]).await;
//
// {
// "market": "0x42d42b30124ed2d93800358dfd1d48253114e4d58cff15cb765cd0c69956555f",
// "asset_id": "53471586309106256293075593293890793127405137223521910882276033765569397092350",
// "timestamp": "1777541385018",
// "hash": "bfb61f58dab4055d956eb5e758dbc9101c9a4e6c",
// "bids": [
// { "price": "0.001", "size": "3147.19" },
// { "price": "0.002", "size": "1432.11" }
// ],
// "asks": [
// { "price": "0.999", "size": "73.68" },
// { "price": "0.998", "size": "7" }
// ],
// "min_order_size": "5",
// "tick_size": "0.001",
// "neg_risk": false,
// "last_trade_price": "0.002"
// }
//
let mut timestamp: Value = self.safe_integer_k(response.clone(), "timestamp", &[]);
let mut orderbook: Value = self.parse_order_book(response, self.safe_outcome_symbol(outcome, &[outcomeObj.clone()]), &[timestamp, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("size".into())]);
return self.safe_prediction_order_book(orderbook, &[outcomeObj]);
Value::Null
}
/*
* @method
* @name polymarket#fetchOHLCV
* @description fetches price history ticks for a single outcome token and buckets them client-side into OHLCV candles, snapping tick timestamps to the candle boundary
* @see https://docs.polymarket.com/api-reference/markets/get-prices-history
* @param {string} outcome unified outcome or outcome token id
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum number of candles to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} a list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".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
}));
if !(matches!((&self.timeframes, &timeframe), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
// hoisted keys list: chaining join onto Object.keys breaks the python transpiler
let mut supportedKeys: Value = Value::Array(self.timeframes.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default());
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() unsupported timeframe ".into())).into()), timeframe).into()), Value::Str(", supported timeframes are ".into())).into()),
Value::Str(supportedKeys.as_array().map(|__a| __a.iter().map(|__v| __v.to_string()).collect::<Vec<String>>().join(", ")).unwrap_or_default().into()))));
}
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj, "outcomeId", &[]);
let mut fidelityMin: Value = self.safe_integer(self.timeframes.clone(), timeframe, &[Value::Int(1)]); // fidelity in minutes
let mut nowS: Value = self.seconds();
let mut startS: Value = Value::Null;
let mut endS: Value = nowS.clone();
if (since != Value::Null) {
startS = self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
if (limit != Value::Null) {
let mut endBound: Value = self.sum(&[startS.clone(), (match (&((match (&(limit), &(fidelityMin)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y),
_ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
endS = (if (endBound.as_f64().unwrap_or(f64::NAN) < nowS.as_f64().unwrap_or(f64::NAN)) { endBound } else { nowS.clone() });
}
} else {
let mut barCount: Value = (if (limit != Value::Null) { limit.clone() } else { Value::Int(100) });
startS = (match (&(nowS), &(((match (&((match (&(barCount), &(fidelityMin)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })),
&(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y),
(Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
}
// the venue rejects startTs/endTs spans over 15 days ("interval is too long")
// regardless of fidelity, so clamp the window to the cap: keep the requested
// `since` anchor (oldest chunk first, consistent with since/limit paging),
// or the most recent window when no `since` was given
let mut maxWindow: Value = self.safe_integer_k(self.options.clone(), "maxPricesHistoryWindow", &[Value::Int(1296000)]);
if ((match (&(endS), &(startS)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })).as_f64().unwrap_or(f64::NAN) > maxWindow.as_f64().unwrap_or(f64::NAN) {
if (since != Value::Null) {
endS = self.sum(&[startS.clone(), maxWindow.clone()]);
} else {
startS = (match (&(endS), &(maxWindow)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
}
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("fidelity".to_string(), fidelityMin.clone());
m.insert("startTs".to_string(), startS);
m.insert("endTs".to_string(), endS);
m
});
let __ws_arg_3 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.clob_public_get_prices_history(&[__ws_arg_3]).await;
//
// {
// "history": [
// { "t": "1776043119", "p": "0.265" },
// ]
// }
//
let mut history: Value = self.safe_list_k(response, "history", &[Value::from(vec![])]);
// Client-side bucket aggregation: snap each tick to its candle boundary and
// build open/high/low/close/volume. Assumes history is sorted ascending by time.
let mut resolutionMs: Value = (match (&((match (&(fidelityMin), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })),
&(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut buckets: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: i64 = 0;
let mut __for_first_1435: bool = true;
while { if !__for_first_1435 { i += 1; } __for_first_1435 = false; i < (history.len() as i64) } {
let mut item: Value = self.safe_dict(history.clone(), Value::Int(i), &[]);
let mut t: Value = self.safe_integer_k(item.clone(), "t", &[]);
let mut price: Value = self.safe_number_k(item.clone(), "p", &[]);
if (t == Value::Null) || (price == Value::Null) {
continue;
}
let mut rawMs: Value = (match (&(t), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut snappedMs: Value = (match (&(self.parse_to_int((match ((rawMs).as_f64(), (resolutionMs).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))), &(resolutionMs)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x),
Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
// the venue supplies no candle volume ({t, p} ticks only) — leave it undefined
// rather than fabricating a 0, probing s/v in case the field ever appears
let mut vol: Value = self.safe_number_k(item.clone(), "s", &[]);
if (vol == Value::Null) {
vol = self.safe_number_k(item, "v", &[]);
}
let mut bucketKey: Value = Value::Str(format!("{}", snappedMs).into());
if !(matches!((&buckets, &bucketKey), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut buckets { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&bucketKey), Value::from(vec![snappedMs, price.clone(), price.clone(), price.clone(), price.clone(), vol.clone()])); }
} else {
let mut candle: Value = self.safe_list(buckets.clone(), bucketKey.clone(), &[Value::from(vec![])]);
{ let __be_tmp = crate::runtime::Math::max(&get_value(&candle, &Value::Int(2)), &price); add_element_to_object(&mut candle, &Value::Int(2), __be_tmp); }; // high
{ let __be_tmp = crate::runtime::Math::min(&get_value(&candle, &Value::Int(3)), &price); add_element_to_object(&mut candle, &Value::Int(3), __be_tmp); }; // low
add_element_to_object(&mut candle, &Value::Int(4), price); // close (last tick wins)
if (vol != Value::Null) {
let mut prevVol: Value = candle.as_array().and_then(|__arr| __arr.get(5)).cloned().unwrap_or(Value::Null);
add_element_to_object(&mut candle, &Value::Int(5), (if (prevVol == Value::Null) { vol.clone() } else { self.sum(&[prevVol, vol]) })); // volume
}
if let Value::Dict(__d) = &mut buckets { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&bucketKey), candle); }; // reassign after mutation, php arrays are value types
}
}
}
let mut bucketKeys: Vec<Value> = Value::Array(buckets.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).as_array().cloned().unwrap_or_default();
let mut unsortedCandles: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1436: bool = true;
while { if !__for_first_1436 { i += 1; } __for_first_1436 = false; i < (bucketKeys.len() as i64) } {
unsortedCandles.push(buckets.as_map().and_then(|__m| bucketKeys.get(i as usize).cloned().unwrap_or(Value::Null).as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null));
}
}
let mut candles: Value = self.sort_by(Value::from(unsortedCandles), Value::Int(0), &[]);
let mut candlesLength: f64 = ((candles.len() as i64) as f64);
if (limit != Value::Null) && (candlesLength > limit.as_f64().unwrap_or(f64::NAN)) {
return self.array_slice(candles.clone(), (match &(limit) { Value::Int(x) => Value::Int(-x), Value::Float(x) => Value::Float(-x), _ => Value::Null }), &[]);
}
return candles;
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
// Unused: fetchOHLCV performs client-side bucket aggregation directly.
//
// {
// "t": "1776043119",
// "p": "0.265"
// }
//
let mut price: Value = self.safe_number_k(ohlcv.clone(), "p", &[]);
return Value::from(vec![self.safe_timestamp_k(ohlcv, "t", &[]), price.clone(), price.clone(), price.clone(), price.clone(), Value::Null]);
Value::Null
}
/*
* @method
* @name polymarket#fetchTime
* @description fetches the current timestamp from the CLOB server
* @see https://docs.polymarket.com/api-reference/data/get-server-time
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current server time in milliseconds
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.clob_public_get_time(&[params]).await;
//
// 1781273248
//
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("serverTime".to_string(), response);
m
});
return self.safe_timestamp_k(Value::Map(result), "serverTime", &[]);
Value::Null
}
/*
* @method
* @name polymarket#fetchStatus
* @description fetches the gamma API health status
* @see https://docs.polymarket.com/api-reference/events/list-events
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure](https://docs.ccxt.com/#/?id=exchange-status-structure)
*/
pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.gamma_public_get_status(&[params]).await;
//
// OK
//
let mut ok: bool = (response.as_str() == Some("OK")) || (response.as_str() == Some("ok"));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if ok { Value::Str("ok".into()) } else { Value::Str("maintenance".into()) }));
m.insert("updated".to_string(), Value::Null);
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
/*
* @method
* @name polymarket#fetchOpenInterest
* @description fetches the open interest of a prediction market outcome
* @see https://docs.polymarket.com/api-reference/misc/get-open-interest
* @param {string} outcome unified outcome or outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [open interest structure](https://docs.ccxt.com/#/?id=open-interest-structure)
*/
pub async fn fetch_open_interest(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut conditionId: Option<String> = self.safe_string_k_opt(outcomeInfo, "conditionId", &[]);
if (conditionId.is_none()) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterest() requires outcome.info.conditionId for ".into())).into()), outcome)));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market".to_string(), conditionId.map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_4 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.data_public_get_oi(&[__ws_arg_4]).await;
//
// [ { "market": "0x7976b8...92", "value": 4925662.470476 } ]
//
let mut first: Value = self.safe_dict(response, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_prediction_open_interest(first, &[outcomeObj]);
Value::Null
}
pub fn parse_prediction_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// { "market": "0x7976b8...92", "value": 4925662.470476 }
//
let mut openInterest: Value = self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_outcome_symbol(Value::Null, &[market.clone()]));
m.insert("openInterestAmount".to_string(), Value::Null);
m.insert("openInterestValue".to_string(), self.safe_number_k(interest.clone(), "value", &[]));
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("info".to_string(), interest);
m
}), &[market.clone()]);
add_element_to_object(&mut openInterest, &Value::Str("outcome".into()), self.safe_outcome_symbol(Value::Null, &[market.clone()]));
add_element_to_object(&mut openInterest, &Value::Str("outcomeId".into()), self.safe_string_k(market.clone(), "outcomeId", &[]));
add_element_to_object(&mut openInterest, &Value::Str("market".into()), self.safe_string_k(market, "market", &[]));
remove(&mut openInterest, &Value::Str("symbol".into()));
return openInterest;
Value::Null
}
/*
* @method
* @name polymarket#fetchTradingFee
* @description fetches the base fee rate for a prediction market outcome token
* @see https://docs.polymarket.com/api-reference/market-data/get-fee-rate
* @param {string} outcome unified outcome or outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [fee structure](https://docs.ccxt.com/#/?id=fee-structure)
*/
pub async fn fetch_trading_fee(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_5 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.clob_public_get_fee_rate(&[__ws_arg_5]).await;
//
// { "base_fee": 30 } // base fee in basis points
//
let mut baseFeeBps: Option<String> = self.safe_string_k_opt(response.clone(), "base_fee", &[]);
let mut rate: Value = (if (baseFeeBps.is_some()) { self.parse_number(crate::precise::Precise::stringDiv(&baseFeeBps.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("10000".into())), &[]) } else { Value::Null });
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("outcome".to_string(), self.safe_outcome_symbol(Value::Null, &[outcomeObj.clone()]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m.insert("maker".to_string(), rate.clone());
m.insert("taker".to_string(), rate);
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m
});
Value::Null
}
/*
* @method
* @name polymarket#fetchTrades
* @description fetches public trade history for a single outcome token from the data API
* @see https://docs.polymarket.com/api-reference/core/get-trades-for-a-user-or-markets
* @param {string} outcome unified outcome or outcome token id
* @param {int} [since] not used by polymarket fetchTrades
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_trades(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[Value::Str("".into())]);
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut conditionId: Option<String> = self.safe_string_k_opt(outcomeInfo, "conditionId", &[]);
if (conditionId.is_none()) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchTrades() requires outcome.info.conditionId for an outcome ".into())).into()), tokenId)));
}
// the endpoint filters by market conditionId (which spans BOTH outcome tokens), then we narrow
// to the requested token client-side below. applying the user's `limit` to this request and
// THEN filtering can return 0 rows on an active outcome (if the top `limit` market trades are
// all the other token). over-fetch a large page here; the user's `limit` is applied AFTER the
// token filter by parsePredictionTrades
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market".to_string(), conditionId.clone().map(Value::from).unwrap_or(Value::Null));
m
});
request.insert("limit".into(), self.safe_integer_k(self.options.clone(), "tradesPageSize", &[Value::Int(500)]));
let __ws_arg_6 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.data_public_get_trades(&[__ws_arg_6]).await;
let mut rawTrades: Value = (if (matches!(&response, Value::Arr(_))) { response.clone() } else { self.safe_list_k(response, "data", &[Value::from(vec![])]) });
let mut filteredTrades: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1437: bool = true;
while { if !__for_first_1437 { i += 1; } __for_first_1437 = false; i < (rawTrades.len() as i64) } {
let mut trade: Value = rawTrades.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut tradeAsset: Value = self.safe_string_k(trade.clone(), "asset", &[]);
if (tradeAsset == tokenId) {
filteredTrades.push(trade);
}
}
}
return self.parse_prediction_trades(Value::from(filteredTrades), &[Value::Null, since, limit]);
Value::Null
}
/*
* @method
* @name polymarket#fetchMyTrades
* @description fetches the authenticated user's trade history from the CLOB, optionally filtered by outcome token
* @see https://docs.polymarket.com/api-reference/trade/get-trades
* @param {string} [outcome] unified outcome or outcome token id
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
outcomeObj = self.load_outcome(outcome, &[]).await;
request.insert("asset_id".into(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
}
let __ws_arg_7 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.clob_private_get_data_trades(&[__ws_arg_7]).await;
let mut rawTrades: Value = (if (matches!(&response, Value::Arr(_))) { response.clone() } else { self.safe_list_k(response, "data", &[Value::from(vec![])]) });
return self.parse_prediction_trades(rawTrades, &[outcomeObj, since, limit]);
Value::Null
}
/*
* @method
* @name polymarket#fetchOrderTrades
* @description fetches all the trades made from a single order
* @see https://docs.polymarket.com/api-reference/trade/get-trades
* @param {string} id the order id
* @param {string} [outcome] unified outcome or outcome token id to narrow the lookup
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_order_trades(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// the /data/trades endpoint has no order filter, so fetch the user's trades and keep
// the ones where this order was the taker or one of the matched makers
let mut trades: Value = self.fetch_my_trades(&[outcome, Value::Null, Value::Null, params]).await;
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1439: bool = true;
while { if !__for_first_1439 { i += 1; } __for_first_1439 = false; i < (trades.len() as i64) } {
let mut trade: Value = trades.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut info: Value = self.safe_dict_k(trade.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut belongs: bool = (self.safe_string_k(trade.clone(), "order", &[]).as_str() == id.as_str()) || (self.safe_string_k(info.clone(), "taker_order_id", &[]).as_str() == id.as_str());
let mut makerOrders: Value = self.safe_list_k(info, "maker_orders", &[Value::from(vec![])]);
{
let mut j: i64 = 0;
let mut __for_first_1438: bool = true;
while { if !__for_first_1438 { j += 1; } __for_first_1438 = false; j < (makerOrders.len() as i64) } {
let mut makerOrder: Value = self.safe_dict(makerOrders.clone(), Value::Int(j), &[]);
if (self.safe_string_k(makerOrder, "order_id", &[]).as_str() == id.as_str()) {
belongs = true;
}
}
}
if belongs {
result.push(trade);
}
}
}
return self.filter_by_since_limit(Value::from(result), &[since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#parsePredictionTrade
* @description parses a raw data API trade object into a unified trade object
* @param {object} trade the raw trade object
* @param {object} [market] the outcome object the trade belongs to
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
// public data-api trades use 'asset'/'orderId'/'transactionHash'/'timestamp';
// the private CLOB /data/trades use 'asset_id'/'taker_order_id'/'transaction_hash'/'match_time'
let mut id: Option<String> = self.safe_string_n_opt(trade.clone(), Value::from(vec![Value::Str("transactionHash".into()), Value::Str("transaction_hash".into()), Value::Str("id".into())]), &[]);
let mut timestamp: Value = self.safe_integer_product_k(trade.clone(), "timestamp", Value::Int(1000), &[]);
if (timestamp == Value::Null) {
timestamp = self.safe_integer_product_k(trade.clone(), "match_time", Value::Int(1000), &[]);
}
let mut price: Value = self.safe_number_k(trade.clone(), "price", &[]);
let mut amount: Value = self.safe_number_k(trade.clone(), "size", &[]);
let mut rawSide: Option<String> = self.safe_string_lower_k_opt(trade.clone(), "side", &[]);
let mut side: Value = Value::Null;
if (rawSide.as_deref() == Some("buy")) || (rawSide.as_deref() == Some("sell")) {
side = rawSide.map(Value::from).unwrap_or(Value::Null);
}
let mut assetId: Option<String> = self.safe_string2_opt(trade.clone(), Value::Str("asset".into()), Value::Str("asset_id".into()), &[]);
let mut mkt: Value = Value::Null;
if (market != Value::Null) {
mkt = market;
} else {
mkt = self.safe_outcome(assetId.clone().map(Value::from).unwrap_or(Value::Null), &[]);
}
let mut outcome: Value = self.safe_outcome_symbol(Value::Null, &[mkt.clone()]);
let mut rawTakerOrMaker: Option<String> = self.safe_string_lower_k_opt(trade.clone(), "trader_side", &[]);
let mut takerOrMaker: Value = Value::Null;
if (rawTakerOrMaker.as_deref() == Some("taker")) || (rawTakerOrMaker.as_deref() == Some("maker")) {
takerOrMaker = rawTakerOrMaker.map(Value::from).unwrap_or(Value::Null);
}
let mut feeRateBps: Option<String> = self.safe_string_k_opt(trade.clone(), "fee_rate_bps", &[]);
let mut fee: Value = Value::Null;
if (feeRateBps.is_some()) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDC".into()));
m.insert("rate".to_string(), self.parse_number(crate::precise::Precise::stringDiv(&feeRateBps.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("10000".into())), &[]));
m
});
}
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("outcome".to_string(), outcome);
m.insert("outcomeId".to_string(), assetId.map(Value::from).unwrap_or(Value::Null));
m.insert("label".to_string(), self.safe_string_k(mkt.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(mkt.clone(), "market", &[]));
m.insert("order".to_string(), self.safe_string2(trade, Value::Str("orderId".into()), Value::Str("taker_order_id".into()), &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[mkt]);
Value::Null
}
/*
* @method
* @name polymarket#fetchBalance
* @description fetches the USDC collateral balance available for trading on the CLOB
* @see https://docs.polymarket.com/api-reference/trade/get-balance-allowance
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.signatureType] 0=EOA, 1=POLY_PROXY, 2=GNOSIS_SAFE, 3=POLY_1271 (deposit wallet); defaults to options.signatureType
* @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
// the collateral balance is tied to the signature type / funder that holds the USDC
let mut signatureType: Value = self.safe_integer2(params.clone(), Value::Str("signatureType".into()), Value::Str("signature_type".into()), &[self.safe_integer_k(self.options.clone(), "signatureType", &[Value::Int(3)])]);
let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("signatureType".into()), Value::Str("signature_type".into())]), &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("asset_type".to_string(), Value::Str("COLLATERAL".into()));
m.insert("signature_type".to_string(), signatureType);
m
});
let __ws_arg_8 = self.extend(Value::Map(request), &[rest]);
let mut response: Value = self.clob_private_get_balance_allowance(&[__ws_arg_8]).await;
return self.parse_balance(response);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#parseBalance
* @description parses a balance-allowance response into a balances object with a USDC entry
* @param {object} response the raw balance-allowance response
* @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
*/
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
// 'balance' is the raw USDC collateral in 6-decimal units (e.g. "8992211" = 8.992211 USDC)
let mut raw: Option<String> = self.safe_string_k_opt(response, "balance", &[]);
let mut total: Value = Value::Null;
if (raw.is_some()) {
total = self.parse_number(crate::precise::Precise::stringDiv(&raw.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("1000000".into())), &[]);
}
result.insert("USDC".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("free".to_string(), total.clone());
m.insert("used".to_string(), Value::Null);
m.insert("total".to_string(), total);
m
}));
return self.safe_balance(Value::Map(result));
Value::Null
}
/*
* @method
* @name polymarket#fetchPositions
* @description fetches open outcome token positions for the wallet from the data API
* @see https://docs.polymarket.com/api-reference/core/get-current-positions-for-a-user
* @param {string[]} [outcomes] unified outcomes to filter by
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction position structures](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomesLength: i64 = 0;
if (outcomes != Value::Null) {
outcomesLength = outcomes.len() as i64;
self.load_outcomes(&[outcomes.clone()]).await;
}
// no bulk warm-up on the unfiltered path: the positions request is self-contained and
// labels resolve cache-only via safeOutcome (raw token ids when the cache is cold)
if (self.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" walletAddress is required to fetchPositions".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), self.walletAddress.clone());
m
});
let __ws_arg_9 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.data_public_get_positions(&[__ws_arg_9]).await;
let mut positions: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
// parse without the base outcome filter (it resolves standard markets, not outcome tokens),
// then filter by the requested outcomes' token ids ourselves
if (((outcomesLength as f64) == 0.0)) {
return self.parse_prediction_positions(positions.clone(), &[]);
}
let mut parsed: Vec<Value> = self.parse_prediction_positions(positions, &[]).as_array().cloned().unwrap_or_default();
let mut wantedIds: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (outcomes == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() missing outcomes".into()))));
}
{
let mut i: i64 = 0;
let mut __for_first_1440: bool = true;
while { if !__for_first_1440 { i += 1; } __for_first_1440 = false; i < (outcomes.len() as i64) } {
let mut outcomeObj: Value = self.outcome(outcomes.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null));
add_element_to_object(&mut wantedIds, &outcomeObj.as_map().and_then(|__m| __m.get("outcomeId")).cloned().unwrap_or(Value::Null), Value::Bool(true));
}
}
let mut result: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_1441: bool = true;
while { if !__for_first_1441 { i += 1; } __for_first_1441 = false; i < (parsed.len() as i64) } {
let mut position: Value = parsed.get(i as usize).cloned().unwrap_or(Value::Null);
let mut info: Value = self.safe_dict_k(position.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut assetId: Option<String> = self.safe_string_k_opt(info, "asset", &[]);
if (assetId.is_some()) && (matches!((&wantedIds, &assetId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Arr(__a) = &mut result { std::sync::Arc::make_mut(__a).push(position); }
}
}
}
return result;
Value::Null
}
/*
* @method
* @name polymarket#fetchPosition
* @description fetches the open position for a single outcome token
* @see https://docs.polymarket.com/api-reference/core/get-current-positions-for-a-user
* @param {string} outcome unified outcome or outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub async fn fetch_position(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut positions: Value = self.fetch_positions(&[Value::from(vec![outcome]), params]).await;
return self.safe_dict(positions, Value::Int(0), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#parsePredictionPosition
* @description parses a raw data API position object into a unified position object
* @param {object} position the raw position object
* @param {object} [market] the outcome object the position belongs to
* @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub fn parse_prediction_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut tokenId: Option<String> = self.safe_string_k_opt(position.clone(), "asset", &[]);
let mut marketData: Value = self.safe_outcome(tokenId.map(Value::from).unwrap_or(Value::Null), &[market]);
let mut size: Value = self.safe_number_k(position.clone(), "size", &[]);
let mut entryPrice: Value = self.safe_number_k(position.clone(), "avgPrice", &[]);
let mut curPrice: Value = self.safe_number_k(position.clone(), "currentPrice", &[]);
let mut notional: Value = Value::Null;
if (size != Value::Null) && (curPrice != Value::Null) {
notional = (match (&(size), &(curPrice)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
}
return self.safe_prediction_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(position.clone(), "id", &[]));
m.insert("outcome".to_string(), self.safe_string_k(marketData.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(marketData.clone(), "outcomeId", &[]));
m.insert("market".to_string(), self.safe_string_k(marketData.clone(), "market", &[]));
m.insert("label".to_string(), self.safe_string_k(marketData.clone(), "label", &[]));
m.insert("event".to_string(), self.safe_string_k(marketData, "event", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("contracts".to_string(), size);
m.insert("contractSize".to_string(), Value::Int(1));
m.insert("side".to_string(), Value::Str("long".into()));
m.insert("notional".to_string(), notional);
m.insert("leverage".to_string(), Value::Int(1));
m.insert("unrealizedPnl".to_string(), Value::Null);
m.insert("realizedPnl".to_string(), self.safe_number_k(position.clone(), "realizedPnl", &[]));
m.insert("collateral".to_string(), Value::Null);
m.insert("entryPrice".to_string(), entryPrice);
m.insert("markPrice".to_string(), curPrice);
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Str("cross".into()));
m.insert("marginType".to_string(), Value::Str("cross".into()));
m.insert("percentage".to_string(), Value::Null);
m.insert("info".to_string(), position);
m
}));
Value::Null
}
/*
* @method
* @name polymarket#fetchOpenOrders
* @description fetches open resting orders for the authenticated user, optionally filtered by outcome token
* @see https://docs.polymarket.com/api-reference/trade/get-user-orders
* @param {string} [outcome] unified outcome or outcome token id
* @param {int} [since] not used by polymarket fetchOpenOrders
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
outcomeObj = self.load_outcome(outcome, &[]).await;
request.insert("asset_id".into(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
}
let __ws_arg_10 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.clob_private_get_data_orders(&[__ws_arg_10]).await;
let mut orders: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_prediction_orders(orders, &[outcomeObj, since, limit]);
Value::Null
}
/*
* @method
* @name polymarket#fetchOrder
* @description fetches a single order by id from the CLOB private data endpoint
* @see https://docs.polymarket.com/api-reference/trade/get-single-order-by-id
* @param {string} id the order id
* @param {string} [outcome] unified outcome or outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// the request only needs the order id; the outcome is a labelling hint, so resolve it from
// cache (no network) — fetchOrder stays a single request even on a cold cache.
self.load_api_credentials().await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m
});
let __ws_arg_11 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.clob_private_get_data_order_id(&[__ws_arg_11]).await;
return self.parse_prediction_order(response, &[]);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#parsePredictionOrder
* @description parses a raw CLOB order object into a unified order object
* @param {object} order the raw order object
* @param {object} [market] the outcome object the order belongs to
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub fn parse_prediction_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "errorMsg":"",
// "orderID":"0xdf6c53273ad44ab208323c8dde43f04304852c89d55df57efaca8e40caf2f363",
// "takingAmount":"",
// "makingAmount":"",
// "status":"live",
// "success":true
// }
// fetchOrder/fetchOpenOrders return 'id'; the createOrder POST response returns 'orderID'
let mut id: Option<String> = self.safe_string2_opt(order.clone(), Value::Str("id".into()), Value::Str("orderID".into()), &[]);
let mut tokenId: Option<String> = self.safe_string_k_opt(order.clone(), "asset_id", &[]);
let mut mkt: Value = self.safe_outcome(tokenId.map(Value::from).unwrap_or(Value::Null), &[market]);
// REST returns 'status'; the user-websocket order event carries lifecycle in 'type'
let mut status: Value = self.parse_order_status(self.safe_string2(order.clone(), Value::Str("status".into()), Value::Str("type".into()), &[])).map(Value::from).unwrap_or(Value::Null);
let mut side: Option<String> = self.safe_string_lower_k_opt(order.clone(), "side", &[]);
let mut price: Value = self.safe_number_k(order.clone(), "price", &[]);
let mut amount: Value = self.safe_number_k(order.clone(), "original_size", &[]);
let mut filled: Value = self.safe_number_k(order.clone(), "size_matched", &[Value::Int(0)]);
let mut ts: Value = self.safe_integer_product_k(order.clone(), "created_at", Value::Int(1000), &[]);
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), order.clone());
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("outcome".to_string(), mkt.as_map().and_then(|__m| __m.get("outcome")).cloned().unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), self.safe_string_k(mkt.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(mkt.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(mkt.clone(), "market", &[]));
m.insert("type".to_string(), Value::Str("limit".into()));
m.insert("timeInForce".to_string(), self.safe_string_k(order.clone(), "time_in_force", &[Value::Str("GTC".into())]));
m.insert("postOnly".to_string(), self.safe_bool_k(order, "postOnly", &[]));
m.insert("side".to_string(), side.map(Value::from).unwrap_or(Value::Null));
m.insert("price".to_string(), price);
m.insert("stopPrice".to_string(), Value::Null);
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m
}), &[mkt]);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#parseOrderStatus
* @description maps a polymarket order status string to the unified status vocabulary
* @param {string} status the raw polymarket order status
* @returns {string} a unified order status
*/
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("live".to_string(), Value::Str("open".into()));
m.insert("matched".to_string(), Value::Str("closed".into()));
m.insert("cancelled".to_string(), Value::Str("canceled".into()));
m.insert("delayed".to_string(), Value::Str("open".into()));
m.insert("placement".to_string(), Value::Str("open".into()));
m.insert("update".to_string(), Value::Str("open".into()));
m.insert("cancellation".to_string(), Value::Str("canceled".into()));
m
});
// the REST data endpoints return upper-case statuses (LIVE, MATCHED, CANCELLED) while the
// user websocket sends lower-case lifecycle types — lower-case before the lookup so both map
let mut normalized: Value = self.safe_string_lower(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), status);
m
}), Value::Str("status".into()), &[]);
return self.safe_string(Value::Map(statuses), normalized.clone(), &[normalized.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name polymarket#createOrder
* @description places a limit or market order on the CLOB for the given outcome token
* @see https://docs.polymarket.com/api-reference/trade/post-a-new-order
* @param {string} outcome unified outcome or outcome token id
* @param {string} type 'market' or 'limit'; market orders default to FOK and, when no price is given, use the outcome's current price as the marketable reference
* @param {string} side 'buy' or 'sell'
* @param {float} amount how many outcome tokens to trade
* @param {float} [price] the price per outcome token between 0 and 1; required for limit orders, defaults to the outcome's current price for market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.orderType] time-in-force override: 'GTC' (default for limit), 'FOK' (default for market), 'GTD' or 'FAK'
* @param {int} [params.signatureType] 0=EOA, 1=POLY_PROXY, 2=GNOSIS_SAFE, 3=POLY_1271 (deposit wallet); defaults to options.signatureType
* @param {string} [params.funder] the wallet that holds the USDC collateral; defaults to options.funder or the signing address
* @param {string} [params.tickSize] the market tick size ('0.1'/'0.01'/'0.001'/'0.0001'); read from the outcome when omitted
* @param {bool} [params.negRisk] whether the market is a neg-risk market; read from the outcome when omitted
* @param {string} [params.salt] order salt; defaults to a strictly-increasing millisecond value (pin it for idempotent retries)
* @param {string} [params.timestamp] order timestamp; defaults to the current time in ms
* @param {string} [params.expiration] unix-seconds expiration for GTD orders; defaults to '0' (no expiry)
* @param {string} [params.builderCode] builder wallet address or full bytes32 builder code attached to the order for attribution (zero fee — tracking only); defaults to options.builder
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_order(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
self.load_outcome(outcome.clone(), &[]).await;
let mut built: Value = self.build_clob_order_body(outcome, type_var, side, amount, &[price, params]);
let mut response: Value = self.clob_private_post_order(&[self.safe_dict_k(built.clone(), "body", &[])]).await;
// request echo first so the response's real orderID/status/success win on overlap
let __ws_arg_12 = self.safe_dict_k(built.clone(), "request", &[]);
let mut enriched: Value = self.extend(__ws_arg_12, &[response.clone()]);
let mut order: Value = self.parse_prediction_order(enriched, &[self.safe_dict_k(built, "outcome", &[])]);
if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("info".to_string(), response); } // keep info the raw exchange response, not the request echo
return order;
Value::Null
}
/*
* @method
* @name polymarket#createOrders
* @description places multiple orders on the CLOB in a single batched request
* @see https://docs.polymarket.com/api-reference/trade/post-orders
* @param {object[]} orders a list of order requests, each an object with outcome, type, side, amount, price and optional params (same params as createOrder)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
// buildClobOrderBody resolves outcomes synchronously from the cache, so batch-warm the
// requested outcomes first (one gamma request for all uncached token ids)
let mut orderOutcomes: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1442: bool = true;
while { if !__for_first_1442 { i += 1; } __for_first_1442 = false; i < (orders.len() as i64) } {
let mut o: Value = self.safe_dict(orders.clone(), Value::Int(i), &[]);
let mut __oc: Option<String> = self.safe_string_k_opt(o.clone(), "outcome", &[]);
if (__oc.is_some()) {
orderOutcomes.push(__oc.map(Value::from).unwrap_or(Value::Null));
}
}
}
self.load_outcomes(&[Value::from(orderOutcomes)]).await;
let mut bodies: Vec<Value> = Vec::new();
let mut outcomes: Vec<Value> = Vec::new();
let mut requests: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1443: bool = true;
while { if !__for_first_1443 { i += 1; } __for_first_1443 = false; i < (orders.len() as i64) } {
let mut o: Value = self.safe_dict(orders.clone(), Value::Int(i), &[]);
let mut orderParams: Value = self.safe_dict_k(o.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.safe_string_k(orderParams.clone(), "salt", &[]) == Value::Null) {
// a distinct salt per order so two identical orders don't collide, within a batch or across calls
let mut orderSalt: Value = self.incrementing_nonce(); // hoisted to a named local: nesting the &mut self call inside numberToString breaks the Rust borrow checker
let __ws_arg_13 = self.number_to_string(orderSalt);
orderParams = self.extend(orderParams.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("salt".to_string(), __ws_arg_13);
m
})]);
}
let mut built: Value = self.build_clob_order_body(self.safe_string_k(o.clone(), "outcome", &[]), self.safe_string_k(o.clone(), "type", &[]), self.safe_string_k(o.clone(), "side", &[]), self.safe_number_k(o.clone(), "amount", &[]), &[self.safe_number_k(o, "price", &[]), orderParams]);
bodies.push(self.safe_dict_k(built.clone(), "body", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]));
outcomes.push(self.safe_dict_k(built.clone(), "outcome", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]));
requests.push(self.safe_dict_k(built, "request", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]));
}
}
let mut response: Value = self.clob_private_post_orders(&[Value::from(bodies)]).await;
let mut result: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_1444: bool = true;
while { if !__for_first_1444 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1444 = false; i.as_f64().unwrap_or(f64::NAN) < ((response.len() as i64) as f64) } {
// request echo first so the response's real orderID/status win on overlap
let mut rawItem: Value = response.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut enriched: Value = self.extend(requests.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[rawItem.clone()]);
let mut parsedItem: Value = self.parse_prediction_order(enriched, &[outcomes.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)]);
if let Value::Dict(__rda) = &mut parsedItem { std::sync::Arc::make_mut(__rda).insert("info".to_string(), rawItem); } // keep info the raw exchange response
if let Value::Arr(__a) = &mut result { std::sync::Arc::make_mut(__a).push(parsedItem); }
}
}
} else {
if let Value::Arr(__a) = &mut result { std::sync::Arc::make_mut(__a).push(self.parse_prediction_order(response, &[])); }
}
return result;
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#buildClobOrderBody
* @description builds and signs a single CLOB order request body (shared by createOrder and createOrders)
* @returns {object} an object with 'body' (the signed order request) and 'outcome' (the resolved outcome)
*/
pub fn build_clob_order_body(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// pure builder, no network I/O — intentionally synchronous. a no-op async method
// transpiles in php to a promise-typed wrapper around a body that returns a plain
// dict, which throws a TypeError
// outcome () validates the outcome against the loaded outcomes (built from events or markets)
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
let mut sideStr: Value = (if let Some(__s) = side.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
let mut isMarket: bool = type_var.as_str() == Some("market");
// CCXT type (limit/market) maps to a polymarket time-in-force: limit -> GTC, market -> FOK.
// native override: params.orderType (GTC, GTD, FOK or FAK)
let mut orderTypeStr: Value = self.safe_string_upper_k(params.clone(), "orderType", &[]);
if (orderTypeStr == Value::Null) {
// otherwise map the unified `timeInForce` onto polymarket's orderType vocabulary
let mut unifiedTif: Option<String> = self.safe_string_upper_k(params.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
if (unifiedTif.as_deref() == Some("GTC")) {
orderTypeStr = Value::Str("GTC".into());
} else if (unifiedTif.as_deref() == Some("FOK")) {
orderTypeStr = Value::Str("FOK".into());
} else if (unifiedTif.as_deref() == Some("IOC")) {
orderTypeStr = Value::Str("FAK".into()); // fill-and-kill == immediate-or-cancel
} else if (unifiedTif.as_deref() == Some("GTD")) {
orderTypeStr = Value::Str("GTD".into());
}
}
if (orderTypeStr == Value::Null) {
orderTypeStr = (if isMarket { Value::Str("FOK".into()) } else { Value::Str("GTC".into()) });
}
let mut priceResolved: Value = price;
if (priceResolved == Value::Null) {
if !isMarket {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price for limit orders".into()))));
}
// market order without an explicit price: use the outcome's current price as the marketable reference
priceResolved = self.safe_number_k(outcomeObj.clone(), "price", &[]);
if (priceResolved == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() could not determine a price from the outcome, pass an explicit price".into()))));
}
}
// tick size + neg-risk flag drive the rounding and the verifying contract; both are read from the
// outcome object (set in parseMarket) and can be overridden via params to keep requests deterministic
let mut outcomePrecision: Value = self.safe_dict_k(outcomeObj.clone(), "precision", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut tickSize: Value = self.safe_string_k(params.clone(), "tickSize", &[self.number_to_string(self.safe_number(outcomePrecision, Value::Str("price".into()), &[Value::Float(0.01)]))]);
let mut negRisk: Value = self.safe_bool_k(params.clone(), "negRisk", &[self.safe_bool(outcomeObj.clone(), Value::Str("negRisk".into()), &[Value::Bool(false)])]);
// maker-only: the CLOB rejects the order if it would immediately take
let mut postOnly: bool = self.safe_bool_k_opt(params.clone(), "postOnly", &[Value::Bool(false)]).unwrap_or(false);
// 0=EOA, 1=POLY_PROXY, 2=GNOSIS_SAFE, 3=POLY_1271 (deposit wallet, default); funder/maker holds the USDC
let mut signatureType: Value = self.safe_integer2(params.clone(), Value::Str("signatureType".into()), Value::Str("signature_type".into()), &[self.safe_integer_k(self.options.clone(), "signatureType", &[Value::Int(3)])]);
// the signer/owner is the EOA behind the privateKey; the funder/maker is the proxy or deposit wallet (walletAddress)
let mut eoa: Value = self.eth_checksum_address(self.eth_get_address_from_private_key(self.privateKey.clone(), &[])).map(Value::from).unwrap_or(Value::Null);
let mut funder: Value = self.eth_checksum_address(self.safe_string2(params.clone(), Value::Str("funder".into()), Value::Str("maker".into()), &[self.safe_string_k(self.options.clone(), "funder", &[self.walletAddress.clone()])])).map(Value::from).unwrap_or(Value::Null);
// the salt defaults to a strictly-increasing millisecond value and the timestamp to the current time; both can be pinned via params for idempotency
let mut defaultSalt: Value = self.incrementing_nonce(); // hoisted to a named local: nesting the &mut self call inside numberToString breaks the Rust borrow checker
let mut salt: Value = self.safe_string_k(params.clone(), "salt", &[self.number_to_string(defaultSalt)]);
let mut timestamp: Value = self.safe_string_k(params.clone(), "timestamp", &[self.number_to_string(self.milliseconds())]);
// GTD (good-til-date) orders need a unix-seconds expiration; 0 means no expiry
let mut expiration: Value = self.safe_string_k(params.clone(), "expiration", &[Value::Str("0".into())]);
// a market buy can be sized by USDC cost instead of shares (see createMarketBuyOrderWithCost)
let mut cost: Value = self.safe_number_k(params.clone(), "cost", &[]);
let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("signatureType".into()), Value::Str("signature_type".into()), Value::Str("funder".into()), Value::Str("maker".into()), Value::Str("orderType".into()), Value::Str("timeInForce".into()), Value::Str("postOnly".into()), Value::Str("tickSize".into()), Value::Str("negRisk".into()),
Value::Str("salt".into()), Value::Str("timestamp".into()), Value::Str("expiration".into()), Value::Str("cost".into()), Value::Str("builder".into()), Value::Str("builderCode".into())]), &[]);
let mut amounts: Value = self.polymarket_order_raw_amounts(sideStr.clone(), amount.clone(), priceResolved.clone(), tickSize, &[cost.clone()]);
let mut makerAmount: Option<String> = self.safe_string_k_opt(amounts.clone(), "makerAmount", &[]);
let mut takerAmount: Option<String> = self.safe_string_k_opt(amounts, "takerAmount", &[]);
let mut sideInt: Value = (if (sideStr.as_str() == Some("BUY")) { Value::Int(0) } else { Value::Int(1) });
let mut bytes32Zero: String = "0x0000000000000000000000000000000000000000000000000000000000000000".to_string();
// builder attribution: the order's bytes32 builder field packs the builder fee (bps,
// upper 12 bytes) and the builder wallet (lower 20 bytes); when options.builderFee is
// false the fee bytes stay zeroed, so orders are attributed for statistics only and
// the user is not charged; a full 32-byte builder code is passed through unchanged
let mut builderRaw: Value = self.safe_string_lower2(params, Value::Str("builder".into()), Value::Str("builderCode".into()), &[self.safe_string_lower_k(self.options.clone(), "builder", &[])]);
let mut builderBytes32: Value = Value::from(bytes32Zero.clone());
if (builderRaw != Value::Null) {
let mut builderHex: Value = self.remove0x_prefix(builderRaw);
if ((builderHex.len() as i64) as f64) <= ((40i64) as f64) {
let mut builderFeeEnabled: bool = self.safe_bool_k_opt(self.options.clone(), "builderFee", &[Value::Bool(true)]).unwrap_or(true);
let mut feeRate: Value = Value::Int(0);
if builderFeeEnabled {
feeRate = self.safe_integer_k(self.options.clone(), "feeRate", &[Value::Int(0)]);
}
let mut feeHex: Value = self.int_to_base16(feeRate, &[]);
feeHex = feeHex.as_str().map(|__s| Value::Str(format!("{:0>24}", __s).into())).unwrap_or(Value::Null);
let mut addressHex: Value = builderHex.as_str().map(|__s| Value::Str(format!("{:0>40}", __s).into())).unwrap_or(Value::Null);
let mut packedHex: Value = Value::Str(format!("{}{}", feeHex, addressHex).into());
builderBytes32 = Value::Str(format!("{}{}", Value::Str("0x".into()), packedHex).into());
} else {
let mut paddedHex: Value = builderHex.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
builderBytes32 = Value::Str(format!("{}{}", Value::Str("0x".into()), paddedHex).into());
}
}
// POLY_1271 (type 3): the order signer is the deposit wallet itself — the exchange calls
// wallet.isValidSignature and the inner ERC-7739 domain's verifyingContract is the wallet (the EOA
// still produces the signature and is checked on-chain as the wallet owner). Otherwise signer = EOA.
let mut maker: Value = funder.clone();
let mut signer: Value = eoa;
if (signatureType.as_f64() == Some(3.0)) {
signer = funder;
}
let mut message: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("salt".to_string(), salt.clone());
m.insert("maker".to_string(), maker.clone());
m.insert("signer".to_string(), signer.clone());
m.insert("tokenId".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("makerAmount".to_string(), makerAmount.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("takerAmount".to_string(), takerAmount.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("side".to_string(), sideInt);
m.insert("signatureType".to_string(), signatureType.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("metadata".to_string(), Value::from(bytes32Zero.clone()));
m.insert("builder".to_string(), builderBytes32.clone());
m
});
let mut exchangeV2: Value = self.safe_string_k(self.options.clone(), "exchangeAddress", &[Value::Str("0xE111180000d2663C0091e4f400237545B87B996B".into())]);
let mut negRiskExchangeV2: Value = self.safe_string_k(self.options.clone(), "negRiskExchangeAddress", &[Value::Str("0xe2222d279d744050d28e00520010520000310F59".into())]);
let mut exchangeAddress: Value = exchangeV2;
if negRisk.as_bool() == Some(true) {
exchangeAddress = negRiskExchangeV2;
}
let mut domainVersion: Value = self.safe_string_k(self.options.clone(), "ctfExchangeVersion", &[Value::Str("2".into())]);
let mut signature: Value = self.sign_clob_order(Value::Map(message), exchangeAddress, domainVersion, signatureType.clone()).map(Value::from).unwrap_or(Value::Null);
let mut owner: Value = self.safe_string_k(self.options.clone(), "l2ApiKey", &[self.apiKey.clone()]);
let mut orderBody: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("deferExec".to_string(), Value::Bool(false));
m.insert("postOnly".to_string(), Value::Bool(postOnly));
m.insert("order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("salt".to_string(), self.parse_to_int(salt));
m.insert("maker".to_string(), maker);
m.insert("signer".to_string(), signer);
m.insert("taker".to_string(), Value::Str("0x0000000000000000000000000000000000000000".into()));
m.insert("tokenId".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("makerAmount".to_string(), makerAmount.map(Value::from).unwrap_or(Value::Null));
m.insert("takerAmount".to_string(), takerAmount.map(Value::from).unwrap_or(Value::Null));
m.insert("side".to_string(), sideStr.clone());
m.insert("signatureType".to_string(), signatureType);
m.insert("timestamp".to_string(), timestamp);
m.insert("expiration".to_string(), expiration);
m.insert("metadata".to_string(), Value::from(bytes32Zero));
m.insert("builder".to_string(), builderBytes32);
m.insert("signature".to_string(), signature);
m
}));
m.insert("owner".to_string(), owner);
m.insert("orderType".to_string(), orderTypeStr.clone());
m
});
// the CLOB create response only echoes {orderID, status}; carry the submitted terms
// keyed as the fetchOrder response fields parsePredictionOrder reads, so createOrder can merge
// them and return a fully-populated order instead of undefined side/price/amount
let mut requestEcho: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("side".to_string(), sideStr);
m.insert("price".to_string(), priceResolved);
m.insert("asset_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m.insert("time_in_force".to_string(), orderTypeStr);
m.insert("postOnly".to_string(), Value::Bool(postOnly));
m
});
if (cost == Value::Null) {
// a cost-sized market buy specifies spend, not shares — leave size to the fill
requestEcho.insert("original_size".into(), amount);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("body".to_string(), self.extend(rest, &[Value::Map(orderBody)]));
m.insert("outcome".to_string(), outcomeObj);
m.insert("request".to_string(), Value::Map(requestEcho));
m
});
Value::Null
}
/*
* @method
* @name polymarket#createMarketBuyOrderWithCost
* @description places a market buy order sized by USDC cost (how much to spend) rather than shares
* @see https://docs.polymarket.com/api-reference/trade/post-a-new-order
* @param {string} outcome unified outcome or outcome token id
* @param {float} cost the amount of USDC to spend
* @param {object} [params] extra parameters specific to the exchange API endpoint (see createOrder)
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_market_buy_order_with_cost(&mut self, mut outcome: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = self.extend(params, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), cost.clone());
m
})]);
return self.create_order(outcome, Value::Str("market".into()), Value::Str("buy".into()), cost, &[Value::Null, request]).await;
Value::Null
}
pub fn polymarket_order_raw_amounts(&self, mut side: Value, mut size: Value, mut price: Value, mut tickSize: Value, optional_args: &[Value]) -> Value {
let mut cost = get_arg(optional_args, 0, Value::Null);
let mut configs: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("0.1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price".to_string(), Value::Int(1));
m.insert("size".to_string(), Value::Int(2));
m.insert("amount".to_string(), Value::Int(3));
m
}));
m.insert("0.01".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price".to_string(), Value::Int(2));
m.insert("size".to_string(), Value::Int(2));
m.insert("amount".to_string(), Value::Int(4));
m
}));
m.insert("0.001".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price".to_string(), Value::Int(3));
m.insert("size".to_string(), Value::Int(2));
m.insert("amount".to_string(), Value::Int(5));
m
}));
m.insert("0.0001".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price".to_string(), Value::Int(4));
m.insert("size".to_string(), Value::Int(2));
m.insert("amount".to_string(), Value::Int(6));
m
}));
m
});
let mut cfg: Value = self.safe_dict(Value::Map(configs.clone()), tickSize, &[self.safe_dict_k(Value::Map(configs), "0.01", &[])]);
let mut priceDecimals: Value = self.safe_integer_k(cfg.clone(), "price", &[]);
let mut sizeDecimals: Value = self.safe_integer_k(cfg.clone(), "size", &[]);
let mut amountDecimals: Value = self.safe_integer_k(cfg, "amount", &[]);
let mut priceStr: Value = self.number_to_string(price);
let mut rawPrice: Value = self.decimal_to_precision(priceStr, Value::Int(crate::runtime::ROUND), priceDecimals, &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
let mut makerRaw: Value = Value::Null;
let mut takerRaw: Value = Value::Null;
if (cost != Value::Null) && (side.as_str() == Some("BUY")) {
// cost-sized market buy: maker pays `cost` USDC, taker receives cost/price shares.
// truncate the shares so the implied price (cost/shares) stays >= the limit, otherwise
// a marketable FOK would round just under the ask and fail to cross
let mut costStr: Value = self.number_to_string(cost);
makerRaw = self.decimal_to_precision(costStr, Value::Int(crate::runtime::TRUNCATE), sizeDecimals.clone(), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
takerRaw = self.decimal_to_precision(crate::precise::Precise::stringDiv(&makerRaw, &rawPrice), Value::Int(crate::runtime::TRUNCATE), amountDecimals.clone(), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
} else if (side.as_str() == Some("BUY")) {
let mut sizeStr: Value = self.number_to_string(size.clone());
takerRaw = self.decimal_to_precision(sizeStr.clone(), Value::Int(crate::runtime::TRUNCATE), sizeDecimals.clone(), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
makerRaw = self.decimal_to_precision(crate::precise::Precise::stringMul(&takerRaw, &rawPrice), Value::Int(crate::runtime::ROUND), amountDecimals.clone(), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
} else {
let mut sizeStr: Value = self.number_to_string(size);
makerRaw = self.decimal_to_precision(sizeStr, Value::Int(crate::runtime::TRUNCATE), sizeDecimals, &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
takerRaw = self.decimal_to_precision(crate::precise::Precise::stringMul(&makerRaw, &rawPrice), Value::Int(crate::runtime::ROUND), amountDecimals, &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
}
// scale to collateral units (USDC has 6 decimals; shares are also scaled by 1e6)
let mut makerAmount: Value = self.decimal_to_precision(crate::precise::Precise::stringMul(&makerRaw, &Value::Str("1000000".into())), Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
let mut takerAmount: Value = self.decimal_to_precision(crate::precise::Precise::stringMul(&takerRaw, &Value::Str("1000000".into())), Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("makerAmount".to_string(), makerAmount);
m.insert("takerAmount".to_string(), takerAmount);
m
});
Value::Null
}
pub fn sign_clob_order(&self, mut message: Value, mut exchangeAddress: Value, mut domainVersion: Value, mut sigType: Value) -> Option<String> {
// param is sigType, not signatureType: the php regex transpiler would rewrite the
// substring "signatureType" inside the orderTypeString literal below into the local
// var '$signatureType', corrupting the EIP-712 type hash
// chainIdValue, not chainId: the php regex transpiler would rewrite the substring "chainId"
// inside the 'EIP712Domain(...uint256 chainId,...)' literal below to the local var '$chainId',
// corrupting the domain type hash
let mut chainIdValue: Option<i64> = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(137)]).as_i64();
let mut domainName: Value = self.safe_string_k(self.options.clone(), "ctfExchangeName", &[Value::Str("Polymarket CTF Exchange".into())]);
let mut orderTypeString: Value = Value::Str("Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)".into());
let mut orderStruct: Value = Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("salt".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("maker".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("signer".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("tokenId".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("makerAmount".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("takerAmount".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("side".into()));
m.insert("type".to_string(), Value::Str("uint8".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("signatureType".into()));
m.insert("type".to_string(), Value::Str("uint8".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("timestamp".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("metadata".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("builder".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
})]);
let mut orderDomain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), domainName.clone());
m.insert("version".to_string(), domainVersion.clone());
m.insert("chainId".to_string(), Value::from(chainIdValue));
m.insert("verifyingContract".to_string(), exchangeAddress.clone());
m
});
// parseToInt: php types the number param as float, and 3.0 !== 3 (int) is true under
// strict comparison, which would always wrongly select the EOA path
if (self.parse_to_int(sigType).as_f64() != Some(3.0)) {
// standard EOA EIP-712 order signature
let mut encoded: Value = self.eth_encode_structured_data(Value::Map(orderDomain.clone()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Order".to_string(), orderStruct.clone());
m
}), message.clone());
let mut eoaSig: indexmap::IndexMap<String, Value> = self.sign_message(encoded, self.privateKey.clone()).as_map().cloned().unwrap_or_default();
// lowercase: intToBase16 emits uppercase hex in some target languages, but the
// signature is case-insensitive bytes and the rest of the hex is lowercase
let mut eoaSignature: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), self.remove0x_prefix(eoaSig.get("r").cloned().unwrap_or(Value::Null))).into()), self.remove0x_prefix(eoaSig.get("s").cloned().unwrap_or(Value::Null))).into()), self.int_to_base16(eoaSig.get("v").cloned().unwrap_or(Value::Null), &[])).into());
return (if let Some(__s) = eoaSignature.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null }).as_str().map(str::to_owned);
}
// POLY_1271 — ERC-7739 wrapped signature validated on-chain by the deposit wallet.
// ethAbiEncode needs portable value types: bytes32 as binary, uint256 as bigint
// raw hex/decimal strings encode in ethers/JS but throw in the python/php codecs
let mut orderTypeHash: Value = self.hash(self.encode(orderTypeString.clone()), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
let mut contentsData: Value = self.eth_abi_encode(Value::from(vec![Value::Str("bytes32".into()), Value::Str("uint256".into()), Value::Str("address".into()), Value::Str("address".into()), Value::Str("uint256".into()), Value::Str("uint256".into()), Value::Str("uint256".into()), Value::Str("uint8".into()), Value::Str("uint8".into()),
Value::Str("uint256".into()), Value::Str("bytes32".into()), Value::Str("bytes32".into())]), Value::from(vec![orderTypeHash, self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("salt")).cloned().unwrap_or(Value::Null)), message.as_map().and_then(|__m| __m.get("maker")).cloned().unwrap_or(Value::Null),
message.as_map().and_then(|__m| __m.get("signer")).cloned().unwrap_or(Value::Null), self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("tokenId")).cloned().unwrap_or(Value::Null)), self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("makerAmount")).cloned().unwrap_or(Value::Null)),
self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("takerAmount")).cloned().unwrap_or(Value::Null)), message.as_map().and_then(|__m| __m.get("side")).cloned().unwrap_or(Value::Null), message.as_map().and_then(|__m| __m.get("signatureType")).cloned().unwrap_or(Value::Null),
self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("timestamp")).cloned().unwrap_or(Value::Null)), self.base16_to_binary(self.remove0x_prefix(message.as_map().and_then(|__m| __m.get("metadata")).cloned().unwrap_or(Value::Null)), &[]), self.base16_to_binary(self.remove0x_prefix(message.as_map().and_then(|__m| __m.get("builder")).cloned().unwrap_or(Value::Null)), &[])]));
let mut contentsHash: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(contentsData, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
let mut domainTypeHash: Value = self.hash(self.encode(Value::Str("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)".into())), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
let mut nameHash: Value = self.hash(self.encode(domainName), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
let mut versionHash: Value = self.hash(self.encode(domainVersion), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
let mut appDomainData: Value = self.eth_abi_encode(Value::from(vec![Value::Str("bytes32".into()), Value::Str("bytes32".into()), Value::Str("bytes32".into()), Value::Str("uint256".into()), Value::Str("address".into())]), Value::from(vec![domainTypeHash, nameHash, versionHash, self.convert_to_big_int(self.number_to_string(Value::from(chainIdValue))), exchangeAddress]));
let mut appDomainSep: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(appDomainData, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
let mut typedDataSignStruct: Value = Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("contents".into()));
m.insert("type".to_string(), Value::Str("Order".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("name".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("version".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("chainId".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("verifyingContract".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("salt".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
})]);
let mut bytes32Zero: String = "0x0000000000000000000000000000000000000000000000000000000000000000".to_string();
let mut innerValue: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("contents".to_string(), message.clone());
m.insert("name".to_string(), Value::Str("DepositWallet".into()));
m.insert("version".to_string(), Value::Str("1".into()));
m.insert("chainId".to_string(), Value::from(chainIdValue));
m.insert("verifyingContract".to_string(), message.as_map().and_then(|__m| __m.get("signer")).cloned().unwrap_or(Value::Null));
m.insert("salt".to_string(), Value::from(bytes32Zero));
m
});
let mut innerEncoded: Value = self.eth_encode_structured_data(Value::Map(orderDomain), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("TypedDataSign".to_string(), typedDataSignStruct);
m.insert("Order".to_string(), orderStruct);
m
}), Value::Map(innerValue));
let mut innerSigObj: indexmap::IndexMap<String, Value> = self.sign_message(innerEncoded, self.privateKey.clone()).as_map().cloned().unwrap_or_default();
let mut innerSig: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.remove0x_prefix(self.safe_string(Value::Map(innerSigObj.clone()), Value::Str("r".into()), &[])), self.remove0x_prefix(self.safe_string(Value::Map(innerSigObj.clone()), Value::Str("s".into()), &[]))).into()), self.int_to_base16(innerSigObj.get("v").cloned().unwrap_or(Value::Null), &[])).into());
// innerSig(65) || appDomainSep(32) || contentsHash(32) || contentsType || uint16_BE(len)
// orderTypeString.length is used inline (not via a `const n = str.length;` statement) so the
// php transpiler emits strlen() — the standalone statement form wrongly becomes count() (array)
let mut ctLenHex: Value = self.int_to_base16(Value::Int(orderTypeString.len() as i64), &[]);
// assign before padStart so the PHP transpiler's str_pad regex (which only matches a
// simple identifier) picks it up instead of leaking a padStart() function call
let mut lenHex: Value = ctLenHex.as_str().map(|__s| Value::Str(format!("{:0>4}", __s).into())).unwrap_or(Value::Null);
let mut orderTypeStringHex: Value = self.binary_to_base16(self.encode(orderTypeString), &[]);
let mut wrappedSignature: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), innerSig).into()), self.remove0x_prefix(appDomainSep)).into()), self.remove0x_prefix(contentsHash)).into()), orderTypeStringHex).into()), lenHex).into());
return (if let Some(__s) = wrappedSignature.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null }).as_str().map(str::to_owned);
}
/*
* @method
* @name polymarket#cancelOrder
* @description cancels a single open order by id on the CLOB
* @see https://docs.polymarket.com/api-reference/trade/cancel-single-order
* @param {string} id the order id
* @param {string} [outcome] unified outcome or outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
// cancelling by id needs no market data, so events do not have to be loaded first
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("orderID".to_string(), id.clone());
m
});
let __ws_arg_14 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.clob_private_delete_order(&[__ws_arg_14]).await;
// the DELETE endpoint returns { canceled: [id], not_canceled: { id: reason } } with no order
// fields, so report the cancellation outcome explicitly rather than parsing an empty order
let mut notCanceled: Value = self.safe_dict_k(response.clone(), "not_canceled", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut failureReason: Option<String> = self.safe_string(notCanceled, id.clone(), &[]).as_str().map(str::to_owned);
let mut status: String = "open".to_string();
if (failureReason.is_none()) {
status = "canceled".to_string();
}
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("status".to_string(), Value::from(status));
m.insert("info".to_string(), response);
m
}), &[]);
Value::Null
}
/*
* @method
* @name polymarket#cancelOrders
* @description cancels multiple open orders by id on the CLOB in a single request
* @see https://docs.polymarket.com/api-reference/trade/cancel-orders
* @param {string[]} ids the order ids to cancel
* @param {string} [outcome] not used by polymarket cancelOrders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
// the request body is the bare array of order ids (DELETE /orders), so params are not merged
let mut response: Value = self.clob_private_delete_orders(&[ids]).await;
let mut canceled: Value = self.safe_list_k(response.clone(), "canceled", &[Value::from(vec![])]);
let mut orders: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_1445: bool = true;
while { if !__for_first_1445 { i += 1; } __for_first_1445 = false; i < (canceled.len() as i64) } {
if let Value::Arr(__a) = &mut orders { std::sync::Arc::make_mut(__a).push(self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string(canceled.clone(), Value::Int(i), &[]));
m.insert("status".to_string(), Value::Str("canceled".into()));
m.insert("info".to_string(), response.clone());
m
}), &[])); }
}
}
return orders;
Value::Null
}
/*
* @method
* @name polymarket#cancelAllOrders
* @description cancels all open orders on the CLOB, optionally scoped to one outcome token
* @see https://docs.polymarket.com/api-reference/trade/cancel-all-orders
* @see https://docs.polymarket.com/api-reference/trade/cancel-market-orders
* @param {string} [outcome] unified outcome or outcome token id; when given only that outcome's orders are cancelled
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
let mut response: Value = Value::Null;
if (outcome != Value::Null) {
// scope to a single outcome token via DELETE /cancel-market-orders { asset_id }
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("asset_id".to_string(), self.safe_string_k(outcomeObj, "outcomeId", &[]));
m
});
let __ws_arg_15 = self.extend(Value::Map(request), &[params.clone()]);
response = self.clob_private_delete_cancel_market_orders(&[__ws_arg_15]).await;
} else {
// cancel every open order via DELETE /cancel-all (no body, no market data needed)
response = self.clob_private_delete_cancel_all(&[params]).await;
}
let mut canceled: Value = self.safe_list_k(response.clone(), "canceled", &[Value::from(vec![])]);
let mut orders: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_1446: bool = true;
while { if !__for_first_1446 { i += 1; } __for_first_1446 = false; i < (canceled.len() as i64) } {
if let Value::Arr(__a) = &mut orders { std::sync::Arc::make_mut(__a).push(self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string(canceled.clone(), Value::Int(i), &[]));
m.insert("status".to_string(), Value::Str("canceled".into()));
m.insert("info".to_string(), response.clone());
m
}), &[])); }
}
}
return orders;
Value::Null
}
/*
* @method
* @name polymarket#fetchEvents
* @description fetches prediction-market events matching the given scope (query/queries/tags/eventId/slug — required) and caches their markets and outcomes on the instance; for an unscoped top-volume browse use fetchMarkets ()
* @see https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles
* @see https://docs.polymarket.com/api-reference/events/list-events
* @param {object} [params] extra exchange-specific parameters
* @param {string} [params.query] a single keyword search term
* @param {string[]} [params.queries] multiple search terms (alternative to query)
* @param {string[]} [params.tags] filter events by tag — human-readable labels ("Fed Rates") or slugs ("fed-rates") both work; multiple tags match ANY (one gamma listing per tag, unioned and deduped)
* @param {int} [params.limit] max number of events to return
* @param {string} [params.sort] 'volume' (default), 'liquidity' or 'newest' — mapped to the gamma order field
* @param {string} [params.status] 'active' (default), 'inactive', 'closed' or 'all' ('inactive' and 'closed' are interchangeable)
* @param {string} [params.searchIn] when searching, restrict the match to 'title' (default), 'description' or 'both'
* @param {string} [params.eventId] direct lookup by event id (short-circuits the listing/search)
* @param {string} [params.slug] direct lookup by event slug
* @param {int} [params.searchPageSize] search page size (gamma limit_per_type, default 100); lower it to shrink the download when a small limit is enough, higher to over-fetch before client-side status/title filtering
* @param {int} [params.maxSearchPages] max search pages to fetch when no limit is given (default 5), bounding a broad query
* @returns {object[]} an array of event structures
*/
pub async fn fetch_events(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.require_event_query(&[params.clone()]);
let mut requestedEventId: Option<String> = self.safe_string_k_opt(params.clone(), "eventId", &[]);
let mut requestedSlug: Option<String> = self.safe_string_k_opt(params.clone(), "slug", &[]);
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("query".into()), Value::Str("queries".into()), Value::Str("eventId".into()), Value::Str("slug".into())]), &[]);
if (queries == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchEvents() missing queries".into()))));
}
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
let mut rawEvents: Value = Value::from(vec![]);
if (requestedEventId.is_some()) || (requestedSlug.is_some()) {
// direct lookup by event id or slug via the events endpoint (returns a list)
let mut lookup: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (requestedEventId.is_some()) {
lookup.insert("id".into(), requestedEventId.clone().map(Value::from).unwrap_or(Value::Null));
} else {
lookup.insert("slug".into(), requestedSlug.clone().map(Value::from).unwrap_or(Value::Null));
}
let mut response: Value = self.gamma_public_get_events(&[Value::Map(lookup)]).await;
let mut responseIsArray: bool = matches!(&response, Value::Arr(_));
rawEvents = (if (responseIsArray) { response } else { Value::from(vec![]) });
} else if queriesLength > ((0i64) as f64) {
rawEvents = self.fetch_raw_events_by_search(queries.clone(), &[rest.clone()]).await;
} else {
rawEvents = self.fetch_raw_events_list(&[rest]).await;
}
// Parse and merge into class-level caches
if (self.exchange.events.clone() == Value::Null) {
self.exchange.events = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut result: Vec<Value> = Vec::new();
{
let mut rei: i64 = 0;
let mut __for_first_1448: bool = true;
while { if !__for_first_1448 { rei += 1; } __for_first_1448 = false; rei < (rawEvents.len() as i64) } {
let mut rawEvent: Value = rawEvents.as_array().map(Vec::as_slice).unwrap_or_default().get(rei as usize).cloned().unwrap_or(Value::Null);
let mut eventForParsing: Value = rawEvent.clone();
let mut ccxtMarkets: Value = self.parse_event_to_markets(eventForParsing.clone());
let mut ccxtMarketsLength: f64 = ((ccxtMarkets.len() as i64) as f64);
if (ccxtMarketsLength == 0.0) {
// search results may omit the nested markets, fall back to the detail endpoint
let mut eventId: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "id", &[]);
let mut rawEventSlug: Option<String> = self.safe_string_k_opt(rawEvent, "slug", &[]);
let mut detailedEvent: Value = Value::Null;
if (eventId.is_some()) {
detailedEvent = self.gamma_public_get_events_id(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), eventId.map(Value::from).unwrap_or(Value::Null));
m
})]).await;
} else if (rawEventSlug.is_some()) {
detailedEvent = self.gamma_public_get_events_slug_slug(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), rawEventSlug.map(Value::from).unwrap_or(Value::Null));
m
})]).await;
}
if (detailedEvent != Value::Null) {
eventForParsing = self.safe_value_k(detailedEvent.clone(), "event", &[detailedEvent.clone()]);
ccxtMarkets = self.parse_event_to_markets(eventForParsing.clone());
}
}
{
let mut mi: i64 = 0;
let mut __for_first_1447: bool = true;
while { if !__for_first_1447 { mi += 1; } __for_first_1447 = false; mi < (ccxtMarkets.len() as i64) } {
let mut m: Value = ccxtMarkets.as_array().map(Vec::as_slice).unwrap_or_default().get(mi as usize).cloned().unwrap_or(Value::Null);
if (m == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchEvents() missing m".into()))));
}
add_element_to_object(&mut self.markets, &m.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null), m.clone());
}
}
let mut parsedEvent: Value = self.parse_event(eventForParsing);
result.push(parsedEvent);
}
}
// populateOutcomes rebuilds the outcome cache from the markets registered above; the
// shared applyEventFetchParams then caches (setEvents) and applies the unified
// eventId/slug/status/tags/searchIn/sort/limit filters, so all five venues behave the same
self.populate_outcomes();
let mut effectiveParams: Value = params.clone();
if queriesLength > ((0i64) as f64) {
// the gamma search endpoint is fuzzy, so default to refining by active status and a
// title match (the caller can override); the other venues search exactly and need no
// such default. inject the defaults as explicit params so the shared pipeline stays
// the single behaviour definition
effectiveParams = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[params.clone()]);
add_element_to_object(&mut effectiveParams, &Value::Str("status".into()), self.safe_string_k(params.clone(), "status", &[Value::Str("active".into())]));
add_element_to_object(&mut effectiveParams, &Value::Str("searchIn".into()), self.safe_string_k(params, "searchIn", &[Value::Str("title".into())]));
}
return self.apply_event_fetch_params(Value::from(result), &[effectiveParams, queries]);
Value::Null
}
/*
* @method
* @name polymarket#fetchEvent
* @description fetches a single prediction-market event by its id or slug
* @see https://docs.polymarket.com/api-reference/events/get-event-by-id
* @see https://docs.polymarket.com/api-reference/events/get-event-by-slug
* @param {string} id the event id (numeric) or slug
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction event structure](https://docs.ccxt.com/#/?id=prediction-event-structure)
*/
pub async fn fetch_event(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = Value::Null;
if id.as_str().unwrap_or("").contains("-") {
let __ws_arg_16 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), id.clone());
m
}), &[params.clone()]);
response = self.gamma_public_get_events_slug_slug(&[__ws_arg_16]).await;
} else {
let __ws_arg_17 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m
}), &[params]);
response = self.gamma_public_get_events_id(&[__ws_arg_17]).await;
}
let mut eventForParsing: Value = self.safe_dict_k(response.clone(), "event", &[response.clone()]);
if (eventForParsing == Value::Null) {
eventForParsing = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
let mut event: Value = self.parse_event(eventForParsing);
self.index_event_outcomes(event.clone());
return event;
Value::Null
}
pub fn parse_event(&self, mut rawEvent: Value) -> Value {
// {
// "id": "73113",
// "ticker": "ukraine-agrees-not-to-join-nato-before-2027",
// "slug": "ukraine-agrees-not-to-join-nato-before-2027",
// "title": "Ukraine agrees not to join NATO before 2027? ",
// "description": "This market will resolve to \\"Yes\\" if Ukraine publicly agrees not to join NATO by December 31, 2026, 11:59 PM ET. Otherwise, this market will resolve to “No”.\\n\\nAn official pledge by Ukraine not to join NATO will qualify for a “Yes” resolution whether as a unilateral announcement or part of an agreement with the Russian Federation.\\n\\nAny agreement or pledge made before the resolution date of this market will qualify, regardless of if/when the agreement goes into effect.\\n\\nAn agreement by Ukraine not to join NATO for any amount of time will count (e.g. If Ukraine not to join NATO for 10 years this will qualify).\\n\\nAn agreement by Ukraine not to join NATO as a precondition of a more comprehensive peace process or deal will qualify, even if the agreement is not finalized or part of a formalized peace deal. The September 8, 1995 “Agreed Basic Principles” between Bosnia and Yugoslavia which recognized the borders and sovereignty of Bosnia and Herzegovina, and was later formalized through the Dayton Peace Agreement is an example of a qualifying agreement. \\n\\nThe primary resolution source for this market will be an official announcement by the Ukraine, however an overwhelming consensus of credible reporting confirming a qualifying agreement has been reached will also count.",
// "resolutionSource": "",
// "startDate": "2025-11-05T17:00:57.200353Z",
// "creationDate": "2025-11-05T17:00:57.20035Z",
// "endDate": "2026-12-31T00:00:00Z",
// "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/ukraine-agrees-not-to-join-nato-before-july-vKEDpScXuAtt.jpg",
// "icon": "https://polymarket-upload.s3.us-east-2.amazonaws.com/ukraine-agrees-not-to-join-nato-before-july-vKEDpScXuAtt.jpg",
// "active": true,
// "closed": false,
// "archived": false,
// "new": false,
// "featured": false,
// "restricted": true,
// "liquidity": "22010.6659",
// "openInterest": "0",
// "createdAt": "2025-11-04T19:27:23.246129Z",
// "updatedAt": "2026-03-14T14:38:21.25643Z",
// "competitive": "0.9538344143456696",
// "enableOrderBook": true,
// "liquidityClob": "22010.6659",
// "commentCount": "0",
// "markets": [],
// "tags": [
// {
// "id": "101970",
// "label": "World",
// "slug": "world",
// "forceShow": false,
// "createdAt": "2025-03-19T23:36:08.498099Z",
// "updatedAt": "2026-03-09T22:25:02.420693Z",
// "requiresTranslation": false
// },
// {
// "id": "270",
// "label": "putin",
// "slug": "putin",
// "publishedAt": "2023-11-02 21:46:19.507+00",
// "createdAt": "2023-11-02T21:46:19.528Z",
// "updatedAt": "2026-03-09T22:29:44.08742Z",
// "requiresTranslation": false
// }
// ],
// "cyom": false,
// "showAllOutcomes": true,
// "showMarketImages": true,
// "enableNegRisk": false,
// "automaticallyActive": true,
// "seriesSlug": "ukraine-not-nato",
// "negRiskAugmented": false,
// "cumulativeMarkets": false,
// "pendingDeployment": false,
// "deploying": false,
// "requiresTranslation": false
// }
let mut marketsList: Value = self.parse_event_to_markets(rawEvent.clone());
let mut slug: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "slug", &[]);
// gamma events use camelCase keys (createdAt/endDate/image/updatedAt/closed);
// the snake_case fallbacks cover older payload shapes
let mut createdAt: Option<String> = self.safe_string2_opt(rawEvent.clone(), Value::Str("createdAt".into()), Value::Str("created_date_iso".into()), &[]);
let mut endDate: Option<String> = self.safe_string2_opt(rawEvent.clone(), Value::Str("endDate".into()), Value::Str("end_date_iso".into()), &[]);
let mut updatedAt: Option<String> = self.safe_string2_opt(rawEvent.clone(), Value::Str("updatedAt".into()), Value::Str("last_updated_date_iso".into()), &[]);
let mut rawActive: Option<bool> = self.safe_bool_k_opt(rawEvent.clone(), "active", &[]);
let mut closed: bool = self.safe_bool_k_opt(rawEvent.clone(), "closed", &[Value::Bool(false)]).unwrap_or(false);
let mut active: Value = Value::Null;
if (rawActive.is_some()) {
active = Value::Bool(rawActive == Some(true) && (!(closed)));
}
// surface gamma's tag objects as a top-level string[] so the unified `tags` filter
// — filterEventsByTags reads event['tags'], not event.info.tags — can actually match.
// prefer the human-readable label ("Fed Rates") over the slug — matching is
// normalized (normalizeTagKey), so the display form is free to be the friendly one
let mut rawTags: Vec<Value> = self.safe_list_k(rawEvent.clone(), "tags", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rawTagsLength: f64 = ((rawTags.len() as i64) as f64);
let mut parsedTags: Vec<Value> = Vec::new();
{
let mut ti: Value = Value::Int(0);
let mut __for_first_1449: bool = true;
while { if !__for_first_1449 { if let Value::Int(n) = &mut ti { *n += 1; } } __for_first_1449 = false; ti.as_f64().unwrap_or(f64::NAN) < rawTagsLength } {
let mut tagLabel: Option<String> = self.safe_string2_opt(rawTags.get(ti.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), Value::Str("label".into()), Value::Str("slug".into()), &[]);
if (tagLabel.is_some()) {
parsedTags.push(tagLabel.map(Value::from).unwrap_or(Value::Null));
}
}
}
let __ws_arg_18 = self.safe_string_k(rawEvent.clone(), "id", &[]);
let __ws_arg_19 = self.shorten_slug(slug.clone().map(Value::from).unwrap_or(Value::Null));
let __ws_arg_20 = self.safe_string_k(rawEvent.clone(), "title", &[]);
let __ws_arg_21 = self.safe_string_k(rawEvent.clone(), "url", &[]);
let __ws_arg_22 = self.safe_string2(rawEvent.clone(), Value::Str("image".into()), Value::Str("image_url".into()), &[]);
let __ws_arg_23 = self.parse8601(createdAt.clone().map(Value::from).unwrap_or(Value::Null));
let __ws_arg_24 = self.parse8601(endDate.clone().map(Value::from).unwrap_or(Value::Null));
let __ws_arg_25 = self.safe_string_k(rawEvent.clone(), "category", &[]);
let __ws_arg_26 = self.parse8601(updatedAt.clone().map(Value::from).unwrap_or(Value::Null));
let __ws_arg_27 = self.safe_string2(rawEvent.clone(), Value::Str("resolutionSource".into()), Value::Str("resolution_source".into()), &[]);
let __ws_arg_28 = self.safe_bool2(rawEvent.clone(), Value::Str("closed".into()), Value::Str("resolved".into()), &[]);
return self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), __ws_arg_18);
m.insert("slug".to_string(), slug.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("event".to_string(), (if ((slug.is_some()) && (slug.as_deref() != Some(""))) { __ws_arg_19 } else { Value::Null }));
m.insert("title".to_string(), __ws_arg_20);
m.insert("tags".to_string(), Value::from(parsedTags));
m.insert("markets".to_string(), marketsList);
m.insert("active".to_string(), active);
m.insert("url".to_string(), __ws_arg_21);
m.insert("image".to_string(), __ws_arg_22);
m.insert("created".to_string(), __ws_arg_23);
m.insert("createdDatetime".to_string(), createdAt.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("end".to_string(), __ws_arg_24);
m.insert("endDatetime".to_string(), endDate.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("category".to_string(), __ws_arg_25);
m.insert("lastUpdatedAt".to_string(), __ws_arg_26);
m.insert("lastUpdatedAtDatetime".to_string(), updatedAt.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("resolutionSource".to_string(), __ws_arg_27);
m.insert("resolved".to_string(), __ws_arg_28);
m.insert("info".to_string(), rawEvent);
m
}), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#parseEvents
* @description parses an array of raw gamma event objects into unified event objects
* @param {object[]} rawEvents the raw gamma event objects
* @returns {object[]} a list of event structures
*/
pub fn parse_events(&self, mut rawEvents: Value) -> Value {
let __rawEvents_empty = Vec::new();
let rawEvents = rawEvents.as_array().unwrap_or(&__rawEvents_empty);
let mut result: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1450: bool = true;
while { if !__for_first_1450 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1450 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawEvents.len() as i64) as f64) } {
let mut rawEvent: Value = rawEvents.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
result.push(self.parse_event(rawEvent));
}
}
return Value::from(result);
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
// the CLOB api returns { "error": "..." } (and createOrder variants use "errorMsg");
// map the known messages so callers can distinguish a dead book or a rejected order
// from a transport outage (the base otherwise maps a bare 404 to a retryable error)
if (response == Value::Null) {
return Value::Null;
}
let mut errorMessage: Option<String> = self.safe_string2_opt(response, Value::Str("error".into()), Value::Str("errorMsg".into()), &[]);
if (errorMessage.is_some()) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorMessage.clone().map(Value::from).unwrap_or(Value::Null), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorMessage.map(Value::from).unwrap_or(Value::Null), feedback);
}
return Value::Null;
Value::Null
}
pub fn nonce(&self) -> Value {
return self.milliseconds();
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#sign
* @description builds the request url and attaches HMAC-SHA256 authentication headers for private endpoints
* @param {string} path the endpoint path
* @param {string[]} api the api group and access level
* @param {string} method the http method
* @param {object} params the request parameters
* @returns {object} a dict with url, method, body and headers
*/
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("gamma".into())]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiGroup: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut access: Option<String> = api.get(1).and_then(Value::as_str).map(str::to_owned);
let mut baseUrls: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null);
let mut baseUrl: Value = self.safe_string(baseUrls.clone(), apiGroup, &[baseUrls.as_map().and_then(|__m| __m.get("gamma")).cloned().unwrap_or(Value::Null)]);
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseUrl, Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
// an empty params container must not become a body: in PHP an empty array is
// indistinguishable from an empty dict, so a bare Array.isArray check would json it to "[]"
let mut isArrayBody: bool = false;
if (matches!(¶ms, Value::Arr(_))) {
let mut paramsList: Value = params.clone();
let mut paramsListLength: f64 = ((paramsList.len() as i64) as f64);
isArrayBody = paramsListLength > ((0i64) as f64);
}
let mut query: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !(isArrayBody) {
query = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
}
let mut bodyValue: Value = Value::Null;
if (method.as_str() == Some("GET")) {
// array-valued params must repeat the key (gamma's clob_token_ids rejects
// comma-joined ids); scalar-only queries keep the plain encoder — the repeat
// encoder capitalizes booleans ("False") under the C# base
let mut hasArrayParam: bool = false;
let mut queryKeys: Value = object_keys(&query);
{
let mut i: i64 = 0;
let mut __for_first_1451: bool = true;
while { if !__for_first_1451 { i += 1; } __for_first_1451 = false; i < (queryKeys.len() as i64) } {
if (matches!(&get_value(&query, &queryKeys.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null)), Value::Arr(_))) {
hasArrayParam = true;
}
}
}
let mut querystring: Value = Value::Null;
if hasArrayParam {
querystring = self.urlencode_with_array_repeat(query.clone());
} else {
querystring = self.urlencode(query.clone(), &[]);
}
if (querystring.as_str() != Some("")) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), querystring).into())).into());
}
} else if isArrayBody {
bodyValue = json_stringify(¶ms);
} else {
let mut queryKeys: Value = object_keys(&query);
let mut queryKeysLength: f64 = ((queryKeys.len() as i64) as f64);
if queryKeysLength > ((0i64) as f64) {
bodyValue = json_stringify(&query);
}
}
let mut headerDefaults: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut headersValue: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Accept".to_string(), Value::Str("application/json".into()));
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m
}), &[Value::Map(headerDefaults)]);
if (access.as_deref() == Some("private")) {
// 'auth/derive-api-key' is built by concatenation so the substring "api" sits at a
// string-literal boundary: the php regex transpiler rewrites a bare "api" flanked by
// '-' into the local var '$api' (it only skips quote/slash-adjacent matches), which
// would corrupt the literal to 'auth/derive-$api-key' and break this check
let mut deriveApiKeyPath: Value = Value::Str(format!("{}{}", Value::Str("auth/derive-".into()), Value::Str("api-key".into())).into());
let mut isL1Auth: bool = (path.as_str() == Some("auth/api-key")) || (path.as_str() == deriveApiKeyPath.as_str()) || (path.as_str() == Some("auth/api-keys"));
if isL1Auth {
// L1 (private-key / EIP-712) auth used to create or derive the L2 api credentials
if (self.privateKey.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), path).into()), Value::Str(" requires a privateKey".into()))));
}
// the L1 signer/owner is the EOA behind the privateKey (walletAddress is the proxy/deposit wallet, not the signer)
let mut address: Value = self.eth_checksum_address(self.eth_get_address_from_private_key(self.privateKey.clone(), &[])).map(Value::from).unwrap_or(Value::Null);
let mut timestamp: Value = Value::Str(format!("{}", self.seconds()).into());
let mut nonce: Value = self.safe_integer_k(params.clone(), "nonce", &[Value::Int(0)]);
let mut l1signature: Value = self.sign_clob_auth(address.clone(), timestamp.clone(), nonce.clone()).map(Value::from).unwrap_or(Value::Null);
let __ws_arg_29 = self.number_to_string(nonce);
headersValue = self.extend(headersValue.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("POLY_ADDRESS".to_string(), address.clone());
m.insert("POLY_SIGNATURE".to_string(), l1signature);
m.insert("POLY_TIMESTAMP".to_string(), timestamp.clone());
m.insert("POLY_NONCE".to_string(), __ws_arg_29);
m
})]);
} else {
// L2 credentials: provided directly (apiKey/secret/password) or derived from
// the privateKey and cached in options (see setApiCredentials/loadApiCredentials)
// prefer the derived creds (owned by the privateKey's EOA) over any externally supplied ones
let mut apiKey: Value = self.safe_string_k(self.options.clone(), "l2ApiKey", &[self.apiKey.clone()]);
let mut secret: Value = self.safe_string_k(self.options.clone(), "l2Secret", &[self.secret.clone()]);
let mut passphrase: Value = self.safe_string_k(self.options.clone(), "l2Passphrase", &[self.password.clone()]);
// POLY_ADDRESS is the api-key owner = the signer EOA (derived from the privateKey when present)
let mut address: Value = Value::Null;
if (self.privateKey.clone() != Value::Null) {
address = self.eth_checksum_address(self.eth_get_address_from_private_key(self.privateKey.clone(), &[])).map(Value::from).unwrap_or(Value::Null);
} else {
address = self.walletAddress.clone();
}
let mut timestamp: Value = Value::Str(format!("{}", self.seconds()).into());
// the L2 HMAC signs only the request path (no query string), matching
// @polymarket/clob-client — query params are sent separately, not signed
let mut requestPath: Value = Value::Str(format!("{}{}", Value::Str("/".into()), self.implode_params(path, params)).into());
let mut auth: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", timestamp, method).into()), requestPath).into());
if (bodyValue != Value::Null) {
auth = Value::Str(format!("{}{}", auth, bodyValue).into());
}
// the L2 api secret is base64url-encoded; decode it to raw bytes for the HMAC key.
// unchained replaceAll: the php transpiler only converts the outermost .replaceAll
// in a chain, leaving the inner call as an (invalid) method call
let mut plusSecret: Value = secret.as_str().map(|__s| Value::Str(__s.replace("-", "+").into())).unwrap_or_else(|| secret.clone());
let mut normalizedSecret: Value = plusSecret.as_str().map(|__s| Value::Str(__s.replace("_", "/").into())).unwrap_or_else(|| plusSecret.clone());
let mut secretBytes: Value = self.base64_to_binary(normalizedSecret, &[]);
let mut signature: Value = self.hmac(self.encode(auth), secretBytes, Value::Str("sha256".into()), &[Value::Str("base64".into())]);
// url-safe base64, preserving '=' padding (matches the reference client)
signature = signature.as_str().map(|__s| Value::Str(__s.replace("+", "-").into())).unwrap_or_else(|| signature.clone());
signature = signature.as_str().map(|__s| Value::Str(__s.replace("/", "_").into())).unwrap_or_else(|| signature.clone());
headersValue = self.extend(headersValue.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("POLY_ADDRESS".to_string(), address);
m.insert("POLY_API_KEY".to_string(), apiKey);
m.insert("POLY_PASSPHRASE".to_string(), passphrase);
m.insert("POLY_SIGNATURE".to_string(), signature);
m.insert("POLY_TIMESTAMP".to_string(), timestamp);
m
})]);
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), bodyValue);
m.insert("headers".to_string(), headersValue);
m
});
Value::Null
}
pub fn hash_message(&self, mut message: Value) -> Option<String> {
return Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(message, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into()).as_str().map(str::to_owned);
}
pub fn eth_checksum_address(&self, mut address: Value) -> Option<String> {
// EIP-55 mixed-case checksum; the CLOB compares the order signer to the api-key owner
// case-sensitively and stores addresses checksummed, so every address we send must be checksummed
let mut cleaned: Value = (self.remove0x_prefix(address)).as_str().map(|__s| Value::Str(__s.to_lowercase().into())).unwrap_or(Value::Null);
let mut hashHex: Value = self.hash(self.encode(cleaned.clone()), Value::Str("keccak".into()), &[Value::Str("hex".into())]);
let mut addrChars: Vec<Value> = self.string_to_chars_array(cleaned).as_array().cloned().unwrap_or_default();
let mut hashChars: Vec<Value> = self.string_to_chars_array(hashHex).as_array().cloned().unwrap_or_default();
let mut upperNibbles: String = "89abcdef".to_string();
let mut result: Value = Value::Str("".into());
{
let mut i: i64 = 0;
let mut __for_first_1452: bool = true;
while { if !__for_first_1452 { i += 1; } __for_first_1452 = false; i < (addrChars.len() as i64) } {
let mut ch: Value = addrChars.get(i as usize).cloned().unwrap_or(Value::Null);
let mut hashCh: Value = hashChars.get(i as usize).cloned().unwrap_or(Value::Null);
if Value::Int(Some(upperNibbles.as_str()).zip(hashCh.as_str()).and_then(|(__s, __n)| __s.find(__n)).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
result = Value::Str(format!("{}{}", result, (if let Some(__s) = ch.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null })).into());
} else {
result = Value::Str(format!("{}{}", result, ch).into());
}
}
}
return Value::Str(format!("{}{}", Value::Str("0x".into()), result).into()).as_str().map(str::to_owned);
}
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Value {
let mut signature: Value = ecdsa(hash.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null),
privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null), Value::Str("secp256k1".into()), Value::Null);
// assign before padStart so the PHP str_pad regex matches (it only handles a bare identifier)
let mut rRaw: Value = signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null);
let mut sRaw: Value = signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null);
let mut r: Value = rRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
let mut s: Value = sRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("r".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), r).into()));
m.insert("s".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), s).into()));
m.insert("v".to_string(), self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]));
m
});
Value::Null
}
pub fn sign_message(&self, mut message: Value, mut privateKey: Value) -> Value {
return self.sign_hash(self.hash_message(message).map(Value::from).unwrap_or(Value::Null), privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null));
Value::Null
}
pub fn sign_clob_auth(&self, mut address: Value, mut timestamp: Value, mut nonce: Value) -> Option<String> {
// EIP-712 ClobAuth signature used for L1 auth (creating/deriving L2 api credentials)
let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("ClobAuthDomain".into()));
m.insert("version".to_string(), Value::Str("1".into()));
m.insert("chainId".to_string(), Value::Int(137));
m
});
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("ClobAuth".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("address".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("timestamp".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("message".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
})]));
m
});
let mut messageData: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("address".to_string(), address);
m.insert("timestamp".to_string(), timestamp);
m.insert("nonce".to_string(), nonce);
m.insert("message".to_string(), Value::Str("This message attests that I control the given wallet".into()));
m
});
let mut encoded: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map(messageTypes), Value::Map(messageData));
let mut sig: indexmap::IndexMap<String, Value> = self.sign_message(encoded, self.privateKey.clone()).as_map().cloned().unwrap_or_default();
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), self.remove0x_prefix(sig.get("r").cloned().unwrap_or(Value::Null))).into()), self.remove0x_prefix(sig.get("s").cloned().unwrap_or(Value::Null))).into()), self.int_to_base16(sig.get("v").cloned().unwrap_or(Value::Null), &[])).into()).as_str().map(str::to_owned);
}
/*
* @method
* @name polymarket#deriveApiKey
* @description derives the L2 api credentials (apiKey, secret, passphrase) deterministically from the wallet private key
* @see https://docs.polymarket.com/developers/CLOB/authentication
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.nonce] the nonce used to derive the credentials, defaults to 0
* @returns {object} the api credentials { apiKey, secret, passphrase }
*/
pub async fn derive_api_key(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.clob_private_get_auth_derive_api_key(&[params]).await;
return self.set_api_credentials(response);
Value::Null
}
/*
* @method
* @name polymarket#createApiKey
* @description creates new L2 api credentials (apiKey, secret, passphrase) for the wallet private key
* @see https://docs.polymarket.com/developers/CLOB/authentication
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.nonce] the nonce used to create the credentials, defaults to 0
* @returns {object} the api credentials { apiKey, secret, passphrase }
*/
pub async fn create_api_key(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.clob_private_post_auth_api_key(&[params]).await;
return self.set_api_credentials(response);
Value::Null
}
/*
* @method
* @name polymarket#createOrDeriveApiKey
* @description derives the existing L2 api credentials for the wallet private key, creating them if none exist yet
* @see https://docs.polymarket.com/developers/CLOB/authentication
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the api credentials { apiKey, secret, passphrase }
*/
pub async fn create_or_derive_api_key(&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 creds: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
creds = self.derive_api_key(&[params.clone()]).await;
#[allow(unreachable_code)] { Value::Null }})).await;
if _try_result.is_err() {
creds = self.create_api_key(&[params]).await;
}
if (creds == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" createOrDeriveApiKey() returned no credentials".into()))));
}
return creds;
Value::Null
}
pub fn set_api_credentials(&self, mut response: Value) -> Value {
//
// { "apiKey": "...", "secret": "...", "passphrase": "..." }
//
let mut creds: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), self.safe_string2(response.clone(), Value::Str("apiKey".into()), Value::Str("key".into()), &[]));
m.insert("secret".to_string(), self.safe_string_k(response.clone(), "secret", &[]));
m.insert("passphrase".to_string(), self.safe_string_k(response, "passphrase", &[]));
m
});
// cache in options rather than the typed apiKey/secret/password fields so the
// assignment is valid in the struct-based languages (C#/Go/Java)
if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("l2ApiKey".into(), creds.get("apiKey").cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("l2Secret".into(), creds.get("secret").cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("l2Passphrase".into(), creds.get("passphrase").cloned().unwrap_or(Value::Null)); }
return Value::Map(creds);
Value::Null
}
/*
* @ignore
* @method
* @name polymarket#loadApiCredentials
* @description ensures L2 api credentials are available for private requests — uses the provided apiKey/secret/password when present, otherwise derives them from the privateKey
*/
pub async fn load_api_credentials(&mut self) -> Value {
// the order signer / L2 POLY_ADDRESS is always the EOA behind the privateKey, so the L2 api key MUST
// belong to that same EOA — derive it from the privateKey rather than trusting externally supplied
// creds that may have been issued to a different wallet
if (self.privateKey.clone() != Value::Null) {
let mut alreadyDerived: Option<String> = self.safe_string_k(self.options.clone(), "l2ApiKey", &[]).as_str().map(str::to_owned);
if (alreadyDerived.is_none()) {
self.create_or_derive_api_key(&[]).await;
}
return Value::Null;
}
let mut apiKey: Value = (if (self.apiKey.clone() != Value::Null) { self.apiKey.clone() } else { self.safe_string_k(self.options.clone(), "l2ApiKey", &[]) });
let mut secret: Value = Value::Null;
if (self.secret.clone() != Value::Null) {
secret = self.secret.clone();
} else {
secret = self.safe_string_k(self.options.clone(), "l2Secret", &[]);
}
let mut passphrase: Value = (if (self.password.clone() != Value::Null) { self.password.clone() } else { self.safe_string_k(self.options.clone(), "l2Passphrase", &[]) });
let mut hasL2: bool = (apiKey != Value::Null) && (secret != Value::Null) && (passphrase != Value::Null);
if hasL2 {
return Value::Null;
}
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" requires L2 api credentials (apiKey, secret, password) or a privateKey to derive them".into()))));
Value::Null
}
pub fn ping(&self, mut client: Value) -> Value {
return Value::Str("PING".into());
Value::Null
}
pub fn handle_text_message(&self, mut client: Value, mut message: Value) {
// Polymarket keeps the ws alive with text PING/PONG (not protocol ping-pong frames), so the
// client's onPong never fires; refresh client.lastPong here on the "PONG" reply, otherwise the
// base keepalive treats the connection as stale and times it out after maxPingPongMisses.
crate::set_value(&mut client, &Value::Str("lastPong".into()), self.milliseconds());
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
self.handle_message_event(client, message);
}
pub fn handle_list_message(&mut self, mut client: Value, mut message: Value) {
let __message_empty = Vec::new();
let message = message.as_array().unwrap_or(&__message_empty);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1453: bool = true;
while { if !__for_first_1453 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1453 = false; i.as_f64().unwrap_or(f64::NAN) < ((message.len() as i64) as f64) } {
let mut event: Value = message.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if (event == Value::Null) || (event == Value::Null) || (!matches!(&event, Value::Dict(_))) {
continue;
}
self.handle_message_event(client.clone(), event);
}
}
}
pub fn handle_message_event(&mut self, mut client: Value, mut event: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &event { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut eventType: Option<String> = (match __pro_message.get("event_type").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (eventType.as_deref() == Some("book")) {
self.handle_order_book_snapshot(client.clone(), event.clone());
} else if (eventType.as_deref() == Some("price_change")) {
self.handle_order_book_delta(client.clone(), event.clone());
} else if (eventType.as_deref() == Some("last_trade_price")) {
self.handle_trade(client.clone(), event.clone());
} else if (eventType.as_deref() == Some("order")) {
self.handle_order(client.clone(), event.clone());
} else if (eventType.as_deref() == Some("trade")) {
self.handle_my_trade(client, event);
}
}
pub fn handle_order_book_snapshot(&self, mut client: Value, mut event: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &event { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut tokenId: Option<String> = match __pro_message.get("asset_id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
let mut outcome: Value = self.token_id_to_symbol(tokenId.clone().map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
if (outcome == Value::Null) {
return;
}
if !(matches!((&self.orderbooks, &outcome), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
let mut seededBook: Value = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut self.orderbooks.clone() { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&outcome), seededBook); }
}
let mut orderbook: Value = (if let (Some(__m), Some(__k)) = (self.orderbooks.as_map(), outcome.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
let mut timestamp: Value = self.parse_poly_timestamp(self.safe_string_k(event, "timestamp", &[]));
let mut rawBids: Value = (match __pro_message.get("bids").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut rawAsks: Value = (match __pro_message.get("asks").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut bids: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1454: bool = true;
while { if !__for_first_1454 { i += 1; } __for_first_1454 = false; i < (rawBids.len() as i64) } {
let mut b: Value = self.safe_dict(rawBids.clone(), Value::Int(i), &[]);
bids.push(Value::from(vec![self.safe_number_k(b.clone(), "price", &[]), self.safe_number_k(b, "size", &[])]));
}
}
let mut asks: Vec<Value> = Vec::new();
{
let mut j: i64 = 0;
let mut __for_first_1455: bool = true;
while { if !__for_first_1455 { j += 1; } __for_first_1455 = false; j < (rawAsks.len() as i64) } {
let mut a: Value = self.safe_dict(rawAsks.clone(), Value::Int(j), &[]);
asks.push(Value::from(vec![self.safe_number_k(a.clone(), "price", &[]), self.safe_number_k(a, "size", &[])]));
}
}
let mut outcomeObj: Value = self.safe_outcome(outcome.clone(), &[]);
orderbook.reset(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("bids".to_string(), Value::from(bids));
m.insert("asks".to_string(), Value::from(asks));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("outcome".to_string(), outcome.clone());
m.insert("outcomeId".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m
}));
client.resolve(&[orderbook.clone(), Value::Str(format!("{}{}", Value::Str("orderbook::".into()), outcome).into())]);
client.resolve(&[orderbook, Value::Str(format!("{}{}", Value::Str("ticker::".into()), outcome).into())]);
}
pub fn handle_order_book_delta(&self, mut client: Value, mut event: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &event { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut timestamp: Value = self.parse_poly_timestamp(self.safe_string_k(event, "timestamp", &[]));
let mut changes: Value = (match __pro_message.get("price_changes").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut updated: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: i64 = 0;
let mut __for_first_1456: bool = true;
while { if !__for_first_1456 { i += 1; } __for_first_1456 = false; i < (changes.len() as i64) } {
let mut change: Value = self.safe_dict(changes.clone(), Value::Int(i), &[]);
let mut tokenId: Option<String> = self.safe_string_k_opt(change.clone(), "asset_id", &[]);
let mut outcome: Value = self.token_id_to_symbol(tokenId.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
if (outcome == Value::Null) || !(matches!((&self.orderbooks, &outcome), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
continue;
}
let mut orderbook: Value = (if let (Some(__m), Some(__k)) = (self.orderbooks.as_map(), outcome.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
let mut price: Value = self.safe_number_k(change.clone(), "price", &[]);
let mut size: Value = self.safe_number_k(change.clone(), "size", &[]);
let mut isBuy: bool = self.safe_string_upper_k(change, "side", &[Value::Str("".into())]).as_str() == Some("BUY");
let mut side: Value = (if isBuy { orderbook.book_field("bids") } else { orderbook.book_field("asks") });
// storeArray([price, size]) inserts/updates or removes (size=0) the level
let mut sideRef: Value = side;
sideRef.store_array(Value::from(vec![price, size]));
orderbook.set_book_meta("timestamp", timestamp.clone());
orderbook.set_book_meta("datetime", self.iso8601(timestamp.clone()));
if let Value::Dict(__d) = &mut updated { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&outcome), Value::Bool(true)); }
}
}
let mut updatedSymbols: Vec<Value> = Value::Array(updated.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).as_array().cloned().unwrap_or_default();
{
let mut k: i64 = 0;
let mut __for_first_1457: bool = true;
while { if !__for_first_1457 { k += 1; } __for_first_1457 = false; k < (updatedSymbols.len() as i64) } {
let mut outcome: Value = updatedSymbols.get(k as usize).cloned().unwrap_or(Value::Null);
let mut orderbook: Value = (if let (Some(__m), Some(__k)) = (self.orderbooks.as_map(), outcome.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
client.resolve(&[orderbook.clone(), Value::Str(format!("{}{}", Value::Str("orderbook::".into()), outcome).into())]);
client.resolve(&[orderbook, Value::Str(format!("{}{}", Value::Str("ticker::".into()), outcome).into())]);
}
}
}
pub fn handle_trade(&mut self, mut client: Value, mut event: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &event { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut tokenId: Option<String> = match __pro_message.get("asset_id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
let mut outcome: Value = self.token_id_to_symbol(tokenId.clone().map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
if (outcome == Value::Null) {
return;
}
let mut timestamp: Value = self.parse_poly_timestamp(self.safe_string_k(event.clone(), "timestamp", &[]));
let mut price: Value = (match __pro_message.get("price").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null });
let mut amount: Value = (match __pro_message.get("size").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null });
let mut market: Value = self.safe_outcome(tokenId.map(Value::from).unwrap_or(Value::Null), &[]);
let mut trade: Value = self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), (match __pro_message.get("transaction_hash").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("info".to_string(), event.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("outcome".to_string(), outcome.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower_k(event, "side", &[]));
m.insert("takerOrMaker".to_string(), Value::Str("taker".into()));
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m
}), &[market]);
if (self.trades.clone() == Value::Null) {
self.trades = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
let mut stored: Value = self.safe_value(self.trades.clone(), outcome.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
stored = ArrayCache::new(limit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&outcome), stored.clone()); }
}
stored.append(trade);
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("trades::".into()), outcome).into())]);
}
/*
* @method
* @name polymarket#watchOrderBook
* @description streams live order-book updates for a single Polymarket outcome token
* @param {string} outcome unified outcome (e.g. "TRUMP_WINS_2028:YES") or an outcome token id
* @param {int} [limit] optional depth limit applied after resolving
* @param {object} [params] extra params (currently unused)
* @returns {object} a [prediction order book structure]{@link https://docs.ccxt.com/#/?id=prediction-order-book-structure}
*/
pub async fn watch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[Value::Str("".into())]);
let outcomeValue: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook::".into()), outcomeValue).into());
let mut subscribeHash: Value = Value::Str(format!("{}{}", Value::Str("subscribe::".into()), tokenId).into());
let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("assets_ids".to_string(), Value::from(vec![tokenId]));
m.insert("type".to_string(), Value::Str("market".into()));
m
});
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, &[Value::Map(subscribeMsg), subscribeHash]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name polymarket#watchTrades
* @description streams live fills for a single Polymarket outcome token
* @param {string} outcome unified outcome
* @param {int} [since] optional unix timestamp (ms) lower bound
* @param {int} [limit] optional max number of trades to return
* @param {object} [params] extra params (unused)
* @returns {object[]} a list of [prediction trade structures]{@link https://docs.ccxt.com/#/?id=prediction-trade-structure}
*/
pub async fn watch_trades(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[Value::Str("".into())]);
let outcomeValue: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trades::".into()), outcomeValue).into());
let mut subscribeHash: Value = Value::Str(format!("{}{}", Value::Str("subscribe::".into()), tokenId).into());
let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("assets_ids".to_string(), Value::from(vec![tokenId]));
m.insert("type".to_string(), Value::Str("market".into()));
m
});
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, &[Value::Map(subscribeMsg), subscribeHash]).await;
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name polymarket#watchTicker
* @description streams a synthetic ticker derived from order-book snapshots and deltas (mid = (bid + ask) / 2)
* @param {string} outcome unified outcome
* @param {object} [params] extra params (unused)
* @returns {object} a [prediction ticker structure]{@link https://docs.ccxt.com/#/?id=prediction-ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[Value::Str("".into())]);
let mut outcomeValue: Option<String> = self.safe_string_k_opt(outcomeObj, "outcome", &[]);
if (outcomeValue.is_none()) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" watchTicker() missing outcome".into()))));
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker::".into()), outcomeValue.clone().map(Value::from).unwrap_or(Value::Null)).into());
let mut subscribeHash: Value = Value::Str(format!("{}{}", Value::Str("subscribe::".into()), tokenId).into());
let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("assets_ids".to_string(), Value::from(vec![tokenId]));
m.insert("type".to_string(), Value::Str("market".into()));
m
});
if !(matches!((&self.orderbooks, &outcomeValue.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
let mut seededBook: Value = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (outcomeValue.is_some()) {
if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(outcomeValue.as_deref().unwrap_or("null").to_string(), seededBook); }
}
}
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, &[Value::Map(subscribeMsg), subscribeHash]).await;
let mut bids: Value = crate::value::get_value_k(&orderbook, "bids");
let mut asks: Value = crate::value::get_value_k(&orderbook, "asks");
let mut bestBid: Value = Value::Null;
let mut bestBidVolume: Value = Value::Null;
let mut bidsLength: Value = Value::Int(0);
if (bids != Value::Null) {
bidsLength = get_array_length(&bids);
}
if (bids != Value::Null) && (bidsLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
bestBid = get_value(&get_value(&bids, &Value::Int(0)), &Value::Int(0));
bestBidVolume = get_value(&get_value(&bids, &Value::Int(0)), &Value::Int(1));
}
let mut bestAsk: Value = Value::Null;
let mut bestAskVolume: Value = Value::Null;
let mut asksLength: Value = Value::Int(0);
if (asks != Value::Null) {
asksLength = get_array_length(&asks);
}
if (asks != Value::Null) && (asksLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
bestAsk = get_value(&get_value(&asks, &Value::Int(0)), &Value::Int(0));
bestAskVolume = get_value(&get_value(&asks, &Value::Int(0)), &Value::Int(1));
}
let mut mid: Value = Value::Null;
if (bestBid != Value::Null) && (bestAsk != Value::Null) {
let mut sum: Value = crate::precise::Precise::stringAdd(&self.number_to_string(bestBid.clone()), &self.number_to_string(bestAsk.clone()));
mid = self.parse_number(crate::precise::Precise::stringDiv(&sum, &Value::Str("2".into())), &[]);
} else if (bestBid != Value::Null) {
mid = bestBid.clone();
} else {
mid = bestAsk.clone();
}
let mut market: Value = self.safe_outcome(outcomeValue.clone().map(Value::from).unwrap_or(Value::Null), &[]);
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcomeValue.map(Value::from).unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
m.insert("timestamp".to_string(), crate::value::get_value_k(&orderbook, "timestamp"));
m.insert("datetime".to_string(), crate::value::get_value_k(&orderbook, "datetime"));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), bestBid);
m.insert("bidVolume".to_string(), bestBidVolume);
m.insert("ask".to_string(), bestAsk);
m.insert("askVolume".to_string(), bestAskVolume);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), mid.clone());
m.insert("last".to_string(), mid.clone());
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), mid);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("info".to_string(), orderbook);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name polymarket#watchOrders
* @description watches the authenticated user's order updates over the CLOB user websocket channel
* @see https://docs.polymarket.com/developers/CLOB/websocket/user-channel
* @param {string} [outcome] unified outcome to filter the stream to one market
* @param {int} [since] the earliest time in ms to return orders for
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
let mut messageHash: Value = Value::Str("orders".into());
let mut outcomeResolved: Value = outcome;
if (outcomeResolved != Value::Null) {
let mut outcomeObj: Value = self.load_outcome(outcomeResolved.clone(), &[]).await;
outcomeResolved = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
let outcomeName: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
messageHash = Value::Str(format!("{}{}", Value::Str("orders::".into()), outcomeName).into());
}
let mut orders: Value = self.subscribe_user_channel(messageHash, &[params]).await;
let mut limitResolved: Value = limit;
if self.newUpdates.as_bool() == Some(true) {
limitResolved = orders.get_limit(outcomeResolved.clone(), limitResolved.clone());
}
return self.filter_by_outcome_since_limit(orders, &[outcomeResolved, since, limitResolved, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name polymarket#watchMyTrades
* @description watches the authenticated user's trade fills over the CLOB user websocket channel
* @see https://docs.polymarket.com/developers/CLOB/websocket/user-channel
* @param {string} [outcome] unified outcome to filter the stream to one market
* @param {int} [since] the earliest time in ms to return trades for
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_credentials().await;
let mut messageHash: Value = Value::Str("myTrades".into());
let mut outcomeResolved: Value = outcome;
if (outcomeResolved != Value::Null) {
let mut outcomeObj: Value = self.load_outcome(outcomeResolved.clone(), &[]).await;
outcomeResolved = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
let outcomeName: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
messageHash = Value::Str(format!("{}{}", Value::Str("myTrades::".into()), outcomeName).into());
}
let mut trades: Value = self.subscribe_user_channel(messageHash, &[params]).await;
let mut limitResolved: Value = limit;
if self.newUpdates.as_bool() == Some(true) {
limitResolved = trades.get_limit(outcomeResolved.clone(), limitResolved.clone());
}
return self.filter_by_outcome_since_limit(trades, &[outcomeResolved, since, limitResolved, Value::Bool(true)]);
Value::Null
}
pub async fn subscribe_user_channel(&mut self, mut messageHash: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// the user channel authenticates inside the subscribe frame, not via HMAC headers
let mut apiKey: Value = (if (self.apiKey.clone() != Value::Null) { self.apiKey.clone() } else { self.safe_string_k(self.options.clone(), "l2ApiKey", &[]) });
let mut secret: Value = Value::Null;
if (self.secret.clone() != Value::Null) {
secret = self.secret.clone();
} else {
secret = self.safe_string_k(self.options.clone(), "l2Secret", &[]);
}
let mut passphrase: Value = (if (self.password.clone() != Value::Null) { self.password.clone() } else { self.safe_string_k(self.options.clone(), "l2Passphrase", &[]) });
let mut auth: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), apiKey);
m.insert("secret".to_string(), secret);
m.insert("passphrase".to_string(), passphrase);
m
});
// an empty markets list subscribes to every market the user is active in
let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("auth".to_string(), Value::Map(auth));
m.insert("markets".to_string(), Value::from(vec![]));
m.insert("type".to_string(), Value::Str("user".into()));
m
});
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("wsUser")).cloned().unwrap_or(Value::Null);
let mut subscribeHash: String = "user".to_string();
let __ws_arg_30 = self.extend(Value::Map(subscribeMsg), &[params]);
return self.watch(url, messageHash, &[__ws_arg_30, Value::from(subscribeHash)]).await;
Value::Null
}
pub fn handle_order(&mut self, mut client: Value, mut event: Value) {
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheByOutcomeById::new(limit);
}
let mut stored: Value = self.orders.clone();
let mut parsed: Value = self.parse_prediction_order(event, &[]);
stored.append(parsed.clone());
client.resolve(&[stored.clone(), Value::Str("orders".into())]);
let mut outcome: Option<String> = self.safe_string_k_opt(parsed, "outcome", &[]);
if (outcome.is_some()) {
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("orders::".into()), outcome.map(Value::from).unwrap_or(Value::Null)).into())]);
}
}
pub fn handle_my_trade(&mut self, mut client: Value, mut event: Value) {
if (self.myTrades.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheByOutcomeById::new(limit);
}
let mut stored: Value = self.myTrades.clone();
let mut parsed: Value = self.parse_prediction_trade(event, &[]);
stored.append(parsed.clone());
client.resolve(&[stored.clone(), Value::Str("myTrades".into())]);
let mut outcome: Option<String> = self.safe_string_k_opt(parsed, "outcome", &[]);
if (outcome.is_some()) {
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("myTrades::".into()), outcome.map(Value::from).unwrap_or(Value::Null)).into())]);
}
}
pub fn token_id_to_symbol(&self, mut tokenId: Value) -> Option<String> {
if (tokenId == Value::Null) || (tokenId.as_str() == Some("")) {
return None;
}
// outcome tokens are keyed in outcomes_by_id (populated by fetchEvents/loadMarkets);
// fall back to markets_by_id for the standard market lookup
let mut outcomeObj: Value = self.safe_dict(self.exchange.outcomes_by_id.clone(), tokenId.clone(), &[]);
if (outcomeObj != Value::Null) {
return self.safe_string_k(outcomeObj, "outcome", &[]).as_str().map(str::to_owned);
}
// safe dict/string access: a bare marketsById[tokenId] / market['market'] is undefined in JS
// but raises KeyError in Python when the token isn't a market id (the ws trade path hits this)
let mut market: Value = self.safe_dict(self.markets_by_id.clone(), tokenId, &[]);
return self.safe_string2(market, Value::Str("market".into()), Value::Str("symbol".into()), &[]).as_str().map(str::to_owned);
}
pub fn parse_poly_timestamp(&self, mut raw: Value) -> Value {
if (raw == Value::Null) {
return Value::Null;
}
return self.parse_to_int(raw);
Value::Null
}
}