// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
use crate::pro::*;
use crate::prediction_exchange_generated::PredictionBase;
use crate::prediction_exchange::PredictionRuntime;
pub struct MyriadCore {
pub exchange: crate::prediction_exchange::PredictionExchange,
}
impl MyriadCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::prediction_exchange::PredictionExchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = MyriadCore::describe(self);
self.initialize_properties(described);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for MyriadCore {
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MyriadCore.
MyriadCore::parse_ohlcv(self, ohlcv, &[market.clone()])
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MyriadCore.
MyriadCore::parse_prediction_trade(self, trade, &[market.clone()])
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MyriadCore.
MyriadCore::parse_prediction_order(self, order, &[market.clone()])
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MyriadCore.
MyriadCore::parse_prediction_position(self, position, &[market.clone()])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on MyriadCore.
MyriadCore::sign(self, path, &[api.clone(), method.clone(), params.clone(), headers.clone(), body.clone()])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on MyriadCore.
MyriadCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for MyriadCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"build_orderbook_order" => self.build_orderbook_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.get(4..).unwrap_or(&[]).to_vec()[..]),
"cancel_all_orders" => self.cancel_all_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"clob_order_message" => self.clob_order_message(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"connect_centrifugo" => self.connect_centrifugo(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"create_amm_order" => self.create_amm_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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"create_orderbook_order" => self.create_orderbook_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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"ensure_erc20_allowance" => self.ensure_erc20_allowance(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)).await,
"eth_rpc" => self.eth_rpc(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)).await,
"fetch_amm_orders" => self.fetch_amm_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_balance" => self.fetch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_event" => self.fetch_event(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_events" => self.fetch_events(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_markets" => self.fetch_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_orders" => self.fetch_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions" => self.fetch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_raw_market_by_id" => self.fetch_raw_market_by_id(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_raw_markets_by_search" => self.fetch_raw_markets_by_search(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_raw_markets_list" => self.fetch_raw_markets_list(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_raw_question_by_id" => self.fetch_raw_question_by_id(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_raw_questions_by_search" => self.fetch_raw_questions_by_search(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_raw_questions_list" => self.fetch_raw_questions_list(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers" => self.fetch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trade_quote" => self.fetch_trade_quote(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..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"from_wei" => self.from_wei(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"from_wei_with_decimals" => self.from_wei_with_decimals(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"get_order_response_from_params" => self.get_order_response_from_params(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"hex_to_decimal_string" => self.hex_to_decimal_string(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"market_outcome_to_symbol" => self.market_outcome_to_symbol(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)),
"order_to_trade" => self.order_to_trade(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_amm_event_to_order" => self.parse_amm_event_to_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_event" => self.parse_event(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_market_to_event" => self.parse_market_to_event(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_myriad_market" => self.parse_myriad_market(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_position" => self.parse_prediction_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_prediction_trade" => self.parse_prediction_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_trade_quote" => self.parse_trade_quote(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_trade_tx" => self.parse_trade_tx(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)),
"parse_wei_order_book" => self.parse_wei_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"pong" => self.pong(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"request_id" => self.request_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"seed_order_book" => self.seed_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"seed_position_balances" => self.seed_position_balances(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"sign_cancel_all" => self.sign_cancel_all(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_clob_order" => self.sign_clob_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_evm_transaction" => self.sign_evm_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_orderbook_typed_data" => self.sign_orderbook_typed_data(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)),
"subscribe_myriad_channel" => self.subscribe_myriad_channel(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"to_orderbook_wei" => self.to_orderbook_wei(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"wallet_address_from_keys" => self.wallet_address_from_keys(),
"wallet_address_or_undefined" => self.wallet_address_or_undefined(),
"watch_my_trades" => self.watch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_ohlcv" => self.watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_orders" => self.watch_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_positions" => self.watch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"watch_tickers" => self.watch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
// Prediction Core: fall through to prediction base methods (then Exchange base).
_ => self.call_dynamic_prediction_base(method, args).await,
}
})
}
}
impl crate::prediction_exchange_generated::PredictionBase for MyriadCore {
fn pred(&self) -> &crate::prediction_exchange::PredictionExchange { &self.exchange }
fn pred_mut(&mut self) -> &mut crate::prediction_exchange::PredictionExchange { &mut self.exchange }
}
impl std::ops::Deref for MyriadCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}
impl std::ops::DerefMut for MyriadCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.exchange) }
}
impl MyriadCore {
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("myriad".to_string()));
m.insert("name".to_string(), Value::Str("Myriad".to_string()));
m.insert("countries".to_string(), Value::List(vec![]));
m.insert("rateLimit".to_string(), Value::Int(200));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchEvent".to_string(), Value::Bool(true));
m.insert("fetchEvents".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(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("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(true));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchPositions".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("24h".to_string()));
m.insert("5m".to_string(), Value::Str("24h".to_string()));
m.insert("15m".to_string(), Value::Str("7d".to_string()));
m.insert("1h".to_string(), Value::Str("7d".to_string()));
m.insert("6h".to_string(), Value::Str("30d".to_string()));
m.insert("1d".to_string(), Value::Str("30d".to_string()));
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/a393c885-99e8-4943-897d-ebc0555c3773".to_string()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("myriad".to_string(), Value::Str("https://api-v2.myriadprotocol.com".to_string()));
m.insert("ws".to_string(), Value::Str("wss://ws.myriadprotocol.com/ws".to_string()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("myriad".to_string(), Value::Str("https://api-v2.staging.myriadprotocol.com".to_string()));
m.insert("ws".to_string(), Value::Str("wss://ws.staging.myriadprotocol.com/ws".to_string()));
m
}));
m.insert("www".to_string(), Value::Str("https://myriad.markets".to_string()));
m.insert("doc".to_string(), Value::List(vec![Value::Str("https://docs.myriad.markets".to_string())]));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("myriad".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("questions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("questions/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{networkId}/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{id}/events".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{id}/orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{id}/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{id}/holders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/{id}/referrals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("events".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/{hash}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("users/{address}/events".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("users/{address}/referrals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("users/{address}/portfolio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("users/{address}/markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("topics".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("markets/quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markets/claim".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/cancel-batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/cancel-all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/split".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/merge".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/redeem".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/redeem-voided".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/neg-risk/split".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/neg-risk/merge".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orders/{hash}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("markets/quote_with_fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("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(false));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("maker".to_string(), Value::Float(0.01));
m.insert("taker".to_string(), Value::Float(0.01));
m
}));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Order not found".to_string(), Value::Str("OrderNotFound".to_string()).clone());
m.insert("Market not found".to_string(), Value::Str("BadSymbol".to_string()).clone());
m.insert("Invalid order payload".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Insufficient".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("allowance".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("not found".to_string(), Value::Str("OrderNotFound".to_string()).clone());
m.insert("Unauthorized".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("Forbidden".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("rate limit".to_string(), Value::Str("RateLimitExceeded".to_string()).clone());
m.insert("Too many requests".to_string(), Value::Str("RateLimitExceeded".to_string()).clone());
m.insert("expired".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("closed".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("resolved".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Invalid".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultFetchMarketsLimit".to_string(), Value::Int(50));
m.insert("defaultFetchEventsLimit".to_string(), Value::Int(50));
m.insert("allowUnscopedFetchEvents".to_string(), Value::Bool(true));
m.insert("defaultMarketStatus".to_string(), Value::Str("open".to_string()));
m.insert("defaultTradingModel".to_string(), Value::Str("all".to_string()));
m.insert("defaultNetworkId".to_string(), Value::Str("56".to_string()));
m.insert("obDomainName".to_string(), Value::Str("MyriadCTFExchange".to_string()));
m.insert("obDomainVersion".to_string(), Value::Str("1".to_string()));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("2741".to_string(), Value::Str("Abstract".to_string()));
m.insert("59144".to_string(), Value::Str("Linea".to_string()));
m.insert("56".to_string(), Value::Str("BNB Chain".to_string()));
m
}));
m.insert("chains".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("56".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rpcUrl".to_string(), Value::Str("https://bsc-dataseed.binance.org/".to_string()));
m.insert("predictionMarket".to_string(), Value::Str("0x39E66eE6b2ddaf4DEfDEd3038E0162180dbeF340".to_string()));
m.insert("obExchangeAddress".to_string(), Value::Str("0xa0b6f8ef8EdB64f395018D1933f2273Ce9f0f16A".to_string()));
m.insert("obConditionalTokens".to_string(), Value::Str("0x6413734f92248D4B29ae35883290BD93212654Dc".to_string()));
m.insert("collateralToken".to_string(), Value::Str("0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d".to_string()));
m.insert("collateralCurrency".to_string(), Value::Str("USD1".to_string()));
m.insert("collateralDecimals".to_string(), Value::Int(18));
m
}));
m.insert("2741".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rpcUrl".to_string(), Value::Str("https://api.mainnet.abs.xyz".to_string()));
m.insert("predictionMarket".to_string(), Value::Str("0x3e0F5F8F5Fb043aBFA475C0308417Bf72c463289".to_string()));
m
}));
m.insert("59144".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rpcUrl".to_string(), Value::Str("https://rpc.linea.build".to_string()));
m.insert("predictionMarket".to_string(), Value::Str("0x39e66ee6b2ddaf4defded3038e0162180dbef340".to_string()));
m
}));
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name myriad#fetchMarkets
* @description retrieves data on all markets for myriad, each prediction market becomes one market with its outcome tokens listed under the outcomes key
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {object} [params] extra exchange-specific parameters
* @param {string} [params.query] a single search term used to filter the fetched markets
* @param {string[]} [params.queries] multiple search terms (alternative to query)
* @param {string} [params.state] 'open', 'closed' or 'resolved', the state of the markets to fetch, defaults to 'open'
* @param {int} [params.limit] max number of markets to collect (defaults to options.fetchMarketsLimit, 1000); stops the pagination once reached
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("query".to_string()), Value::Str("queries".to_string())]), &[]);
let mut queriesLength: Value = get_array_length(&queries);
let mut rawMarkets: Value = Value::List(vec![]);
if is_greater_than(&queriesLength, &Value::Int(0)) {
rawMarkets = self.fetch_raw_markets_by_search(queries.clone(), &[rest.clone()]).await;
} else {
rawMarkets = self.fetch_raw_markets_list(&[rest.clone()]).await;
}
let mut flatMarkets: Value = Value::List(vec![]);
let mut eventsDict: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1289: bool = true;
while { if !__for_first_1289 { i = add(&i, &Value::Int(1)); } __for_first_1289 = false; is_less_than(&i, &get_array_length(&rawMarkets)) } {
let mut raw: Value = get_value(&rawMarkets, &i);
let mut raw: Value = get_value(&rawMarkets, &i);
let mut m: Value = self.parse_myriad_market(raw.clone(), &[]);
append_to_array(&mut flatMarkets, m.clone());
let mut ev: Value = self.parse_market_to_event(raw.clone(), m.clone());
let mut evKey: Value = self.safe_string_k(ev.clone(), "event", &[]);
if !is_equal(&evKey, &Value::Null) {
add_element_to_object(&mut eventsDict, &evKey, ev.clone());
}
}
}
self.exchange.events = eventsDict.clone();
return flatMarkets;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#fetchRawMarketsBySearch
* @description fetches raw myriad market objects matching the given search terms via the markets keyword filter
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {string[]} queries search terms
* @param {object} [params] extra exchange-specific parameters
* @param {int} [params.limit] maximum number of markets per query, defaults to 50
* @param {string} [params.state] 'open', 'closed' or 'resolved', defaults to options.defaultMarketStatus
* @returns {object[]} an array of raw myriad market objects
*/
pub async fn fetch_raw_markets_by_search(&mut self, mut queries: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut limit: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("defaultFetchEventsLimit".to_string()), &[Value::Int(50)])]);
let mut state: Value = self.safe_string_k(params.clone(), "state", &[self.safe_string(self.options.clone(), Value::Str("defaultMarketStatus".to_string()), &[Value::Str("open".to_string())])]);
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("limit".to_string()), Value::Str("state".to_string())]), &[]);
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut rawMarkets: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1291: bool = true;
while { if !__for_first_1291 { i = add(&i, &Value::Int(1)); } __for_first_1291 = false; is_less_than(&i, &get_array_length(&queries)) } {
let mut q: Value = get_value(&queries, &i);
let mut q: Value = get_value(&queries, &i);
let __ws_arg_0 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("keyword".to_string(), q.clone());
m.insert("state".to_string(), state.clone());
m.insert("limit".to_string(), limit.clone());
m
}), &[rest.clone()]);
let mut response: Value = self.myriad_public_get_markets(&[__ws_arg_0]).await;
let mut responseIsArray: Value = Value::Bool(is_array(&response));
let mut foundList: Value = ternary(is_true(&(responseIsArray)), response.clone(), self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]));
let mut found: Value = ternary(is_true(&(!is_equal(&foundList, &Value::Null))), foundList.clone(), Value::List(vec![]));
{
let mut j: Value = Value::Int(0);
let mut __for_first_1290: bool = true;
while { if !__for_first_1290 { j = add(&j, &Value::Int(1)); } __for_first_1290 = false; is_less_than(&j, &get_array_length(&found)) } {
let mut raw: Value = get_value(&found, &j);
let mut raw: Value = get_value(&found, &j);
let mut networkId: Value = self.safe_string_k(raw.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(raw.clone(), "id", &[]);
let mut key: Value = add(&add(&networkId, &Value::Str(":".to_string())), &marketId);
if !is_true(&(Value::Bool(in_op(&seen, &key)))) {
add_element_to_object(&mut seen, &key, Value::Bool(true));
append_to_array(&mut rawMarkets, raw.clone());
}
}
}
}
}
return rawMarkets;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#fetchRawMarketsList
* @description fetches raw myriad market objects from the paginated markets listing
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {object} [params] extra exchange-specific parameters
* @param {string} [params.state] 'open', 'closed' or 'resolved', defaults to options.defaultMarketStatus
* @returns {object[]} an array of raw myriad market objects
*/
pub async fn fetch_raw_markets_list(&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 limit: Value = self.safe_integer_k(self.options.clone(), "defaultFetchMarketsLimit", &[Value::Int(50)]);
// scope the listing: without a search query loadMarkets would otherwise page through
// every open myriad market. Cap the total number of markets collected.
let mut maxMarkets: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("fetchMarketsLimit".to_string()), &[Value::Int(1000)])]);
let mut state: Value = self.safe_string2(params.clone(), Value::Str("state".to_string()), Value::Str("status".to_string()), &[self.safe_string_k(self.options.clone(), "defaultMarketStatus", &[Value::Str("open".to_string())])]);
// include both AMM and order-book markets so order-book trading methods can resolve their markets
let mut tradingModel: Value = self.safe_string2(params.clone(), Value::Str("tradingModel".to_string()), Value::Str("trading_model".to_string()), &[self.safe_string_k(self.options.clone(), "defaultTradingModel", &[Value::Str("all".to_string())])]);
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("state".to_string()), Value::Str("status".to_string()), Value::Str("limit".to_string()), Value::Str("tradingModel".to_string()), Value::Str("trading_model".to_string())]), &[]);
let mut allRawMarkets: Value = Value::List(vec![]);
// track the running count with an explicit counter (avoids inline array .length / .slice,
// which the regex transpiler otherwise mistakes for string strlen()/mb_substr())
let mut collected: Value = Value::Int(0);
let mut page: Value = Value::Int(1);
while is_true(&Value::Bool(true)) {
let __ws_arg_1 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("state".to_string(), state.clone());
m.insert("limit".to_string(), limit.clone());
m.insert("page".to_string(), page.clone());
m.insert("trading_model".to_string(), tradingModel.clone());
m
}), &[rest.clone()]);
let mut response: Value = self.myriad_public_get_markets(&[__ws_arg_1]).await;
let mut responseIsArray: Value = Value::Bool(is_array(&response));
let mut rawMarketsList: Value = ternary(is_true(&(responseIsArray)), response.clone(), self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]));
let mut rawMarkets: Value = ternary(is_true(&(!is_equal(&rawMarketsList, &Value::Null))), rawMarketsList.clone(), Value::List(vec![]));
let mut rawMarketsLength: Value = get_array_length(&rawMarkets);
if is_equal(&rawMarketsLength, &Value::Int(0)) {
break;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1292: bool = true;
while { if !__for_first_1292 { i = add(&i, &Value::Int(1)); } __for_first_1292 = false; is_less_than(&i, &rawMarketsLength) } {
if is_less_than(&collected, &maxMarkets) {
append_to_array(&mut allRawMarkets, get_value(&rawMarkets, &i));
collected = self.sum(&[collected.clone(), Value::Int(1)]);
}
}
}
page = self.sum(&[page.clone(), Value::Int(1)]);
if is_less_than(&rawMarketsLength, &limit) || is_greater_than_or_equal(&collected, &maxMarkets) {
break;
}
}
return allRawMarkets;
Value::Null
}
/*
* @method
* @name myriad#fetchEvent
* @description fetches a single prediction-market event by its market id, or orderbook slug
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {string} id the market id, or orderbook slug
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction event structure](https://docs.ccxt.com/#/?id=prediction-event-structure)
*/
pub async fn fetch_event(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_less_than(&get_index_of(&id, &Value::Str(":".to_string())), &Value::Int(0)) {
let mut rawQuestion: Value = self.fetch_raw_question_by_id(id.clone(), &[params.clone()]).await;
let mut orderBookEvent: Value = self.parse_event(rawQuestion.clone());
self.index_event_outcomes(orderBookEvent.clone());
return orderBookEvent;
}
let mut response: Value = self.fetch_raw_market_by_id(id.clone(), &[params.clone()]).await;
let mut market: Value = self.parse_myriad_market(response.clone(), &[]);
let mut event: Value = self.parse_market_to_event(response.clone(), market.clone());
self.index_event_outcomes(event.clone());
return event;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#fetchRawMarketById
* @description fetches a single raw myriad market object by its unified event id (a composite networkId:marketId)
* @param {string} id the unified event/market id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the raw myriad market object
*/
pub async fn fetch_raw_market_by_id(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// the unified event id is a composite networkId:marketId
let mut parts: Value = split(&id, &Value::Str(":".to_string()));
let mut partsLength: Value = get_array_length(&parts);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_greater_than(&partsLength, &Value::Int(1)) {
add_element_to_object(&mut request, &Value::Str("network_id".to_string()), self.safe_string(parts.clone(), Value::Int(0), &[]));
add_element_to_object(&mut request, &Value::Str("id".to_string()), self.safe_string(parts.clone(), Value::Int(1), &[]));
} else {
add_element_to_object(&mut request, &Value::Str("id".to_string()), id.clone());
}
let __ws_arg_2 = self.extend(request.clone(), &[params.clone()]);
return self.myriad_public_get_markets_id(&[__ws_arg_2]).await;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#fetchRawQuestionById
* @description fetches a single raw myriad question object by question id; falls back to keyword search by id/slug/title when direct lookup is unavailable
* @param {string} id the question id or slug
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the raw question object
*/
pub async fn fetch_raw_question_by_id(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m
});
let mut result: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let __ws_arg_3 = self.extend(request.clone(), &[params.clone()]);
result = self.myriad_public_get_questions_id(&[__ws_arg_3]).await;
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if is_true(&(is_instance(&e, &Value::Str("RateLimitExceeded".to_string())))) || is_true(&(is_instance(&e, &Value::Str("AuthenticationError".to_string())))) {
panic!("{}", e);
}
let mut keywordRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("keyword".to_string(), id.clone());
m.insert("limit".to_string(), Value::Int(50));
m
});
let __ws_arg_4 = self.extend(keywordRequest.clone(), &[params.clone()]);
let mut response: Value = self.myriad_public_get_questions(&[__ws_arg_4]).await;
let mut questions: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut questionsLength: Value = get_array_length(&questions);
let mut idLower: Value = to_lower(&id);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1293: bool = true;
while { if !__for_first_1293 { i = add(&i, &Value::Int(1)); } __for_first_1293 = false; is_less_than(&i, &questionsLength) } {
let mut q: Value = self.safe_dict(questions.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut qId: Value = self.safe_string_k(q.clone(), "id", &[Value::Str("".to_string())]);
let mut qSlug: Value = self.safe_string_k(q.clone(), "slug", &[Value::Str("".to_string())]);
let mut qTitle: Value = self.safe_string_k(q.clone(), "title", &[Value::Str("".to_string())]);
let mut qHandle: Value = self.shorten_slug(qSlug.clone());
if is_true(&(is_equal(&to_lower(&qId), &idLower))) || is_true(&(is_equal(&to_lower(&qSlug), &idLower))) || is_true(&(is_equal(&to_lower(&qTitle), &idLower))) || is_true(&(is_true(&(!is_equal(&qHandle, &Value::Null))) && is_true(&(is_equal(&to_lower(&qHandle), &idLower))))) {
return q;
}
}
}
panic!("{}", e);
}
return result;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#fetchRawQuestionsBySearch
* @description fetches raw myriad question objects matching the given search terms via the questions keyword filter
* @param {string[]} queries search terms
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of raw myriad question objects
*/
pub async fn fetch_raw_questions_by_search(&mut self, mut queries: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut limit: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("defaultFetchEventsLimit".to_string()), &[Value::Int(50)])]);
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("limit".to_string())]), &[]);
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut rawQuestions: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1295: bool = true;
while { if !__for_first_1295 { i = add(&i, &Value::Int(1)); } __for_first_1295 = false; is_less_than(&i, &get_array_length(&queries)) } {
let mut q: Value = get_value(&queries, &i);
let mut q: Value = get_value(&queries, &i);
let __ws_arg_5 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("keyword".to_string(), q.clone());
m.insert("limit".to_string(), limit.clone());
m
}), &[rest.clone()]);
let mut response: Value = self.myriad_public_get_questions(&[__ws_arg_5]).await;
let mut responseIsArray: Value = Value::Bool(is_array(&response));
let mut foundList: Value = ternary(is_true(&(responseIsArray)), response.clone(), self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]));
let mut found: Value = ternary(is_true(&(!is_equal(&foundList, &Value::Null))), foundList.clone(), Value::List(vec![]));
{
let mut j: Value = Value::Int(0);
let mut __for_first_1294: bool = true;
while { if !__for_first_1294 { j = add(&j, &Value::Int(1)); } __for_first_1294 = false; is_less_than(&j, &get_array_length(&found)) } {
let mut raw: Value = get_value(&found, &j);
let mut raw: Value = get_value(&found, &j);
let mut questionId: Value = self.safe_string_k(raw.clone(), "id", &[]);
if is_true(&(!is_equal(&questionId, &Value::Null))) && !is_true(&(Value::Bool(in_op(&seen, &questionId)))) {
add_element_to_object(&mut seen, &questionId, Value::Bool(true));
append_to_array(&mut rawQuestions, raw.clone());
}
}
}
}
}
return rawQuestions;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#fetchRawQuestionsList
* @description fetches raw myriad question objects from the paginated questions listing
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.state] optional question state filter when supported by the backend
* @returns {object[]} an array of raw myriad question objects
*/
pub async fn fetch_raw_questions_list(&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 limit: Value = self.safe_integer_k(self.options.clone(), "defaultFetchEventsLimit", &[Value::Int(50)]);
let mut maxQuestions: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("fetchEventsLimit".to_string()), &[Value::Int(1000)])]);
let mut state: Value = self.safe_string2(params.clone(), Value::Str("state".to_string()), Value::Str("status".to_string()), &[self.safe_string_k(self.options.clone(), "defaultMarketStatus", &[Value::Str("open".to_string())])]);
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("state".to_string()), Value::Str("status".to_string()), Value::Str("limit".to_string()), Value::Str("tradingModel".to_string()), Value::Str("trading_model".to_string())]), &[]);
let mut allRawQuestions: Value = Value::List(vec![]);
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut collected: Value = Value::Int(0);
let mut page: Value = Value::Int(1);
while is_true(&Value::Bool(true)) {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), limit.clone());
m.insert("page".to_string(), page.clone());
m
});
if !is_equal(&state, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("state".to_string()), state.clone());
}
let __ws_arg_6 = self.extend(request.clone(), &[rest.clone()]);
let mut response: Value = self.myriad_public_get_questions(&[__ws_arg_6]).await;
let mut responseIsArray: Value = Value::Bool(is_array(&response));
let mut rawQuestionsList: Value = ternary(is_true(&(responseIsArray)), response.clone(), self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]));
let mut rawQuestions: Value = ternary(is_true(&(!is_equal(&rawQuestionsList, &Value::Null))), rawQuestionsList.clone(), Value::List(vec![]));
let mut rawQuestionsLength: Value = get_array_length(&rawQuestions);
if is_equal(&rawQuestionsLength, &Value::Int(0)) {
break;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1296: bool = true;
while { if !__for_first_1296 { i = add(&i, &Value::Int(1)); } __for_first_1296 = false; is_less_than(&i, &rawQuestionsLength) } {
let mut rawQuestion: Value = get_value(&rawQuestions, &i);
let mut rawQuestion: Value = get_value(&rawQuestions, &i);
let mut questionId: Value = self.safe_string_k(rawQuestion.clone(), "id", &[]);
if is_true(&(!is_equal(&questionId, &Value::Null))) && is_true(&(Value::Bool(in_op(&seen, &questionId)))) {
continue;
}
if !is_equal(&questionId, &Value::Null) {
add_element_to_object(&mut seen, &questionId, Value::Bool(true));
}
if is_less_than(&collected, &maxQuestions) {
append_to_array(&mut allRawQuestions, rawQuestion.clone());
collected = self.sum(&[collected.clone(), Value::Int(1)]);
}
}
}
page = self.sum(&[page.clone(), Value::Int(1)]);
if is_true(&(is_less_than(&rawQuestionsLength, &limit))) || is_true(&(is_greater_than_or_equal(&collected, &maxQuestions))) {
break;
}
}
return allRawQuestions;
Value::Null
}
/*
* @method
* @name myriad#fetchPositions
* @description fetch the open outcome-token positions held by a wallet (myriad settles trades on-chain, so only read-only portfolio data is exposed by the API)
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {string[]} [outcomes] unified outcomes to filter by
* @param {object} [params] extra exchange-specific parameters
* @param {string} [params.address] the wallet address to query, defaults to this.walletAddress
* @returns {object[]} a list of [prediction position structures](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// resolve the owner the same way fetchBalance does — derive from the configured privateKey
// when no explicit walletAddress/param is set, so a privateKey-only config works for both
let mut address: Value = self.safe_string2(params.clone(), Value::Str("address".to_string()), Value::Str("user".to_string()), &[self.wallet_address_or_undefined()]);
if is_equal(&address, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchPositions() requires a walletAddress or an address parameter".to_string()))));
}
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("address".to_string()), Value::Str("user".to_string())]), &[]);
let __ws_arg_7 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("address".to_string(), address.clone());
m
}), &[rest.clone()]);
let mut response: Value = self.myriad_public_get_users_address_portfolio(&[__ws_arg_7]).await;
//
// {
// "data": [
// {
// "marketId": 170145,
// "marketTitle": "Will Base TGE in 2026?",
// "marketSlug": "will-base-tge-in-2026",
// "imageUrl": "https://cdn.polkamarkets.com/Qmacfs1qiiUW5cnMRUyzji393Vn2DcvNdydGukf1Xk82b6",
// "outcomeId": 0,
// "outcomeTitle": "Yes",
// "networkId": 56,
// "token": "0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d",
// "tokenId": null,
// "shares": 8.23666644,
// "price": 0.1214083400468503,
// "value": 0.9823048396344001,
// "profit": -0.017695160365599896,
// "roi": -0.017695160365599896,
// "totalProfit": -0.017695160365599927,
// "totalRoi": -0.017695160365599927,
// "positionFees": 0.02,
// "totalFees": 0.02,
// "winningsToClaim": false,
// "winningsClaimed": false,
// "voidedWinningsToClaim": false,
// "voidedWinningsClaimed": false,
// "status": "ongoing",
// "claimed": false,
// "executionMode": 0,
// "expiresAt": "2026-12-31 23:59:00",
// "eventId": null
// }
// ],
// "pagination": {
// "page": 1,
// "limit": 20,
// "total": 1,
// "totalPages": 1,
// "hasNext": false,
// "hasPrev": false
// }
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1297: bool = true;
while { if !__for_first_1297 { i = add(&i, &Value::Int(1)); } __for_first_1297 = false; is_less_than(&i, &get_array_length(&data)) } {
append_to_array(&mut result, self.parse_prediction_position(get_value(&data, &i), &[]));
}
}
return self.filter_by_array(result.clone(), Value::Str("outcome".to_string()), &[outcomes.clone(), Value::Bool(false)]);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parsePredictionPosition
* @description parses a raw myriad portfolio entry into a unified position structure
* @param {object} position the raw portfolio entry
* @param {object} [market] not used by myriad
* @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub fn parse_prediction_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketSlug: Value = self.safe_string_k(position.clone(), "marketSlug", &[Value::Str("".to_string())]);
let mut outcomeTitle: Value = self.safe_string_k(position.clone(), "outcomeTitle", &[Value::Str("".to_string())]);
let mut outcome: Value = self.slug_to_outcome_symbol(marketSlug.clone(), marketSlug.clone(), outcomeTitle.clone());
let mut marketSymbol: Value = self.slug_to_market_symbol(marketSlug.clone(), marketSlug.clone());
let mut networkId: Value = self.safe_string_k(position.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(position.clone(), "marketId", &[]);
let mut outcomeId: Value = self.safe_string_k(position.clone(), "outcomeId", &[]);
let mut id: Value = add(&add(&add(&add(&networkId, &Value::Str(":".to_string())), &marketId), &Value::Str("/".to_string())), &outcomeId);
let mut shares: Value = self.safe_number_k(position.clone(), "shares", &[]);
let mut value: Value = self.safe_number_k(position.clone(), "value", &[]);
let mut profit: Value = self.safe_number_k(position.clone(), "profit", &[]);
let mut roi: Value = self.safe_string_k(position.clone(), "roi", &[]);
let mut percentage: Value = Value::Null;
if !is_equal(&roi, &Value::Null) {
percentage = crate::precise::Precise::stringMul(&roi, &Value::Str("100".to_string()));
}
return self.safe_prediction_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), id.clone());
m.insert("outcome".to_string(), outcome.clone());
m.insert("outcomeId".to_string(), outcomeId.clone());
m.insert("label".to_string(), outcomeTitle.clone());
m.insert("market".to_string(), marketSymbol.clone());
m.insert("contracts".to_string(), shares.clone());
m.insert("side".to_string(), Value::Str("long".to_string()));
m.insert("notional".to_string(), value.clone());
m.insert("markPrice".to_string(), self.safe_number_k(position.clone(), "price", &[]));
m.insert("unrealizedPnl".to_string(), profit.clone());
m.insert("percentage".to_string(), self.parse_number(percentage.clone(), &[]));
m.insert("marginMode".to_string(), Value::Str("cash".to_string()));
m.insert("hedged".to_string(), Value::Bool(false));
m
}));
Value::Null
}
/*
* @method
* @name myriad#fetchTradeQuote
* @description fetches a trade quote — price, shares, fees and the on-chain calldata — for buying or selling an outcome. Myriad settles trades on-chain, so this returns the calldata to submit to the prediction-market contract rather than placing an off-chain order
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {string} outcome unified outcome or outcome id
* @param {string} side 'buy' or 'sell'
* @param {float} amount for 'buy' the collateral value to spend; for 'sell' the number of shares to sell
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {float} [params.slippage] maximum slippage tolerance (default 0.005)
* @returns {object} a quote object with price, shares, fees and the on-chain calldata
*/
pub async fn fetch_trade_quote(&mut self, mut outcome: Value, mut side: 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
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(info.clone(), "marketId", &[]);
let mut outcomeId: Value = self.safe_integer_k(info.clone(), "outcomeId", &[]);
let mut sideStr: Value = to_lower(&side);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_id".to_string(), self.parse_to_int(marketId.clone()));
m.insert("network_id".to_string(), self.parse_to_int(networkId.clone()));
m.insert("outcome_id".to_string(), outcomeId.clone());
m.insert("action".to_string(), sideStr.clone());
m.insert("slippage".to_string(), self.safe_number_k(params.clone(), "slippage", &[Value::Float(0.005)]));
m
});
if is_equal(&sideStr, &Value::Str("buy".to_string())) {
add_element_to_object(&mut request, &Value::Str("value".to_string()), amount.clone());
} else {
add_element_to_object(&mut request, &Value::Str("shares".to_string()), amount.clone());
}
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("slippage".to_string())]), &[]);
let __ws_arg_8 = self.extend(request.clone(), &[rest.clone()]);
let mut response: Value = self.myriad_public_post_markets_quote(&[__ws_arg_8]).await;
let __ws_arg_9 = self.extend(response.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), sideStr.clone());
m
})]);
return self.parse_trade_quote(__ws_arg_9, &[outcomeObj.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parseTradeQuote
* @description parses a raw myriad quote response into a unified-ish quote object
* @param {object} quote the raw quote response
* @param {object} [market] the outcome the quote belongs to
* @returns {object} a quote object
*/
pub fn parse_trade_quote(&self, mut quote: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), self.safe_string_k(market.clone(), "outcome", &[]));
m.insert("side".to_string(), self.safe_string_lower(quote.clone(), Value::Str("action".to_string()), &[]));
m.insert("value".to_string(), self.safe_number_k(quote.clone(), "value", &[]));
m.insert("shares".to_string(), self.safe_number_k(quote.clone(), "shares", &[]));
m.insert("sharesThreshold".to_string(), self.safe_number_k(quote.clone(), "shares_threshold", &[]));
m.insert("priceAverage".to_string(), self.safe_number_k(quote.clone(), "price_average", &[]));
m.insert("priceBefore".to_string(), self.safe_number_k(quote.clone(), "price_before", &[]));
m.insert("priceAfter".to_string(), self.safe_number_k(quote.clone(), "price_after", &[]));
m.insert("netAmount".to_string(), self.safe_number_k(quote.clone(), "net_amount", &[]));
m.insert("fees".to_string(), self.safe_dict_k(quote.clone(), "fees", &[]));
m.insert("calldata".to_string(), self.safe_string_k(quote.clone(), "calldata", &[]));
m.insert("info".to_string(), quote.clone());
m
});
Value::Null
}
pub fn sign_evm_transaction(&self, mut tx: Value, mut privateKey: Value) -> Value {
// builds and signs an EIP-1559 (type 0x02) transaction, returning the signed raw tx hex.
// tx fields (nonce/gas/fees/value) are hex strings; chainId is an int. Verified
// byte-identical to ethers' serialization
let mut accessList: Value = self.rlp_encode_list(Value::List(vec![]));
let mut fields: Value = Value::List(vec![self.rlp_encode_bytes(self.int_to_rlp_hex(self.safe_integer_k(tx.clone(), "chainId", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "nonce", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "maxPriorityFeePerGas", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "maxFeePerGas", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "gasLimit", &[]))), self.rlp_encode_bytes(self.remove0x_prefix(self.safe_string_k(tx.clone(), "to", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "value", &[Value::Str("0x0".to_string())]))), self.rlp_encode_bytes(self.remove0x_prefix(self.safe_string_k(tx.clone(), "data", &[Value::Str("0x".to_string())]))), accessList.clone()]);
let mut payload: Value = add(&Value::Str("02".to_string()), &self.rlp_encode_list(fields.clone()));
let mut hashHex: Value = self.hash(self.base16_to_binary(payload.clone(), &[]), Value::Str("keccak".to_string()), &[Value::Str("hex".to_string())]);
let mut signature: Value = ecdsa(hashHex.clone(), self.remove0x_prefix(privateKey.clone()), Value::Str("secp256k1".to_string()), Value::Null);
let mut rHex: Value = self.safe_string_k(signature.clone(), "r", &[]);
let mut sHex: Value = self.safe_string_k(signature.clone(), "s", &[]);
if is_equal(&rHex, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" signEvmTransaction() missing rHex".to_string()))));
}
let mut rHexLength: Value = get_array_length(&rHex);
if !is_equal(&(mod_val(&rHexLength, &Value::Int(2))), &Value::Int(0)) {
rHex = add(&Value::Str("0".to_string()), &rHex);
}
if is_equal(&sHex, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" signEvmTransaction() missing sHex".to_string()))));
}
let mut sHexLength: Value = get_array_length(&sHex);
if !is_equal(&(mod_val(&sHexLength, &Value::Int(2))), &Value::Int(0)) {
sHex = add(&Value::Str("0".to_string()), &sHex);
}
let mut yParity: Value = self.safe_integer_k(signature.clone(), "v", &[]);
let mut signedFields: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1298: bool = true;
while { if !__for_first_1298 { i = add(&i, &Value::Int(1)); } __for_first_1298 = false; is_less_than(&i, &get_array_length(&fields)) } {
append_to_array(&mut signedFields, get_value(&fields, &i));
}
}
append_to_array(&mut signedFields, self.rlp_encode_bytes(self.int_to_rlp_hex(yParity.clone())));
append_to_array(&mut signedFields, self.rlp_encode_bytes(rHex.clone()));
append_to_array(&mut signedFields, self.rlp_encode_bytes(sHex.clone()));
return add(&Value::Str("0x02".to_string()), &self.rlp_encode_list(signedFields.clone()));
Value::Null
}
pub async fn eth_rpc(&mut self, mut rpcUrl: Value, mut method: Value, mut rpcParams: Value) -> Value {
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".to_string()));
m.insert("id".to_string(), Value::Int(1));
m.insert("method".to_string(), method.clone());
m.insert("params".to_string(), rpcParams.clone());
m
});
let mut headers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("application/json".to_string()));
m
});
let __ws_arg_10 = self.json(payload.clone());
let mut response: Value = self.fetch(rpcUrl.clone(), &[Value::Str("POST".to_string()), headers.clone(), __ws_arg_10]).await;
let mut rpcError: Value = self.safe_value_k(response.clone(), "error", &[]);
if !is_equal(&rpcError, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&add(&add(&add(&self.id, &Value::Str(" rpc ".to_string())), &method), &Value::Str(" error: ".to_string())), &self.json(rpcError.clone()))));
}
return self.safe_value_k(response.clone(), "result", &[]);
Value::Null
}
pub async fn ensure_erc20_allowance(&mut self, mut rpcUrl: Value, mut networkId: Value, mut token: Value, mut owner: Value, mut spender: Value) -> Value {
// allowance(owner, spender)
let mut allowanceData: Value = add(&add(&Value::Str("0xdd62ed3e".to_string()), &self.pad_hex_address(owner.clone())), &self.pad_hex_address(spender.clone()));
let mut current: Value = self.eth_rpc(rpcUrl.clone(), Value::Str("eth_call".to_string()), Value::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("to".to_string(), token.clone());
m.insert("data".to_string(), allowanceData.clone());
m
}), Value::Str("latest".to_string())])).await;
let mut trimmed: Value = self.hex_to_rlp_bytes(current.clone());
// a max-approved allowance is ~32 bytes (64 nibbles); anything much smaller needs (re)approval
if is_greater_than_or_equal(&get_array_length(&trimmed), &Value::Int(50)) {
return Value::Null;
}
// approve(spender, maxUint256)
let mut maxUint: Value = Value::Str("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".to_string());
let mut approveData: Value = add(&add(&Value::Str("0x095ea7b3".to_string()), &self.pad_hex_address(spender.clone())), &maxUint);
let __ws_arg_11 = self.parse_to_int(networkId.clone());
let mut approveHash: Value = self.send_evm_transaction(rpcUrl.clone(), __ws_arg_11, owner.clone(), token.clone(), Value::Str("0x0".to_string()), approveData.clone(), Value::Str("0x186a0".to_string())).await;
self.wait_for_transaction_receipt(rpcUrl.clone(), approveHash.clone(), &[]).await;
return Value::Null;
Value::Null
}
/*
* @method
* @name myriad#createOrder
* @description create a trade order. Myriad has two trading models: a gasless order book (CLOB) where an EIP-712 signed order is posted off-chain and settled by the operator, and an on-chain AMM. Order-book markets are used by default; the model can be forced via params.tradingModel
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da8281e2bc49cf4914b07528
* @param {string} outcome unified outcome or outcome id
* @param {string} type 'limit' or 'market' (order book); ignored by the AMM path
* @param {string} side 'buy' or 'sell'
* @param {float} amount number of outcome shares to trade (AMM 'buy' spends this as collateral value instead)
* @param {float} [price] price per share as a fraction in [0, 1] (required for order-book limit orders)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.tradingModel] 'ob' to force the order book, 'amm' to force the on-chain AMM; defaults to the market's model
* @param {string} [params.timeInForce] order-book time in force: 'GTC', 'GTD', 'FOK', 'FAK' or 'PO'
* @param {string} [params.expiration] unix-seconds expiration for a GTD order
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_order(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultModel: Value = self.safe_string_k(info.clone(), "tradingModel", &[Value::Str("amm".to_string())]);
let mut tradingModel: Value = self.safe_string_lower(params.clone(), Value::Str("tradingModel".to_string()), &[defaultModel.clone()]);
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("tradingModel".to_string())]), &[]);
if is_equal(&tradingModel, &Value::Str("ob".to_string())) {
return self.create_orderbook_order(outcome.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), rest.clone()]).await;
}
// the on-chain AMM path requires native gas and has not been verified end to end; keep it behind
// an explicit opt-in so callers do not silently hit an untested signing/broadcast path
let mut enableAmm: Value = self.safe_bool2(params.clone(), Value::Str("enableAmm".to_string()), Value::Str("enableAmmOrders".to_string()), &[self.safe_bool_k(self.options.clone(), "enableAmmOrders", &[Value::Bool(false)])]);
if !is_equal(&enableAmm, &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" createOrder() only supports the gasless order book; this market uses the on-chain AMM (needs native gas and is unverified) — pass params.enableAmm=true to opt in".to_string()))));
}
return self.create_amm_order(outcome.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), self.omit(rest.clone(), Value::List(vec![Value::Str("enableAmm".to_string()), Value::Str("enableAmmOrders".to_string())]), &[])]).await;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#createOrderbookOrder
* @description signs an EIP-712 order and posts it to the gasless order book; the operator settles the match on-chain
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_orderbook_order(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut built: Value = self.build_orderbook_order(outcome.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]);
let mut order: Value = self.safe_dict_k(built.clone(), "order", &[]);
let mut networkId: Value = self.safe_string_k(built.clone(), "networkId", &[]);
let mut timeInForce: Value = self.safe_string_k(built.clone(), "timeInForce", &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), order.clone());
m.insert("signature".to_string(), self.safe_string_k(built.clone(), "signature", &[]));
m.insert("network_id".to_string(), self.parse_to_int(networkId.clone()));
m.insert("time_in_force".to_string(), timeInForce.clone());
m
});
let mut response: Value = self.myriad_public_post_orders(&[request.clone()]).await;
//
// {
// "orderHash": "0x758a1763c59bbe61c314f3c0c9b5bae0ad942120500eb39e3e8349bbe13990e0",
// "status": "open",
// "timeInForce": "GTC"
// }
//
let mut orderForResponse: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trader".to_string(), self.safe_string_k(order.clone(), "trader", &[]));
m.insert("marketId".to_string(), self.safe_string_k(order.clone(), "marketId", &[]));
m.insert("outcomeId".to_string(), self.safe_number_k(order.clone(), "outcomeId", &[]));
m.insert("side".to_string(), self.safe_number_k(order.clone(), "side", &[]));
m.insert("amount".to_string(), self.safe_string_k(order.clone(), "amount", &[]));
m.insert("price".to_string(), self.safe_string_k(order.clone(), "price", &[]));
m.insert("minFillAmount".to_string(), self.safe_string_k(order.clone(), "minFillAmount", &[]));
m.insert("nonce".to_string(), self.safe_string_k(order.clone(), "nonce", &[]));
m.insert("expiration".to_string(), self.safe_string_k(order.clone(), "expiration", &[]));
m
});
let mut wrapper: Value = self.extend(response.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), orderForResponse.clone());
m.insert("networkId".to_string(), networkId.clone());
m.insert("timeInForce".to_string(), timeInForce.clone());
m
})]);
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut parsed: Value = self.parse_prediction_order(wrapper.clone(), &[outcomeObj.clone()]);
// the POST /orders response is minimal (hash + status), so backfill the known request values
// side/type/price/amount/timeInForce and a creation timestamp - when parsePredictionOrder left them empty
let mut sideStr: Value = ternary(is_true(&(is_equal(&side, &Value::Null))), Value::Null, to_lower(&side));
let mut typeStr: Value = ternary(is_true(&(is_equal(&type_var, &Value::Null))), Value::Str("limit".to_string()), to_lower(&type_var));
if is_equal(&self.safe_string_k(parsed.clone(), "side", &[]), &Value::Null) {
add_element_to_object(&mut parsed, &Value::Str("side".to_string()), sideStr.clone());
}
if is_equal(&self.safe_string_k(parsed.clone(), "type", &[]), &Value::Null) {
add_element_to_object(&mut parsed, &Value::Str("type".to_string()), typeStr.clone());
}
if is_equal(&self.safe_string_k(parsed.clone(), "timeInForce", &[]), &Value::Null) {
add_element_to_object(&mut parsed, &Value::Str("timeInForce".to_string()), timeInForce.clone());
}
if is_true(&(is_equal(&self.safe_number_k(parsed.clone(), "price", &[]), &Value::Null))) && is_true(&(!is_equal(&price, &Value::Null))) {
add_element_to_object(&mut parsed, &Value::Str("price".to_string()), price.clone());
}
if is_true(&(is_equal(&self.safe_number_k(parsed.clone(), "amount", &[]), &Value::Null))) && is_true(&(!is_equal(&amount, &Value::Null))) {
add_element_to_object(&mut parsed, &Value::Str("amount".to_string()), amount.clone());
}
if is_equal(&self.safe_integer_k(parsed.clone(), "timestamp", &[]), &Value::Null) {
let mut now: Value = self.milliseconds();
add_element_to_object(&mut parsed, &Value::Str("timestamp".to_string()), now.clone());
add_element_to_object(&mut parsed, &Value::Str("datetime".to_string()), self.iso8601(now.clone()));
}
if is_equal(&self.safe_string_k(parsed.clone(), "status", &[]), &Value::Null) {
add_element_to_object(&mut parsed, &Value::Str("status".to_string()), Value::Str("open".to_string()));
}
return parsed;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#buildOrderbookOrder
* @description builds and EIP-712 signs a single order-book order; shared by createOrder and createOrders
* @returns {object} a dict with the signed order, signature, timeInForce and networkId
*/
pub fn build_orderbook_order(&self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.privateKey, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrder() requires a privateKey to sign the order".to_string()))));
}
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[self.safe_string(self.options.clone(), Value::Str("defaultNetworkId".to_string()), &[Value::Str("56".to_string())])]);
let mut marketId: Value = self.safe_string_k(info.clone(), "marketId", &[]);
let mut outcomeId: Value = self.safe_integer_k(info.clone(), "outcomeId", &[Value::Int(0)]);
let mut trader: Value = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
let mut typeStr: Value = ternary(is_true(&(is_equal(&type_var, &Value::Null))), Value::Str("limit".to_string()), to_lower(&type_var));
let mut sideStr: Value = to_lower(&side);
let mut sideInt: Value = ternary(is_true(&(is_equal(&sideStr, &Value::Str("buy".to_string())))), Value::Int(0), Value::Int(1));
let mut isMarket: bool = is_equal(&typeStr, &Value::Str("market".to_string()));
let mut defaultTif: Value = ternary(is_true(&isMarket), Value::Str("FOK".to_string()), Value::Str("GTC".to_string()));
let mut timeInForce: Value = self.safe_string_upper(params.clone(), Value::Str("timeInForce".to_string()), &[defaultTif.clone()]);
let mut priceValue: Value = price.clone();
if is_equal(&priceValue, &Value::Null) {
if is_true(&isMarket) {
priceValue = ternary(is_true(&(is_equal(&sideInt, &Value::Int(0)))), Value::Int(1), Value::Int(0));
} else {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrder() requires a price for limit orders".to_string()))));
}
}
let mut priceWei: Value = self.to_orderbook_wei(priceValue.clone());
if is_true(&crate::precise::Precise::stringLt(&priceWei, &Value::Str("1".to_string()))) {
priceWei = Value::Str("1".to_string());
}
// price is a fraction in (0, 1] encoded as 1..1e18 wei (tick is 1 wei); reject out-of-range early
if is_true(&crate::precise::Precise::stringGt(&priceWei, &Value::Str("1000000000000000000".to_string()))) {
panic!("{}", crate::exchange_errors::invalid_order(add(&self.id, &Value::Str(" createOrder() price must be a fraction between 0 and 1".to_string()))));
}
let mut amountWei: Value = self.to_orderbook_wei(amount.clone());
// shares are integer wei (1e18 = 1 share); a sub-wei amount that rounds to zero is invalid
if is_true(&crate::precise::Precise::stringLt(&amountWei, &Value::Str("1".to_string()))) {
panic!("{}", crate::exchange_errors::invalid_order(add(&self.id, &Value::Str(" createOrder() amount is too small (rounds to zero shares)".to_string()))));
}
let mut nonce: Value = self.safe_string_k(params.clone(), "nonce", &[self.number_to_string(self.milliseconds())]);
let mut expiration: Value = self.safe_string_k(params.clone(), "expiration", &[Value::Str("0".to_string())]);
let mut minFillAmount: Value = self.safe_string_k(params.clone(), "minFillAmount", &[Value::Str("0".to_string())]);
let mut order: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trader".to_string(), trader.clone());
m.insert("marketId".to_string(), marketId.clone());
m.insert("outcomeId".to_string(), self.parse_to_numeric(outcomeId.clone()));
m.insert("side".to_string(), self.parse_to_numeric(sideInt.clone()));
m.insert("amount".to_string(), amountWei.clone());
m.insert("price".to_string(), priceWei.clone());
m.insert("minFillAmount".to_string(), minFillAmount.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("expiration".to_string(), expiration.clone());
m
});
let mut signature: Value = self.sign_clob_order(order.clone(), networkId.clone());
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), order.clone());
m.insert("signature".to_string(), signature.clone());
m.insert("timeInForce".to_string(), timeInForce.clone());
m.insert("networkId".to_string(), networkId.clone());
m
});
Value::Null
}
/*
* @method
* @name myriad#createOrders
* @description places multiple order book orders. Myriad's batch endpoint is not reliable, so the
* orders are signed and submitted sequentially (not atomically)
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da8281e2bc49cf4914b07528
* @param {object[]} orders a list of order requests, each with outcome, type, side, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut ordersLength: Value = get_array_length(&orders);
let mut orderOutcomes: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1299: bool = true;
while { if !__for_first_1299 { i = add(&i, &Value::Int(1)); } __for_first_1299 = false; is_less_than(&i, &ordersLength) } {
let mut __oc: Value = self.safe_string_k(get_value(&orders, &i), "outcome", &[]);
if !is_equal(&__oc, &Value::Null) {
append_to_array(&mut orderOutcomes, __oc.clone());
}
}
}
self.load_outcomes(&[orderOutcomes.clone()]).await;
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1300: bool = true;
while { if !__for_first_1300 { i = add(&i, &Value::Int(1)); } __for_first_1300 = false; is_less_than(&i, &ordersLength) } {
let mut o: Value = get_value(&orders, &i);
let mut o: Value = get_value(&orders, &i);
let mut outcome: Value = self.safe_string_k(o.clone(), "outcome", &[]);
let mut type_var: Value = self.safe_string_k(o.clone(), "type", &[]);
let mut side: Value = self.safe_string_k(o.clone(), "side", &[]);
let mut amount: Value = self.safe_number_k(o.clone(), "amount", &[]);
let mut price: Value = self.safe_number_k(o.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(o.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_12 = self.extend(orderParams.clone(), &[params.clone()]);
let mut placed: Value = self.create_orderbook_order(outcome.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), __ws_arg_12]).await;
append_to_array(&mut result, placed.clone());
}
}
return result;
Value::Null
}
/*
* @method
* @name myriad#editOrder
* @description edits an open order by cancelling it and placing a replacement (gasless). Myriad's
* batch-modify endpoint is not reliable, so the cancel and replace are submitted sequentially
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da8281b58c5adb2f5998eec8
* @param {string} id the hash of the order to replace
* @param {string} outcome unified outcome of the new order
* @param {string} type 'limit' or 'market'
* @param {string} side 'buy' or 'sell'
* @param {float} amount number of outcome shares for the new order
* @param {float} [price] price per share as a fraction in [0, 1]
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {object} [params.orderResponse] a pre-fetched fetchOrder-style response for the order being replaced; avoids the internal lookup when already available, call fetchOrder to retrieve this data
* @param {object} [params.rawOrder] the raw order payload to cancel as an alternative to params.orderResponse, call fetchOrder to retrieve this data
* @param {string} [params.networkId] the order-book network id, required when using params.rawOrder without an embedded network id
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn edit_order(&mut self, mut id: Value, mut outcome: 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_outcome(outcome.clone(), &[]).await;
self.cancel_order(id.clone(), &[outcome.clone(), params.clone()]).await;
return self.create_orderbook_order(outcome.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]).await;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#createAmmOrder
* @description buys or sells outcome shares by submitting the quote's calldata as an on-chain AMM transaction. Requires a privateKey with gas + collateral on the market's network
* @param {string} outcome unified outcome or outcome id
* @param {string} [type] not used by the AMM path
* @param {string} side 'buy' or 'sell'
* @param {float} amount for buys this is collateral value to spend (when costDenominated=true); for sells this is shares to sell
* @param {float} [price] not used by the AMM path
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {object} [params.quote] a pre-fetched fetchTradeQuote result to reuse instead of requesting a new quote, call fetchTradeQuote to retrieve this data
* @param {string} [params.transactionHash] a pre-broadcast transaction hash; when provided the method skips transaction submission and only parses the order result, capture this value from sendEvmTransaction
* @param {boolean} [params.skipAllowance] optional override to skip the ERC20 allowance check/approval before a buy; implied true when params.transactionHash is provided
* @param {boolean} [params.skipWaitForReceipt] optional override to skip the post-send receipt wait; implied true when params.transactionHash is provided
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_amm_order(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// the AMM buy endpoint is priced in COLLATERAL, not shares — so a bare createOrder market buy
// would silently size `amount` as dollars (inconsistent with every other venue and the wiki).
// route dollar-sizing through createMarketBuyOrderWithCost (which sets costDenominated); a
// plain createOrder buy on the AMM is rejected so it can't misinterpret shares as collateral
let mut sideLower: Value = ternary(is_true(&(!is_equal(&side, &Value::Null))), to_lower(&side), Value::Null);
let mut isCostDenominated: Value = self.safe_bool_k(params.clone(), "costDenominated", &[Value::Bool(false)]);
if is_true(&(is_equal(&sideLower, &Value::Str("buy".to_string())))) && is_true(&(!is_equal(&isCostDenominated, &Value::Bool(true)))) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" createOrder() market buy on the AMM sizes by collateral, not shares — use createMarketBuyOrderWithCost(outcome, collateral) for a dollar buy, or the default order book (omit enableAmm) for a share-denominated order".to_string()))));
}
if is_equal(&self.privateKey, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrder() requires a privateKey to sign the on-chain transaction".to_string()))));
}
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[]);
let mut chains: Value = self.safe_dict_k(self.options.clone(), "chains", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut chainConfig: Value = self.safe_dict(chains.clone(), networkId.clone(), &[]);
if is_equal(&chainConfig, &Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(add(&add(&self.id, &Value::Str(" createOrder() has no on-chain config for network ".to_string())), &networkId)));
}
let mut rpcUrl: Value = self.safe_string2(params.clone(), Value::Str("rpcUrl".to_string()), Value::Str("rpc".to_string()), &[self.safe_string_k(chainConfig.clone(), "rpcUrl", &[])]);
let mut predictionMarket: Value = self.safe_string_k(chainConfig.clone(), "predictionMarket", &[]);
let mut tokenAddress: Value = self.safe_string2(params.clone(), Value::Str("token".to_string()), Value::Str("tokenAddress".to_string()), &[self.safe_string_k(info.clone(), "tokenAddress", &[])]);
let mut gasLimit: Value = self.safe_string_k(params.clone(), "gasLimit", &[Value::Str("0xaae60".to_string())]);
let mut sideStr: Value = sideLower.clone();
let mut quoteParams: Value = self.omit(params.clone(), Value::List(vec![Value::Str("rpcUrl".to_string()), Value::Str("rpc".to_string()), Value::Str("token".to_string()), Value::Str("tokenAddress".to_string()), Value::Str("gasLimit".to_string()), Value::Str("costDenominated".to_string()), Value::Str("quote".to_string()), Value::Str("transactionHash".to_string()), Value::Str("txHash".to_string()), Value::Str("skipAllowance".to_string()), Value::Str("skipWaitForReceipt".to_string())]), &[]);
let mut quote: Value = self.safe_dict_k(params.clone(), "quote", &[]);
if is_equal("e, &Value::Null) {
quote = self.fetch_trade_quote(outcome.clone(), sideStr.clone(), amount.clone(), &[quoteParams.clone()]).await;
}
let mut calldata: Value = self.safe_string(self.safe_dict_k(quote.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("calldata".to_string()), &[]);
if is_equal(&calldata, &Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" createAmmOrder is missing calldata from fetchTradeQuote".to_string()))));
}
let mut fromAddress: Value = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
let mut txHashParam: Value = self.safe_string2(params.clone(), Value::Str("transactionHash".to_string()), Value::Str("txHash".to_string()), &[]);
let mut hasPreBroadcastTxHash: Value = Value::Bool(!is_equal(&txHashParam, &Value::Null));
let mut skipAllowance: Value = self.safe_bool_k(params.clone(), "skipAllowance", &[hasPreBroadcastTxHash.clone()]);
if is_true(&(is_equal(&sideStr, &Value::Str("buy".to_string())))) && is_true(&(!is_equal(&tokenAddress, &Value::Null))) && is_true(&(!is_equal(&skipAllowance, &Value::Bool(true)))) {
self.ensure_erc20_allowance(rpcUrl.clone(), networkId.clone(), tokenAddress.clone(), fromAddress.clone(), predictionMarket.clone()).await;
}
let mut skipWaitForReceipt: Value = self.safe_bool_k(params.clone(), "skipWaitForReceipt", &[hasPreBroadcastTxHash.clone()]);
let mut txHash: Value = txHashParam.clone();
if is_equal(&txHash, &Value::Null) {
let __ws_arg_13 = self.parse_to_int(networkId.clone());
txHash = self.send_evm_transaction(rpcUrl.clone(), __ws_arg_13, fromAddress.clone(), predictionMarket.clone(), Value::Str("0x0".to_string()), calldata.clone(), gasLimit.clone()).await;
}
if !is_equal(&skipWaitForReceipt, &Value::Bool(true)) {
self.wait_for_transaction_receipt(rpcUrl.clone(), txHash.clone(), &[]).await;
}
return self.parse_trade_tx(txHash.clone(), quote.clone(), outcomeObj.clone(), sideStr.clone());
Value::Null
}
/*
* @method
* @name myriad#createMarketBuyOrderWithCost
* @description buys an outcome by spending a fixed collateral amount on the AMM (dollar-sizing)
* @see createAmmOrder supports params.quote from fetchTradeQuote(outcome, 'buy', amount)
* @param {string} outcome unified outcome handle
* @param {number} cost collateral amount to spend
* @param {object} [params] extra parameters passed through to createAmmOrder
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_market_buy_order_with_cost(&mut self, mut outcome: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// myriad's AMM prices buys in COLLATERAL, so `cost` maps directly onto the AMM value input.
// mark the order cost-denominated so createAmmOrder spends exactly `cost` (not `cost` shares)
let mut request: Value = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("enableAmm".to_string(), Value::Bool(true));
m.insert("costDenominated".to_string(), Value::Bool(true));
m
})]);
return self.create_order(outcome.clone(), Value::Str("market".to_string()), Value::Str("buy".to_string()), cost.clone(), &[Value::Null, request.clone()]).await;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#signOrderbookTypedData
* @description EIP-712 signs an order-book typed-data message with the wallet private key (returns a 65-byte 0x signature)
* @returns {string} the hex signature
*/
pub fn sign_orderbook_typed_data(&self, mut types: Value, mut message: Value, mut networkId: Value) -> Value {
let mut chains: Value = self.safe_dict_k(self.options.clone(), "chains", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut chainConfig: Value = self.safe_dict(chains.clone(), networkId.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut exchangeAddress: Value = self.safe_string_k(chainConfig.clone(), "obExchangeAddress", &[]);
if is_equal(&exchangeAddress, &Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(add(&add(&self.id, &Value::Str(" order book trading is not configured for network ".to_string())), &networkId)));
}
let mut domainName: Value = self.safe_string_k(self.options.clone(), "obDomainName", &[Value::Str("MyriadCTFExchange".to_string())]);
let mut domainVersion: Value = self.safe_string_k(self.options.clone(), "obDomainVersion", &[Value::Str("1".to_string())]);
let mut domain: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), domainName.clone());
m.insert("version".to_string(), domainVersion.clone());
m.insert("chainId".to_string(), self.parse_to_int(networkId.clone()));
m.insert("verifyingContract".to_string(), exchangeAddress.clone());
m
});
let mut encoded: Value = self.eth_encode_structured_data(domain.clone(), types.clone(), message.clone());
let mut digest: Value = self.hash(encoded.clone(), Value::Str("keccak".to_string()), &[Value::Str("hex".to_string())]);
let mut signature: Value = ecdsa(digest.clone(), self.remove0x_prefix(self.privateKey.clone()), Value::Str("secp256k1".to_string()), Value::Null);
let mut rRaw: Value = get_value(&signature, &Value::Str("r".to_string()));
let mut sRaw: Value = get_value(&signature, &Value::Str("s".to_string()));
let mut r: Value = pad_start(&rRaw, &Value::Int(64), &Value::Str("0".to_string()));
let mut s: Value = pad_start(&sRaw, &Value::Int(64), &Value::Str("0".to_string()));
let mut v: Value = self.sum(&[Value::Int(27), get_value(&signature, &Value::Str("v".to_string()))]);
let mut sigHex: Value = add(&add(&add(&Value::Str("0x".to_string()), &r), &s), &self.int_to_base16(v.clone(), &[]));
return to_lower(&sigHex);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#signClobOrder
* @description EIP-712 signs the order-book Order struct
* @returns {string} the hex signature
*/
pub fn sign_clob_order(&self, mut message: Value, mut networkId: Value) -> Value {
let mut orderStruct: Value = Value::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("trader".to_string()));
m.insert("type".to_string(), Value::Str("address".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("marketId".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("outcomeId".to_string()));
m.insert("type".to_string(), Value::Str("uint8".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("side".to_string()));
m.insert("type".to_string(), Value::Str("uint8".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("price".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("minFillAmount".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("expiration".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
})]);
return self.sign_orderbook_typed_data(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Order".to_string(), orderStruct.clone());
m
}), message.clone(), networkId.clone());
Value::Null
}
/*
* @ignore
* @method
* @name myriad#signCancelAll
* @description EIP-712 signs the order-book CancelAll struct
* @returns {string} the hex signature
*/
pub fn sign_cancel_all(&self, mut message: Value, mut networkId: Value) -> Value {
let mut cancelStruct: Value = Value::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("trader".to_string()));
m.insert("type".to_string(), Value::Str("address".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("marketId".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("timestamp".to_string()));
m.insert("type".to_string(), Value::Str("uint256".to_string()));
m
})]);
return self.sign_orderbook_typed_data(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CancelAll".to_string(), cancelStruct.clone());
m
}), message.clone(), networkId.clone());
Value::Null
}
/*
* @ignore
* @method
* @name myriad#clobOrderMessage
* @description normalises a fetched order-book order into a typed-data message (uint256 fields as strings, uint8 fields as ints)
* @returns {object} the typed-data message
*/
pub fn clob_order_message(&self, mut rawOrder: Value) -> Value {
let mut signer: Value = self.safe_string2(rawOrder.clone(), Value::Str("trader".to_string()), Value::Str("user".to_string()), &[]);
if !is_equal(&self.privateKey, &Value::Null) {
signer = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
} else {
signer = self.wallet_address_or_undefined();
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trader".to_string(), signer.clone());
m.insert("marketId".to_string(), self.safe_string_k(rawOrder.clone(), "marketId", &[]));
m.insert("outcomeId".to_string(), self.safe_integer_k(rawOrder.clone(), "outcomeId", &[Value::Int(0)]));
m.insert("side".to_string(), self.safe_integer_k(rawOrder.clone(), "side", &[Value::Int(0)]));
m.insert("amount".to_string(), self.safe_string_k(rawOrder.clone(), "amount", &[]));
m.insert("price".to_string(), self.safe_string_k(rawOrder.clone(), "price", &[]));
m.insert("minFillAmount".to_string(), self.safe_string_k(rawOrder.clone(), "minFillAmount", &[Value::Str("0".to_string())]));
m.insert("nonce".to_string(), self.safe_string_k(rawOrder.clone(), "nonce", &[]));
m.insert("expiration".to_string(), self.safe_string_k(rawOrder.clone(), "expiration", &[Value::Str("0".to_string())]));
m
});
Value::Null
}
/*
* @ignore
* @method
* @name myriad#getOrderResponseFromParams
* @description extracts an optional pre-fetched order response from params for static tests and higher-level callers that already resolved the original order
* @returns {object} the fetchOrder-style response wrapper or a raw-order wrapper
*/
pub fn get_order_response_from_params(&self, mut id: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut orderResponse: Value = self.safe_dict_k(params.clone(), "orderResponse", &[]);
if !is_equal(&orderResponse, &Value::Null) {
return orderResponse;
}
let mut rawOrder: Value = self.safe_dict_k(params.clone(), "rawOrder", &[]);
if !is_equal(&rawOrder, &Value::Null) {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderHash".to_string(), id.clone());
m.insert("order".to_string(), rawOrder.clone());
m.insert("networkId".to_string(), self.safe_string2(params.clone(), Value::Str("networkId".to_string()), Value::Str("network_id".to_string()), &[]));
m
});
}
let mut orderResponsesById: Value = self.safe_dict_k(params.clone(), "orderResponses", &[]);
if !is_equal(&orderResponsesById, &Value::Null) {
let mut keyedResponse: Value = self.safe_dict(orderResponsesById.clone(), id.clone(), &[]);
if !is_equal(&keyedResponse, &Value::Null) {
return keyedResponse;
}
}
let mut orderResponses: Value = self.safe_list_k(params.clone(), "orderResponses", &[]);
if !is_equal(&orderResponses, &Value::Null) {
let mut responsesLength: Value = get_array_length(&orderResponses);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1301: bool = true;
while { if !__for_first_1301 { i = add(&i, &Value::Int(1)); } __for_first_1301 = false; is_less_than(&i, &responsesLength) } {
let mut current: Value = self.safe_dict(orderResponses.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut currentId: Value = self.safe_string_n(current.clone(), Value::List(vec![Value::Str("orderHash".to_string()), Value::Str("hash".to_string()), Value::Str("id".to_string())]), &[]);
if is_true(&(!is_equal(¤tId, &Value::Null))) && is_true(&(is_equal(¤tId, &id))) {
return current;
}
}
}
}
return Value::Null;
Value::Null
}
/*
* @ignore
* @method
* @name myriad#toOrderbookWei
* @description scales a decimal value by 1e18 and truncates to an integer wei string
* @returns {string} the integer wei string
*/
pub fn to_orderbook_wei(&self, mut value: Value) -> Value {
let mut valueStr: Value = self.number_to_string(value.clone());
let mut scaled: Value = crate::precise::Precise::stringMul(&valueStr, &Value::Str("1000000000000000000".to_string()));
// use > -1 (not >= 0): when '.' is absent PHP's mb_strpos returns false, and false >= 0
// coerces to true (wrongly truncating to empty), whereas false > -1 correctly coerces to false
if is_equal(&scaled, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" toOrderbookWei() missing scaled".to_string()))));
}
let mut dotIndex: Value = get_index_of(&scaled, &Value::Str(".".to_string()));
if is_equal(&scaled, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" toOrderbookWei() missing scaled".to_string()))));
}
if is_greater_than(&dotIndex, &negate(&Value::Int(1))) {
return slice(&scaled, &Value::Int(0), &dotIndex);
}
return scaled;
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("open".to_string(), Value::Str("open".to_string()));
m.insert("pending".to_string(), Value::Str("open".to_string()));
m.insert("partially_filled".to_string(), Value::Str("open".to_string()));
m.insert("filled".to_string(), Value::Str("closed".to_string()));
m.insert("cancelled".to_string(), Value::Str("canceled".to_string()));
m.insert("canceled".to_string(), Value::Str("canceled".to_string()));
m.insert("expired".to_string(), Value::Str("expired".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_prediction_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut inner: Value = self.safe_dict_k(order.clone(), "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderHash: Value = self.safe_string2(order.clone(), Value::Str("orderHash".to_string()), Value::Str("hash".to_string()), &[]);
let mut sideInt: Value = self.safe_integer_k(inner.clone(), "side", &[]);
let mut side: Value = ternary(is_true(&(is_equal(&sideInt, &Value::Int(1)))), Value::Str("sell".to_string()), Value::Str("buy".to_string()));
let mut amountWei: Value = self.safe_string_k(inner.clone(), "amount", &[]);
let mut priceWei: Value = self.safe_string_k(inner.clone(), "price", &[]);
let mut filledWei: Value = self.safe_string_k(order.clone(), "filledAmount", &[]);
let mut amount: Value = ternary(is_true(&(is_equal(&amountWei, &Value::Null))), Value::Null, self.parse_number(crate::precise::Precise::stringDiv(&amountWei, &Value::Str("1000000000000000000".to_string())), &[]));
let mut price: Value = ternary(is_true(&(is_equal(&priceWei, &Value::Null))), Value::Null, self.parse_number(crate::precise::Precise::stringDiv(&priceWei, &Value::Str("1000000000000000000".to_string())), &[]));
let mut filled: Value = ternary(is_true(&(is_equal(&filledWei, &Value::Null))), Value::Null, self.parse_number(crate::precise::Precise::stringDiv(&filledWei, &Value::Str("1000000000000000000".to_string())), &[]));
let mut statusRaw: Value = self.safe_string_lower(order.clone(), Value::Str("status".to_string()), &[]);
let mut status: Value = self.parse_order_status(statusRaw.clone());
let mut timestamp: Value = self.parse8601(self.safe_string_k(order.clone(), "createdAt", &[]));
let mut tif: Value = self.safe_string_upper(order.clone(), Value::Str("timeInForce".to_string()), &[]);
let mut isMarketTif: bool = is_true(&(is_equal(&tif, &Value::Str("FOK".to_string())))) || is_true(&(is_equal(&tif, &Value::Str("FAK".to_string()))));
// resolve the outcome from market/outcome ids when no market was passed (e.g. fetchOrders without a outcome)
let mut outcome: Value = ternary(is_true(&(is_equal(&market, &Value::Null))), Value::Null, self.safe_string_k(market.clone(), "outcome", &[]));
let mut outcomeObj: Value = market.clone();
if is_equal(&outcome, &Value::Null) {
// the REST order has no top-level networkId; order book lives on the default network
let mut networkId: Value = self.safe_string2(order.clone(), Value::Str("networkId".to_string()), Value::Str("network_id".to_string()), &[self.safe_string_k(self.options.clone(), "defaultNetworkId", &[Value::Str("56".to_string())])]);
let mut marketId: Value = self.safe_string_k(inner.clone(), "marketId", &[]);
let mut outcomeId: Value = self.safe_string_k(inner.clone(), "outcomeId", &[]);
let mut composite: Value = Value::Null;
if is_true(&(!is_equal(&networkId, &Value::Null))) && is_true(&(!is_equal(&marketId, &Value::Null))) && is_true(&(!is_equal(&outcomeId, &Value::Null))) {
composite = add(&add(&add(&add(&networkId, &Value::Str(":".to_string())), &marketId), &Value::Str("/".to_string())), &outcomeId);
}
outcomeObj = self.safe_outcome(composite.clone(), &[market.clone()]);
outcome = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
}
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), orderHash.clone());
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), order.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("outcome".to_string(), outcome.clone());
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("type".to_string(), ternary(is_true(&isMarketTif), Value::Str("market".to_string()), Value::Str("limit".to_string())));
m.insert("timeInForce".to_string(), tif.clone());
m.insert("postOnly".to_string(), Value::Bool((is_equal(&tif, &Value::Str("PO".to_string())))));
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), price.clone());
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("amount".to_string(), amount.clone());
m.insert("filled".to_string(), filled.clone());
m.insert("remaining".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("status".to_string(), status.clone());
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parseAmmEventToOrder
* @description parses a user event row from the AMM activity feed into a closed prediction order structure
* @param {object} trade the raw user event row
* @param {object} [market] the outcome object the trade belongs to
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub fn parse_amm_event_to_order(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut networkId: Value = self.safe_string_k(trade.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(trade.clone(), "marketId", &[]);
let mut rawOutcomeId: Value = self.safe_string_k(trade.clone(), "outcomeId", &[]);
let mut composite: Value = Value::Null;
if is_true(&(!is_equal(&networkId, &Value::Null))) && is_true(&(!is_equal(&marketId, &Value::Null))) && is_true(&(!is_equal(&rawOutcomeId, &Value::Null))) {
composite = add(&add(&add(&add(&networkId, &Value::Str(":".to_string())), &marketId), &Value::Str("/".to_string())), &rawOutcomeId);
}
let mut outcomeObj: Value = self.safe_outcome(composite.clone(), &[market.clone()]);
let mut marketSlug: Value = self.safe_string_k(trade.clone(), "marketSlug", &[marketId.clone()]);
let mut outcomeTitle: Value = self.safe_string_k(trade.clone(), "outcomeTitle", &[rawOutcomeId.clone()]);
let mut outcome: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
if is_equal(&outcome, &Value::Null) {
outcome = self.slug_to_outcome_symbol(marketSlug.clone(), marketSlug.clone(), outcomeTitle.clone());
}
let mut marketSymbol: Value = self.safe_string_k(outcomeObj.clone(), "market", &[]);
if is_equal(&marketSymbol, &Value::Null) {
marketSymbol = self.slug_to_market_symbol(marketSlug.clone(), marketSlug.clone());
}
let mut label: Value = self.safe_string_k(outcomeObj.clone(), "label", &[]);
if is_equal(&label, &Value::Null) {
label = outcomeTitle.clone();
}
let mut timestamp: Value = self.safe_timestamp(trade.clone(), Value::Str("timestamp".to_string()), &[]);
let mut amountStr: Value = self.safe_string_k(trade.clone(), "shares", &[]);
let mut costStr: Value = self.safe_string_k(trade.clone(), "value", &[]);
let mut priceStr: Value = Value::Null;
if is_true(&(!is_equal(&amountStr, &Value::Null))) && is_true(&(!is_equal(&costStr, &Value::Null))) && !is_true(&crate::precise::Precise::stringEq(&amountStr, &Value::Str("0".to_string()))) {
priceStr = crate::precise::Precise::stringDiv(&costStr, &amountStr);
}
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string2(trade.clone(), Value::Str("txId".to_string()), Value::Str("id".to_string()), &[]));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("lastTradeTimestamp".to_string(), timestamp.clone());
m.insert("lastUpdateTimestamp".to_string(), Value::Null);
m.insert("status".to_string(), Value::Str("closed".to_string()));
m.insert("outcome".to_string(), outcome.clone());
m.insert("outcomeId".to_string(), composite.clone());
m.insert("label".to_string(), label.clone());
m.insert("market".to_string(), marketSymbol.clone());
m.insert("type".to_string(), Value::Str("market".to_string()));
m.insert("timeInForce".to_string(), Value::Str("IOC".to_string()));
m.insert("postOnly".to_string(), Value::Bool(false));
m.insert("side".to_string(), self.safe_string_lower(trade.clone(), Value::Str("action".to_string()), &[]));
m.insert("price".to_string(), self.parse_number(priceStr.clone(), &[]));
m.insert("triggerPrice".to_string(), Value::Null);
m.insert("amount".to_string(), self.parse_number(amountStr.clone(), &[]));
m.insert("filled".to_string(), self.parse_number(amountStr.clone(), &[]));
m.insert("remaining".to_string(), Value::Int(0));
m.insert("cost".to_string(), self.parse_number(costStr.clone(), &[]));
m.insert("average".to_string(), self.parse_number(priceStr.clone(), &[]));
m.insert("fee".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), Value::Null);
m.insert("trades".to_string(), Value::List(vec![]));
m.insert("event".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#fetchAmmOrders
* @description fetches executed AMM trades for a wallet from the user events feed and exposes them as closed prediction orders
* @param {string} [outcome] unified outcome to filter by
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra exchange-specific parameters
* @returns {object[]} a list of closed [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_amm_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut requestedStatus: Value = self.safe_string_lower(params.clone(), Value::Str("status".to_string()), &[]);
if is_true(&(is_equal(&requestedStatus, &Value::Str("open".to_string())))) || is_true(&(is_equal(&requestedStatus, &Value::Str("cancelled".to_string())))) || is_true(&(is_equal(&requestedStatus, &Value::Str("canceled".to_string())))) || is_true(&(is_equal(&requestedStatus, &Value::Str("expired".to_string())))) {
return Value::List(vec![]);
}
let mut trader: Value = self.safe_string2(params.clone(), Value::Str("trader".to_string()), Value::Str("address".to_string()), &[]);
if is_equal(&trader, &Value::Null) {
trader = self.wallet_address_or_undefined();
}
if is_equal(&trader, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchOrders() for AMM history requires a trader address or wallet/privateKey".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("address".to_string(), trader.clone());
m
});
let mut outcomeObj: Value = Value::Null;
let mut outcomeSymbol: Value = Value::Null;
let mut rowOutcomeId: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
outcomeObj = self.load_outcome(outcome.clone(), &[]).await;
outcomeSymbol = self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome.clone()]);
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
add_element_to_object(&mut request, &Value::Str("market_id".to_string()), self.safe_string_k(info.clone(), "marketId", &[]));
add_element_to_object(&mut request, &Value::Str("network_id".to_string()), self.safe_string_k(info.clone(), "networkId", &[]));
rowOutcomeId = self.safe_string_k(info.clone(), "outcomeId", &[]);
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("since".to_string()), self.parse_to_int(divide(&since, &Value::Int(1000))));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("trader".to_string()), Value::Str("address".to_string()), Value::Str("status".to_string())]), &[]);
let __ws_arg_14 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.myriad_public_get_users_address_events(&[__ws_arg_14]).await;
//
// {
// "data": [
// {
// "user": "0xd282B1436BC99A86eC24A164f7BEeed42CFE8511",
// "action": "sell",
// "marketTitle": "Will Base TGE in 2026?",
// "marketSlug": "will-base-tge-in-2026",
// "marketId": 170145,
// "networkId": 56,
// "outcomeTitle": "Yes",
// "outcomeId": 0,
// "imageUrl": "https://cdn.polkamarkets.com/Qmacfs1qiiUW5cnMRUyzji393Vn2DcvNdydGukf1Xk82b6",
// "shares": 8.22739948,
// "value": 0.9789,
// "timestamp": 1784708801,
// "blockNumber": 111442601,
// "token": "0x8d0D000Ee44948FC98c9B98A4FA4921476f08B0d",
// "txId": "0x93842cbb56b852436f53f7bd5d03580a550c0ac08d49fa80cafaed316d7590d7"
// },
// ],
// "pagination": {
// "page": 1,
// "limit": 20,
// "total": 2,
// "totalPages": 1,
// "hasNext": false,
// "hasPrev": false
// }
// }
//
let mut rows: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
let mut rowsLength: Value = get_array_length(&rows);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1302: bool = true;
while { if !__for_first_1302 { i = add(&i, &Value::Int(1)); } __for_first_1302 = false; is_less_than(&i, &rowsLength) } {
let mut row: Value = get_value(&rows, &i);
let mut row: Value = get_value(&rows, &i);
let mut action: Value = self.safe_string_lower(row.clone(), Value::Str("action".to_string()), &[]);
if is_true(&(!is_equal(&action, &Value::Str("buy".to_string())))) && is_true(&(!is_equal(&action, &Value::Str("sell".to_string())))) {
continue;
}
let mut currentOutcomeId: Value = self.safe_string_k(row.clone(), "outcomeId", &[]);
if is_true(&(!is_equal(&rowOutcomeId, &Value::Null))) && is_true(&(!is_equal(¤tOutcomeId, &rowOutcomeId))) {
continue;
}
append_to_array(&mut result, self.parse_amm_event_to_order(row.clone(), &[outcomeObj.clone()]));
}
}
let mut sorted: Value = self.sort_by(result.clone(), Value::Str("timestamp".to_string()), &[Value::Bool(true)]);
return self.filter_by_outcome_since_limit(sorted.clone(), &[outcomeSymbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name myriad#cancelOrder
* @description cancels an open order book order by its hash (re-signs the original order to prove ownership; gasless)
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da8281b58c5adb2f5998eec8
* @param {string} id the order hash returned by createOrder
* @param {string} [outcome] unified outcome the order belongs to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {object} [params.orderResponse] a pre-fetched fetchOrder-style response for the target order; avoids the internal order lookup when already available, call fetchOrder to retrieve this data
* @param {object} [params.rawOrder] the raw order payload to sign as an alternative to params.orderResponse, call fetchOrder to retrieve this data
* @param {string} [params.networkId] the order-book network id, required when using params.rawOrder without an embedded network id
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.privateKey, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelOrder() requires a privateKey to sign the cancellation".to_string()))));
}
let mut fetched: Value = self.get_order_response_from_params(id.clone(), &[params.clone()]);
let mut networkIdParam: Value = self.safe_string2(params.clone(), Value::Str("networkId".to_string()), Value::Str("network_id".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("orderResponse".to_string()), Value::Str("orderResponses".to_string()), Value::Str("rawOrder".to_string()), Value::Str("networkId".to_string()), Value::Str("network_id".to_string())]), &[]);
if is_equal(&fetched, &Value::Null) {
let __ws_arg_15 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hash".to_string(), id.clone());
m
}), &[params.clone()]);
fetched = self.myriad_public_get_orders_hash(&[__ws_arg_15]).await;
}
let mut fetchedInfo: Value = self.safe_dict_k(fetched.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawOrder: Value = self.safe_dict_k(fetched.clone(), "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawOrderKeys: Value = object_keys(&rawOrder);
let mut rawOrderKeysLength: Value = get_array_length(&rawOrderKeys);
if is_equal(&rawOrderKeysLength, &Value::Int(0)) {
rawOrder = self.safe_dict_k(fetchedInfo.clone(), "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
let mut networkId: Value = self.safe_string_n(fetched.clone(), Value::List(vec![Value::Str("networkId".to_string()), Value::Str("network_id".to_string())]), &[]);
if is_equal(&networkId, &Value::Null) {
networkId = self.safe_string_n(fetchedInfo.clone(), Value::List(vec![Value::Str("networkId".to_string()), Value::Str("network_id".to_string())]), &[]);
}
if is_equal(&networkId, &Value::Null) {
networkId = networkIdParam.clone();
}
if is_equal(&networkId, &Value::Null) {
networkId = self.safe_string_k(self.options.clone(), "defaultNetworkId", &[Value::Str("56".to_string())]);
}
let mut message: Value = self.clob_order_message(rawOrder.clone());
let mut signature: Value = self.sign_clob_order(message.clone(), networkId.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hash".to_string(), id.clone());
m.insert("order".to_string(), message.clone());
m.insert("signature".to_string(), signature.clone());
m.insert("network_id".to_string(), self.parse_to_int(networkId.clone()));
m
});
let __ws_arg_16 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.myriad_public_delete_orders_hash(&[__ws_arg_16]).await;
//
// {
// "orderHash": "0x758a1763c59bbe61c314f3c0c9b5bae0ad942120500eb39e3e8349bbe13990e0",
// "status": "cancelled"
// }
//
let mut status: Value = self.safe_string_k(response.clone(), "status", &[Value::Str("canceled".to_string())]);
let mut wrapper: Value = self.extend(fetched.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), status.clone());
m.insert("networkId".to_string(), networkId.clone());
m
})]);
let mut market: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
market = self.load_outcome(outcome.clone(), &[]).await;
}
return self.parse_prediction_order(wrapper.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name myriad#cancelAllOrders
* @description cancels all open order book orders for the wallet, optionally scoped to one market (gasless)
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da8281e7a14cd34e6a716761
* @param {string} [outcome] unified outcome; when omitted cancels across all markets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list with one [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure) whose `info` carries the cancelled count
*/
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.privateKey, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelAllOrders() requires a privateKey to sign the cancellation".to_string()))));
}
let mut trader: Value = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
let mut marketId: Value = self.safe_string_k(params.clone(), "market_id", &[Value::Str("0".to_string())]);
let mut networkId: Value = self.safe_string_k(params.clone(), "network_id", &[self.safe_string(self.options.clone(), Value::Str("defaultNetworkId".to_string()), &[Value::Str("56".to_string())])]);
if !is_equal(&outcome, &Value::Null) {
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
marketId = self.safe_string_k(info.clone(), "marketId", &[marketId.clone()]);
networkId = self.safe_string_k(info.clone(), "networkId", &[networkId.clone()]);
}
// timestamp defaults to now (unix seconds) but can be pinned via params for idempotent retries
let mut timestamp: Value = self.safe_string_k(params.clone(), "timestamp", &[self.number_to_string(self.seconds())]);
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trader".to_string(), trader.clone());
m.insert("marketId".to_string(), marketId.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m
});
let mut signature: Value = self.sign_cancel_all(message.clone(), networkId.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trader".to_string(), trader.clone());
m.insert("market_id".to_string(), self.parse_to_int(marketId.clone()));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("signature".to_string(), signature.clone());
m.insert("network_id".to_string(), self.parse_to_int(networkId.clone()));
m
});
let mut response: Value = self.myriad_public_post_orders_cancel_all(&[request.clone()]).await;
return Value::List(vec![self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("status".to_string(), Value::Str("canceled".to_string()));
m
}), &[])]);
Value::Null
}
/*
* @method
* @name myriad#cancelOrders
* @description cancels multiple open order book orders by hash in one request (gasless)
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da828177961fd94a6055966f
* @param {string[]} ids the order hashes to cancel
* @param {string} [outcome] not used by myriad cancelOrders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {object} [params.orderResponses] pre-fetched fetchOrder-style responses keyed by order hash, or an array of such responses; avoids the internal per-order lookups when already available, call fetchOrder for each id to retrieve this data
* @param {string} [params.networkId] the order-book network id fallback for any supplied raw order data
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.privateKey, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelOrders() requires a privateKey to sign the cancellations".to_string()))));
}
let mut paramsForLookup: Value = params.clone();
let mut networkIdParam: Value = self.safe_string2(params.clone(), Value::Str("networkId".to_string()), Value::Str("network_id".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("orderResponse".to_string()), Value::Str("orderResponses".to_string()), Value::Str("rawOrder".to_string()), Value::Str("networkId".to_string()), Value::Str("network_id".to_string())]), &[]);
let mut idsLength: Value = get_array_length(&ids);
let mut signedOrders: Value = Value::List(vec![]);
let mut wrappers: Value = Value::List(vec![]);
let mut networkId: Value = self.safe_string_k(self.options.clone(), "defaultNetworkId", &[Value::Str("56".to_string())]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1303: bool = true;
while { if !__for_first_1303 { i = add(&i, &Value::Int(1)); } __for_first_1303 = false; is_less_than(&i, &idsLength) } {
let mut id: Value = get_value(&ids, &i);
let mut id: Value = get_value(&ids, &i);
let mut fetched: Value = self.get_order_response_from_params(id.clone(), &[paramsForLookup.clone()]);
if is_equal(&fetched, &Value::Null) {
fetched = self.myriad_public_get_orders_hash(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hash".to_string(), id.clone());
m
})]).await;
}
let mut fetchedInfo: Value = self.safe_dict_k(fetched.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawOrder: Value = self.safe_dict_k(fetched.clone(), "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawOrderKeys: Value = object_keys(&rawOrder);
let mut rawOrderKeysLength: Value = get_array_length(&rawOrderKeys);
if is_equal(&rawOrderKeysLength, &Value::Int(0)) {
rawOrder = self.safe_dict_k(fetchedInfo.clone(), "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
let mut fetchedNetworkId: Value = self.safe_string_n(fetched.clone(), Value::List(vec![Value::Str("networkId".to_string()), Value::Str("network_id".to_string())]), &[]);
if is_equal(&fetchedNetworkId, &Value::Null) {
fetchedNetworkId = self.safe_string_n(fetchedInfo.clone(), Value::List(vec![Value::Str("networkId".to_string()), Value::Str("network_id".to_string())]), &[]);
}
if is_equal(&fetchedNetworkId, &Value::Null) {
fetchedNetworkId = networkIdParam.clone();
}
if !is_equal(&fetchedNetworkId, &Value::Null) {
networkId = fetchedNetworkId.clone();
}
let mut message: Value = self.clob_order_message(rawOrder.clone());
let mut signature: Value = self.sign_clob_order(message.clone(), networkId.clone());
append_to_array(&mut signedOrders, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), message.clone());
m.insert("signature".to_string(), signature.clone());
m
}));
append_to_array(&mut wrappers, self.extend(fetched.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("canceled".to_string()));
m.insert("networkId".to_string(), networkId.clone());
m
})]));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), signedOrders.clone());
m.insert("network_id".to_string(), self.parse_to_int(networkId.clone()));
m
});
let __ws_arg_17 = self.extend(request.clone(), &[params.clone()]);
self.myriad_public_post_orders_cancel_batch(&[__ws_arg_17]).await;
return self.parse_prediction_orders(wrappers.clone(), &[]);
Value::Null
}
/*
* @method
* @name myriad#fetchOrder
* @description fetches a single order book order by its hash
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da828116b8a0d976baea1df0
* @param {string} id the order hash
* @param {string} [outcome] unified outcome the order belongs to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __ws_arg_18 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hash".to_string(), id.clone());
m
}), &[params.clone()]);
let mut response: Value = self.myriad_public_get_orders_hash(&[__ws_arg_18]).await;
//
// {
// "orderHash": "0x758a1763c59bbe61c314f3c0c9b5bae0ad942120500eb39e3e8349bbe13990e0",
// "clientOrderId": null,
// "order": {
// "trader": "0xd282B1436BC99A86eC24A164f7BEeed42CFE8511",
// "marketId": 827,
// "outcomeId": 0,
// "side": 0,
// "amount": "1000000000000000000",
// "price": "10000000000000000",
// "minFillAmount": "0",
// "nonce": "1784793980668",
// "expiration": "0"
// },
// "status": "cancelled",
// "signatureType": 0,
// "filledAmount": "0",
// "timeInForce": "GTC",
// "createdAt": "2026-07-23T08:06:21.279Z",
// "filledAt": null,
// "networkId": 56,
// "updatedAt": "2026-07-23T08:22:23.987Z",
// "cancelledAt": "2026-07-23T08:22:23.987Z"
// }
//
let mut market: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
market = self.load_outcome(outcome.clone(), &[]).await;
}
return self.parse_prediction_order(response.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name myriad#fetchOrders
* @description fetches order book orders for the wallet (or any trader passed via params.trader), or amm closed orders
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da828171a003cf996487d008
* @param {string} [outcome] unified outcome to filter by
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.trader] wallet address to query (defaults to the configured wallet)
* @param {string} [params.status] 'open', 'filled', 'cancelled' or 'expired'
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut trader: Value = self.safe_string_k(params.clone(), "trader", &[]);
if is_equal(&trader, &Value::Null) {
if !is_equal(&self.privateKey, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("trader".to_string()), self.eth_get_address_from_private_key(self.privateKey.clone(), &[]));
} else if !is_equal(&self.walletAddress, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("trader".to_string()), self.walletAddress.clone());
}
}
let mut requestedTradingModel: Value = self.safe_string_lower2(params.clone(), Value::Str("tradingModel".to_string()), Value::Str("trading_model".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("tradingModel".to_string()), Value::Str("trading_model".to_string())]), &[]);
let mut outcomeObj: Value = Value::Null;
let mut outcomeSymbol: Value = Value::Null;
if !is_equal(&outcome, &Value::Null) {
outcomeObj = self.load_outcome(outcome.clone(), &[]).await;
outcomeSymbol = self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome.clone()]);
if is_equal(&requestedTradingModel, &Value::Null) {
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
requestedTradingModel = self.safe_string_lower(info.clone(), Value::Str("tradingModel".to_string()), &[]);
}
}
if is_equal(&requestedTradingModel, &Value::Str("amm".to_string())) {
return self.fetch_amm_orders(&[outcome.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let __ws_arg_19 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.myriad_public_get_orders(&[__ws_arg_19]).await;
//
// {
// "data": [
// {
// "orderHash": "0x88e5c348bedc7336037bf9a2dc3e074431d386a01a2be07763373c794d28ffc2",
// "clientOrderId": null,
// "order": {
// "trader": "0xd282B1436BC99A86eC24A164f7BEeed42CFE8511",
// "marketId": 827,
// "outcomeId": 0,
// "side": 0,
// "amount": "1000000000000000000",
// "price": "10000000000000000",
// "minFillAmount": "0",
// "nonce": "1784713298605",
// "expiration": "0"
// },
// "status": "open",
// "signatureType": 0,
// "filledAmount": "0",
// "timeInForce": "GTC",
// "createdAt": "2026-07-22T09:41:39.035Z",
// "filledAt": null
// }
// ],
// "pagination": {
// "page": 1,
// "limit": 5000,
// "total": 1,
// "totalPages": 1,
// "hasNext": false,
// "hasPrev": false
// }
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
// the /orders endpoint ignores a market_id filter server-side (it returns nothing even for a
// valid market), so parse every order — each self-resolves its outcome from the network/market/
// outcome ids — and filter by the requested outcome client-side
let mut orders: Value = self.parse_prediction_orders(data.clone(), &[]);
return self.filter_by_outcome_since_limit(orders.clone(), &[outcomeSymbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name myriad#fetchOpenOrders
* @description fetches open order book orders for the wallet
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da828171a003cf996487d008
* @param {string} [outcome] unified outcome to filter by
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("open".to_string()));
m
});
let __ws_arg_20 = self.extend(request.clone(), &[params.clone()]);
return self.fetch_orders(&[outcome.clone(), since.clone(), limit.clone(), __ws_arg_20]).await;
Value::Null
}
/*
* @method
* @name myriad#fetchClosedOrders
* @description fetches the wallet's filled order book orders
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da828171a003cf996487d008
* @param {string} [outcome] unified outcome to filter by
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("filled".to_string()));
m
});
let __ws_arg_21 = self.extend(request.clone(), &[params.clone()]);
return self.fetch_orders(&[outcome.clone(), since.clone(), limit.clone(), __ws_arg_21]).await;
Value::Null
}
/*
* @method
* @name myriad#fetchCanceledOrders
* @description fetches the wallet's cancelled order book orders
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da828171a003cf996487d008
* @param {string} [outcome] unified outcome to filter by
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn fetch_canceled_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("cancelled".to_string()));
m
});
let __ws_arg_22 = self.extend(request.clone(), &[params.clone()]);
return self.fetch_orders(&[outcome.clone(), since.clone(), limit.clone(), __ws_arg_22]).await;
Value::Null
}
/*
* @method
* @name myriad#fetchMyTrades
* @description fetches the wallet's filled order book orders as trades. Note: Myriad's REST exposes the order's
* limit price, not the per-fill execution price, so the price reflects the order's limit (exact for resting/limit
* fills, an upper/lower bound for market orders) — use watchTrades for live execution prices
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da828171a003cf996487d008
* @param {string} [outcome] unified outcome to filter by
* @param {int} [since] timestamp in ms of the earliest trade
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("filled".to_string()));
m
});
let __ws_arg_23 = self.extend(request.clone(), &[params.clone()]);
let mut orders: Value = self.fetch_orders(&[outcome.clone(), since.clone(), limit.clone(), __ws_arg_23]).await;
let mut trades: Value = Value::List(vec![]);
let mut ordersLength: Value = get_array_length(&orders);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1304: bool = true;
while { if !__for_first_1304 { i = add(&i, &Value::Int(1)); } __for_first_1304 = false; is_less_than(&i, &ordersLength) } {
let mut order: Value = get_value(&orders, &i);
let mut order: Value = get_value(&orders, &i);
append_to_array(&mut trades, self.order_to_trade(order.clone()));
}
}
return self.filter_by_value_since_limit(trades.clone(), Value::Str("outcome".to_string()), &[outcome.clone(), since.clone(), limit.clone(), Value::Str("timestamp".to_string()), Value::Bool(true)]);
Value::Null
}
pub fn order_to_trade(&self, mut order: Value) -> Value {
let mut timestamp: Value = self.safe_integer_k(order.clone(), "timestamp", &[]);
let mut orderType: Value = self.safe_string_k(order.clone(), "type", &[]);
// the REST filled-order response carries the order's limit price (= the fill price for limit
// orders, but only the protective bound for market orders), so omit the price for market orders
let mut price: Value = Value::Null;
if !is_equal(&orderType, &Value::Str("market".to_string())) {
price = self.safe_number_k(order.clone(), "price", &[]);
}
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(order.clone(), "id", &[]));
m.insert("order".to_string(), self.safe_string_k(order.clone(), "id", &[]));
m.insert("info".to_string(), self.safe_dict_k(order.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("outcome".to_string(), self.safe_string_k(order.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(order.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(order.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(order.clone(), "market", &[]));
m.insert("type".to_string(), orderType.clone());
m.insert("side".to_string(), self.safe_string_k(order.clone(), "side", &[]));
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("price".to_string(), price.clone());
m.insert("amount".to_string(), self.safe_number_k(order.clone(), "filled", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m
}), &[]);
Value::Null
}
/*
* @method
* @name myriad#fetchBalance
* @description fetches the wallet's on-chain collateral balance for the order-book network (USD1 on BNB Chain)
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network_id] the network id (defaults to options.defaultNetworkId, '56')
* @param {string} [params.network] alias for params.network_id
* @param {string} [params.currency] output balance currency code override, e.g. 'USDC' or 'USDT'
* @param {int} [params.decimals] for USDC and USDT it's 6, default is 18 for USD1
* @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut networkId: Value = self.safe_string2(params.clone(), Value::Str("network_id".to_string()), Value::Str("network".to_string()), &[self.safe_string_k(self.options.clone(), "defaultNetworkId", &[Value::Str("56".to_string())])]);
let mut chains: Value = self.safe_dict_k(self.options.clone(), "chains", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut chainConfig: Value = self.safe_dict(chains.clone(), networkId.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rpcUrl: Value = self.safe_string2(params.clone(), Value::Str("rpcUrl".to_string()), Value::Str("rpc".to_string()), &[self.safe_string_k(chainConfig.clone(), "rpcUrl", &[])]);
let mut token: Value = self.safe_string2(params.clone(), Value::Str("token".to_string()), Value::Str("tokenAddress".to_string()), &[self.safe_string_k(chainConfig.clone(), "collateralToken", &[])]);
if is_equal(&token, &Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(add(&add(&self.id, &Value::Str(" fetchBalance() has no collateral token configured for network ".to_string())), &networkId)));
}
let mut currency: Value = self.safe_string_k(params.clone(), "currency", &[self.safe_string(chainConfig.clone(), Value::Str("collateralCurrency".to_string()), &[Value::Str("USD1".to_string())])]);
let mut decimals: Value = self.safe_integer_k(params.clone(), "decimals", &[self.safe_integer(chainConfig.clone(), Value::Str("collateralDecimals".to_string()), &[Value::Int(18)])]);
let mut owner: Value = self.wallet_address_from_keys();
// ERC20 balanceOf(owner) = selector 0x70a08231 + the 32-byte left-padded owner address
let mut callData: Value = add(&Value::Str("0x70a08231".to_string()), &self.pad_hex_address(owner.clone()));
let mut callParams: Value = Value::List(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("to".to_string(), token.clone());
m.insert("data".to_string(), callData.clone());
m
}), Value::Str("latest".to_string())]);
let mut raw: Value = self.eth_rpc(rpcUrl.clone(), Value::Str("eth_call".to_string()), callParams.clone()).await;
let mut balanceString: Value = self.from_wei_with_decimals(raw.clone(), decimals.clone());
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("balanceHex".to_string(), raw.clone());
m.insert("token".to_string(), token.clone());
m.insert("networkId".to_string(), networkId.clone());
m
}));
m
});
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".to_string()), balanceString.clone());
add_element_to_object(&mut account, &Value::Str("total".to_string()), balanceString.clone());
add_element_to_object(&mut result, ¤cy, account.clone());
return self.safe_balance(result.clone());
Value::Null
}
pub fn hex_to_decimal_string(&self, mut hexValue: Value) -> Value {
// portable hex -> decimal string (avoids convertToBigInt, which is not uniform across languages)
let mut stripped: Value = self.remove0x_prefix(hexValue.clone());
if is_true(&(is_equal(&stripped, &Value::Null))) || is_true(&(is_equal(&stripped, &Value::Str("".to_string())))) {
return Value::Null;
}
let mut chars: Value = self.string_to_chars_array(to_lower(&stripped));
let mut n: Value = get_array_length(&chars);
let mut digits: Value = Value::Str("0123456789abcdef".to_string());
let mut result: Value = Value::Str("0".to_string());
{
let mut i: Value = Value::Int(0);
let mut __for_first_1305: bool = true;
while { if !__for_first_1305 { i = add(&i, &Value::Int(1)); } __for_first_1305 = false; is_less_than(&i, &n) } {
let mut v: Value = get_index_of(&digits, &get_value(&chars, &i));
if is_greater_than(&v, &negate(&Value::Int(1))) {
let mut mul: Value = crate::precise::Precise::stringMul(&result, &Value::Str("16".to_string()));
let mut digit: Value = self.number_to_string(v.clone());
result = crate::precise::Precise::stringAdd(&mul, &digit);
}
}
}
return result;
Value::Null
}
pub fn from_wei_with_decimals(&self, mut hexValue: Value, mut decimals: Value) -> Value {
let mut decimalString: Value = self.hex_to_decimal_string(hexValue.clone());
if is_equal(&decimalString, &Value::Null) {
return Value::Null;
}
let mut scale: Value = Value::Str("1".to_string());
if is_equal(&decimals, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fromWeiWithDecimals() missing decimals".to_string()))));
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1306: bool = true;
while { if !__for_first_1306 { i = add(&i, &Value::Int(1)); } __for_first_1306 = false; is_less_than(&i, &decimals) } {
scale = add(&scale, &Value::Str("0".to_string()));
}
}
return crate::precise::Precise::stringDiv(&decimalString, &scale);
Value::Null
}
pub fn parse_trade_tx(&self, mut txHash: Value, mut quote: Value, mut market: Value, mut side: Value) -> Value {
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), txHash.clone());
m.insert("clientOrderId".to_string(), Value::Null);
let __ws_arg_24 = self.safe_dict_k(quote.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
m.insert("info".to_string(), self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("transactionHash".to_string(), txHash.clone());
m
}), &[__ws_arg_24]));
m.insert("outcome".to_string(), self.safe_string_k(market.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
m.insert("type".to_string(), Value::Str("market".to_string()));
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), self.safe_number_k(quote.clone(), "priceAverage", &[]));
m.insert("amount".to_string(), self.safe_number_k(quote.clone(), "shares", &[]));
m.insert("cost".to_string(), self.safe_number_k(quote.clone(), "value", &[]));
m.insert("status".to_string(), Value::Str("closed".to_string()));
m.insert("fee".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parseMarketToEvent
* @description wraps a parsed myriad market into a unified event structure
* @param {object} raw the raw myriad market object
* @param {object} market the parsed ccxt market
* @returns {object} an event structure
*/
pub fn parse_market_to_event(&self, mut raw: Value, mut market: Value) -> Value {
let mut slug: Value = self.safe_string_k(raw.clone(), "slug", &[self.safe_string(raw.clone(), Value::Str("id".to_string()), &[])]);
let mut state: Value = self.safe_string_k(raw.clone(), "state", &[Value::Str("open".to_string())]);
let mut endDate: Value = self.safe_string_k(raw.clone(), "expiresAt", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("slug".to_string(), slug.clone());
m.insert("event".to_string(), get_value(&market, &Value::Str("market".to_string())));
m.insert("title".to_string(), self.safe_string2(raw.clone(), Value::Str("title".to_string()), Value::Str("shortName".to_string()), &[]));
m.insert("description".to_string(), self.safe_string_k(raw.clone(), "description", &[]));
m.insert("markets".to_string(), Value::List(vec![market.clone()]));
m.insert("volume".to_string(), self.safe_number2(raw.clone(), Value::Str("volumeNotional24h".to_string()), Value::Str("volume24h".to_string()), &[]));
m.insert("liquidity".to_string(), self.safe_number_k(raw.clone(), "liquidity", &[]));
m.insert("url".to_string(), Value::Null);
m.insert("image".to_string(), self.safe_string_k(raw.clone(), "imageUrl", &[]));
m.insert("active".to_string(), Value::Bool((is_equal(&state, &Value::Str("open".to_string())))));
m.insert("resolved".to_string(), Value::Bool((is_equal(&state, &Value::Str("resolved".to_string())))));
m.insert("category".to_string(), Value::Null);
m.insert("tags".to_string(), self.safe_list_k(raw.clone(), "topics", &[]));
m.insert("created".to_string(), self.parse8601(self.safe_string_k(raw.clone(), "publishedAt", &[])));
m.insert("createdDatetime".to_string(), self.safe_string_k(raw.clone(), "publishedAt", &[]));
m.insert("end".to_string(), ternary(is_true(&(!is_equal(&endDate, &Value::Null))), self.parse8601(endDate.clone()), Value::Null));
m.insert("endDatetime".to_string(), endDate.clone());
m.insert("lastUpdatedAt".to_string(), Value::Null);
m.insert("resolutionSource".to_string(), self.safe_string_k(raw.clone(), "resolutionSource", &[]));
m.insert("info".to_string(), raw.clone());
m
});
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parseMyriadMarket
* @description converts a single raw myriad market into one ccxt market with a list of outcome objects
* @param {object} raw the raw myriad market object
* @param {string} [eventSlug] the slug of the parent event
* @returns {object} a [market structure](https://docs.ccxt.com/#/?id=market-structure)
*/
pub fn parse_myriad_market(&self, mut raw: Value, optional_args: &[Value]) -> Value {
let mut eventSlug = get_arg(optional_args, 0, Value::Null);
let mut networkId: Value = self.safe_string_k(raw.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(raw.clone(), "id", &[]);
let mut slug: Value = self.safe_string_k(raw.clone(), "slug", &[marketId.clone()]);
let mut rawOutcomes: Value = self.safe_list_k(raw.clone(), "outcomes", &[Value::List(vec![])]);
let mut endDate: Value = self.safe_string_k(raw.clone(), "expiresAt", &[]);
let mut state: Value = self.safe_string_k(raw.clone(), "state", &[Value::Str("open".to_string())]);
let mut active: Value = Value::Bool(is_equal(&state, &Value::Str("open".to_string())));
// resolution: resolvedOutcomeId is "-1" until the market resolves, then the winning outcome id
let mut resolvedOutcomeId: Value = self.safe_string_k(raw.clone(), "resolvedOutcomeId", &[Value::Str("-1".to_string())]);
let mut voided: Value = self.safe_bool_k(raw.clone(), "voided", &[Value::Bool(false)]);
let mut hasResolution: bool = is_true(&(!is_equal(&resolvedOutcomeId, &Value::Str("-1".to_string())))) && is_true(&(!is_equal(&resolvedOutcomeId, &Value::Null))) && is_true(&(!is_equal(&resolvedOutcomeId, &Value::Str("".to_string()))));
let mut marketResolved: Value = Value::Bool(is_true(&hasResolution) || is_true(&voided));
let mut resolvedOutcome: Value = Value::Null;
let mut volume24h: Value = self.safe_number_k(raw.clone(), "volume24h", &[]);
// qualify the handle only with a real event slug (when passed); myriad market slugs are
// globally unique, so do NOT fall back to networkId — that would prefix every handle.
// eventSlug may be undefined (single-market load) — slugToMarketSymbol accepts a nullable slug.
let mut marketSymbol: Value = self.slug_to_market_symbol(eventSlug.clone(), slug.clone());
// the collateral token (outcome + address + decimals) is per-market; carry it for on-chain trading
let mut tokenObj: Value = self.safe_dict_k(raw.clone(), "token", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut tokenAddress: Value = self.safe_string_k(tokenObj.clone(), "address", &[]);
let mut tokenDecimals: Value = self.safe_integer_k(tokenObj.clone(), "decimals", &[Value::Int(18)]);
let mut quoteCurrency: Value = self.safe_string_k(tokenObj.clone(), "symbol", &[Value::Str("USDC".to_string())]);
// per-side fees: buys are charged the taker fee, sells the maker fee (mirrors fetchTradingFee)
let mut feesObj: Value = self.safe_dict_k(raw.clone(), "fees", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut buyFees: Value = self.safe_dict_k(feesObj.clone(), "buy", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut sellFees: Value = self.safe_dict_k(feesObj.clone(), "sell", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut takerFee: Value = self.safe_number_k(buyFees.clone(), "fee", &[Value::Float(0.01)]);
let mut makerFee: Value = self.safe_number_k(sellFees.clone(), "fee", &[Value::Int(0)]);
let mut outcomes: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1307: bool = true;
while { if !__for_first_1307 { i = add(&i, &Value::Int(1)); } __for_first_1307 = false; is_less_than(&i, &get_array_length(&rawOutcomes)) } {
let mut outcome: Value = self.safe_dict(rawOutcomes.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut outcomeId: Value = self.safe_string_k(outcome.clone(), "outcomeId", &[self.safe_string(outcome.clone(), Value::Str("id".to_string()), &[to_string_val(&i)])]);
let mut outcomeLabel: Value = self.safe_string_k(outcome.clone(), "label", &[self.safe_string(outcome.clone(), Value::Str("title".to_string()), &[outcomeId.clone()])]);
let mut price: Value = self.safe_number_k(outcome.clone(), "price", &[]);
let mut outcomeHandle: Value = self.slug_to_outcome_symbol(eventSlug.clone(), slug.clone(), outcomeLabel.clone());
let mut outcomeCompositeId: Value = add(&add(&add(&add(&networkId, &Value::Str(":".to_string())), &marketId), &Value::Str("/".to_string())), &outcomeId);
let mut winnerRaw: Value = Value::Null;
let mut settleFractionRaw: Value = Value::Null;
if is_true(&hasResolution) {
winnerRaw = Value::Bool(is_equal(&outcomeId, &resolvedOutcomeId));
settleFractionRaw = ternary(is_true(&winnerRaw), Value::Int(1), Value::Int(0));
if is_true(&winnerRaw) {
resolvedOutcome = outcomeHandle.clone();
}
} else if is_equal(&voided, &Value::Bool(true)) {
winnerRaw = Value::Bool(false);
}
// effectively-final copies for the object literal below (Java cannot capture a
// reassigned local into the anonymous inner class it emits for a map literal)
let mut winner: Value = winnerRaw.clone();
let mut settleFraction: Value = settleFractionRaw.clone();
append_to_array(&mut outcomes, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), outcomeCompositeId.clone());
m.insert("outcomeId".to_string(), outcomeCompositeId.clone());
m.insert("outcome".to_string(), outcomeHandle.clone());
m.insert("market".to_string(), marketSymbol.clone());
m.insert("label".to_string(), outcomeLabel.clone());
m.insert("active".to_string(), active.clone());
m.insert("winner".to_string(), winner.clone());
m.insert("settleFraction".to_string(), settleFraction.clone());
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Float(0.01));
m.insert("price".to_string(), Value::Float(0.001));
m
}));
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("networkId".to_string(), networkId.clone());
m.insert("marketId".to_string(), marketId.clone());
m.insert("slug".to_string(), slug.clone());
m.insert("outcomeId".to_string(), outcomeId.clone());
m.insert("outcomeLabel".to_string(), outcomeLabel.clone());
m.insert("outcomePrice".to_string(), price.clone());
m.insert("volume24h".to_string(), volume24h.clone());
m.insert("state".to_string(), state.clone());
m.insert("tradingModel".to_string(), self.safe_string_k(raw.clone(), "tradingModel", &[Value::Str("amm".to_string())]));
m.insert("tokenAddress".to_string(), tokenAddress.clone());
m.insert("tokenDecimals".to_string(), tokenDecimals.clone());
m
}));
m
}));
}
}
let mut marketTradingModel: Value = self.safe_string_k(raw.clone(), "tradingModel", &[Value::Str("amm".to_string())]);
let mut marketExecutionModel: Value = ternary(is_true(&(is_equal(&marketTradingModel, &Value::Str("amm".to_string())))), Value::Str("amm".to_string()), Value::Str("clob".to_string()));
let mut outcomesLength: Value = get_array_length(&outcomes);
// effectively-final copy for the market object literal below (reassigned in the loop)
let mut marketResolvedOutcome: Value = resolvedOutcome.clone();
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), add(&add(&networkId, &Value::Str(":".to_string())), &marketId));
m.insert("market".to_string(), marketSymbol.clone());
m.insert("marketType".to_string(), ternary(is_true(&(is_greater_than(&outcomesLength, &Value::Int(2)))), Value::Str("categorical".to_string()), Value::Str("binary".to_string())));
m.insert("executionModel".to_string(), marketExecutionModel.clone());
m.insert("base".to_string(), slug.clone());
m.insert("quote".to_string(), quoteCurrency.clone());
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), add(&add(&networkId, &Value::Str(":".to_string())), &marketId));
m.insert("quoteId".to_string(), quoteCurrency.clone());
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("prediction".to_string()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("active".to_string(), active.clone());
m.insert("resolved".to_string(), marketResolved.clone());
m.insert("resolvedOutcome".to_string(), marketResolvedOutcome.clone());
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), ternary(is_true(&(!is_equal(&endDate, &Value::Null) && !is_equal(&endDate, &Value::Str("".to_string())))), self.parse8601(endDate.clone()), Value::Null));
m.insert("expiryDatetime".to_string(), endDate.clone());
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("taker".to_string(), takerFee.clone());
m.insert("maker".to_string(), makerFee.clone());
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("feeSide".to_string(), Value::Str("get".to_string()));
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Float(0.01));
m.insert("price".to_string(), Value::Float(0.001));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(1));
m.insert("max".to_string(), Value::Int(1));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(0));
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Float(0.001));
m.insert("max".to_string(), Value::Float(0.999));
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("outcomes".to_string(), outcomes.clone());
m.insert("info".to_string(), self.extend(raw.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("networkId".to_string(), networkId.clone());
m.insert("marketId".to_string(), marketId.clone());
m.insert("slug".to_string(), slug.clone());
m.insert("volume24h".to_string(), volume24h.clone());
m.insert("state".to_string(), state.clone());
m
})]));
m.insert("created".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name myriad#fetchTicker
* @description fetches the current price for a single outcome by loading the parent market
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {string} outcome unified outcome like TRUMP_WIN:YES or an outcome id like 2741:756/0
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub async fn fetch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut networkId: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("networkId".to_string()), &[]);
let mut marketId: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("marketId".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId.clone());
m.insert("network_id".to_string(), networkId.clone());
m
});
let __ws_arg_25 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.myriad_public_get_markets_id(&[__ws_arg_25]).await;
return self.parse_prediction_ticker(response.clone(), &[outcomeObj.clone()]);
Value::Null
}
/*
* @method
* @name myriad#fetchTradingFee
* @description fetches the buy/sell fee rates for a market outcome
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {string} outcome unified outcome or outcome id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [fee structure](https://docs.ccxt.com/#/?id=fee-structure)
*/
pub async fn fetch_trading_fee(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(info.clone(), "marketId", &[]));
m.insert("network_id".to_string(), self.safe_string_k(info.clone(), "networkId", &[]));
m
});
let __ws_arg_26 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.myriad_public_get_markets_id(&[__ws_arg_26]).await;
//
// {
// "fees": {
// "buy": { "fee": "0.02", "treasury_fee": "0.01", "distributor_fee": "0.01" },
// "sell": { "fee": "0", "treasury_fee": "0", "distributor_fee": "0" }
// }
// }
//
let mut fees: Value = self.safe_dict_k(response.clone(), "fees", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut buy: Value = self.safe_dict_k(fees.clone(), "buy", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut sell: Value = self.safe_dict_k(fees.clone(), "sell", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("outcome".to_string(), self.safe_outcome_symbol(Value::Null, &[outcomeObj.clone()]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
m.insert("maker".to_string(), self.safe_number_k(sell.clone(), "fee", &[]));
m.insert("taker".to_string(), self.safe_number_k(buy.clone(), "fee", &[]));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m
});
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parsePredictionTicker
* @description parses a raw myriad market object into a unified ticker for the specified outcome
* @param {object} raw the raw myriad market object
* @param {object} [market] the outcome object the ticker belongs to
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub fn parse_prediction_ticker(&self, mut raw: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "id": "756",
// "networkId": "2741",
// "slug": "will-trump-capture-another-president-before-his-birthday",
// "title": "Will Trump capture another president before his birthday?",
// "description": "string"
// "publishedAt": "2026-01-16T18:05:36.000Z",
// "expiresAt": "2026-06-14T04:59:00.000Z",
// "resolvesAt": null,
// "fees": {
// "buy": { "fee": "0.01", "treasury_fee": "0.01", "distributor_fee": "0.01" },
// "sell": { "fee": "0", "treasury_fee": "0", "distributor_fee": "0" },
// "treasury": "0x5E3EbEc100e2294C0EB2264FC96225dF067AAaa3",
// "distributor": "0xE44984C586FeBB31605D23b6316cA11B6f4D86b2"
// },
// "state": "open",
// "voided": false,
// "resolvedOutcomeId": "-1",
// "topics": [ "Politics" ],
// "resolutionSource": "https://www.whitehouse.gov/",
// "resolutionTitle": "White House",
// "token": {
// "name": "Bridged USDC (Stargate)",
// "address": "0x84A71ccD554Cc1b02749b35d22F684CC8ec987e1",
// "symbol": "USDC.e",
// "decimals": "6"
// },
// "imageUrl": "https://cdn.polkamarkets.com/Qma9FAX15kHewT8vm61vykGA9bqQhNdDLvEbQWSp72i3PQ",
// "bannerImageUrl": "https://imagedelivery.net/YN1-rdnufJQJCgu3i1CbVw/255d431f-1bb4-4d90-032b-d1f7032e8000/public",
// "ogImageUrl": "https://imagedelivery.net/YN1-rdnufJQJCgu3i1CbVw/cf1af79c-07b9-40f0-283b-ed59865b3c00/public",
// "liquidity": "2000",
// "liquidityPrice": "0.32532445",
// "volume": "10891.236893",
// "volume24h": "0.939",
// "volumeNotional": "13570.426814",
// "volumeNotional24h": "1.028382",
// "users": "122",
// "shares": "4098.474144",
// "featured": false,
// "featuredAt": null,
// "inPlay": false,
// "inPlayStartsAt": null,
// "perpetual": false,
// "moneyline": false,
// "executionMode": "0",
// "tradingModel": "amm",
// "topHolders": [
// "0x8A611AEE71b6448a6F99B6001D1234d020f7d546",
// "0x2993249A3D107B759c886a4BD4e02B70d471eA9B",
// "0x82a5b3BD2A9216369537583f63fa576a1D57c7E7"
// ],
// "outcomes": [
// {
// "id": "0",
// "title": "Yes",
// "shares": "3742.174971",
// "sharesHeld": "138.741271",
// "price": "0.08693459",
// "closingPrice": null,
// "priceChange24h": "0.00045828",
// "imageUrl": "https://cdn.polkamarkets.com/Qma9FAX15kHewT8vm61vykGA9bqQhNdDLvEbQWSp72i3PQ",
// "holders": "7",
// "tokenId": "1512",
// "price_charts": [Array]
// },
// ],
// "eventId": null,
// "outcomeIndex": null,
// "negRisk": false,
// "externalSources": []
// }
//
let mut outcomeId: Value = ternary(is_true(&(!is_equal(&market, &Value::Null) && !is_equal(&market, &Value::Null))), self.safe_string(get_value(&market, &Value::Str("info".to_string())), Value::Str("outcomeId".to_string()), &[]), Value::Null);
let mut outcomes: Value = self.safe_list_k(raw.clone(), "outcomes", &[Value::List(vec![])]);
let mut price: Value = Value::Null;
let mut change: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1308: bool = true;
while { if !__for_first_1308 { i = add(&i, &Value::Int(1)); } __for_first_1308 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
let mut o: Value = get_value(&outcomes, &i);
let mut o: Value = get_value(&outcomes, &i);
if is_equal(&self.safe_string_k(o.clone(), "outcomeId", &[self.safe_string(o.clone(), Value::Str("id".to_string()), &[])]), &outcomeId) {
price = self.safe_number_k(o.clone(), "price", &[]);
change = self.safe_number_k(o.clone(), "priceChange24h", &[]);
break;
}
}
}
let mut now: Value = self.milliseconds();
// priceChange24h is an ABSOLUTE price delta; derive the previous close and the TRUE
// percentage from it — setting percentage = the absolute change (as before) was wrong
let mut previousClose: Value = Value::Null;
let mut percentage: Value = Value::Null;
if is_true(&(!is_equal(&price, &Value::Null))) && is_true(&(!is_equal(&change, &Value::Null))) {
previousClose = subtract(&price, &change);
if is_equal(&previousClose, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" method() missing previousClose".to_string()))));
}
if !is_equal(&previousClose, &Value::Int(0)) {
percentage = multiply(÷(&change, &previousClose), &Value::Int(100));
}
}
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), self.safe_string_k(market.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
m.insert("timestamp".to_string(), now.clone());
m.insert("datetime".to_string(), self.iso8601(now.clone()));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), price.clone());
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), price.clone());
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), previousClose.clone());
m.insert("close".to_string(), price.clone());
m.insert("last".to_string(), price.clone());
m.insert("previousClose".to_string(), previousClose.clone());
m.insert("change".to_string(), change.clone());
m.insert("percentage".to_string(), percentage.clone());
m.insert("average".to_string(), price.clone());
m.insert("baseVolume".to_string(), self.safe_number_k(raw.clone(), "volumeNotional24h", &[]));
m.insert("quoteVolume".to_string(), self.safe_number_k(raw.clone(), "volume24h", &[]));
m.insert("info".to_string(), raw.clone());
m
}), &[market.clone()]);
Value::Null
}
/*
* @method
* @name myriad#fetchOrderBook
* @description fetches the real order book for order-book markets, or synthesizes a one-level book from the AMM price otherwise
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da8281bba6aaf24dd61f2bb1
* @param {string} outcome unified outcome like TRUMP_WIN:YES or an outcome id
* @param {int} [limit] not used by myriad fetchOrderBook
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
*/
pub async fn fetch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut networkId: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("networkId".to_string()), &[]);
let mut marketId: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("marketId".to_string()), &[]);
let mut outcomeId: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("outcomeId".to_string()), &[]);
let mut tradingModel: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("tradingModel".to_string()), &[Value::Str("amm".to_string())]);
if is_equal(&tradingModel, &Value::Str("ob".to_string())) {
let mut obRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId.clone());
m.insert("network_id".to_string(), networkId.clone());
m.insert("outcome".to_string(), outcomeId.clone());
m
});
let __ws_arg_27 = self.extend(obRequest.clone(), &[params.clone()]);
let mut obResponse: Value = self.myriad_public_get_markets_id_orderbook(&[__ws_arg_27]).await;
return self.safe_prediction_order_book(self.parse_wei_order_book(obResponse.clone(), self.safe_outcome_symbol(outcome.clone(), &[outcomeObj.clone()])), &[outcomeObj.clone()]);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId.clone());
m.insert("network_id".to_string(), networkId.clone());
m
});
let __ws_arg_28 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.myriad_public_get_markets_id(&[__ws_arg_28]).await;
//
// {
// "id": "756",
// "networkId": "2741",
// "slug": "will-trump-capture-another-president-before-his-birthday",
// "title": "Will Trump capture another president before his birthday?",
// "shortName": null,
// "description": "### **Market Dates:**"
// "publishedAt": "2026-01-16T18:05:36.000Z",
// "expiresAt": "2026-06-14T04:59:00.000Z",
// "resolvesAt": null,
// "fees": {
// "buy": { "fee": "0.01", "treasury_fee": "0.01", "distributor_fee": "0.01" },
// "sell": { "fee": "0", "treasury_fee": "0", "distributor_fee": "0" },
// "treasury": "0x5E3EbEc100e2294C0EB2264FC96225dF067AAaa3",
// "distributor": "0xE44984C586FeBB31605D23b6316cA11B6f4D86b2"
// },
// "state": "open",
// "voided": false,
// "resolvedOutcomeId": "-1",
// "topics": [ "Politics" ],
// "resolutionSource": "https://www.whitehouse.gov/",
// "resolutionTitle": "White House",
// "token": {
// "name": "Bridged USDC (Stargate)",
// "address": "0x84A71ccD554Cc1b02749b35d22F684CC8ec987e1",
// "symbol": "USDC.e",
// "decimals": "6"
// },
// "imageUrl": "https://cdn.polkamarkets.com/Qma9FAX15kHewT8vm61vykGA9bqQhNdDLvEbQWSp72i3PQ",
// "bannerImageUrl": "https://imagedelivery.net/YN1-rdnufJQJCgu3i1CbVw/255d431f-1bb4-4d90-032b-d1f7032e8000/public",
// "ogImageUrl": "https://imagedelivery.net/YN1-rdnufJQJCgu3i1CbVw/d3d60089-3d08-45ac-aa9d-139156e3f900/public",
// "liquidity": "2000",
// "liquidityPrice": "0.29322839",
// "volume": "11396.236893",
// "volume24h": "500",
// "volumeNotional": "14101.517862",
// "volumeNotional24h": "525.779869",
// "users": "124",
// "shares": "4547.083096",
// "featured": false,
// "featuredAt": null,
// "inPlay": false,
// "inPlayStartsAt": null,
// "perpetual": false,
// "moneyline": false,
// "executionMode": "0",
// "tradingModel": "amm",
// "topHolders": [
// "0x8A611AEE71b6448a6F99B6001D1234d020f7d546",
// "0x2993249A3D107B759c886a4BD4e02B70d471eA9B"
// ],
// "outcomes": [
// {
// "id": "0",
// "title": "Yes",
// "shares": "4232.024971",
// "sharesHeld": "138.741271",
// "price": "0.06928796",
// "closingPrice": null,
// "priceChange24h": "-0.20109988",
// "imageUrl": "https://cdn.polkamarkets.com/Qma9FAX15kHewT8vm61vykGA9bqQhNdDLvEbQWSp72i3PQ",
// "holders": "7",
// "tokenId": "1512",
// "price_charts": [Array]
// }
// ],
// "eventId": null,
// "outcomeIndex": null,
// "negRisk": false,
// "externalSources": []
// }
//
let mut outcomes: Value = self.safe_list_k(response.clone(), "outcomes", &[Value::List(vec![])]);
let mut price: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1309: bool = true;
while { if !__for_first_1309 { i = add(&i, &Value::Int(1)); } __for_first_1309 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
let mut o: Value = get_value(&outcomes, &i);
let mut o: Value = get_value(&outcomes, &i);
if is_equal(&self.safe_string_k(o.clone(), "outcomeId", &[self.safe_string(o.clone(), Value::Str("id".to_string()), &[])]), &outcomeId) {
price = self.safe_number_k(o.clone(), "price", &[]);
break;
}
}
}
let mut timestamp: Value = self.milliseconds();
// AMM: synthesize a single bid/ask pair around the current implied price, clamped into the valid (0, 1) range
let mut bid: Value = Value::Null;
let mut ask: Value = Value::Null;
if !is_equal(&price, &Value::Null) {
if is_greater_than(&price, &Value::Float(0.001)) {
bid = self.parse_number(crate::precise::Precise::stringSub(&self.number_to_string(price.clone()), &Value::Str("0.001".to_string())), &[]);
}
if is_less_than(&price, &Value::Float(0.999)) {
ask = self.parse_number(crate::precise::Precise::stringAdd(&self.number_to_string(price.clone()), &Value::Str("0.001".to_string())), &[]);
}
}
// the synthetic size must be a parsed float, an int literal breaks the typed go wrapper conversion
let mut synthSize: Value = self.parse_number(Value::Str("9999".to_string()), &[]);
let mut bids: Value = Value::List(vec![]);
if !is_equal(&bid, &Value::Null) {
append_to_array(&mut bids, Value::List(vec![bid.clone(), synthSize.clone()]));
}
let mut asks: Value = Value::List(vec![]);
if !is_equal(&ask, &Value::Null) {
append_to_array(&mut asks, Value::List(vec![ask.clone(), synthSize.clone()]));
}
let mut orderbook: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), self.safe_outcome_symbol(outcome.clone(), &[outcomeObj.clone()]));
m.insert("bids".to_string(), bids.clone());
m.insert("asks".to_string(), asks.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("nonce".to_string(), Value::Null);
m
});
return self.safe_prediction_order_book(orderbook.clone(), &[outcomeObj.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parseWeiOrderBook
* @description parses an order book whose price and amount levels are 1e18-scaled integer strings
* @param {object} response the raw orderbook response with bids and asks arrays
* @param {string} outcome the unified outcome of the order book
* @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
*/
pub fn parse_wei_order_book(&self, mut response: Value, mut outcome: Value) -> Value {
let mut rawBids: Value = self.safe_list_k(response.clone(), "bids", &[Value::List(vec![])]);
let mut rawAsks: Value = self.safe_list_k(response.clone(), "asks", &[Value::List(vec![])]);
let mut bids: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1310: bool = true;
while { if !__for_first_1310 { i = add(&i, &Value::Int(1)); } __for_first_1310 = false; is_less_than(&i, &get_array_length(&rawBids)) } {
let mut row: Value = get_value(&rawBids, &i);
let mut row: Value = get_value(&rawBids, &i);
let mut rowPrice: Value = crate::precise::Precise::stringDiv(&self.safe_string(row.clone(), Value::Int(0), &[]), &Value::Str("1000000000000000000".to_string()));
let mut rowAmount: Value = crate::precise::Precise::stringDiv(&self.safe_string(row.clone(), Value::Int(1), &[]), &Value::Str("1000000000000000000".to_string()));
append_to_array(&mut bids, Value::List(vec![self.parse_number(rowPrice.clone(), &[]), self.parse_number(rowAmount.clone(), &[])]));
}
}
let mut asks: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1311: bool = true;
while { if !__for_first_1311 { i = add(&i, &Value::Int(1)); } __for_first_1311 = false; is_less_than(&i, &get_array_length(&rawAsks)) } {
let mut row: Value = get_value(&rawAsks, &i);
let mut row: Value = get_value(&rawAsks, &i);
let mut rowPrice: Value = crate::precise::Precise::stringDiv(&self.safe_string(row.clone(), Value::Int(0), &[]), &Value::Str("1000000000000000000".to_string()));
let mut rowAmount: Value = crate::precise::Precise::stringDiv(&self.safe_string(row.clone(), Value::Int(1), &[]), &Value::Str("1000000000000000000".to_string()));
append_to_array(&mut asks, Value::List(vec![self.parse_number(rowPrice.clone(), &[]), self.parse_number(rowAmount.clone(), &[])]));
}
}
let mut timestamp: Value = self.milliseconds();
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcome.clone());
m.insert("bids".to_string(), self.sort_by(bids.clone(), Value::Int(0), &[Value::Bool(true)]));
m.insert("asks".to_string(), self.sort_by(asks.clone(), Value::Int(0), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("nonce".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name myriad#fetchOHLCV
* @description fetches price history for an outcome from the price_charts bucket embedded in the market response
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {string} outcome unified outcome like TRUMP_WIN:YES or an outcome id
* @param {string} timeframe mapped to the closest available chart bucket (24h, 7d or 30d)
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum number of candles to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} a list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1d".to_string()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("networkId".to_string()), &[]);
let mut marketId: Value = self.safe_string(get_value(&outcomeObj, &Value::Str("info".to_string())), Value::Str("marketId".to_string()), &[]);
let mut outcomeId: Value = self.safe_string_k(outcomeInfo.clone(), "outcomeId", &[self.safe_string(outcomeInfo.clone(), Value::Str("id".to_string()), &[])]);
let mut outcomeTitle: Value = self.safe_string_k(outcomeInfo.clone(), "outcomeLabel", &[self.safe_string(outcomeInfo.clone(), Value::Str("label".to_string()), &[self.safe_string(outcomeInfo.clone(), Value::Str("title".to_string()), &[])])]);
let mut bucketKey: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[Value::Str("30d".to_string())]);
let __ws_arg_29 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId.clone());
m.insert("network_id".to_string(), networkId.clone());
m
}), &[params.clone()]);
let mut response: Value = self.myriad_public_get_markets_id(&[__ws_arg_29]).await;
//
// {
// "id": "164",
// "networkId": "2741",
// "slug": "trump-out-as-president-2027",
// "title": "Will Trump cease to be President before 2027?",
// "state": "open",
// "outcomes": [
// {
// "id": "0",
// "outcomeId": "0",
// "title": "YES",
// "label": "YES",
// "price": 0.42,
// "priceChange24h": -0.02
// }
// ],
// "price_charts": {
// "24h": {
// "timeframe": "24h",
// "prices": [
// {
// "timestamp": 1705318200,
// "open": 0.40,
// "high": 0.45,
// "low": 0.39,
// "close": 0.42,
// "price": 0.42,
// "value": 0.42
// }
// ]
// },
// "7d": {...},
// "30d": {...}
// }
// }
//
let mut outcomes: Value = self.safe_list_k(response.clone(), "outcomes", &[Value::List(vec![])]);
let mut selectedOutcome: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1312: bool = true;
while { if !__for_first_1312 { i = add(&i, &Value::Int(1)); } __for_first_1312 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
let mut oc: Value = get_value(&outcomes, &i);
let mut oc: Value = get_value(&outcomes, &i);
let mut currentId: Value = self.safe_string_k(oc.clone(), "id", &[self.safe_string(oc.clone(), Value::Str("outcomeId".to_string()), &[])]);
let mut currentTitle: Value = self.safe_string_k(oc.clone(), "title", &[self.safe_string(oc.clone(), Value::Str("label".to_string()), &[])]);
if is_true(&(!is_equal(&outcomeId, &Value::Null))) && is_true(&(is_equal(¤tId, &outcomeId))) {
selectedOutcome = oc.clone();
break;
}
if is_true(&(is_equal(&selectedOutcome, &Value::Null))) && is_true(&(!is_equal(&outcomeTitle, &Value::Null))) && is_true(&(is_equal(¤tTitle, &outcomeTitle))) {
selectedOutcome = oc.clone();
}
}
}
// price_charts is a list of { timeframe, prices } buckets, with a dict variant on some deployments
let mut chart: Value = Value::Null;
let mut chartsList: Value = self.safe_list_k(selectedOutcome.clone(), "price_charts", &[]);
if !is_equal(&chartsList, &Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_1313: bool = true;
while { if !__for_first_1313 { i = add(&i, &Value::Int(1)); } __for_first_1313 = false; is_less_than(&i, &get_array_length(&chartsList)) } {
let mut chartObj: Value = get_value(&chartsList, &i);
let mut chartObj: Value = get_value(&chartsList, &i);
if is_equal(&self.safe_string_k(chartObj.clone(), "timeframe", &[]), &bucketKey) {
chart = chartObj.clone();
break;
}
}
}
} else {
let mut chartsDict: Value = self.safe_dict_k(selectedOutcome.clone(), "price_charts", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
chart = self.safe_value(chartsDict.clone(), bucketKey.clone(), &[]);
}
let mut pointsList: Value = self.safe_list_k(chart.clone(), "prices", &[self.safe_list(chart.clone(), Value::Str("data".to_string()), &[chart.clone()])]);
let mut points: Value = ternary(is_true(&(!is_equal(&pointsList, &Value::Null))), pointsList.clone(), Value::List(vec![]));
let mut pointsLength: Value = get_array_length(&points);
if is_equal(&pointsLength, &Value::Int(0)) {
let mut priceCharts: Value = self.safe_dict_k(response.clone(), "price_charts", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bucket: Value = self.safe_value(priceCharts.clone(), bucketKey.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
points = self.safe_list(bucket.clone(), outcomeId.clone(), &[self.safe_list_k(bucket.clone(), "data", &[Value::List(vec![])])]);
}
let mut usablePoints: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1314: bool = true;
while { if !__for_first_1314 { i = add(&i, &Value::Int(1)); } __for_first_1314 = false; is_less_than(&i, &get_array_length(&points)) } {
let mut point: Value = get_value(&points, &i);
let mut point: Value = get_value(&points, &i);
let mut pointOpen: Value = self.safe_number_k(point.clone(), "open", &[]);
let mut pointPrice: Value = self.safe_number_k(point.clone(), "price", &[self.safe_number(point.clone(), Value::Str("value".to_string()), &[])]);
let mut pointTs: Value = self.safe_integer_k(point.clone(), "timestamp", &[]);
if is_true(&(is_true(&(!is_equal(&pointOpen, &Value::Null))) || is_true(&(!is_equal(&pointPrice, &Value::Null))))) && is_true(&(!is_equal(&pointTs, &Value::Null))) {
append_to_array(&mut usablePoints, point.clone());
}
}
}
return self.parse_ohlc_vs(usablePoints.clone(), &[outcomeObj.clone(), timeframe.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parseOHLCV
* @description parses a single myriad price chart data point into an ohlcv tuple
* @param {object} ohlcv the raw price chart data point
* @param {object} [market] the outcome object the candle belongs to
* @returns {int[]} a candle ordered as timestamp, open, high, low, close, volume
*/
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "timestamp": 1705318200,
// "open": 0.40,
// "high": 0.45,
// "low": 0.39,
// "close": 0.42,
// "price": 0.42,
// "value": 0.42
// }
//
let mut open: Value = self.safe_number_k(ohlcv.clone(), "open", &[]);
let mut high: Value = self.safe_number_k(ohlcv.clone(), "high", &[]);
let mut low: Value = self.safe_number_k(ohlcv.clone(), "low", &[]);
let mut close: Value = self.safe_number_k(ohlcv.clone(), "close", &[]);
let mut price: Value = self.safe_number_k(ohlcv.clone(), "price", &[self.safe_number(ohlcv.clone(), Value::Str("value".to_string()), &[])]); // fallback single-value tick
return Value::List(vec![self.safe_timestamp(ohlcv.clone(), Value::Str("timestamp".to_string()), &[]), ternary(is_true(&(!is_equal(&open, &Value::Null))), open.clone(), price.clone()), ternary(is_true(&(!is_equal(&high, &Value::Null))), high.clone(), price.clone()), ternary(is_true(&(!is_equal(&low, &Value::Null))), low.clone(), price.clone()), ternary(is_true(&(!is_equal(&close, &Value::Null))), close.clone(), price.clone()), Value::Int(0)]);
Value::Null
}
/*
* @method
* @name myriad#fetchTickers
* @description fetches tickers for multiple outcomes, grouping requested outcomes by their parent market to fetch each market only once
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {string[]} outcomes unified outcomes — required: myriad has no endpoint returning all tickers at once, so an unscoped call is not supported
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [prediction ticker structures](https://docs.ccxt.com/#/?id=prediction-ticker-structure) indexed by outcome
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&outcomes, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles to fetch (discover them via fetchEvents ())".to_string()))));
}
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
// resolve the uncached outcomes first, then group by parent market to fetch each market only once
self.load_outcomes(&[outcomes.clone()]).await;
let mut outcomesByMarket: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut marketKeys: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1315: bool = true;
while { if !__for_first_1315 { i = add(&i, &Value::Int(1)); } __for_first_1315 = false; is_less_than(&i, &get_array_length(&outcomes)) } {
let mut outcomeObj: Value = self.outcome(get_value(&outcomes, &i));
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(info.clone(), "marketId", &[]);
let mut key: Value = add(&add(&networkId, &Value::Str(":".to_string())), &marketId);
if !is_true(&(Value::Bool(in_op(&outcomesByMarket, &key)))) {
add_element_to_object(&mut outcomesByMarket, &key, Value::List(vec![]));
append_to_array(&mut marketKeys, key.clone());
}
// reassign after push, plain mutation through a local is lost in transpiled php (arrays are value types there)
let mut grouped: Value = get_value(&outcomesByMarket, &key);
append_to_array(&mut grouped, outcomeObj.clone());
crate::set_value(&mut outcomesByMarket, &key, grouped.clone());
add_element_to_object(&mut outcomesByMarket, &key, grouped.clone());
}
}
let mut promises: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1316: bool = true;
while { if !__for_first_1316 { i = add(&i, &Value::Int(1)); } __for_first_1316 = false; is_less_than(&i, &get_array_length(&marketKeys)) } {
let mut key: Value = get_value(&marketKeys, &i);
let mut key: Value = get_value(&marketKeys, &i);
let mut grouped: Value = get_value(&outcomesByMarket, &key);
let mut grouped: Value = get_value(&outcomesByMarket, &key);
let mut firstOutcome: Value = get_value(&grouped, &Value::Int(0));
let mut info: Value = self.safe_dict_k(firstOutcome.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_30 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(info.clone(), "marketId", &[]));
m.insert("network_id".to_string(), self.safe_string_k(info.clone(), "networkId", &[]));
m
}), &[params.clone()]);
append_to_array(&mut promises, self.myriad_public_get_markets_id(&[__ws_arg_30]).await);
}
}
let mut responses: Value = promise_all(&promises).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1318: bool = true;
while { if !__for_first_1318 { i = add(&i, &Value::Int(1)); } __for_first_1318 = false; is_less_than(&i, &get_array_length(&marketKeys)) } {
let mut key: Value = get_value(&marketKeys, &i);
let mut key: Value = get_value(&marketKeys, &i);
let mut response: Value = get_value(&responses, &i);
let mut response: Value = get_value(&responses, &i);
let mut grouped: Value = get_value(&outcomesByMarket, &key);
let mut grouped: Value = get_value(&outcomesByMarket, &key);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1317: bool = true;
while { if !__for_first_1317 { j = add(&j, &Value::Int(1)); } __for_first_1317 = false; is_less_than(&j, &get_array_length(&grouped)) } {
let mut outcomeObj: Value = get_value(&grouped, &j);
let mut outcomeObj: Value = get_value(&grouped, &j);
let mut ticker: Value = self.parse_prediction_ticker(response.clone(), &[outcomeObj.clone()]);
let mut symbolKey: Value = self.safe_string_k(ticker.clone(), "outcome", &[]);
if !is_equal(&symbolKey, &Value::Null) {
add_element_to_object(&mut result, &symbolKey, ticker.clone());
}
}
}
}
}
return result;
Value::Null
}
/*
* @method
* @name myriad#fetchTrades
* @description fetches recent public trades for a single outcome from the market action feed
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {string} outcome unified outcome like TRUMP_WIN:YES or an outcome id
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_trades(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(info.clone(), "marketId", &[]);
let mut outcomeId: Value = self.safe_string_k(info.clone(), "outcomeId", &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId.clone());
m.insert("network_id".to_string(), networkId.clone());
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let __ws_arg_31 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.myriad_public_get_markets_id_events(&[__ws_arg_31]).await;
//
// {
// "data": [
// {
// "user": "0xAE7Bfff784EeEe7812D6527B72c77A7Ed773Ed9D",
// "action": "buy",
// "marketTitle": "BNB candles from 10:00 to 10:05 UTC",
// "marketSlug": "bnb-candles-from-10-00-to-10-05-utc",
// "marketId": 218,
// "networkId": 56,
// "outcomeTitle": "More Green",
// "outcomeId": 0,
// "shares": 500,
// "value": 500,
// "timestamp": 1761645928,
// "blockNumber": 66193433,
// "token": "0x55d398326f99059fF775485246999027B3197955",
// "txId": "0x3c81447bd6e5c4c80a6e1425383c0b044ddcb1525d09027c2b371ff84f9b9fa0"
// }
// ]
// }
//
let mut responseIsArray: Value = Value::Bool(is_array(&response));
let mut rowsList: Value = ternary(is_true(&(responseIsArray)), response.clone(), self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]));
let mut rows: Value = ternary(is_true(&(!is_equal(&rowsList, &Value::Null))), rowsList.clone(), Value::List(vec![]));
let mut trades: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1319: bool = true;
while { if !__for_first_1319 { i = add(&i, &Value::Int(1)); } __for_first_1319 = false; is_less_than(&i, &get_array_length(&rows)) } {
let mut row: Value = get_value(&rows, &i);
let mut row: Value = get_value(&rows, &i);
let mut action: Value = self.safe_string_k(row.clone(), "action", &[]);
if is_true(&(!is_equal(&action, &Value::Str("buy".to_string())))) && is_true(&(!is_equal(&action, &Value::Str("sell".to_string())))) {
continue;
}
let mut rowOutcomeId: Value = self.safe_string_k(row.clone(), "outcomeId", &[]);
if is_true(&(!is_equal(&outcomeId, &Value::Null))) && is_true(&(!is_equal(&rowOutcomeId, &outcomeId))) {
continue;
}
append_to_array(&mut trades, row.clone());
}
}
return self.parse_prediction_trades(trades.clone(), &[outcomeObj.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parsePredictionTrade
* @description parses a raw market action feed row into a unified trade object
* @param {object} trade the raw action feed row
* @param {object} [market] the outcome object the trade belongs to
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Value = self.safe_timestamp(trade.clone(), Value::Str("timestamp".to_string()), &[]);
let mut amountStr: Value = self.safe_string_k(trade.clone(), "shares", &[]);
let mut costStr: Value = self.safe_string_k(trade.clone(), "value", &[]);
let mut priceStr: Value = Value::Null;
if is_true(&(!is_equal(&amountStr, &Value::Null))) && is_true(&(!is_equal(&costStr, &Value::Null))) && !is_true(&crate::precise::Precise::stringEq(&amountStr, &Value::Str("0".to_string()))) {
priceStr = crate::precise::Precise::stringDiv(&costStr, &amountStr);
}
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "txId", &[]));
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("outcome".to_string(), self.safe_string_k(market.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_k(trade.clone(), "action", &[]));
m.insert("takerOrMaker".to_string(), Value::Str("taker".to_string()));
m.insert("price".to_string(), self.parse_number(priceStr.clone(), &[]));
m.insert("amount".to_string(), self.parse_number(amountStr.clone(), &[]));
m.insert("cost".to_string(), self.parse_number(costStr.clone(), &[]));
m.insert("fee".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
/*
* @method
* @name myriad#fetchEvents
* @description fetches prediction-market events matching the given scope (query/queries/tags/eventId) and caches their markets and outcomes on the instance
* @see https://docs.myriad.markets/builders/myriad-api-reference
* @param {object} [params] extra exchange-specific parameters
* @param {string} [params.query] a single search term; an eventId does a direct lookup and tags map to server-side keyword searches
* @param {string[]} [params.queries] multiple search terms (alternative to query)
* @param {string[]} [params.tags] tag slugs to scope by (searched as keywords, e.g. ['bitcoin', 'world-cup'])
* @param {string} [params.eventId] direct lookup by unified event id (composite networkId:marketId) like '56:170145' or questions path like '793bfc47-ddcd-47d2-aad5-52c7002fc823'
* @param {int} [params.limit] maximum number of markets per query, defaults to 50
* @param {string} [params.state] 'open', 'closed' or 'resolved', defaults to 'open'
* @returns {object[]} an array of event structures
*/
pub async fn fetch_events(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut allowUnscopedFetchEvents: Value = self.safe_bool_k(self.options.clone(), "allowUnscopedFetchEvents", &[Value::Bool(false)]);
if !is_equal(&allowUnscopedFetchEvents, &Value::Bool(true)) {
self.require_event_query(&[params.clone()]);
}
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
let mut rest: Value = self.omit(params.clone(), Value::List(vec![Value::Str("query".to_string()), Value::Str("queries".to_string()), Value::Str("sort".to_string()), Value::Str("searchIn".to_string()), Value::Str("eventId".to_string()), Value::Str("slug".to_string()), Value::Str("status".to_string()), Value::Str("tags".to_string())]), &[]);
if is_equal(&queries, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchEvents() missing queries".to_string()))));
}
let mut queriesLength: Value = get_array_length(&queries);
let mut eventId: Value = self.safe_string_k(params.clone(), "eventId", &[]);
// always fetch fresh from the API (never serve the possibly-cold cache): a query searches,
// an eventId does a direct lookup, and tags map to server-side keyword searches (the
// markets listing ignores tag filter params, but tag slugs match through keyword=)
let mut rawMarkets: Value = Value::List(vec![]);
let mut rawQuestions: Value = Value::List(vec![]);
if is_greater_than(&queriesLength, &Value::Int(0)) {
// some markets are only discoverable through the questions search endpoint
let mut responses: Value = promise_all(&Value::List(vec![self.fetch_raw_markets_by_search(queries.clone(), &[rest.clone()]).await, self.fetch_raw_questions_by_search(queries.clone(), &[rest.clone()]).await])).await;
rawMarkets = self.safe_list(responses.clone(), Value::Int(0), &[Value::List(vec![])]);
rawQuestions = self.safe_list(responses.clone(), Value::Int(1), &[Value::List(vec![])]);
} else if !is_equal(&eventId, &Value::Null) {
if is_greater_than(&get_index_of(&eventId, &Value::Str(":".to_string())), &negate(&Value::Int(1))) {
let mut rawMarket: Value = self.fetch_raw_market_by_id(eventId.clone(), &[rest.clone()]).await;
rawMarkets = Value::List(vec![rawMarket.clone()]);
} else {
let mut rawQuestion: Value = self.fetch_raw_question_by_id(eventId.clone(), &[rest.clone()]).await;
rawQuestions = Value::List(vec![rawQuestion.clone()]);
}
} else {
let mut requestedTags: Value = self.safe_list_k(params.clone(), "tags", &[Value::List(vec![])]);
let mut requestedTagsLength: Value = get_array_length(&requestedTags);
if is_equal(&requestedTagsLength, &Value::Int(0)) {
// unscoped mode: fetch bounded open lists from both sources and merge
let mut listResponses: Value = promise_all(&Value::List(vec![self.fetch_raw_markets_list(&[rest.clone()]).await, self.fetch_raw_questions_list(&[rest.clone()]).await])).await;
rawMarkets = self.safe_list(listResponses.clone(), Value::Int(0), &[Value::List(vec![])]);
rawQuestions = self.safe_list(listResponses.clone(), Value::Int(1), &[Value::List(vec![])]);
} else {
let mut tagQueries: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1320: bool = true;
while { if !__for_first_1320 { i = add(&i, &Value::Int(1)); } __for_first_1320 = false; is_less_than(&i, &requestedTagsLength) } {
// tag slugs are hyphenated ('world-cup'); search with spaces so titles match
let mut tagSlug: Value = get_value(&requestedTags, &i);
let mut tagSlug: Value = get_value(&requestedTags, &i);
append_to_array(&mut tagQueries, replace_all_str(&tagSlug, &Value::Str("-".to_string()), &Value::Str(" ".to_string())));
}
}
// run both searches in parallel; some events are only discoverable from questions,
// while market search is still the primary source for market-level data
let mut responses: Value = promise_all(&Value::List(vec![self.fetch_raw_markets_by_search(tagQueries.clone(), &[rest.clone()]).await, self.fetch_raw_questions_by_search(tagQueries.clone(), &[rest.clone()]).await])).await;
rawMarkets = self.safe_list(responses.clone(), Value::Int(0), &[Value::List(vec![])]);
rawQuestions = self.safe_list(responses.clone(), Value::Int(1), &[Value::List(vec![])]);
}
}
if is_equal(&self.markets, &Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut seenMarketHandles: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut result: Value = Value::List(vec![]);
let mut rawQuestionsLength: Value = get_array_length(&rawQuestions);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1322: bool = true;
while { if !__for_first_1322 { i = add(&i, &Value::Int(1)); } __for_first_1322 = false; is_less_than(&i, &rawQuestionsLength) } {
let mut rawQuestion: Value = get_value(&rawQuestions, &i);
let mut rawQuestion: Value = get_value(&rawQuestions, &i);
let mut ev: Value = self.parse_event(rawQuestion.clone());
let mut evMarkets: Value = self.safe_list_k(ev.clone(), "markets", &[Value::List(vec![])]);
let mut evMarketsLength: Value = get_array_length(&evMarkets);
let mut filteredMarkets: Value = Value::List(vec![]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1321: bool = true;
while { if !__for_first_1321 { j = add(&j, &Value::Int(1)); } __for_first_1321 = false; is_less_than(&j, &evMarketsLength) } {
let mut m: Value = self.safe_dict(evMarkets.clone(), j.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketHandle: Value = self.safe_string_k(m.clone(), "market", &[]);
if !is_equal(&marketHandle, &Value::Null) {
if is_true(&Value::Bool(in_op(&seenMarketHandles, &marketHandle))) {
continue;
}
add_element_to_object(&mut seenMarketHandles, &marketHandle, Value::Bool(true));
add_element_to_object(&mut self.markets, &marketHandle, m.clone());
}
append_to_array(&mut filteredMarkets, m.clone());
}
}
// skip question events that contribute no new markets after de-duplicating by market handle
let mut filteredMarketsLength: Value = get_array_length(&filteredMarkets);
if is_true(&(is_greater_than(&evMarketsLength, &Value::Int(0)))) && is_true(&(is_equal(&filteredMarketsLength, &Value::Int(0)))) {
continue;
}
add_element_to_object(&mut ev, &Value::Str("markets".to_string()), filteredMarkets.clone());
append_to_array(&mut result, ev.clone());
}
}
let mut rawMarketsLength: Value = get_array_length(&rawMarkets);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1323: bool = true;
while { if !__for_first_1323 { i = add(&i, &Value::Int(1)); } __for_first_1323 = false; is_less_than(&i, &rawMarketsLength) } {
let mut raw: Value = get_value(&rawMarkets, &i);
let mut raw: Value = get_value(&rawMarkets, &i);
let mut m: Value = self.parse_myriad_market(raw.clone(), &[]);
let mut marketHandle: Value = self.safe_string_k(m.clone(), "market", &[]);
if is_true(&(!is_equal(&marketHandle, &Value::Null))) && is_true(&(Value::Bool(in_op(&seenMarketHandles, &marketHandle)))) {
add_element_to_object(&mut self.markets, &marketHandle, m.clone());
continue;
}
if !is_equal(&marketHandle, &Value::Null) {
add_element_to_object(&mut seenMarketHandles, &marketHandle, Value::Bool(true));
add_element_to_object(&mut self.markets, &marketHandle, m.clone());
}
let mut ev: Value = self.parse_market_to_event(raw.clone(), m.clone());
append_to_array(&mut result, ev.clone());
}
}
// setEvents keys events by id/slug/handle; populateOutcomes rebuilds the outcome cache
self.set_events(result.clone());
self.populate_outcomes();
// tags were already applied server-side (mapped to keyword searches); strip them before
// the client-side pass — raw markets don't carry a matching event-level tags field
let mut postParams: Value = self.omit(params.clone(), Value::List(vec![Value::Str("tags".to_string())]), &[]);
return self.apply_event_fetch_params(result.clone(), &[postParams.clone(), queries.clone()]);
Value::Null
}
/*
* @ignore
* @method
* @name myriad#parseEvent
* @description parses a raw myriad question object into the unified event shape with a nested markets list
* @param {object} rawEvent the raw myriad question object
* @returns {object} an event structure
*/
pub fn parse_event(&self, mut rawEvent: Value) -> Value {
let mut questionSlug: Value = self.safe_string_k(rawEvent.clone(), "slug", &[self.safe_string(rawEvent.clone(), Value::Str("id".to_string()), &[])]);
let mut rawMarkets: Value = self.safe_list_k(rawEvent.clone(), "markets", &[Value::List(vec![])]);
let mut marketsList: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1324: bool = true;
while { if !__for_first_1324 { i = add(&i, &Value::Int(1)); } __for_first_1324 = false; is_less_than(&i, &get_array_length(&rawMarkets)) } {
let mut rawMarket: Value = get_value(&rawMarkets, &i);
let mut rawMarket: Value = get_value(&rawMarkets, &i);
append_to_array(&mut marketsList, self.parse_myriad_market(rawMarket.clone(), &[questionSlug.clone()]));
}
}
let mut endDate: Value = self.safe_string_k(rawEvent.clone(), "expiresAt", &[self.safe_string(rawEvent.clone(), Value::Str("endDate".to_string()), &[])]);
let __ws_arg_32 = self.safe_string_k(rawEvent.clone(), "id", &[]);
let __ws_arg_33 = self.shorten_slug(questionSlug.clone());
let __ws_arg_34 = self.safe_string_k(rawEvent.clone(), "title", &[]);
let __ws_arg_35 = self.safe_string_k(rawEvent.clone(), "description", &[]);
let __ws_arg_36 = self.safe_number2(rawEvent.clone(), Value::Str("volumeNotional24h".to_string()), Value::Str("volume24h".to_string()), &[]);
let __ws_arg_37 = self.safe_number_k(rawEvent.clone(), "liquidity", &[]);
let __ws_arg_38 = self.safe_string_k(rawEvent.clone(), "url", &[]);
let __ws_arg_39 = self.safe_string_k(rawEvent.clone(), "imageUrl", &[self.safe_string(rawEvent.clone(), Value::Str("image".to_string()), &[])]);
let __ws_arg_40 = self.safe_bool_k(rawEvent.clone(), "active", &[]);
let __ws_arg_41 = self.safe_bool_k(rawEvent.clone(), "resolved", &[Value::Bool(false)]);
let __ws_arg_42 = self.safe_string_k(rawEvent.clone(), "category", &[]);
let __ws_arg_43 = self.safe_list_k(rawEvent.clone(), "tags", &[]);
let __ws_arg_44 = self.parse8601(self.safe_string_k(rawEvent.clone(), "createdAt", &[]));
let __ws_arg_45 = self.safe_string_k(rawEvent.clone(), "createdAt", &[]);
let __ws_arg_46 = self.parse8601(endDate.clone());
let __ws_arg_47 = self.parse8601(self.safe_string_k(rawEvent.clone(), "updatedAt", &[]));
let __ws_arg_48 = self.safe_string_k(rawEvent.clone(), "resolutionSource", &[]);
return self.extend(rawEvent.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), __ws_arg_32);
m.insert("slug".to_string(), questionSlug.clone());
m.insert("event".to_string(), ternary(is_true(&(!is_equal(&questionSlug, &Value::Null) && !is_equal(&questionSlug, &Value::Str("".to_string())))), __ws_arg_33, Value::Null));
m.insert("title".to_string(), __ws_arg_34);
m.insert("description".to_string(), __ws_arg_35);
m.insert("markets".to_string(), marketsList.clone());
m.insert("volume".to_string(), __ws_arg_36);
m.insert("liquidity".to_string(), __ws_arg_37);
m.insert("url".to_string(), __ws_arg_38);
m.insert("image".to_string(), __ws_arg_39);
m.insert("active".to_string(), __ws_arg_40);
m.insert("resolved".to_string(), __ws_arg_41);
m.insert("category".to_string(), __ws_arg_42);
m.insert("tags".to_string(), __ws_arg_43);
m.insert("created".to_string(), __ws_arg_44);
m.insert("createdDatetime".to_string(), __ws_arg_45);
m.insert("end".to_string(), ternary(is_true(&(!is_equal(&endDate, &Value::Null) && !is_equal(&endDate, &Value::Str("".to_string())))), __ws_arg_46, Value::Null));
m.insert("endDatetime".to_string(), endDate.clone());
m.insert("lastUpdatedAt".to_string(), __ws_arg_47);
m.insert("resolutionSource".to_string(), __ws_arg_48);
m.insert("info".to_string(), rawEvent.clone());
m
})]);
Value::Null
}
pub fn request_id(&self, mut url: Value) -> Value {
let mut existing: Value = self.safe_value_k(self.options.clone(), "requestId", &[]);
if is_equal(&existing, &Value::Null) {
{ let __be_tmp = self.create_safe_dictionary(&[]); add_element_to_object(&mut self.options.clone(), &Value::Str("requestId".to_string()), __be_tmp); };
}
let mut options: Value = get_value(&self.options, &Value::Str("requestId".to_string()));
let mut previousValue: Value = self.safe_integer(options.clone(), url.clone(), &[Value::Int(0)]);
let mut newValue: Value = self.sum(&[previousValue.clone(), Value::Int(1)]);
if !is_equal(&url, &Value::Null) {
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("requestId".to_string())), &url, newValue.clone());
}
return newValue;
Value::Null
}
pub fn from_wei(&self, mut wei: Value) -> Value {
if is_equal(&wei, &Value::Null) {
return Value::Null;
}
return self.parse_number(crate::precise::Precise::stringDiv(&wei, &Value::Str("1000000000000000000".to_string())), &[]);
Value::Null
}
pub fn market_outcome_to_symbol(&self, mut networkId: Value, mut marketId: Value, mut outcomeId: Value) -> Value {
// guard the ids before concatenating: a missing id would crash on string + None in Python/PHP
if is_true(&(is_equal(&networkId, &Value::Null))) || is_true(&(is_equal(&marketId, &Value::Null))) || is_true(&(is_equal(&outcomeId, &Value::Null))) {
return Value::Null;
}
let mut ocId: Value = add(&add(&add(&add(&networkId, &Value::Str(":".to_string())), &marketId), &Value::Str("/".to_string())), &outcomeId);
let mut outcomeObj: Value = self.safe_dict(self.exchange.outcomes_by_id.clone(), ocId.clone(), &[]);
return self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
Value::Null
}
pub async fn connect_centrifugo(&mut self, mut url: Value) -> Value {
// Centrifugo requires an anonymous connect command before any subscribe. This sends it once per
// connection and resolves when the connect reply arrives (see handleCentrifugoFrame). The base
// clears client.subscriptions on reconnect, so an absent 'connect' marker means a fresh handshake.
let mut client: Value = self.client(&[url.clone()]);
let mut connectSent: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".to_string())), Value::Str("connect".to_string()), &[]);
if is_equal(&connectSent, &Value::Null) {
add_element_to_object(&mut self.options, &Value::Str("wsConnected".to_string()), Value::Bool(false));
let mut requestId: Value = self.request_id(url.clone());
// give the anonymous connect a name so the params object is non-empty (PHP serialises an
// empty array as a JSON array, which Centrifugo rejects)
let mut connectMsg: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("connect".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("ccxt".to_string()));
m
}));
m.insert("id".to_string(), requestId.clone());
m
});
return self.watch(url.clone(), Value::Str("centrifugoConnected".to_string()), &[connectMsg.clone(), Value::Str("connect".to_string())]).await;
}
if is_true(&self.safe_bool_k(self.options.clone(), "wsConnected", &[Value::Bool(false)])) {
return Value::Null;
}
return crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str("centrifugoConnected".to_string())])).await;
Value::Null
}
pub async fn pong(&mut self, mut client: Value, optional_args: &[Value]) -> Value {
let mut message = get_arg(optional_args, 0, Value::Null);
// Centrifugo server pings are empty frames; reply with the same empty frame to keep the link alive
client.send(&[Value::Str("{}".to_string())]);
Value::Null
}
pub async fn subscribe_myriad_channel(&mut self, mut messageHash: Value, mut channel: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut url: Value = self.safe_string(get_value(&self.urls, &Value::Str("api".to_string())), Value::Str("ws".to_string()), &[]);
// finish the connect handshake first so the subscribe frame is sent after the connect reply
self.connect_centrifugo(url.clone()).await;
let mut requestId: Value = self.request_id(url.clone());
let mut subscribeMsg: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subscribe".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), channel.clone());
m
}));
m.insert("id".to_string(), requestId.clone());
m
});
return self.watch(url.clone(), messageHash.clone(), &[subscribeMsg.clone(), channel.clone()]).await;
Value::Null
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
// Centrifugo packs several commands per frame joined by \n; a multi-command frame fails the
// base JSON.parse and arrives here as a raw string, a single command arrives already parsed
if is_string(&message) {
let mut lines: Value = split(&message, &Value::Str("\n".to_string()));
let mut linesLength: Value = get_array_length(&lines);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1325: bool = true;
while { if !__for_first_1325 { i = add(&i, &Value::Int(1)); } __for_first_1325 = false; is_less_than(&i, &linesLength) } {
let mut line: Value = get_value(&lines, &i);
let mut line: Value = get_value(&lines, &i);
if is_greater_than(&get_array_length(&line), &Value::Int(0)) {
let mut parsed: Value = json_parse(&line);
self.handle_centrifugo_frame(client.clone(), parsed.clone());
}
}
}
return;
}
self.handle_centrifugo_frame(client.clone(), message.clone());
}
pub fn handle_centrifugo_frame(&mut self, mut client: Value, mut msg: Value) {
let mut keys: Value = object_keys(&msg);
let mut keysLength: Value = get_array_length(&keys);
if is_equal(&keysLength, &Value::Int(0)) {
self.spawn(&[Value::Null.clone(), client.clone(), msg.clone()]);
return;
}
let mut connectReply: Value = self.safe_dict_k(msg.clone(), "connect", &[]);
if !is_equal(&connectReply, &Value::Null) {
// connect acknowledged — unblock connectCentrifugo so channel subscribes can be sent
add_element_to_object(&mut self.options.clone(), &Value::Str("wsConnected".to_string()), Value::Bool(true));
client.resolve(&[Value::Bool(true), Value::Str("centrifugoConnected".to_string())]);
return;
}
let mut push: Value = self.safe_dict_k(msg.clone(), "push", &[]);
if is_equal(&push, &Value::Null) {
return;
}
let mut channel: Value = self.safe_string_k(push.clone(), "channel", &[]);
if is_equal(&channel, &Value::Null) {
return;
}
let mut pub_val: Value = self.safe_dict_k(push.clone(), "pub", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(pub_val.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut parts: Value = split(&channel, &Value::Str(":".to_string()));
let mut channelType: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
if is_equal(&channelType, &Value::Str("orderbook".to_string())) {
self.handle_order_book(client.clone(), data.clone());
} else if is_equal(&channelType, &Value::Str("trades".to_string())) {
self.handle_trades(client.clone(), data.clone());
} else if is_equal(&channelType, &Value::Str("prices".to_string())) {
self.handle_ticker(client.clone(), data.clone());
} else if is_equal(&channelType, &Value::Str("orders".to_string())) {
self.handle_order(client.clone(), data.clone());
} else if is_equal(&channelType, &Value::Str("positions".to_string())) {
self.handle_position(client.clone(), data.clone());
}
}
/*
* @method
* @name myriad#watchOrderBook
* @description streams the order book for an outcome over the Centrifugo websocket; the channel is delta-only so the book is seeded from the REST snapshot
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da82810581f8d2c8be2364fa
* @param {string} outcome unified outcome
* @param {int} [limit] the maximum number of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
*/
pub async fn watch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(info.clone(), "marketId", &[]);
let mut sym: Value = self.safe_outcome_symbol(outcome.clone(), &[outcomeObj.clone()]);
let mut channel: Value = add(&add(&add(&Value::Str("orderbook:".to_string()), &networkId), &Value::Str(":".to_string())), &marketId);
let mut messageHash: Value = add(&Value::Str("orderbook::".to_string()), &sym);
let mut url: Value = self.safe_string(get_value(&self.urls, &Value::Str("api".to_string())), Value::Str("ws".to_string()), &[]);
// finish the connect handshake first so the client exists and the subscribe follows the connect reply
self.connect_centrifugo(url.clone()).await;
let mut client: Value = self.client(&[url.clone()]);
let mut isNewSubscription: bool = is_equal(&self.safe_value(get_value(&client, &Value::Str("subscriptions".to_string())), channel.clone(), &[]), &Value::Null);
if is_true(&isNewSubscription) {
// the channel only streams deltas, so (re)seed the live book from the REST snapshot on a
// fresh subscription (first call or after a reconnect that cleared client.subscriptions)
self.seed_order_book(outcome.clone(), sym.clone(), &[limit.clone()]).await;
}
let mut requestId: Value = self.request_id(url.clone());
let mut subscribeMsg: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subscribe".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), channel.clone());
m
}));
m.insert("id".to_string(), requestId.clone());
m
});
let mut future: Value = self.watch(url.clone(), messageHash.clone(), &[subscribeMsg.clone(), channel.clone()]).await;
if is_true(&isNewSubscription) {
// return the freshly-seeded book immediately instead of blocking until the next delta
client.resolve(&[self.safe_value(self.orderbooks.clone(), sym.clone(), &[]), messageHash.clone()]);
}
let mut orderbook: Value = crate::exchange_stubs::ws_await_flight(&future).await;
return orderbook.limit();
Value::Null
}
pub async fn seed_order_book(&mut self, mut outcome: Value, mut sym: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
// the order book channel streams deltas only, so seed the live book from the REST snapshot
let mut snapshot: Value = self.fetch_order_book(outcome.clone(), &[limit.clone()]).await;
let mut orderbook: Value = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
orderbook.reset(snapshot.clone());
add_element_to_object(&mut self.orderbooks, &sym, orderbook.clone());
Value::Null
}
pub fn handle_order_book(&self, mut client: Value, mut data: Value) {
let mut networkId: Value = self.safe_string_k(data.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "marketId", &[]);
let mut ts: Value = self.safe_integer_k(data.clone(), "ts", &[]);
let mut changes: Value = self.safe_list_k(data.clone(), "changes", &[Value::List(vec![])]);
let mut changesLength: Value = get_array_length(&changes);
let mut updated: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1326: bool = true;
while { if !__for_first_1326 { i = add(&i, &Value::Int(1)); } __for_first_1326 = false; is_less_than(&i, &changesLength) } {
let mut change: Value = get_value(&changes, &i);
let mut change: Value = get_value(&changes, &i);
let mut outcomeId: Value = self.safe_string_k(change.clone(), "outcome", &[]);
let mut sym: Value = self.market_outcome_to_symbol(networkId.clone(), marketId.clone(), outcomeId.clone());
if is_equal(&sym, &Value::Null) {
continue;
}
if is_equal(&self.safe_value(self.orderbooks.clone(), sym.clone(), &[]), &Value::Null) {
continue;
}
let mut orderbook: Value = get_value(&self.orderbooks, &sym);
let mut price: Value = self.from_wei(self.safe_string_k(change.clone(), "price", &[]));
let mut amount: Value = self.from_wei(self.safe_string_k(change.clone(), "amount", &[]));
let mut sideStr: Value = self.safe_string_k(change.clone(), "side", &[]);
let mut bookSide: Value = ternary(is_true(&(is_equal(&sideStr, &Value::Str("bid".to_string())))), get_value(&orderbook, &Value::Str("bids".to_string())), get_value(&orderbook, &Value::Str("asks".to_string())));
bookSide.store_array(Value::List(vec![price.clone(), amount.clone()]));
add_element_to_object(&mut orderbook, &Value::Str("timestamp".to_string()), ts.clone());
add_element_to_object(&mut orderbook, &Value::Str("datetime".to_string()), self.iso8601(ts.clone()));
add_element_to_object(&mut updated, &sym, Value::Bool(true));
}
}
let mut updatedSymbols: Value = object_keys(&updated);
let mut updatedLength: Value = get_array_length(&updatedSymbols);
{
let mut k: Value = Value::Int(0);
let mut __for_first_1327: bool = true;
while { if !__for_first_1327 { k = add(&k, &Value::Int(1)); } __for_first_1327 = false; is_less_than(&k, &updatedLength) } {
let mut sym: Value = get_value(&updatedSymbols, &k);
let mut sym: Value = get_value(&updatedSymbols, &k);
client.resolve(&[get_value(&self.orderbooks, &sym), add(&Value::Str("orderbook::".to_string()), &sym)]);
}
}
}
/*
* @method
* @name myriad#watchTrades
* @description streams public trades for an outcome over the Centrifugo websocket
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da82810581f8d2c8be2364fa
* @param {string} outcome unified outcome
* @param {int} [since] timestamp in ms of the earliest trade
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn watch_trades(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(info.clone(), "marketId", &[]);
let mut sym: Value = self.safe_outcome_symbol(outcome.clone(), &[outcomeObj.clone()]);
let mut channel: Value = add(&add(&add(&Value::Str("trades:".to_string()), &networkId), &Value::Str(":".to_string())), &marketId);
let mut messageHash: Value = add(&Value::Str("trades::".to_string()), &sym);
let mut trades: Value = self.subscribe_myriad_channel(messageHash.clone(), channel.clone(), &[params.clone()]).await;
return self.filter_by_since_limit(trades.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name myriad#watchMyTrades
* @description streams the wallet's own fills for a market over the Centrifugo trades channel (real
* execution prices, unlike the REST fetchMyTrades); requires a market outcome since the channel is per-market
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da82810581f8d2c8be2364fa
* @param {string} outcome unified outcome whose market to watch
* @param {int} [since] timestamp in ms of the earliest trade
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&outcome, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" watchMyTrades() requires a outcome (the trades channel is per-market)".to_string()))));
}
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(info.clone(), "marketId", &[]);
let mut sym: Value = self.safe_outcome_symbol(outcome.clone(), &[outcomeObj.clone()]);
let mut channel: Value = add(&add(&add(&Value::Str("trades:".to_string()), &networkId), &Value::Str(":".to_string())), &marketId);
let mut messageHash: Value = Value::Str("myTrades".to_string());
let mut trades: Value = self.subscribe_myriad_channel(messageHash.clone(), channel.clone(), &[params.clone()]).await;
return self.filter_by_value_since_limit(trades.clone(), Value::Str("outcome".to_string()), &[sym.clone(), since.clone(), limit.clone(), Value::Str("timestamp".to_string()), Value::Bool(true)]);
Value::Null
}
pub fn wallet_address_or_undefined(&self) -> Value {
// like walletAddressFromKeys but returns undefined instead of throwing when no wallet is configured
if is_true(&(!is_equal(&self.walletAddress, &Value::Null))) && is_true(&(is_greater_than(&get_array_length(&self.walletAddress), &Value::Int(0)))) {
return to_lower(&self.walletAddress);
}
if !is_equal(&self.privateKey, &Value::Null) {
return to_lower(&self.eth_get_address_from_private_key(self.privateKey.clone(), &[]));
}
return Value::Null;
Value::Null
}
pub fn handle_trades(&mut self, mut client: Value, mut data: Value) {
let mut networkId: Value = self.safe_string_k(data.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "marketId", &[]);
let mut ts: Value = self.safe_integer_k(data.clone(), "ts", &[]);
let mut txHash: Value = self.safe_string_k(data.clone(), "txHash", &[]);
let mut taker: Value = self.safe_dict_k(data.clone(), "taker", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut outcomeId: Value = self.safe_string_k(taker.clone(), "outcome", &[]);
let mut sym: Value = self.market_outcome_to_symbol(networkId.clone(), marketId.clone(), outcomeId.clone());
if is_equal(&sym, &Value::Null) {
return;
}
let mut market: Value = self.safe_market(&[sym.clone()]);
let mut outcomeObj: Value = self.safe_outcome(sym.clone(), &[]);
// the trades channel reports human-decimal values (averagePrice "0.14", totalAmount "1"),
// unlike the orders channel which is 1e18-scaled — so read them directly without fromWei
let mut fees: Value = self.safe_dict_k(taker.clone(), "totalFees", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut trade: Value = self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), txHash.clone());
m.insert("info".to_string(), data.clone());
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts.clone()));
m.insert("outcome".to_string(), sym.clone());
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("order".to_string(), self.safe_string_k(taker.clone(), "orderHash", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower(taker.clone(), Value::Str("side".to_string()), &[]));
m.insert("takerOrMaker".to_string(), Value::Str("taker".to_string()));
m.insert("price".to_string(), self.safe_number_k(taker.clone(), "averagePrice", &[]));
m.insert("amount".to_string(), self.safe_number_k(taker.clone(), "totalAmount", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_number_k(fees.clone(), "total", &[]));
m.insert("currency".to_string(), self.safe_string_k(market.clone(), "quote", &[]));
m
}));
m
}), &[market.clone()]);
if is_equal(&self.trades, &Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.trades = __t; }
}
if is_equal(&self.safe_value(self.trades.clone(), sym.clone(), &[]), &Value::Null) {
let mut tradesLimit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
add_element_to_object(&mut self.trades.clone(), &sym, ArrayCache::new(tradesLimit.clone()));
}
let mut stored: Value = get_value(&self.trades, &sym);
stored.append(trade.clone());
client.resolve(&[stored.clone(), add(&Value::Str("trades::".to_string()), &sym)]);
// also surface the wallet's own fills (taker or maker leg) with their real execution prices
let mut myWallet: Value = self.wallet_address_or_undefined();
if !is_equal(&myWallet, &Value::Null) {
let mut myLegs: Value = Value::List(vec![]);
let mut takerTrader: Value = self.safe_string_lower(taker.clone(), Value::Str("trader".to_string()), &[]);
if is_equal(&takerTrader, &myWallet) {
append_to_array(&mut myLegs, trade.clone());
}
let mut makers: Value = self.safe_list_k(data.clone(), "makers", &[Value::List(vec![])]);
let mut makersLength: Value = get_array_length(&makers);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1328: bool = true;
while { if !__for_first_1328 { i = add(&i, &Value::Int(1)); } __for_first_1328 = false; is_less_than(&i, &makersLength) } {
let mut maker: Value = get_value(&makers, &i);
let mut maker: Value = get_value(&makers, &i);
let mut makerTrader: Value = self.safe_string_lower(maker.clone(), Value::Str("trader".to_string()), &[]);
if is_equal(&makerTrader, &myWallet) {
let mut makerSym: Value = self.market_outcome_to_symbol(networkId.clone(), marketId.clone(), self.safe_string_k(maker.clone(), "outcome", &[]));
let mut makerMarket: Value = self.safe_market(&[makerSym.clone()]);
let mut makerOutcomeObj: Value = self.safe_outcome(makerSym.clone(), &[]);
let mut makerFees: Value = self.safe_dict_k(maker.clone(), "fees", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut makerTrade: Value = self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), txHash.clone());
m.insert("info".to_string(), maker.clone());
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts.clone()));
m.insert("outcome".to_string(), makerSym.clone());
m.insert("outcomeId".to_string(), self.safe_string_k(makerOutcomeObj.clone(), "id", &[]));
m.insert("label".to_string(), self.safe_string_k(makerOutcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(makerOutcomeObj.clone(), "market", &[]));
m.insert("order".to_string(), self.safe_string_k(maker.clone(), "orderHash", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower(maker.clone(), Value::Str("side".to_string()), &[]));
m.insert("takerOrMaker".to_string(), Value::Str("maker".to_string()));
m.insert("price".to_string(), self.safe_number_k(maker.clone(), "price", &[]));
m.insert("amount".to_string(), self.safe_number_k(maker.clone(), "amount", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_number_k(makerFees.clone(), "total", &[]));
m.insert("currency".to_string(), self.safe_string_k(makerMarket.clone(), "quote", &[]));
m
}));
m
}), &[makerMarket.clone()]);
append_to_array(&mut myLegs, makerTrade.clone());
}
}
}
let mut myLegsLength: Value = get_array_length(&myLegs);
if is_greater_than(&myLegsLength, &Value::Int(0)) {
if is_equal(&self.myTrades, &Value::Null) {
let mut myTradesLimit: Value = self.safe_integer_k(self.options.clone(), "myTradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheByOutcomeById::new(myTradesLimit.clone());
}
let mut myStored: Value = self.myTrades.clone();
{
let mut k: Value = Value::Int(0);
let mut __for_first_1329: bool = true;
while { if !__for_first_1329 { k = add(&k, &Value::Int(1)); } __for_first_1329 = false; is_less_than(&k, &myLegsLength) } {
myStored.append(get_value(&myLegs, &k));
}
}
client.resolve(&[myStored.clone(), Value::Str("myTrades".to_string())]);
}
}
}
/*
* @method
* @name myriad#watchTicker
* @description streams best bid/ask/last for an outcome over the Centrifugo prices channel
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da82810581f8d2c8be2364fa
* @param {string} outcome unified outcome
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub async fn watch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(info.clone(), "marketId", &[]);
let mut sym: Value = self.safe_outcome_symbol(outcome.clone(), &[outcomeObj.clone()]);
let mut channel: Value = add(&add(&add(&Value::Str("prices:".to_string()), &networkId), &Value::Str(":".to_string())), &marketId);
let mut messageHash: Value = add(&Value::Str("ticker::".to_string()), &sym);
return self.subscribe_myriad_channel(messageHash.clone(), channel.clone(), &[params.clone()]).await;
Value::Null
}
/*
* @method
* @name myriad#watchTickers
* @description streams best bid/ask/last for several outcomes over the Centrifugo prices channels
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da82810581f8d2c8be2364fa
* @param {string[]} outcomes unified outcomes to watch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dict of [prediction ticker structures](https://docs.ccxt.com/#/?id=prediction-ticker-structure) indexed by outcome
*/
pub async fn watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&outcomes, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" watchTickers() requires a list of outcomes (the prices channel is per-market)".to_string()))));
}
let mut symbolsLength: Value = get_array_length(&outcomes);
let mut url: Value = self.safe_string(get_value(&self.urls, &Value::Str("api".to_string())), Value::Str("ws".to_string()), &[]);
self.connect_centrifugo(url.clone()).await;
self.load_outcomes(&[outcomes.clone()]).await;
let mut client: Value = self.client(&[url.clone()]);
let mut seenChannels: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut resolvedSymbols: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1330: bool = true;
while { if !__for_first_1330 { i = add(&i, &Value::Int(1)); } __for_first_1330 = false; is_less_than(&i, &symbolsLength) } {
let mut outcomeObj: Value = self.outcome(get_value(&outcomes, &i));
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkId: Value = self.safe_string_k(info.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(info.clone(), "marketId", &[]);
let mut channel: Value = add(&add(&add(&Value::Str("prices:".to_string()), &networkId), &Value::Str(":".to_string())), &marketId);
append_to_array(&mut resolvedSymbols, self.safe_outcome_symbol(get_value(&outcomes, &i), &[outcomeObj.clone()]));
if is_equal(&self.safe_value(seenChannels.clone(), channel.clone(), &[]), &Value::Null) {
add_element_to_object(&mut seenChannels, &channel, Value::Bool(true));
let mut requestId: Value = self.request_id(url.clone());
let mut subscribeMsg: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subscribe".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), channel.clone());
m
}));
m.insert("id".to_string(), requestId.clone());
m
});
self.watch(url.clone(), Value::Str("tickers".to_string()), &[subscribeMsg.clone(), channel.clone()]).await;
}
}
}
let mut tickers: Value = crate::exchange_stubs::ws_await_flight(&client.future(&[Value::Str("tickers".to_string())])).await;
return self.filter_by_array(tickers.clone(), Value::Str("outcome".to_string()), &[resolvedSymbols.clone(), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name myriad#watchOHLCV
* @description streams OHLCV candles for an outcome, synthesised from the live trades channel
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da82810581f8d2c8be2364fa
* @param {string} outcome unified outcome
* @param {string} timeframe the length of each candle (e.g. '1m', '1h', '1d')
* @param {int} [since] timestamp in ms of the earliest candle
* @param {int} [limit] the maximum number of candles to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} a list of [timestamp, open, high, low, close, volume] candles
*/
pub async fn watch_ohlcv(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".to_string()));
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
}));
// Myriad has no OHLCV websocket channel, so build candles from the live trade stream
let mut trades: Value = self.watch_trades(outcome.clone(), &[since.clone(), limit.clone(), params.clone()]).await;
let mut ohlcvc: Value = self.build_ohlcvc(trades.clone(), &[timeframe.clone(), Value::Int(0), Value::Int(2147483647)]);
let mut result: Value = Value::List(vec![]);
let mut ohlcvcLength: Value = get_array_length(&ohlcvc);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1331: bool = true;
while { if !__for_first_1331 { i = add(&i, &Value::Int(1)); } __for_first_1331 = false; is_less_than(&i, &ohlcvcLength) } {
let mut candle: Value = get_value(&ohlcvc, &i);
let mut candle: Value = get_value(&ohlcvc, &i);
append_to_array(&mut result, Value::List(vec![get_value(&candle, &Value::Int(0)), get_value(&candle, &Value::Int(1)), get_value(&candle, &Value::Int(2)), get_value(&candle, &Value::Int(3)), get_value(&candle, &Value::Int(4)), get_value(&candle, &Value::Int(5))]));
}
}
return self.filter_by_since_limit(result.clone(), &[since.clone(), limit.clone(), Value::Int(0), Value::Bool(true)]);
Value::Null
}
pub fn handle_ticker(&mut self, mut client: Value, mut data: Value) {
let mut networkId: Value = self.safe_string_k(data.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "marketId", &[]);
let mut ts: Value = self.safe_integer_k(data.clone(), "ts", &[]);
let mut outcomes: Value = self.safe_list_k(data.clone(), "outcomes", &[Value::List(vec![])]);
let mut outcomesLength: Value = get_array_length(&outcomes);
if is_equal(&self.tickers, &Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.tickers = __t; }
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1332: bool = true;
while { if !__for_first_1332 { i = add(&i, &Value::Int(1)); } __for_first_1332 = false; is_less_than(&i, &outcomesLength) } {
let mut oc: Value = get_value(&outcomes, &i);
let mut oc: Value = get_value(&outcomes, &i);
let mut outcomeId: Value = self.safe_string_k(oc.clone(), "outcome", &[]);
let mut sym: Value = self.market_outcome_to_symbol(networkId.clone(), marketId.clone(), outcomeId.clone());
if is_equal(&sym, &Value::Null) {
continue;
}
let mut market: Value = self.safe_market(&[sym.clone()]);
let mut outcomeObj: Value = self.safe_outcome(sym.clone(), &[]);
let mut last: Value = self.from_wei(self.safe_string_k(oc.clone(), "last", &[]));
let mut ticker: Value = self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), sym.clone());
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts.clone()));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), self.from_wei(self.safe_string_k(oc.clone(), "bestBid", &[])));
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), self.from_wei(self.safe_string_k(oc.clone(), "bestAsk", &[])));
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last.clone());
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("info".to_string(), oc.clone());
m
}), &[market.clone()]);
add_element_to_object(&mut self.tickers.clone(), &sym, ticker.clone());
client.resolve(&[ticker.clone(), add(&Value::Str("ticker::".to_string()), &sym)]);
}
}
client.resolve(&[self.tickers.clone(), Value::Str("tickers".to_string())]);
}
/*
* @method
* @name myriad#watchOrders
* @description streams the wallet's order lifecycle updates over the Centrifugo orders channel
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da82810581f8d2c8be2364fa
* @param {string} [outcome] unified outcome to filter by
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut trader: Value = self.wallet_address_from_keys();
let mut networkId: Value = self.safe_string_k(self.options.clone(), "defaultNetworkId", &[Value::Str("56".to_string())]);
if !is_equal(&outcome, &Value::Null) {
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
networkId = self.safe_string_k(info.clone(), "networkId", &[networkId.clone()]);
outcome = self.safe_outcome_symbol(outcome.clone(), &[outcomeObj.clone()]);
}
let mut channel: Value = add(&add(&add(&Value::Str("orders:".to_string()), &networkId), &Value::Str(":".to_string())), &trader);
let mut messageHash: Value = Value::Str("orders".to_string());
let mut orders: Value = self.subscribe_myriad_channel(messageHash.clone(), channel.clone(), &[params.clone()]).await;
return self.filter_by_value_since_limit(orders.clone(), Value::Str("outcome".to_string()), &[outcome.clone(), since.clone(), limit.clone(), Value::Str("timestamp".to_string()), Value::Bool(true)]);
Value::Null
}
pub fn handle_order(&mut self, mut client: Value, mut data: Value) {
if is_equal(&self.orders, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheByOutcomeById::new(limit.clone());
}
let mut networkId: Value = self.safe_string_k(data.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "marketId", &[]);
let mut outcomeId: Value = self.safe_string_k(data.clone(), "outcome", &[]);
let mut sym: Value = self.market_outcome_to_symbol(networkId.clone(), marketId.clone(), outcomeId.clone());
let mut outcomeObj: Value = self.safe_outcome(sym.clone(), &[]);
let mut price: Value = self.from_wei(self.safe_string_k(data.clone(), "price", &[]));
let mut amount: Value = self.from_wei(self.safe_string_k(data.clone(), "amount", &[]));
let mut filled: Value = self.from_wei(self.safe_string_k(data.clone(), "filledAmount", &[]));
let mut status: Value = self.parse_order_status(self.safe_string_lower(data.clone(), Value::Str("status".to_string()), &[]));
let mut tif: Value = self.safe_string_upper(data.clone(), Value::Str("timeInForce".to_string()), &[]);
let mut isMarketTif: bool = is_true(&(is_equal(&tif, &Value::Str("FOK".to_string())))) || is_true(&(is_equal(&tif, &Value::Str("FAK".to_string()))));
let mut timestamp: Value = self.parse8601(self.safe_string2(data.clone(), Value::Str("updatedAt".to_string()), Value::Str("createdAt".to_string()), &[]));
let mut parsed: Value = self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(data.clone(), "orderHash", &[]));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), data.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("outcome".to_string(), sym.clone());
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".to_string()), Value::Str("id".to_string()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("type".to_string(), ternary(is_true(&isMarketTif), Value::Str("market".to_string()), Value::Str("limit".to_string())));
m.insert("timeInForce".to_string(), tif.clone());
m.insert("side".to_string(), self.safe_string_lower(data.clone(), Value::Str("side".to_string()), &[]));
m.insert("price".to_string(), price.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("filled".to_string(), filled.clone());
m.insert("remaining".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("status".to_string(), status.clone());
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[]);
let mut stored: Value = self.orders.clone();
stored.append(parsed.clone());
client.resolve(&[stored.clone(), Value::Str("orders".to_string())]);
if !is_equal(&sym, &Value::Null) {
client.resolve(&[stored.clone(), add(&Value::Str("orders::".to_string()), &sym)]);
}
}
/*
* @method
* @name myriad#watchPositions
* @description streams the wallet's share-balance changes over the Centrifugo positions channel
* @see https://docs.myriad.markets/builders/myriad-order-book/order-book-api#37dc9e49da82810581f8d2c8be2364fa
* @param {string[]} [outcomes] unified outcomes to filter by
* @param {int} [since] timestamp in ms of the earliest position update
* @param {int} [limit] the maximum number of position updates to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction position structures](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub async fn watch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = 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 !is_equal(&outcomes, &Value::Null) {
self.load_outcomes(&[outcomes.clone()]).await;
}
let mut trader: Value = self.wallet_address_from_keys();
let mut networkId: Value = self.safe_string_k(self.options.clone(), "defaultNetworkId", &[Value::Str("56".to_string())]);
let mut channel: Value = add(&add(&add(&Value::Str("positions:".to_string()), &networkId), &Value::Str(":".to_string())), &trader);
let mut messageHash: Value = Value::Str("positions".to_string());
let mut url: Value = self.safe_string(get_value(&self.urls, &Value::Str("api".to_string())), Value::Str("ws".to_string()), &[]);
self.connect_centrifugo(url.clone()).await;
let mut client: Value = self.client(&[url.clone()]);
let mut isNewSubscription: bool = is_equal(&self.safe_value(get_value(&client, &Value::Str("subscriptions".to_string())), channel.clone(), &[]), &Value::Null);
if is_true(&isNewSubscription) {
// the channel pushes only signed deltas; seed absolute share balances from REST so
// handlePosition can maintain a running contracts figure
self.seed_position_balances(trader.clone()).await;
}
let mut requestId: Value = self.request_id(url.clone());
let mut subscribeMsg: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subscribe".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), channel.clone());
m
}));
m.insert("id".to_string(), requestId.clone());
m
});
let mut positions: Value = self.watch(url.clone(), messageHash.clone(), &[subscribeMsg.clone(), channel.clone()]).await;
if is_true(&self.newUpdates) {
return positions;
}
return self.filter_by_outcomes_since_limit(positions.clone(), &[outcomes.clone(), since.clone(), limit.clone(), Value::Bool(true)]);
Value::Null
}
pub async fn seed_position_balances(&mut self, mut trader: Value) -> Value {
let mut positions: Value = self.fetch_positions(&[Value::Null, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("address".to_string(), trader.clone());
m
})]).await;
let mut balances: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut positionsLength: Value = get_array_length(&positions);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1333: bool = true;
while { if !__for_first_1333 { i = add(&i, &Value::Int(1)); } __for_first_1333 = false; is_less_than(&i, &positionsLength) } {
let mut p: Value = get_value(&positions, &i);
let mut p: Value = get_value(&positions, &i);
let mut id: Value = self.safe_string_k(p.clone(), "id", &[]);
if !is_equal(&id, &Value::Null) {
add_element_to_object(&mut balances, &id, self.number_to_string(self.safe_number_k(p.clone(), "contracts", &[Value::Int(0)])));
}
}
}
add_element_to_object(&mut self.options, &Value::Str("positionBalances".to_string()), balances.clone());
Value::Null
}
pub fn handle_position(&mut self, mut client: Value, mut data: Value) {
if is_equal(&self.positions, &Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "positionsLimit", &[Value::Int(1000)]);
self.positions = ArrayCacheByOutcomeById::new(limit.clone());
}
let mut networkId: Value = self.safe_string_k(data.clone(), "networkId", &[]);
let mut marketId: Value = self.safe_string_k(data.clone(), "marketId", &[]);
let mut outcomeId: Value = self.safe_string_k(data.clone(), "outcome", &[]);
let mut sym: Value = self.market_outcome_to_symbol(networkId.clone(), marketId.clone(), outcomeId.clone());
let mut outcomeObj: Value = self.safe_outcome(sym.clone(), &[]);
let mut ts: Value = self.safe_integer_k(data.clone(), "ts", &[]);
// the channel pushes a signed share delta per fill/redeem/split/merge (no absolute balance);
// apply it to the REST-seeded balance keyed by outcome id to maintain a running contracts figure
let mut deltaStr: Value = self.safe_string_k(data.clone(), "delta", &[Value::Str("0".to_string())]);
let mut firstChar: Value = slice(&deltaStr, &Value::Int(0), &Value::Int(1));
if is_equal(&firstChar, &Value::Str("+".to_string())) {
deltaStr = slice(&deltaStr, &Value::Int(1), &Value::Null);
}
let mut deltaShares: Value = crate::precise::Precise::stringDiv(&deltaStr, &Value::Str("1000000000000000000".to_string()));
let mut contracts: Value = Value::Null;
let mut posId: Value = Value::Null;
if is_true(&(!is_equal(&networkId, &Value::Null))) && is_true(&(!is_equal(&marketId, &Value::Null))) && is_true(&(!is_equal(&outcomeId, &Value::Null))) {
posId = add(&add(&add(&add(&networkId, &Value::Str(":".to_string())), &marketId), &Value::Str("/".to_string())), &outcomeId);
let mut balances: Value = self.safe_dict_k(self.options.clone(), "positionBalances", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut prior: Value = self.safe_string(balances.clone(), posId.clone(), &[Value::Str("0".to_string())]);
let mut updated: Value = crate::precise::Precise::stringAdd(&prior, &deltaShares);
if !is_equal(&posId, &Value::Null) {
add_element_to_object(&mut balances, &posId, updated.clone());
}
add_element_to_object(&mut self.options.clone(), &Value::Str("positionBalances".to_string()), balances.clone());
contracts = self.parse_number(updated.clone(), &[]);
}
let mut parsed: Value = self.safe_prediction_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data.clone());
m.insert("id".to_string(), posId.clone());
m.insert("outcome".to_string(), sym.clone());
m.insert("outcomeId".to_string(), posId.clone());
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts.clone()));
m.insert("side".to_string(), Value::Str("long".to_string()));
m.insert("contracts".to_string(), contracts.clone());
m.insert("entryPrice".to_string(), Value::Null);
m.insert("markPrice".to_string(), Value::Null);
m.insert("notional".to_string(), Value::Null);
m.insert("collateral".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), Value::Null);
m
}));
let mut stored: Value = self.positions.clone();
stored.append(parsed.clone());
client.resolve(&[stored.clone(), Value::Str("positions".to_string())]);
}
pub fn wallet_address_from_keys(&self) -> Value {
// the orders/positions channels are keyed by the lowercase trader address (Centrifugo channels
// are case-sensitive); lowercase here so the channel matches regardless of the address checksum.
// check length too: an unset walletAddress is an empty string (not undefined) in some languages
let mut address: Value = self.walletAddress.clone();
let mut hasWallet: bool = is_true(&(!is_equal(&address, &Value::Null))) && is_true(&(is_greater_than(&get_array_length(&self.walletAddress), &Value::Int(0))));
if !is_true(&hasWallet) {
if is_equal(&self.privateKey, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires a walletAddress or privateKey to watch private channels".to_string()))));
}
address = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
}
return to_lower(&address);
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 {
// Myriad error responses are { "error": "<message>", "details": [...] } with a 4xx status
if is_equal(&response, &Value::Null) {
return Value::Null;
}
let mut error: Value = self.safe_string_k(response.clone(), "error", &[]);
if is_true(&(is_equal(&error, &Value::Null))) || is_true(&(is_equal(&error, &Value::Str("".to_string())))) {
return Value::Null;
}
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), error.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), error.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
Value::Null
}
/*
* @ignore
* @method
* @name myriad#sign
* @description builds the request url and attaches the x-api-key header for private endpoints
* @param {string} path the endpoint path
* @param {string|string[]} api the api group and access level
* @param {string} method the http method
* @param {object} params the request parameters
* @param {object} [headers] request headers
* @param {string} [body] the request body
* @returns {object} a dict with url, method, body and headers
*/
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("myriad".to_string()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".to_string()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut apiGroup: Value = ternary(is_string(&api), api.clone(), get_value(&api, &Value::Int(0)));
let mut baseUrls: Value = get_value(&self.urls, &Value::Str("api".to_string()));
let mut baseUrl: Value = self.safe_string(baseUrls.clone(), apiGroup.clone(), &[get_value(&baseUrls, &Value::Str("myriad".to_string()))]);
let mut url: Value = add(&add(&baseUrl, &Value::Str("/".to_string())), &self.implode_params(path.clone(), params.clone()));
let mut query: Value = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
if is_equal(&method, &Value::Str("GET".to_string())) {
let mut querystring: Value = self.urlencode(query.clone(), &[]);
if !is_equal(&querystring, &Value::Str("".to_string())) {
url = add(&url, &add(&Value::Str("?".to_string()), &querystring));
}
}
let mut existingHeaders: Value = ternary(is_true(&(!is_equal(&headers, &Value::Null))), headers.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
headers = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Accept".to_string(), Value::Str("application/json".to_string()));
m.insert("Content-Type".to_string(), Value::Str("application/json".to_string()));
m
}), &[existingHeaders.clone()]);
// non-GET requests carry the params as a JSON body (public POSTs like markets/quote
// included — the previous logic only sent a body for authenticated requests)
if !is_equal(&method, &Value::Str("GET".to_string())) {
let mut queryKeys: Value = object_keys(&query);
let mut queryKeysLength: Value = get_array_length(&queryKeys);
if is_greater_than(&queryKeysLength, &Value::Int(0)) {
body = self.json(query.clone());
}
}
if is_true(&(!is_equal(&self.apiKey, &Value::Null))) && is_true(&(!is_equal(&self.apiKey, &Value::Str("".to_string())))) {
headers = self.extend(headers.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("x-api-key".to_string(), self.apiKey.clone());
m
})]);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), body.clone());
m.insert("headers".to_string(), headers.clone());
m
});
Value::Null
}
}