#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
use crate::exchange::CallDynamicChecked;
pub struct PolymarketCore {
pub exchange: crate::exchange::Exchange,
}
impl PolymarketCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::exchange::Exchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = PolymarketCore::describe(self);
self.initialize_properties(described);
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for PolymarketCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
PolymarketCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
PolymarketCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
PolymarketCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
PolymarketCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
PolymarketCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
PolymarketCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
PolymarketCore::parse_funding_rate(self, rate, &[market])
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
PolymarketCore::parse_open_interest(self, interest, &[market])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
PolymarketCore::parse_transaction(self, transaction, &[currency])
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
PolymarketCore::parse_leverage(self, leverage, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
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 {
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 {
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"amount_to_precision" => self.amount_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"calculate_rate_limiter_cost" => self.calculate_rate_limiter_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_all_orders_after" => self.cancel_all_orders_after(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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,
"compact_signable" => self.compact_signable(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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_order_request" => self.create_order_request(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())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_proxy_credentials" => self.create_proxy_credentials(&args[..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_bids_asks" => self.fetch_bids_asks(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args[..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_leverage" => self.fetch_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_margin_mode" => self.fetch_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_interests" => self.fetch_open_interests(&args[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_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_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_fees" => self.fetch_trading_fees(&args[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).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)),
"hash_message" => self.hash_message(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"load_proxy_credentials" => self.load_proxy_credentials(&args[..]).await,
"modify_margin_helper" => self.modify_margin_helper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_leverage" => self.parse_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market" => self.parse_market(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_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"price_to_precision" => self.price_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"reduce_margin" => self.reduce_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"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)),
"sign_perps_op" => self.sign_perps_op(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for PolymarketCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for PolymarketCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &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("version".to_string(), Value::Str("v1".into()));
m.insert("rateLimit".to_string(), Value::Int(60));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("dex".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(true));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelAllOrdersAfter".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBidsAsks".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingInterval".to_string(), Value::Bool(false));
m.insert("fetchFundingIntervals".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchLedger".to_string(), Value::Bool(false));
m.insert("fetchLeverage".to_string(), Value::Bool(true));
m.insert("fetchMarginMode".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenInterests".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("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(false));
m.insert("fetchTradingFees".to_string(), Value::Bool(true));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(true));
m.insert("sandbox".to_string(), Value::Bool(false));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("transfer".to_string(), Value::Bool(false));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1s".to_string(), Value::Str("1s".into()));
m.insert("1m".to_string(), Value::Str("1m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15m".to_string(), Value::Str("15m".into()));
m.insert("30m".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("6h".to_string(), Value::Str("6h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m
}));
m.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("public".to_string(), Value::Str("https://api.perpetuals.polymarket.com/v1".into()));
m.insert("private".to_string(), Value::Str("https://api.perpetuals.polymarket.com/v1".into()));
m.insert("trade".to_string(), Value::Str("https://api.perpetuals.polymarket.com/v1".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://polymarket.com/perps".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.polymarket.com/perps/overview".into()), Value::Str("https://docs.polymarket.com/api-reference/perps/overview".into())]));
m.insert("fees".to_string(), Value::Str("https://docs.polymarket.com/perps/learn-about-trading/fees".into()));
m
}));
m.insert("api".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("info/ping".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("info/time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("info/exchange".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("info/assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("info/instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("info/tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("info/statistics".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("info/klines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("info/mark-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("info/bbo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("info/book".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("info/index".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("info/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("info/portfolio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("info/position-fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("info/funding".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("info/fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("info/limit-tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("info/invite".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("account/credentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/open-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("account/balances".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/portfolio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/equity".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/pnl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/funding".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/deposits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/withdrawals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/auto-cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("trade".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("trade/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/proxy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("patch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-coid".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/margin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/auto-cancel".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("trade/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-coid".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders/all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/proxy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(false));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("walletAddress".to_string(), Value::Bool(false));
m.insert("privateKey".to_string(), Value::Bool(true));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(true));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0004".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.000125".into()), &[]));
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("chainId".to_string(), Value::Int(137));
m.insert("collateral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), Value::Str("pUSD".into()));
m.insert("address".to_string(), Value::Str("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB".into()));
m.insert("decimals".to_string(), Value::Int(6));
m
}));
m.insert("proxyCredentials".to_string(), Value::Null);
m.insert("proxyExpiry".to_string(), Value::Int(604800000));
m.insert("proxyRefreshMargin".to_string(), Value::Int(3600000));
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("unauthorized".to_string(), Value::Str("AuthenticationError".into()));
m.insert("ip_rate_limited".to_string(), Value::Str("RateLimitExceeded".into()));
m.insert("action_rate_limited".to_string(), Value::Str("RateLimitExceeded".into()));
m.insert("message_rate_limited".to_string(), Value::Str("RateLimitExceeded".into()));
m.insert("service_unavailable".to_string(), Value::Str("ExchangeNotAvailable".into()));
m.insert("insufficient_margin".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("insufficient_balance".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("order_not_found".to_string(), Value::Str("OrderNotFound".into()));
m.insert("order_not_in_orderbook".to_string(), Value::Str("OrderNotFound".into()));
m.insert("reduce_only_invalid".to_string(), Value::Str("InvalidOrder".into()));
m.insert("price_outside_bounds".to_string(), Value::Str("InvalidOrder".into()));
m.insert("position_not_found".to_string(), Value::Str("BadRequest".into()));
m.insert("invalid_margin_mode".to_string(), Value::Str("BadRequest".into()));
m.insert("invalid_margin_amount".to_string(), Value::Str("BadRequest".into()));
m.insert("open_orders_limit".to_string(), Value::Str("InvalidOrder".into()));
m.insert("margin_below_required_initial".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("account_liquidating".to_string(), Value::Str("InvalidOrder".into()));
m.insert("invalid_margin_signature_timestamp".to_string(), Value::Str("InvalidNonce".into()));
m.insert("signature_already_used".to_string(), Value::Str("InvalidNonce".into()));
m.insert("order_already_terminal".to_string(), Value::Str("OrderNotFound".into()));
m.insert("order_unknown".to_string(), Value::Str("OrderNotFound".into()));
m.insert("order_in_flight".to_string(), Value::Str("OperationFailed".into()));
m.insert("order_not_pending_risk".to_string(), Value::Str("OperationFailed".into()));
m.insert("order_not_pending_engine".to_string(), Value::Str("OperationFailed".into()));
m.insert("order_not_modifiable".to_string(), Value::Str("InvalidOrder".into()));
m.insert("order_has_tpsl".to_string(), Value::Str("InvalidOrder".into()));
m.insert("modify_already_pending".to_string(), Value::Str("OperationFailed".into()));
m.insert("modify_no_op".to_string(), Value::Str("InvalidOrder".into()));
m.insert("modify_limit_reached".to_string(), Value::Str("InvalidOrder".into()));
m.insert("modify_would_cross".to_string(), Value::Str("InvalidOrder".into()));
m.insert("modify_quantity_not_above_filled".to_string(), Value::Str("InvalidOrder".into()));
m.insert("duplicate_order_in_batch".to_string(), Value::Str("InvalidOrder".into()));
m.insert("invalid_command".to_string(), Value::Str("InvalidOrder".into()));
m.insert("auto_cancel_deadline_too_soon".to_string(), Value::Str("BadRequest".into()));
m.insert("auto_cancel_daily_limit_reached".to_string(), Value::Str("RateLimitExceeded".into()));
m.insert("auto_cancel_in_flight".to_string(), Value::Str("OperationFailed".into()));
m.insert("cancel_only_mode".to_string(), Value::Str("OnMaintenance".into()));
m.insert("blp_leverage_locked".to_string(), Value::Str("BadRequest".into()));
m.insert("request_body_timeout".to_string(), Value::Str("RequestTimeout".into()));
m.insert("payload_too_large".to_string(), Value::Str("BadRequest".into()));
m.insert("not_found".to_string(), Value::Str("NotSupported".into()));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("invalid query parameters".to_string(), Value::Str("BadRequest".into()));
m.insert("invalid path parameters".to_string(), Value::Str("BadRequest".into()));
m.insert("invalid instrument".to_string(), Value::Str("BadRequest".into()));
m.insert("invalid signature".to_string(), Value::Str("AuthenticationError".into()));
m.insert("signature expired".to_string(), Value::Str("AuthenticationError".into()));
m.insert("account not found for proxy".to_string(), Value::Str("AuthenticationError".into()));
m.insert("command expired".to_string(), Value::Str("InvalidOrder".into()));
m.insert("command expiry too far in future".to_string(), Value::Str("InvalidOrder".into()));
m
}));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Null);
m.insert("forPerps".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(false));
m.insert("triggerDirection".to_string(), Value::Bool(false));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Bool(false));
m.insert("takeProfitPrice".to_string(), Value::Bool(false));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(true));
m.insert("FOK".to_string(), Value::Bool(true));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Null);
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(1000));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".into()));
m
}));
m.insert("inverse".to_string(), Value::Null);
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
m
}));
m
})]);
Value::Null
}
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.public_get_info_time(&[params]).await;
return self.safe_integer_k(response, "time", &[]);
Value::Null
}
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.public_get_info_exchange(&[params]).await;
let mut cancelOnly: bool = self.safe_bool_k_opt(response.clone(), "cancel_only", &[Value::Bool(false)]).unwrap_or(false);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if cancelOnly { Value::Str("maintenance".into()) } else { Value::Str("ok".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
}
pub async fn fetch_currencies(&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 promises: Value = Value::from(vec![self.public_get_info_instruments(&[params.clone()]).await, self.public_get_info_assets(&[params]).await]);
let mut responses: Value = promise_all(&promises).await;
let mut instruments: Vec<Value> = self.safe_list(responses.clone(), Value::Int(0), &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut assets: Vec<Value> = self.safe_list(responses, Value::Int(1), &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: i64 = 0;
let mut __for_first_1100: bool = true;
while { if !__for_first_1100 { i += 1; } __for_first_1100 = false; i < (instruments.len() as i64) } {
let mut instrument: Value = instruments.get(i as usize).cloned().unwrap_or(Value::Null);
let mut baseId: Option<String> = self.safe_string_k_opt(instrument.clone(), "base_asset", &[]);
if (baseId.is_none()) {
continue;
}
let mut code: Value = self.safe_currency_code(baseId.clone().map(Value::from).unwrap_or(Value::Null), &[]);
if !(matches!((&result, &code), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
let mut category: Option<String> = self.safe_string_k(instrument.clone(), "category", &[]).as_str().map(str::to_owned);
let mut currencyType: Value = (if (category.as_deref() == Some("crypto")) { Value::Str("crypto".into()) } else { Value::Str("other".into()) });
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), baseId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("code".to_string(), code.clone());
m.insert("name".to_string(), baseId.map(Value::from).unwrap_or(Value::Null));
m.insert("info".to_string(), instrument.clone());
m.insert("active".to_string(), Value::Bool(true));
m.insert("deposit".to_string(), Value::Bool(false));
m.insert("withdraw".to_string(), Value::Bool(false));
m.insert("fee".to_string(), Value::Null);
m.insert("precision".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(instrument, "quantity_decimals", &[])]), &[]));
m.insert("type".to_string(), currencyType);
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}))); }
}
}
}
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("USD".into(), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("USD".into()));
m.insert("code".to_string(), Value::Str("USD".into()));
m.insert("name".to_string(), Value::Str("USD".into()));
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("active".to_string(), Value::Bool(true));
m.insert("deposit".to_string(), Value::Bool(false));
m.insert("withdraw".to_string(), Value::Bool(false));
m.insert("fee".to_string(), Value::Null);
m.insert("precision".to_string(), self.parse_number(Value::Str("0.01".into()), &[]));
m.insert("type".to_string(), Value::Str("fiat".into()));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}))); }
{
let mut i: i64 = 0;
let mut __for_first_1101: bool = true;
while { if !__for_first_1101 { i += 1; } __for_first_1101 = false; i < (assets.len() as i64) } {
let mut asset: Value = assets.get(i as usize).cloned().unwrap_or(Value::Null);
let mut currencyId: Option<String> = self.safe_string_k_opt(asset.clone(), "asset", &[]);
if (currencyId.is_none()) {
continue;
}
let mut code: Value = self.safe_currency_code(currencyId.clone().map(Value::from).unwrap_or(Value::Null), &[]);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), currencyId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("code".to_string(), code.clone());
m.insert("name".to_string(), currencyId.map(Value::from).unwrap_or(Value::Null));
m.insert("info".to_string(), asset.clone());
m.insert("active".to_string(), Value::Bool(true));
m.insert("deposit".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m.insert("fee".to_string(), self.safe_number_k(asset.clone(), "withdrawal_fee", &[]));
m.insert("precision".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(asset, "decimals", &[])]), &[]));
m.insert("type".to_string(), Value::Str("crypto".into()));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}))); }
}
}
return result;
Value::Null
}
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 response: Value = self.public_get_info_instruments(&[params]).await;
return self.parse_markets(response);
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
let mut numericId: Option<String> = self.safe_string_k_opt(market.clone(), "instrument_id", &[]);
let mut venueSymbol: Option<String> = self.safe_string_k_opt(market.clone(), "symbol", &[]);
let mut baseId: Option<String> = self.safe_string_k_opt(market.clone(), "base_asset", &[]);
let mut settleId: Option<String> = self.safe_string_k_opt(market.clone(), "quote_asset", &[]);
let mut parts: Value = Value::Array(if let Some(__s) = venueSymbol.as_deref() { __s.split("-").map(Value::from).collect() } else { Vec::new() });
let mut quoteId: Value = self.safe_string(parts, Value::Int(1), &[Value::Str("USD".into())]);
let mut base: Value = self.safe_currency_code(baseId.clone().map(Value::from).unwrap_or(Value::Null), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
let mut settle: Value = self.safe_currency_code(settleId.clone().map(Value::from).unwrap_or(Value::Null), &[]);
let mut crossAllowed: Value = Value::Bool(!(self.safe_bool_k(market.clone(), "isolated_only", &[Value::Bool(false)]).as_bool() == Some(true)));
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), numericId.map(Value::from).unwrap_or(Value::Null));
m.insert("symbol".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into()), Value::Str(":".into())).into()), settle).into()));
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId.map(Value::from).unwrap_or(Value::Null));
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId.map(Value::from).unwrap_or(Value::Null));
m.insert("type".to_string(), Value::Str("swap".into()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(true));
m.insert("contract".to_string(), Value::Bool(true));
m.insert("linear".to_string(), Value::Bool(true));
m.insert("inverse".to_string(), Value::Bool(false));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0004".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.000125".into()), &[]));
m.insert("contractSize".to_string(), self.parse_number(Value::Str("1".into()), &[]));
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("marginModes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cross".to_string(), crossAllowed);
m.insert("isolated".to_string(), Value::Bool(true));
m
}));
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "quantity_decimals", &[])]), &[]));
m.insert("price".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "price_decimals", &[])]), &[]));
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(), self.parse_number(Value::Str("1".into()), &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "max_leverage", &[]));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(market.clone(), "min_notional", &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "max_limit_notional", &[]));
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
pub async fn fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut tickers: Value = self.fetch_tickers(&[Value::from(vec![symbolResolved.clone()]), params]).await;
let mut ticker: Value = self.safe_dict(tickers, symbolResolved.clone(), &[]);
if (ticker == Value::Null) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchTicker() could not find a ticker for ".into())).into()), symbolResolved)));
}
return ticker;
Value::Null
}
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut promises: Value = Value::from(vec![self.public_get_info_tickers(&[params.clone()]).await, self.public_get_info_statistics(&[params.clone()]).await, self.public_get_info_bbo(&[params]).await]);
let mut responses: Value = promise_all(&promises).await;
let mut merged: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut statistics: Vec<Value> = self.safe_list(responses.clone(), Value::Int(1), &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
{
let mut i: i64 = 0;
let mut __for_first_1102: bool = true;
while { if !__for_first_1102 { i += 1; } __for_first_1102 = false; i < (statistics.len() as i64) } {
let mut entry: Value = statistics.get(i as usize).cloned().unwrap_or(Value::Null);
let mut instrumentId: Option<String> = self.safe_string_k_opt(entry.clone(), "instrument_id", &[]);
merged.insert(instrumentId.as_deref().unwrap_or("null").to_string(), self.omit(entry.clone(), Value::Str("klines".into()), &[]));
}
}
let mut bbos: Vec<Value> = self.safe_list(responses.clone(), Value::Int(2), &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
{
let mut i: i64 = 0;
let mut __for_first_1103: bool = true;
while { if !__for_first_1103 { i += 1; } __for_first_1103 = false; i < (bbos.len() as i64) } {
let mut entry: Value = bbos.get(i as usize).cloned().unwrap_or(Value::Null);
let mut instrumentId: Option<String> = self.safe_string_k_opt(entry.clone(), "instrument_id", &[]);
let mut previous: Value = self.safe_dict(Value::Map(merged.clone()), instrumentId.clone().map(Value::from).unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
merged.insert(instrumentId.as_deref().unwrap_or("null").to_string(), self.extend(previous.clone(), &[entry.clone()]));
}
}
let mut tickers: Vec<Value> = self.safe_list(responses, Value::Int(0), &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1104: bool = true;
while { if !__for_first_1104 { i += 1; } __for_first_1104 = false; i < (tickers.len() as i64) } {
let mut entry: Value = tickers.get(i as usize).cloned().unwrap_or(Value::Null);
let mut instrumentId: Option<String> = self.safe_string_k_opt(entry.clone(), "instrument_id", &[]);
let mut previous: Value = self.safe_dict(Value::Map(merged.clone()), instrumentId.map(Value::from).unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
result.push(self.extend(previous, &[entry]));
}
}
return self.parse_tickers(Value::from(result), &[symbolsNormalized]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string_k_opt(ticker.clone(), "instrument_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut timestamp: Option<i64> = self.safe_integer_k(ticker.clone(), "timestamp", &[]).as_i64();
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
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_string_k(ticker.clone(), "bid_price", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(ticker.clone(), "bid_quantity", &[]));
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "ask_price", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(ticker.clone(), "ask_quantity", &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), self.safe_string_k(ticker.clone(), "open_price", &[]));
m.insert("close".to_string(), self.safe_string_k(ticker.clone(), "last_price", &[]));
m.insert("last".to_string(), self.safe_string_k(ticker.clone(), "last_price", &[]));
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), self.safe_string_k(ticker.clone(), "volume", &[]));
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "mark_price", &[]));
m.insert("indexPrice".to_string(), self.safe_string_k(ticker.clone(), "index_price", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
pub async fn fetch_bids_asks(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut response: Value = self.public_get_info_bbo(&[params]).await;
return self.parse_tickers(response, &[symbolsNormalized]);
Value::Null
}
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (limit != Value::Null) {
request.insert("depth".into(), limit);
}
let __ws_arg_0 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_get_info_book(&[__ws_arg_0]).await;
let mut timestamp: Value = self.safe_integer_k(response.clone(), "timestamp", &[]);
let mut orderbook: indexmap::IndexMap<String, Value> = self.parse_order_book(response.clone(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[timestamp]).as_map().cloned().unwrap_or_default();
orderbook.insert("nonce".into(), self.safe_integer_k(response, "sequence", &[]));
return Value::Map(orderbook);
Value::Null
}
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
request.insert("start_timestamp".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = params;
if (until != Value::Null) {
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("until".into()), &[]);
request.insert("end_timestamp".into(), until);
}
let __ws_arg_1 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.public_get_info_trades(&[__ws_arg_1]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(data, &[market, since, limit]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string2_opt(trade.clone(), Value::Str("instrument_id".into()), Value::Str("iid".into()), &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut timestamp: Option<i64> = self.safe_integer2(trade.clone(), Value::Str("timestamp".into()), Value::Str("ts".into()), &[]).as_i64();
let mut side: Value = self.safe_string_lower_k(trade.clone(), "side", &[]);
if (side.as_str() == Some("long")) {
side = Value::Str("buy".into());
} else if (side.as_str() == Some("short")) {
side = Value::Str("sell".into());
}
let mut isTaker: Option<bool> = self.safe_bool_k_opt(trade.clone(), "taker", &[]);
let mut takerOrMaker: Value = Value::Null;
if (isTaker.is_some()) {
takerOrMaker = (if isTaker == Some(true) { Value::Str("taker".into()) } else { Value::Str("maker".into()) });
}
let mut feeCost: Option<String> = self.safe_string_k_opt(trade.clone(), "fee", &[]);
let mut fee: Value = Value::Null;
if (feeCost.is_some()) {
let mut feeCurrencyId: Option<String> = self.safe_string2_opt(trade.clone(), Value::Str("fee_asset".into()), Value::Str("fea".into()), &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost.map(Value::from).unwrap_or(Value::Null));
m.insert("currency".to_string(), self.safe_currency_code(feeCurrencyId.map(Value::from).unwrap_or(Value::Null), &[]));
m
});
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string2(trade.clone(), Value::Str("trade_id".into()), Value::Str("tid".into()), &[]));
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("order".to_string(), self.safe_string2(trade.clone(), Value::Str("order_id".into()), Value::Str("oid".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(), self.safe_string2(trade.clone(), Value::Str("price".into()), Value::Str("p".into()), &[]));
m.insert("amount".to_string(), self.safe_string2(trade, Value::Str("quantity".into()), Value::Str("qty".into()), &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[marketResolved]);
Value::Null
}
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut paginate: Value = Value::Bool(false);
let mut paramsOmitted: Value = params;
{ let __destr_tmp: Vec<Value> = self.handle_option_and_params(paramsOmitted.clone(), Value::Str("fetchOHLCV".into()), Value::Str("paginate".into()), &[]).as_array().cloned().unwrap_or_default(); paginate = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); paramsOmitted = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".into()), &[symbol.clone(), since.clone(), limit.clone(), timeframe.clone(), paramsOmitted.clone(), Value::Int(1000)]).await;
}
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("interval".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m
});
let mut until: Value = self.safe_integer_k(paramsOmitted.clone(), "until", &[]);
if (until != Value::Null) {
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("until".into()), &[]);
request.insert("end_timestamp".into(), until.clone());
}
let mut duration: Value = (match (&(self.parse_timeframe(timeframe.clone())), &(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 });
if (since != Value::Null) {
request.insert("start_timestamp".into(), since.clone());
} else {
let mut end: Value = (if (until != Value::Null) { until } else { self.milliseconds() });
let mut requestedLimit: Value = (if (limit != Value::Null) { limit.clone() } else { Value::Int(100) });
request.insert("start_timestamp".into(), (match (&(end), &((match (&(((match (&(requestedLimit), &(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 }))), &(duration)) { (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 }));
}
let __ws_arg_2 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.public_get_info_klines(&[__ws_arg_2]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_ohlc_vs(data, &[market, timeframe, since, limit]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_integer(ohlcv.clone(), Value::Int(0), &[]), self.safe_number(ohlcv.clone(), Value::Int(1), &[]), self.safe_number(ohlcv.clone(), Value::Int(2), &[]), self.safe_number(ohlcv.clone(), Value::Int(3), &[]), self.safe_number(ohlcv.clone(), Value::Int(4), &[]), self.safe_number(ohlcv, Value::Int(5), &[])]);
Value::Null
}
pub async fn fetch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut fundingRates: Value = self.fetch_funding_rates(&[Value::from(vec![symbolResolved.clone()]), params]).await;
let mut fundingRate: Value = self.safe_dict(fundingRates, symbolResolved.clone(), &[]);
if (fundingRate == Value::Null) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRate() could not find the funding rate for ".into())).into()), symbolResolved)));
}
return fundingRate;
Value::Null
}
pub async fn fetch_funding_rates(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut response: Value = self.public_get_info_tickers(&[params]).await;
let mut result: Value = self.parse_funding_rates(response, &[]);
return self.index_by(self.filter_by_array(result, Value::Str("symbol".into()), &[symbolsNormalized, Value::Bool(false)]), Value::Str("symbol".into()));
Value::Null
}
pub fn parse_funding_rate(&self, mut contract: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string_k_opt(contract.clone(), "instrument_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut timestamp: Option<i64> = self.safe_integer_k(contract.clone(), "timestamp", &[]).as_i64();
let mut nextFundingTimestamp: Option<i64> = self.safe_integer_k(contract.clone(), "next_funding", &[]).as_i64();
let mut interval: Option<String> = self.safe_string_opt(marketResolved.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("funding_interval".into()), &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("markPrice".to_string(), self.safe_number_k(contract.clone(), "mark_price", &[]));
m.insert("indexPrice".to_string(), self.safe_number_k(contract.clone(), "index_price", &[]));
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("fundingRate".to_string(), self.safe_number_k(contract, "funding_rate", &[]));
m.insert("fundingTimestamp".to_string(), Value::Null);
m.insert("fundingDatetime".to_string(), Value::Null);
m.insert("nextFundingRate".to_string(), Value::Null);
m.insert("nextFundingTimestamp".to_string(), Value::from(nextFundingTimestamp));
m.insert("nextFundingDatetime".to_string(), self.iso8601(Value::from(nextFundingTimestamp)));
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), interval.map(Value::from).unwrap_or(Value::Null));
m
});
Value::Null
}
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
self.load_markets(&[]).await;
let mut paginate: Value = Value::Bool(false);
let mut paramsOmitted: Value = params;
{ let __destr_tmp: Vec<Value> = self.handle_option_and_params(paramsOmitted.clone(), Value::Str("fetchFundingRateHistory".into()), Value::Str("paginate".into()), &[]).as_array().cloned().unwrap_or_default(); paginate = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); paramsOmitted = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchFundingRateHistory".into()), &[symbol.clone(), since.clone(), limit.clone(), Value::Str("1h".into()), paramsOmitted.clone(), Value::Int(100)]).await;
}
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
request.insert("start_timestamp".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(paramsOmitted.clone(), "until", &[]);
if (until != Value::Null) {
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("until".into()), &[]);
request.insert("end_timestamp".into(), until);
}
let __ws_arg_3 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.public_get_info_funding(&[__ws_arg_3]).await;
let mut data: Vec<Value> = self.safe_list_k(response, "data", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rates: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1105: bool = true;
while { if !__for_first_1105 { i += 1; } __for_first_1105 = false; i < (data.len() as i64) } {
let mut entry: Value = data.get(i as usize).cloned().unwrap_or(Value::Null);
let mut timestamp: Option<i64> = self.safe_integer_k(entry.clone(), "timestamp", &[]).as_i64();
rates.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("fundingRate".to_string(), self.safe_number_k(entry, "funding_rate", &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m
}));
}
}
let mut sorted: Value = self.sort_by(Value::from(rates), Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), since, limit]);
Value::Null
}
pub async fn fetch_open_interest(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut symbolResolved: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut openInterests: Value = self.fetch_open_interests(&[Value::from(vec![symbolResolved.clone()]), params]).await;
let mut openInterest: Value = self.safe_dict(openInterests, symbolResolved.clone(), &[]);
if (openInterest == Value::Null) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterest() could not find the open interest for ".into())).into()), symbolResolved)));
}
return openInterest;
Value::Null
}
pub async fn fetch_open_interests(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut response: Value = self.public_get_info_tickers(&[params]).await;
let mut result: Value = self.parse_open_interests(response, &[]);
return self.index_by(self.filter_by_array(result, Value::Str("symbol".into()), &[symbolsNormalized, Value::Bool(false)]), Value::Str("symbol".into()));
Value::Null
}
pub fn parse_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string_k_opt(interest.clone(), "instrument_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut timestamp: Option<i64> = self.safe_integer_k(interest.clone(), "timestamp", &[]).as_i64();
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("openInterestAmount".to_string(), self.safe_string_k(interest.clone(), "open_interest", &[]));
m.insert("openInterestValue".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("info".to_string(), interest);
m
}), &[marketResolved]);
Value::Null
}
pub async fn fetch_trading_fees(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut response: Value = self.public_get_info_fees(&[params]).await;
let mut schedule: Value = self.safe_list_k(response, "fee_schedule", &[Value::from(vec![])]);
let mut byCategory: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: i64 = 0;
let mut __for_first_1106: bool = true;
while { if !__for_first_1106 { i += 1; } __for_first_1106 = false; i < (schedule.len() as i64) } {
let mut entry: Value = schedule.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut category: Option<String> = self.safe_string_k_opt(entry.clone(), "category", &[]);
byCategory.insert(category.as_deref().unwrap_or("null").to_string(), entry.clone());
}
}
let mut fallback: Value = self.safe_dict(schedule, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: i64 = 0;
let mut __for_first_1107: bool = true;
while { if !__for_first_1107 { i += 1; } __for_first_1107 = false; i < (self.symbols.len() as i64) } {
let mut symbol: Value = self.safe_string(self.symbols.clone(), Value::Int(i), &[Value::Str("".into())]);
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol.clone()).as_map().cloned().unwrap_or_default();
let mut category: Option<String> = self.safe_string_k_opt(market.get("info").cloned().unwrap_or(Value::Null), "category", &[]);
let mut entry: Value = self.safe_dict(Value::Map(byCategory.clone()), category.map(Value::from).unwrap_or(Value::Null), &[fallback.clone()]);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("maker".to_string(), self.safe_number_k(entry.clone(), "maker_fee_rate", &[]));
m.insert("taker".to_string(), self.safe_number_k(entry, "taker_fee_rate", &[]));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(true));
m
})); }
}
}
return result;
Value::Null
}
pub fn create_order_request(&self, mut market: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut triggerPrice: Option<String> = self.safe_string_n(params.clone(), Value::from(vec![Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("trailingPercent".into()), Value::Str("trailingAmount".into())]), &[]).as_str().map(str::to_owned);
let mut attached: Value = self.safe_value_n(params.clone(), Value::from(vec![Value::Str("stopLoss".into()), Value::Str("takeProfit".into())]), &[]);
if (triggerPrice.is_some()) || (attached != Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support trigger or attached stop orders yet".into()))));
}
let mut symbol: Value = self.safe_symbol(Value::Null, &[market.clone()]);
let mut isMarketOrder: Value = (Value::Bool(type_var.as_str() == Some("market")));
let mut timeInForce: Value = self.safe_string_upper_k(params.clone(), "timeInForce", &[]);
let mut isPostOnlyTimeInForce: Value = (Value::Bool(timeInForce.as_str() == Some("PO")));
let mut postOnly: Value = Value::Bool(false);
let mut paramsOmitted: Value = params;
{ let __destr_tmp: Vec<Value> = self.handle_post_only(isMarketOrder.clone(), isPostOnlyTimeInForce, &[paramsOmitted.clone()]).as_array().cloned().unwrap_or_default(); postOnly = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); paramsOmitted = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
if matches!(&isMarketOrder, Value::Bool(true)) {
if (timeInForce.as_str() == Some("GTC")) || (timeInForce.as_str() == Some("PO")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support the ".into())).into()), timeInForce).into()), Value::Str(" timeInForce on market orders".into()))));
}
if (timeInForce == Value::Null) {
timeInForce = Value::Str("IOC".into());
}
} else {
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price argument for limit orders".into()))));
}
if (timeInForce == Value::Null) || (timeInForce.as_str() == Some("PO")) {
timeInForce = Value::Str("GTC".into());
}
}
let mut tif: Value = (if let Some(__s) = timeInForce.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null });
let mut reduceOnly: bool = self.safe_bool_k_opt(paramsOmitted.clone(), "reduceOnly", &[Value::Bool(false)]).unwrap_or(false);
let mut clientOrderId: Option<String> = self.safe_string2_opt(paramsOmitted.clone(), Value::Str("clientOrderId".into()), Value::Str("c".into()), &[]);
paramsOmitted = self.omit(paramsOmitted.clone(), Value::from(vec![Value::Str("timeInForce".into()), Value::Str("reduceOnly".into()), Value::Str("clientOrderId".into())]), &[]);
let mut instrumentId: Value = self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
let mut isBuy: Value = (Value::Bool(side.as_str() == Some("buy")));
let mut quantity: Value = self.amount_to_precision(symbol.clone(), amount);
let mut priceString: Value = Value::Null;
if (price != Value::Null) {
priceString = self.price_to_precision(symbol, price);
}
let mut reduceOnlyValue: Value = (if reduceOnly { Value::Bool(true) } else { Value::Null });
let mut row: Value = Value::from(vec![instrumentId.clone(), isBuy.clone(), priceString.clone(), quantity.clone(), tif.clone(), postOnly.clone(), reduceOnlyValue.clone(), clientOrderId.clone().map(Value::from).unwrap_or(Value::Null)]);
let mut signable: Value = self.compact_signable(row);
let mut entry: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("iid".to_string(), instrumentId);
m.insert("buy".to_string(), isBuy);
m.insert("po".to_string(), postOnly);
m.insert("qty".to_string(), quantity);
m.insert("tif".to_string(), tif);
m
});
if (priceString != Value::Null) {
entry.insert("p".into(), priceString);
}
if (reduceOnlyValue != Value::Null) {
entry.insert("ro".into(), reduceOnlyValue);
}
if (clientOrderId.is_some()) {
entry.insert("c".into(), clientOrderId.map(Value::from).unwrap_or(Value::Null));
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("signable".to_string(), signable);
m.insert("entry".to_string(), Value::Map(entry));
m.insert("params".to_string(), paramsOmitted);
m
});
Value::Null
}
pub async fn create_order(&mut self, mut symbol: 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_markets(&[]).await;
let mut order: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("side".to_string(), side);
m.insert("amount".to_string(), amount);
m.insert("price".to_string(), price);
m.insert("params".to_string(), params.clone());
m
});
let mut orders: Value = self.create_orders(Value::from(vec![order]), &[params]).await;
let mut first: Value = self.safe_dict(orders.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut firstStatus: Option<String> = self.safe_string_k(first.clone(), "status", &[]).as_str().map(str::to_owned);
if (firstStatus.as_deref() == Some("rejected")) {
let mut firstInfo: Value = self.safe_dict_k(first, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut errorId: Option<String> = self.safe_string_k_opt(firstInfo.clone(), "error", &[]);
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder() rejected: ".into())).into()), json_stringify(&firstInfo)).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorId.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), errorId.map(Value::from).unwrap_or(Value::Null), feedback.clone());
panic!("{}", crate::exchange_errors::invalid_order(feedback));
}
let mut created: Value = self.safe_dict(orders, Value::Int(0), &[]);
return created;
Value::Null
}
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
}));
let __orders_empty = Vec::new();
let orders = orders.as_array().unwrap_or(&__orders_empty);
self.load_markets(&[]).await;
let mut rows: Vec<Value> = vec![];
let mut entries: Vec<Value> = Vec::new();
let mut ordersMarkets: Vec<Value> = Vec::new();
let mut ordersEntries: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1108: bool = true;
while { if !__for_first_1108 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1108 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = orders.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut symbol: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "symbol", &[]);
let mut market: Value = self.market(symbol.map(Value::from).unwrap_or(Value::Null));
let mut type_var: Option<String> = self.safe_string_lower_k_opt(rawOrder.clone(), "type", &[]);
let mut side: Option<String> = self.safe_string_lower_k_opt(rawOrder.clone(), "side", &[]);
let mut amount: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "amount", &[]);
let mut price: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: indexmap::IndexMap<String, Value> = self.create_order_request(market.clone(), type_var.map(Value::from).unwrap_or(Value::Null), side.map(Value::from).unwrap_or(Value::Null), amount.map(Value::from).unwrap_or(Value::Null), &[price.map(Value::from).unwrap_or(Value::Null), orderParams]).as_map().cloned().unwrap_or_default();
rows.push(request.get("signable").cloned().unwrap_or(Value::Null));
entries.push(request.get("entry").cloned().unwrap_or(Value::Null));
ordersMarkets.push(market);
if let Value::Arr(__a) = &mut ordersEntries { std::sync::Arc::make_mut(__a).push(request.get("entry").cloned().unwrap_or(Value::Null)); }
}
}
let mut signable: Value = Value::from(vec![Value::Str("createOrders".into()), Value::Array(rows)]);
let mut bodyOp: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("createOrders".into()));
m.insert("args".to_string(), Value::from(entries));
m
});
let mut signed: Value = self.sign_perps_op(signable, Value::Map(bodyOp), &[params]).await;
let mut response: Value = self.trade_post_trade_orders(&[signed]).await;
let mut results: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1109: bool = true;
while { if !__for_first_1109 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1109 = false; i.as_f64().unwrap_or(f64::NAN) < ((response.len() as i64) as f64) } {
let mut ack: Value = self.safe_dict(response.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketInner: Value = ordersMarkets.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut echo: Value = self.safe_dict(ordersEntries.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Option<String> = self.safe_string_k(ack.clone(), "status", &[]).as_str().map(str::to_owned);
let __ws_arg_4 = self.safe_integer_k(ack.clone(), "oid", &[]);
let __ws_arg_5 = self.safe_string2(ack.clone(), Value::Str("coid".into()), Value::Str("c".into()), &[]);
let mut merged: Value = self.extend(echo, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("oid".to_string(), __ws_arg_4);
m.insert("coid".to_string(), __ws_arg_5);
m
})]);
if (status.as_deref() == Some("err")) {
if let Value::Dict(__d) = &mut merged { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("rejected".into())); }
} else {
if let Value::Dict(__d) = &mut merged { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Null); }
}
let mut parsed: Value = self.parse_order(merged, &[marketInner]);
if let Value::Dict(__rda) = &mut parsed { std::sync::Arc::make_mut(__rda).insert("info".to_string(), ack); }
results.push(parsed);
}
}
return Value::from(results);
Value::Null
}
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut orders: Value = self.cancel_orders(Value::from(vec![id]), &[symbol, params]).await;
let mut canceled: Value = self.safe_dict(orders, Value::Int(0), &[]);
return canceled;
Value::Null
}
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut clientOrderIds: Value = self.safe_list2(params.clone(), Value::Str("clientOrderIds".into()), Value::Str("clientOrderId".into()), &[]);
if (clientOrderIds == Value::Null) {
let mut clientOrderId: Option<String> = self.safe_string_k_opt(params.clone(), "clientOrderId", &[]);
if (clientOrderId.is_some()) {
clientOrderIds = Value::from(vec![clientOrderId.map(Value::from).unwrap_or(Value::Null)]);
}
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("clientOrderIds".into()), Value::Str("clientOrderId".into())]), &[]);
let mut signable: Value = Value::Null;
let mut bodyOp: Value = Value::Null;
let mut response: Value = Value::Null;
if (clientOrderIds != Value::Null) {
signable = Value::from(vec![Value::Str("cancelOrdersCOID".into()), clientOrderIds.clone()]);
bodyOp = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("cancelOrdersCOID".into()));
m.insert("args".to_string(), clientOrderIds);
m
});
let mut signed: Value = self.sign_perps_op(signable.clone(), bodyOp.clone(), &[paramsOmitted.clone()]).await;
response = self.trade_delete_trade_orders_coid(&[signed.clone()]).await;
} else {
let mut numericIds: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_1110: bool = true;
while { if !__for_first_1110 { i += 1; } __for_first_1110 = false; i < (ids.len() as i64) } {
if let Value::Arr(__a) = &mut numericIds { std::sync::Arc::make_mut(__a).push(self.parse_to_int(self.safe_string(ids.clone(), Value::Int(i), &[]))); };
}
}
signable = Value::from(vec![Value::Str("cancelOrders".into()), numericIds.clone()]);
bodyOp = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("cancelOrders".into()));
m.insert("args".to_string(), numericIds);
m
});
let mut signed: Value = self.sign_perps_op(signable, bodyOp, &[paramsOmitted]).await;
response = self.trade_delete_trade_orders(&[signed]).await;
}
let mut results: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1111: bool = true;
while { if !__for_first_1111 { i += 1; } __for_first_1111 = false; i < (response.len() as i64) } {
let mut ack: Value = self.safe_dict(response.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Option<String> = self.safe_string_k(ack.clone(), "status", &[]).as_str().map(str::to_owned);
let mut unified: Value = (if (status.as_deref() == Some("err")) { Value::Str("rejected".into()) } else { Value::Str("canceled".into()) });
let mut merged: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("oid".to_string(), self.safe_integer_k(ack.clone(), "oid", &[]));
m.insert("coid".to_string(), self.safe_string_k(ack.clone(), "coid", &[]));
m.insert("uts".to_string(), self.safe_integer_k(ack.clone(), "ts", &[]));
m.insert("status".to_string(), unified);
m
});
let mut parsed: Value = self.parse_order(Value::Map(merged), &[]);
if let Value::Dict(__rda) = &mut parsed { std::sync::Arc::make_mut(__rda).insert("info".to_string(), ack); }
results.push(parsed);
}
}
return Value::from(results);
Value::Null
}
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut args: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut signableArgs: Value = Value::from(vec![]);
if (symbol != Value::Null) {
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol).as_map().cloned().unwrap_or_default();
let mut instrumentId: Value = self.parse_to_int(market.get("id").cloned().unwrap_or(Value::Null));
args.insert("iid".into(), instrumentId.clone());
signableArgs = Value::from(vec![instrumentId]);
}
let mut signable: Value = Value::from(vec![Value::Str("cancelAll".into()), signableArgs]);
let mut bodyOp: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("cancelAll".into()));
m.insert("args".to_string(), Value::Map(args));
m
});
let mut signed: Value = self.sign_perps_op(signable, Value::Map(bodyOp), &[]).await;
let mut response: Value = self.trade_delete_trade_orders_all(&[signed]).await;
return Value::from(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[])]);
Value::Null
}
pub async fn cancel_all_orders_after(&mut self, mut timeout: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut deadline: Value = Value::Int(0);
if (timeout != Value::Null) && (timeout.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
deadline = self.sum(&[self.milliseconds(), timeout]);
}
let mut signable: Value = Value::from(vec![Value::Str("autoCancel".into()), Value::from(vec![deadline.clone()])]);
let mut bodyOp: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("autoCancel".into()));
m.insert("args".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("time".to_string(), deadline);
m
}));
m
});
let mut signed: Value = self.sign_perps_op(signable, Value::Map(bodyOp), &[]).await;
let mut response: Value = self.trade_patch_trade_auto_cancel(&[signed]).await;
return response;
Value::Null
}
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
if (amount == Value::Null) || (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires both the amount and the price arguments".into()))));
}
let mut orderId: Value = self.parse_to_int(id);
let mut priceString: Value = self.price_to_precision(market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), price);
let mut quantity: Value = self.amount_to_precision(market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), amount);
let mut signable: Value = Value::from(vec![Value::Str("modifyOrders".into()), Value::from(vec![Value::from(vec![orderId.clone(), priceString.clone(), quantity.clone()])])]);
let mut bodyOp: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("modifyOrders".into()));
m.insert("args".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("oid".to_string(), orderId);
m.insert("p".to_string(), priceString);
m.insert("qty".to_string(), quantity);
m
})]));
m
});
let mut signed: Value = self.sign_perps_op(signable, Value::Map(bodyOp), &[params]).await;
let mut response: Value = self.trade_patch_trade_orders(&[signed]).await;
let mut first: Value = self.safe_dict(response, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Option<String> = self.safe_string_k(first.clone(), "status", &[]).as_str().map(str::to_owned);
if (status.as_deref() == Some("err")) {
let mut merged: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("oid".to_string(), self.safe_integer_k(first.clone(), "oid", &[]));
m.insert("coid".to_string(), self.safe_string_k(first.clone(), "coid", &[]));
m.insert("status".to_string(), Value::Str("rejected".into()));
m
});
let mut rejected: indexmap::IndexMap<String, Value> = self.parse_order(Value::Map(merged), &[market.clone()]).as_map().cloned().unwrap_or_default();
rejected.insert("info".into(), first.clone());
return Value::Map(rejected);
}
let mut order: Value = self.safe_dict_k(first, "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(order, &[market]);
Value::Null
}
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("accepted".to_string(), Value::Str("open".into()));
m.insert("open".to_string(), Value::Str("open".into()));
m.insert("partial".to_string(), Value::Str("open".into()));
m.insert("untriggered".to_string(), Value::Str("open".into()));
m.insert("armed".to_string(), Value::Str("open".into()));
m.insert("triggered".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("cancelled".to_string(), Value::Str("canceled".into()));
m.insert("auto_cancelled".to_string(), Value::Str("canceled".into()));
m.insert("fok_unfilled".to_string(), Value::Str("canceled".into()));
m.insert("ioc_no_fill".to_string(), Value::Str("canceled".into()));
m.insert("ioc_expired".to_string(), Value::Str("canceled".into()));
m.insert("stp_cancelled".to_string(), Value::Str("canceled".into()));
m.insert("reduce_only_expired".to_string(), Value::Str("canceled".into()));
m.insert("parent_cancelled".to_string(), Value::Str("canceled".into()));
m.insert("position_closed".to_string(), Value::Str("canceled".into()));
m.insert("position_flipped".to_string(), Value::Str("canceled".into()));
m.insert("reduce_only_invalid_at_trigger".to_string(), Value::Str("canceled".into()));
m.insert("order_expired".to_string(), Value::Str("expired".into()));
m.insert("expired".to_string(), Value::Str("expired".into()));
m.insert("post_only_rejected".to_string(), Value::Str("rejected".into()));
m.insert("zero_quantity".to_string(), Value::Str("rejected".into()));
m.insert("duplicate_order".to_string(), Value::Str("rejected".into()));
m.insert("order_not_found".to_string(), Value::Str("rejected".into()));
m.insert("reduce_only_invalid".to_string(), Value::Str("rejected".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string2_opt(order.clone(), Value::Str("instrument_id".into()), Value::Str("iid".into()), &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut timestamp: Option<i64> = self.safe_integer2(order.clone(), Value::Str("created_timestamp".into()), Value::Str("cts".into()), &[]).as_i64();
let mut lastUpdateTimestamp: Option<i64> = self.safe_integer2(order.clone(), Value::Str("updated_timestamp".into()), Value::Str("uts".into()), &[]).as_i64();
let mut isBuy: Option<bool> = self.safe_bool_k_opt(order.clone(), "buy", &[]);
let mut side: Value = Value::Null;
if (isBuy.is_some()) {
side = (if isBuy == Some(true) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
}
let mut price: Value = self.omit_zero(self.safe_string2(order.clone(), Value::Str("price".into()), Value::Str("p".into()), &[]));
let mut type_var: Value = Value::Null;
let mut tif: Option<String> = self.safe_string_k(order.clone(), "tif", &[]).as_str().map(str::to_owned);
if (tif.is_some()) {
type_var = (if (price == Value::Null) { Value::Str("market".into()) } else { Value::Str("limit".into()) });
}
let mut tpsl: Value = self.safe_dict_k(order.clone(), "tpsl", &[]);
let mut stopLossPrice: Value = Value::Null;
let mut takeProfitPrice: Value = Value::Null;
if (tpsl != Value::Null) {
let mut kind: Option<String> = self.safe_string_k(tpsl.clone(), "kind", &[]).as_str().map(str::to_owned);
let mut triggerValue: Option<String> = self.safe_string_k_opt(tpsl, "trp", &[]);
if (kind.as_deref() == Some("sl")) {
stopLossPrice = triggerValue.clone().map(Value::from).unwrap_or(Value::Null);
} else if (kind.as_deref() == Some("tp")) {
takeProfitPrice = triggerValue.map(Value::from).unwrap_or(Value::Null);
}
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string2(order.clone(), Value::Str("order_id".into()), Value::Str("oid".into()), &[]));
m.insert("clientOrderId".to_string(), self.safe_string2(order.clone(), Value::Str("client_order_id".into()), Value::Str("coid".into()), &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), Value::from(lastUpdateTimestamp));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), type_var);
m.insert("timeInForce".to_string(), self.safe_string_upper_k(order.clone(), "tif", &[]));
m.insert("postOnly".to_string(), self.safe_bool2(order.clone(), Value::Str("post_only".into()), Value::Str("po".into()), &[]));
m.insert("reduceOnly".to_string(), self.safe_bool_k(order.clone(), "ro", &[]));
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("amount".to_string(), self.safe_string2(order.clone(), Value::Str("quantity".into()), Value::Str("qty".into()), &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("filled".to_string(), self.safe_string2(order.clone(), Value::Str("filled_quantity".into()), Value::Str("fill".into()), &[]));
m.insert("remaining".to_string(), self.safe_string2(order.clone(), Value::Str("resting_quantity".into()), Value::Str("rest".into()), &[]));
m.insert("status".to_string(), self.parse_order_status(self.safe_string_k(order, "status", &[])).map(Value::from).unwrap_or(Value::Null));
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[marketResolved]);
Value::Null
}
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_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut response: Value = self.private_get_account_portfolio(&[params]).await;
let mut margin: Value = self.safe_dict_k(response.clone(), "margin", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Option<i64> = self.safe_integer_k(response.clone(), "timestamp", &[]).as_i64();
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m
});
let mut account: indexmap::IndexMap<String, Value> = self.account().as_map().cloned().unwrap_or_default();
account.insert("total".into(), self.safe_string_k(margin.clone(), "total_account_value", &[]));
account.insert("free".into(), self.safe_string_k(margin.clone(), "available_order_margin", &[]));
account.insert("used".into(), self.safe_string_k(margin, "total_initial_margin", &[]));
result.insert("PUSD".into(), Value::Map(account));
return self.safe_balance(Value::Map(result));
Value::Null
}
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut response: Value = self.private_get_account_portfolio(&[params]).await;
let mut timestamp: Option<i64> = self.safe_integer_k(response.clone(), "timestamp", &[]).as_i64();
let mut rows: Vec<Value> = self.safe_list_k(response, "positions", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut positions: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1112: bool = true;
while { if !__for_first_1112 { i += 1; } __for_first_1112 = false; i < (rows.len() as i64) } {
let mut extended: Value = self.extend(rows.get(i as usize).cloned().unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timestamp".to_string(), Value::from(timestamp));
m
})]);
positions.push(self.parse_position(extended, &[]));
}
}
return self.filter_by_array_positions(Value::from(positions), Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
pub async fn fetch_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut positions: Value = self.fetch_positions(&[Value::from(vec![symbol]), params]).await;
let mut position: Value = self.safe_dict(positions, Value::Int(0), &[]);
return position;
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string_k_opt(position.clone(), "instrument_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut size: Option<String> = self.safe_string_k_opt(position.clone(), "size", &[]);
let mut side: Value = Value::Null;
if (size.is_some()) {
let mut isLong: Value = crate::precise::Precise::stringGt(&size.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("0".into()));
side = (if isLong.as_bool() == Some(true) { Value::Str("long".into()) } else { Value::Str("short".into()) });
}
let mut isCross: Option<bool> = self.safe_bool_k_opt(position.clone(), "cross", &[]);
let mut marginMode: Value = Value::Null;
if (isCross.is_some()) {
marginMode = (if isCross == Some(true) { Value::Str("cross".into()) } else { Value::Str("isolated".into()) });
}
let mut timestamp: Option<i64> = self.safe_integer_k(position.clone(), "timestamp", &[]).as_i64();
let mut roe: Option<String> = self.safe_string_k_opt(position.clone(), "return_on_equity", &[]);
let mut percentage: Value = Value::Null;
if (roe.is_some()) {
percentage = self.parse_number(crate::precise::Precise::stringMul(&roe.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("100".into())), &[]);
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("lastUpdateTimestamp".to_string(), Value::Null);
m.insert("initialMargin".to_string(), self.safe_number_k(position.clone(), "initial_margin", &[]));
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), self.safe_number_k(position.clone(), "maintenance_margin", &[]));
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "entry_price", &[]));
m.insert("notional".to_string(), self.safe_number_k(position.clone(), "position_value", &[]));
m.insert("leverage".to_string(), self.safe_integer_k(position.clone(), "leverage", &[]));
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "unrealized_pnl", &[]));
m.insert("realizedPnl".to_string(), Value::Null);
m.insert("contracts".to_string(), self.parse_number(crate::precise::Precise::stringAbs(&size.clone().map(Value::from).unwrap_or(Value::Null)), &[]));
m.insert("contractSize".to_string(), marketResolved.as_map().and_then(|__m| __m.get("contractSize")).cloned().unwrap_or(Value::Null));
m.insert("marginRatio".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), self.parse_number(self.omit_zero(self.safe_string_k(position.clone(), "liquidation_price", &[])), &[]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("lastPrice".to_string(), Value::Null);
m.insert("collateral".to_string(), self.safe_number_k(position, "initial_margin", &[]));
m.insert("marginMode".to_string(), marginMode);
m.insert("side".to_string(), side);
m.insert("percentage".to_string(), percentage);
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
request.insert("instrument_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
let __ws_arg_6 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_get_account_open_orders(&[__ws_arg_6]).await;
return self.parse_orders(response, &[market, since, limit]);
Value::Null
}
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
request.insert("instrument_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
if (since != Value::Null) {
request.insert("start_timestamp".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = params;
if (until != Value::Null) {
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("until".into()), &[]);
request.insert("end_timestamp".into(), until);
}
let mut clientOrderId: Option<String> = self.safe_string_k_opt(paramsOmitted.clone(), "clientOrderId", &[]);
if (clientOrderId.is_some()) {
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("clientOrderId".into()), &[]);
request.insert("client_order_id".into(), clientOrderId.map(Value::from).unwrap_or(Value::Null));
}
let __ws_arg_7 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.private_get_account_orders(&[__ws_arg_7]).await;
return self.parse_orders(response, &[market, since, limit]);
Value::Null
}
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id.clone());
m
});
let __ws_arg_8 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_get_account_orders(&[__ws_arg_8]).await;
{
let mut i: i64 = 0;
let mut __for_first_1113: bool = true;
while { if !__for_first_1113 { i += 1; } __for_first_1113 = false; i < (response.len() as i64) } {
let mut row: Value = self.safe_dict(response.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rowId: Option<String> = self.safe_string_k_opt(row.clone(), "order_id", &[]);
if (rowId.as_deref() == id.as_str()) {
return self.parse_order(row, &[market.clone()]);
}
}
}
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder() could not find the order ".into())).into()), id)));
Value::Null
}
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (since != Value::Null) {
request.insert("start_timestamp".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = params;
if (until != Value::Null) {
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("until".into()), &[]);
request.insert("end_timestamp".into(), until);
}
let __ws_arg_9 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.private_get_account_fills(&[__ws_arg_9]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(data, &[market, since, limit]);
Value::Null
}
pub async fn fetch_funding_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut market: Value = Value::Null;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
let mut symbolMarket: Value = self.market(symbol.clone());
market = symbolMarket.clone();
request.insert("instrument_id".into(), symbolMarket.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
if (since != Value::Null) {
request.insert("start_timestamp".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = params;
if (until != Value::Null) {
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("until".into()), &[]);
request.insert("end_timestamp".into(), until);
}
let __ws_arg_10 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.private_get_account_funding(&[__ws_arg_10]).await;
let mut data: Vec<Value> = self.safe_list_k(response, "data", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1114: bool = true;
while { if !__for_first_1114 { i += 1; } __for_first_1114 = false; i < (data.len() as i64) } {
let mut entry: Value = data.get(i as usize).cloned().unwrap_or(Value::Null);
let mut marketId: Option<String> = self.safe_string_k_opt(entry.clone(), "instrument_id", &[]);
let mut timestamp: Option<i64> = self.safe_integer_k(entry.clone(), "timestamp", &[]).as_i64();
result.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.map(Value::from).unwrap_or(Value::Null), &[market.clone()]));
m.insert("code".to_string(), self.safe_currency_code(self.safe_string_k(entry.clone(), "funding_asset", &[]), &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("id".to_string(), self.safe_string_k(entry.clone(), "id", &[]));
m.insert("amount".to_string(), self.safe_number_k(entry, "funding", &[]));
m
}));
}
}
return self.filter_by_symbol_since_limit(Value::from(result), &[symbol, since, limit]);
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value) -> Option<String> {
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("pending".to_string(), Value::Str("pending".into()));
m.insert("confirmed".to_string(), Value::Str("ok".into()));
m.insert("removed".to_string(), Value::Str("failed".into()));
m.insert("failed".to_string(), Value::Str("failed".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let mut withdrawId: Option<String> = self.safe_string_k_opt(transaction.clone(), "withdraw_id", &[]);
let mut type_var: Value = (if (withdrawId.is_some()) { Value::Str("withdrawal".into()) } else { Value::Str("deposit".into()) });
let mut currencyId: Option<String> = self.safe_string_k_opt(transaction.clone(), "asset", &[]);
let mut code: Value = self.safe_currency_code(currencyId.map(Value::from).unwrap_or(Value::Null), &[currency]);
let mut timestamp: Option<i64> = self.safe_integer_k(transaction.clone(), "created_timestamp", &[]).as_i64();
let mut rawHash: Value = self.safe_string_k(transaction.clone(), "hash", &[]);
let mut txid: Value = (if (rawHash.as_str() == Some("0x")) { Value::Null } else { rawHash });
let mut feeCost: Option<String> = self.safe_string_k_opt(transaction.clone(), "fee", &[]);
let mut fee: Value = Value::Null;
if (feeCost.is_some()) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(feeCost.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("currency".to_string(), code.clone());
m
});
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), withdrawId.map(Value::from).unwrap_or(Value::Null));
m.insert("txid".to_string(), txid);
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("network".to_string(), Value::Null);
m.insert("address".to_string(), Value::Null);
m.insert("addressTo".to_string(), self.safe_string_k(transaction.clone(), "to", &[]));
m.insert("addressFrom".to_string(), self.safe_string_k(transaction.clone(), "from", &[]));
m.insert("tag".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), type_var);
m.insert("amount".to_string(), self.safe_number_k(transaction.clone(), "amount", &[]));
m.insert("currency".to_string(), code);
m.insert("status".to_string(), self.parse_transaction_status(self.safe_string_k(transaction.clone(), "status", &[])).map(Value::from).unwrap_or(Value::Null));
m.insert("updated".to_string(), self.safe_integer_k(transaction, "confirmed_timestamp", &[]));
m.insert("comment".to_string(), Value::Null);
m.insert("internal".to_string(), Value::Bool(false));
m.insert("fee".to_string(), fee);
m
});
Value::Null
}
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (since != Value::Null) {
request.insert("start_timestamp".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = params;
if (until != Value::Null) {
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("until".into()), &[]);
request.insert("end_timestamp".into(), until);
}
let __ws_arg_11 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.private_get_account_deposits(&[__ws_arg_11]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
}
return self.parse_transactions(data, &[currency, since, limit]);
Value::Null
}
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (since != Value::Null) {
request.insert("start_timestamp".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = params;
if (until != Value::Null) {
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("until".into()), &[]);
request.insert("end_timestamp".into(), until);
}
let __ws_arg_12 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.private_get_account_withdrawals(&[__ws_arg_12]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
}
return self.parse_transactions(data, &[currency, since, limit]);
Value::Null
}
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
self.load_markets(&[]).await;
let mut currency: Value = self.currency(code);
let mut owner: Value = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
let mut collateral: Value = self.safe_dict_k(self.options.clone(), "collateral", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut tokenAddress: Option<String> = self.safe_string_k_opt(collateral.clone(), "address", &[]);
let mut decimals: Value = self.safe_string_k(collateral, "decimals", &[Value::Str("6".into())]);
let mut precision: Value = self.parse_precision(&[decimals]);
let mut precised: Value = self.decimal_to_precision(self.number_to_string(amount), Value::Int(crate::runtime::TRUNCATE), self.parse_number(precision.clone(), &[]), &[Value::Int(crate::runtime::TICK_SIZE)]);
let mut baseUnits: Value = crate::precise::Precise::stringDiv(&precised, &precision);
let mut ts: Value = self.seconds();
let mut salt: Value = self.rand_number(Value::Int(9));
let mut chainId: Option<i64> = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(137)]).as_i64();
let mut contract: Value = self.safe_string_k(self.options.clone(), "depositContract", &[Value::Str("0xDCa4af75705dbB50f62437045afF9921947917d2".into())]);
let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("Polymarket".into()));
m.insert("version".to_string(), Value::Str("1".into()));
m.insert("chainId".to_string(), Value::from(chainId));
m.insert("verifyingContract".to_string(), contract);
m
});
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("Withdraw".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("account".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("token".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("amount".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("fee".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("to".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("uint64".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("ts".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
let mut message: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("account".to_string(), owner.clone());
m.insert("token".to_string(), tokenAddress.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("amount".to_string(), self.parse_to_int(baseUnits.clone()));
m.insert("fee".to_string(), Value::Int(0));
m.insert("to".to_string(), address.clone());
m.insert("salt".to_string(), salt.clone());
m.insert("ts".to_string(), ts.clone());
m
});
let mut encoded: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map(messageTypes), Value::Map(message));
let mut signature: Value = self.sign_message(encoded, self.privateKey.clone());
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("withdraw".into()));
m.insert("args".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account".to_string(), owner);
m.insert("token".to_string(), tokenAddress.map(Value::from).unwrap_or(Value::Null));
m.insert("amount".to_string(), baseUnits);
m.insert("to".to_string(), address);
m
}));
m
}));
m.insert("salt".to_string(), salt);
m.insert("sig".to_string(), signature);
m.insert("ts".to_string(), ts);
m
});
let __ws_arg_13 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.trade_post_account_withdraw(&[__ws_arg_13]).await;
let mut stripped: Value = self.omit(response, Value::Str("status".into()), &[]);
let mut transaction: indexmap::IndexMap<String, Value> = self.parse_transaction(stripped, &[currency]).as_map().cloned().unwrap_or_default();
transaction.insert("status".into(), Value::Str("pending".into()));
return Value::Map(transaction);
Value::Null
}
pub async fn fetch_leverage(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
self.load_proxy_credentials(&[]).await;
let mut market: Value = self.market(symbol.clone());
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("instrument_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_14 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_get_account_config(&[__ws_arg_14]).await;
{
let mut i: i64 = 0;
let mut __for_first_1115: bool = true;
while { if !__for_first_1115 { i += 1; } __for_first_1115 = false; i < (response.len() as i64) } {
let mut row: Value = self.safe_dict(response.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rowId: Option<String> = self.safe_string_k_opt(row.clone(), "instrument_id", &[]);
if (rowId.as_deref() == market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null).as_str()) {
return self.parse_leverage(row, &[market.clone()]);
}
}
}
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchLeverage() could not find the configuration for ".into())).into()), symbol)));
Value::Null
}
pub fn parse_leverage(&self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string_k_opt(leverage.clone(), "instrument_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut isCross: Option<bool> = self.safe_bool_k_opt(leverage.clone(), "cross", &[]);
let mut marginMode: Value = Value::Null;
if (isCross.is_some()) {
marginMode = (if isCross == Some(true) { Value::Str("cross".into()) } else { Value::Str("isolated".into()) });
}
let mut value: Option<i64> = self.safe_integer_k(leverage.clone(), "leverage", &[]).as_i64();
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), leverage);
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("marginMode".to_string(), marginMode);
m.insert("longLeverage".to_string(), Value::from(value));
m.insert("shortLeverage".to_string(), Value::from(value));
m
});
Value::Null
}
pub async fn fetch_margin_mode(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut leverage: Value = self.fetch_leverage(symbol, &[params]).await;
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), self.safe_dict_k(leverage.clone(), "info", &[]));
m.insert("symbol".to_string(), self.safe_string_k(leverage.clone(), "symbol", &[]));
m.insert("marginMode".to_string(), self.safe_string_k(leverage, "marginMode", &[]));
m
});
Value::Null
}
pub async fn set_leverage(&mut self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut symbol = 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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a symbol argument".into()))));
}
self.load_markets(&[]).await;
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol).as_map().cloned().unwrap_or_default();
let mut marginMode: Value = Value::Null;
let mut paramsOmitted: Value = params;
{ let __destr_tmp: Vec<Value> = self.handle_margin_mode_and_params(Value::Str("setLeverage".into()), &[paramsOmitted.clone(), Value::Str("cross".into())]).as_array().cloned().unwrap_or_default(); marginMode = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); paramsOmitted = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
let mut isCross: Value = (Value::Bool(marginMode.as_str() != Some("isolated")));
let mut instrumentId: Value = self.parse_to_int(market.get("id").cloned().unwrap_or(Value::Null));
let mut leverageInt: Value = self.parse_to_int(leverage);
let mut signable: Value = Value::from(vec![Value::Str("updateLeverage".into()), Value::from(vec![instrumentId.clone(), leverageInt.clone(), isCross.clone()])]);
let mut bodyOp: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateLeverage".into()));
m.insert("args".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cross".to_string(), isCross);
m.insert("iid".to_string(), instrumentId);
m.insert("lev".to_string(), leverageInt);
m
}));
m
});
let mut signed: Value = self.sign_perps_op(signable, Value::Map(bodyOp), &[]).await;
let mut response: Value = self.trade_patch_trade_leverage(&[signed]).await;
return response;
Value::Null
}
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = 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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a symbol argument".into()))));
}
let mut leverage: Value = self.safe_integer_k(params.clone(), "leverage", &[]);
if (leverage == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a params.leverage argument, the venue updates the mode and the leverage in one operation".into()))));
}
let mut paramsOmitted: Value = self.omit(params, Value::Str("leverage".into()), &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), marginMode);
m
});
let mut leverageInt: Value = self.parse_to_int(leverage);
let __ws_arg_15 = self.extend(Value::Map(request), &[paramsOmitted]);
return self.set_leverage(leverageInt, &[symbol, __ws_arg_15]).await;
Value::Null
}
pub async fn modify_margin_helper(&mut self, mut symbol: Value, mut amount: Value, mut type_var: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut instrumentId: Value = self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
let mut collateral: Value = self.safe_dict_k(self.options.clone(), "collateral", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut decimals: Value = self.safe_string_k(collateral, "decimals", &[Value::Str("6".into())]);
let mut precision: Value = self.parse_precision(&[decimals]);
let mut amountString: Value = self.decimal_to_precision(self.number_to_string(amount), Value::Int(crate::runtime::TRUNCATE), self.parse_number(precision, &[]), &[Value::Int(crate::runtime::TICK_SIZE)]);
if (type_var.as_str() == Some("reduce")) {
amountString = Value::Str(format!("{}{}", Value::Str("-".into()), amountString).into());
}
let mut signable: Value = Value::from(vec![Value::Str("updateMargin".into()), Value::from(vec![instrumentId.clone(), amountString.clone()])]);
let mut bodyOp: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateMargin".into()));
m.insert("args".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amt".to_string(), amountString.clone());
m.insert("iid".to_string(), instrumentId);
m
}));
m
});
let mut signed: Value = self.sign_perps_op(signable, Value::Map(bodyOp), &[]).await;
let mut response: Value = self.trade_patch_trade_margin(&[signed]).await;
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), type_var);
m.insert("marginMode".to_string(), Value::Str("isolated".into()));
m.insert("amount".to_string(), self.parse_number(amountString, &[]));
m.insert("total".to_string(), Value::Null);
m.insert("code".to_string(), market.as_map().and_then(|__m| __m.get("settle")).cloned().unwrap_or(Value::Null));
m.insert("status".to_string(), Value::Str("ok".into()));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
Value::Null
}
pub async fn add_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Str("add".into()), &[params]).await;
Value::Null
}
pub async fn reduce_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Str("reduce".into()), &[params]).await;
Value::Null
}
pub fn hash_message(&self, mut message: Value) -> Value {
return Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(message, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
Value::Null
}
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Value {
let mut signature: Value = ecdsa((match (&(hash), (-64i64), (match &(Value::Null) { Value::Int(__n) => Some(*__n), Value::Float(__f) => Some(*__f as i64), Value::Str(__s) => __s.parse::<i64>().ok(), Value::Bool(__b) => Some(if *__b { 1 } else { 0 }), _ => None })) { (Value::Str(__sv), __b,
__e) => match (__sv.chars().count() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l, Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i,
__j) => if __i <= __j { Value::Str(__sv.chars().skip(__i as usize).take((__j - __i) as usize).collect::<String>().into()) } else { Value::Str(String::new().into()) } } }, (Value::Arr(__a), __b, __e) => match (__a.len() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l,
Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i, __j) => if __i <= __j { Value::Array(__a[__i as usize..__j as usize].to_vec()) } else { Value::Array(vec![]) } } }, _ => Value::Null }), (match (&(privateKey), (-64i64), (match &(Value::Null) { Value::Int(__n) => Some(*__n), Value::Float(__f) => Some(*__f as i64),
Value::Str(__s) => __s.parse::<i64>().ok(), Value::Bool(__b) => Some(if *__b { 1 } else { 0 }), _ => None })) { (Value::Str(__sv), __b, __e) => match (__sv.chars().count() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l,
Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i, __j) => if __i <= __j { Value::Str(__sv.chars().skip(__i as usize).take((__j - __i) as usize).collect::<String>().into()) } else { Value::Str(String::new().into()) } } }, (Value::Arr(__a), __b,
__e) => match (__a.len() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l, Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i, __j) => if __i <= __j { Value::Array(__a[__i as usize..__j as usize].to_vec()) } else { Value::Array(vec![]) } } }, _ => Value::Null }),
Value::Str("secp256k1".into()), Value::Null);
let mut r: Value = signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null);
let mut sVal: Value = signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null);
let mut v: Value = self.int_to_base16(self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]), &[]);
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), r.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null)).into()), sVal.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null)).into()), v).into());
Value::Null
}
pub fn sign_message(&self, mut message: Value, mut privateKey: Value) -> Value {
return self.sign_hash(self.hash_message(message), privateKey);
Value::Null
}
pub async fn create_proxy_credentials(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
let mut nonceMessage: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("polymarket-perps-proxy:".into()), Value::Str(format!("{}", self.milliseconds()).into())).into()), Value::Str(":".into())).into()), Value::Str(format!("{}", self.rand_number(Value::Int(9))).into())).into());
let mut seedSignature: Value = self.sign_message(nonceMessage, self.privateKey.clone());
let mut proxyPrivateKey: Value = self.hash(self.encode(seedSignature), Value::Str("keccak".into()), &[Value::Str("hex".into())]);
let mut proxyAddress: Value = self.eth_get_address_from_private_key(proxyPrivateKey.clone(), &[]);
let mut owner: Value = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
let mut ts: Value = self.milliseconds();
let mut lifetime: Value = self.safe_integer_k(self.options.clone(), "proxyExpiry", &[Value::Int(604800000)]);
let mut expiry: Value = self.sum(&[ts.clone(), lifetime]);
let mut salt: Value = self.rand_number(Value::Int(9));
let mut chainId: Option<i64> = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(137)]).as_i64();
let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("Polymarket".into()));
m.insert("version".to_string(), Value::Str("1".into()));
m.insert("chainId".to_string(), Value::from(chainId));
m
});
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("CreateProxy".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("addr".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("exp".into()));
m.insert("type".to_string(), Value::Str("uint64".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("uint64".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("ts".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
let mut message: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("addr".to_string(), proxyAddress.clone());
m.insert("exp".to_string(), expiry.clone());
m.insert("salt".to_string(), salt.clone());
m.insert("ts".to_string(), ts.clone());
m
});
let mut encoded: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map(messageTypes), Value::Map(message));
let mut signature: Value = self.sign_message(encoded, self.privateKey.clone());
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("createProxy".into()));
m.insert("args".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("expiry".to_string(), expiry.clone());
m.insert("owner".to_string(), owner);
m.insert("proxy".to_string(), proxyAddress.clone());
m
}));
m
}));
m.insert("salt".to_string(), salt);
m.insert("sig".to_string(), signature);
m.insert("ts".to_string(), ts);
m
});
let __ws_arg_16 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.trade_post_account_proxy(&[__ws_arg_16]).await;
let mut credentials: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("proxy".to_string(), proxyAddress);
m.insert("privateKey".to_string(), proxyPrivateKey);
m.insert("secret".to_string(), self.safe_string_k(response, "secret", &[]));
m.insert("expires".to_string(), expiry);
m
});
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("proxyCredentials".into(), Value::Map(credentials.clone())); }
return Value::Map(credentials);
Value::Null
}
pub async fn load_proxy_credentials(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut credentials: Value = self.safe_dict_k(self.options.clone(), "proxyCredentials", &[]);
if (credentials != Value::Null) {
let mut expires: Value = self.safe_integer_k(credentials.clone(), "expires", &[]);
let mut margin: Value = self.safe_integer_k(self.options.clone(), "proxyRefreshMargin", &[Value::Int(3600000)]);
if (expires == Value::Null) {
return credentials;
}
let mut refreshAfter: Value = (match (&(expires), &(margin)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
if self.milliseconds().as_f64().unwrap_or(f64::NAN) < refreshAfter.as_f64().unwrap_or(f64::NAN) {
return credentials;
}
}
return self.create_proxy_credentials(&[params]).await;
Value::Null
}
pub async fn sign_perps_op(&mut self, mut signable: Value, mut bodyOp: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __params_empty = indexmap::IndexMap::new();
let params = params.as_map().unwrap_or(&__params_empty);
let mut credentials: Value = self.load_proxy_credentials(&[]).await;
let mut packed: Value = self.packb(signable, &[]);
let mut dataHash: Value = self.hash_message(packed);
let mut ts: Value = self.milliseconds();
let mut salt: Value = self.rand_number(Value::Int(9));
let mut chainId: Option<i64> = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(137)]).as_i64();
let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("Polymarket".into()));
m.insert("version".to_string(), Value::Str("1".into()));
m.insert("chainId".to_string(), Value::from(chainId));
m
});
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("Op".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("data".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("salt".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("ts".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
let mut message: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("data".to_string(), dataHash);
m.insert("salt".to_string(), salt.clone());
m.insert("ts".to_string(), ts.clone());
m
});
let mut encoded: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map(messageTypes), Value::Map(message));
let mut proxyPrivateKey: Option<String> = self.safe_string_k_opt(credentials, "privateKey", &[]);
let mut signature: Value = self.sign_message(encoded, proxyPrivateKey.map(Value::from).unwrap_or(Value::Null));
let mut envelope: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("op".to_string(), bodyOp);
m.insert("sig".to_string(), signature);
m.insert("salt".to_string(), salt);
m.insert("ts".to_string(), ts);
m
});
let mut exp: Value = (match params.get("exp") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if (exp != Value::Null) {
envelope.insert("exp".into(), exp);
}
return Value::Map(envelope);
Value::Null
}
pub fn compact_signable(&self, mut row: Value) -> Value {
let __row_empty = Vec::new();
let row = row.as_array().unwrap_or(&__row_empty);
let mut result: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1116: bool = true;
while { if !__for_first_1116 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1116 = false; i.as_f64().unwrap_or(f64::NAN) < ((row.len() as i64) as f64) } {
if (row.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null) != Value::Null) {
result.push(row.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
}
}
}
return Value::from(result);
Value::Null
}
pub fn price_to_precision(&self, mut symbol: Value, mut price: Value) -> Value {
if (price == Value::Null) {
return Value::Null;
}
let mut market: Value = self.market(symbol);
let mut precision: indexmap::IndexMap<String, Value> = self.safe_dict_k(market.clone(), "precision", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).as_map().cloned().unwrap_or_default();
let mut significant: Value = self.decimal_to_precision(price, Value::Int(crate::runtime::ROUND), Value::Int(5), &[Value::Int(crate::runtime::SIGNIFICANT_DIGITS)]);
let mut result: Value = self.decimal_to_precision(significant, Value::Int(crate::runtime::ROUND), precision.get("price").cloned().unwrap_or(Value::Null), &[Value::Int(crate::runtime::TICK_SIZE)]);
if (result.as_str() == Some("0")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" price of ".into())).into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into()),
Value::Str(" must be greater than minimum price precision of ".into())).into()), self.number_to_string(precision.get("price").cloned().unwrap_or(Value::Null)))));
}
return result;
Value::Null
}
pub fn amount_to_precision(&self, mut symbol: Value, mut amount: Value) -> Value {
if (amount == Value::Null) {
return Value::Null;
}
let mut market: Value = self.market(symbol);
let mut precision: indexmap::IndexMap<String, Value> = self.safe_dict_k(market.clone(), "precision", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).as_map().cloned().unwrap_or_default();
let mut significant: Value = self.decimal_to_precision(amount, Value::Int(crate::runtime::TRUNCATE), Value::Int(5), &[Value::Int(crate::runtime::SIGNIFICANT_DIGITS)]);
let mut result: Value = self.decimal_to_precision(significant, Value::Int(crate::runtime::TRUNCATE), precision.get("amount").cloned().unwrap_or(Value::Null), &[Value::Int(crate::runtime::TICK_SIZE)]);
if (result.as_str() == Some("0")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" amount of ".into())).into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into()),
Value::Str(" must be greater than minimum amount precision of ".into())).into()), self.number_to_string(precision.get("amount").cloned().unwrap_or(Value::Null)))));
}
return result;
Value::Null
}
pub fn calculate_rate_limiter_cost(&self, mut api: Value, mut method: Value, mut path: Value, mut params: Value, optional_args: &[Value]) -> Value {
let mut config = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (path.as_str() == Some("account/orders")) {
return (if (in_op(¶ms, &Value::Str("order_id".into()))) { Value::Int(1) } else { Value::Int(10) });
}
if (path.as_str() == Some("account/open-orders")) {
return (if (in_op(¶ms, &Value::Str("instrument_id".into()))) { Value::Int(1) } else { Value::Int(20) });
}
if (path.as_str() == Some("trade/orders")) || (path.as_str() == Some("trade/orders-coid")) {
let mut op: Value = self.safe_dict_k(params.clone(), "op", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut args: Vec<Value> = self.safe_list_k(op, "args", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
return self.sum(&[Value::Int(1), self.parse_to_int((match ((Value::Int(args.len() as i64)).as_f64(), (Value::Int(20)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))]);
}
if (path.as_str() == Some("info/book")) {
let mut depth: Value = self.safe_integer_k(params, "depth", &[Value::Int(100)]);
if depth.as_f64().unwrap_or(f64::NAN) <= ((10i64) as f64) {
return Value::Int(2);
} else if depth.as_f64().unwrap_or(f64::NAN) <= ((100i64) as f64) {
return Value::Int(5);
} else if depth.as_f64().unwrap_or(f64::NAN) <= ((500i64) as f64) {
return Value::Int(10);
}
return Value::Int(20);
}
return self.safe_value_k(config, "cost", &[Value::Int(1)]);
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("public".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 apiType: Value = api.get(0).cloned().unwrap_or(Value::Null);
let baseUrl: String = self.safe_string_opt(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), apiType.clone(), &[Value::Str("".into())]).unwrap_or_default();
let mut implodedPath: Value = self.implode_params(path.clone(), params.clone());
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseUrl, Value::Str("/".into())).into()), implodedPath).into());
let mut query: Value = self.omit(params, self.extract_params(path), &[]);
let mut headersResolved: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("Accept".to_string(), Value::Str("application/json".into()));
m
});
let mut bodyResolved: Value = Value::Null;
if (apiType.as_str() == Some("trade")) {
bodyResolved = json_stringify(&query);
headersResolved.insert("Content-Type".into(), Value::Str("application/json".into()));
} else {
if (method.as_str() == Some("GET")) {
let mut keys: Vec<Value> = Value::Array(query.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 keysLength: f64 = ((keys.len() as i64) as f64);
if keysLength > ((0i64) as f64) {
url = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseUrl, Value::Str("/".into())).into()), implodedPath).into()), Value::Str("?".into())).into()), self.urlencode(query, &[])).into());
}
}
if (apiType.as_str() == Some("private")) {
let mut credentials: Value = self.safe_dict_k(self.options.clone(), "proxyCredentials", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
headersResolved.insert("POLYMARKET-PROXY".into(), self.safe_string_k(credentials.clone(), "proxy", &[]));
headersResolved.insert("POLYMARKET-SECRET".into(), self.safe_string_k(credentials, "secret", &[]));
}
}
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(), bodyResolved);
m.insert("headers".to_string(), Value::Map(headersResolved));
m
});
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
let mut source: Value = response.clone();
if (matches!(&response, Value::Arr(_))) && (code.as_f64().unwrap_or(f64::NAN) >= ((400i64) as f64)) {
source = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
let mut status: Option<String> = self.safe_string_k(source.clone(), "status", &[]).as_str().map(str::to_owned);
let mut error: Option<String> = self.safe_string_k_opt(source, "error", &[]);
if (status.as_deref() == Some("err")) || (error.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), error.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), error.map(Value::from).unwrap_or(Value::Null), feedback.clone());
if (code.as_f64() == Some(400.0)) {
panic!("{}", crate::exchange_errors::bad_request(feedback));
}
let mut codeAsString: Value = Value::Str(format!("{}", code).into());
if (code.as_f64().unwrap_or(f64::NAN) < ((400i64) as f64)) || !(matches!((&self.httpExceptions, &codeAsString), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
}
return Value::Null;
Value::Null
}
}