// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
use crate::pro::*;
use crate::prediction_exchange_generated::PredictionBase;
use crate::prediction_exchange::PredictionRuntime;
pub struct OpinionCore {
pub exchange: crate::prediction_exchange::PredictionExchange,
}
impl OpinionCore {
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 = OpinionCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for OpinionCore {
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OpinionCore.
OpinionCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on OpinionCore.
OpinionCore::parse_balance(self, response)
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OpinionCore.
OpinionCore::parse_prediction_trade(self, trade, &[market])
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OpinionCore.
OpinionCore::parse_prediction_order(self, order, &[market])
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OpinionCore.
OpinionCore::parse_prediction_position(self, position, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on OpinionCore.
OpinionCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on OpinionCore.
OpinionCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for OpinionCore {
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 {
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_api_key" => self.create_api_key(&args[..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"delete_api_key" => self.delete_api_key(&args[..]).await,
"fetch_api_key" => self.fetch_api_key(&args[..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_event" => self.fetch_event(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_events" => self.fetch_events(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_outcome" => self.fetch_outcome(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"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 },
"load_api_key" => self.load_api_key().await,
"load_multi_sign_address" => self.load_multi_sign_address().await,
"load_quote_token" => self.load_quote_token(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"load_trade_market" => self.load_trade_market(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"opinion_order_raw_amounts" => self.opinion_order_raw_amounts(args.get(0).map(|v| v.is_truthy()).unwrap_or(false), 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)),
"opinion_outcome_by_market_id_side" => self.opinion_outcome_by_market_id_side(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_event" => self.parse_event(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_opinion_market" => self.parse_opinion_market(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_position" => self.parse_prediction_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_trade" => self.parse_prediction_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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[2.min(args.len())..]).await,
"set_api_credentials" => self.set_api_credentials(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"sign_hash" => self.sign_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_message" => self.sign_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"subscribe_opinion_channel" => self.subscribe_opinion_channel(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,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// Prediction Core: fall through to prediction base methods (then Exchange base).
_ => self.call_dynamic_prediction_base(method, args).await,
}
})
}
}
impl crate::prediction_exchange_generated::PredictionBase for OpinionCore {
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 OpinionCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}
impl std::ops::DerefMut for OpinionCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.exchange) }
}
impl OpinionCore {
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("opinion".into()));
m.insert("name".to_string(), Value::Str("Opinion".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("HK".into())]));
m.insert("rateLimit".to_string(), Value::Int(67));
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("cancelOrder".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchEvent".to_string(), Value::Bool(true));
m.insert("fetchEvents".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("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("prediction".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/9905d9d4-3eb3-48d2-bdb3-551a9ddc7559".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("opinion".to_string(), Value::Str("https://openapi.opinion.trade/openapi".into()));
m.insert("ws".to_string(), Value::Str("wss://ws.opinion.trade".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://opinion.trade".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.opinion.trade".into())]));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("opinion".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("market".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/{marketId}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/categorical/{marketId}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/slug/{slug}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("label".to_string(), Value::Int(1));
m.insert("token/latest-price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("token/orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("token/price-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quoteToken".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("order/{orderId}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/user/{walletAddress}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/user/{walletAddress}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("auth/api-key".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("user/auth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("user/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("auth/api-key".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("order/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("auth/api-key".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(true));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("walletAddress".to_string(), Value::Bool(true));
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.02));
m.insert("taker".to_string(), Value::Float(0.04));
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("10014".to_string(), Value::Str("AccountNotEnabled".into()));
m.insert("10403".to_string(), Value::Str("PermissionDenied".into()));
m.insert("11001".to_string(), Value::Str("AuthenticationError".into()));
m.insert("11002".to_string(), Value::Str("AuthenticationError".into()));
m.insert("10605".to_string(), Value::Str("InvalidOrder".into()));
m.insert("10610".to_string(), Value::Str("InvalidOrder".into()));
m.insert("11004".to_string(), Value::Str("AuthenticationError".into()));
m.insert("11005".to_string(), Value::Str("AuthenticationError".into()));
m.insert("11009".to_string(), Value::Str("AuthenticationError".into()));
m.insert("11010".to_string(), Value::Str("AuthenticationError".into()));
m.insert("11011".to_string(), Value::Str("AuthenticationError".into()));
m.insert("11012".to_string(), Value::Str("AuthenticationError".into()));
m.insert("11013".to_string(), Value::Str("AuthenticationError".into()));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Insufficient token balance".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("below the minimum required value".to_string(), Value::Str("InvalidOrder".into()));
m.insert("must be the current multi-signature wallet".to_string(), Value::Str("InvalidOrder".into()));
m
}));
m
}));
m.insert("streaming".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("keepAlive".to_string(), Value::Int(25000));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tradesLimit".to_string(), Value::Int(1000));
m.insert("ordersLimit".to_string(), Value::Int(1000));
m.insert("myTradesLimit".to_string(), Value::Int(1000));
m.insert("eventScopeParams".to_string(), Value::from(vec![Value::Str("labelId".into())]));
m.insert("defaultFetchEventsLimit".to_string(), Value::Int(20));
m.insert("maxFetchEventsResults".to_string(), Value::Int(100));
m.insert("maxEventsPages".to_string(), Value::Int(50));
m.insert("marketsPageLimit".to_string(), Value::Int(20));
m.insert("maxMarketsPages".to_string(), Value::Int(50));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name opinion#fetchMarkets
* @description fetches every kind of opinion market
* categorical parents double as our unified "events" and are cached into this.events as a side effect
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/market
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.limit] max number of markets to collect (defaults to options.marketsPageLimit * options.maxMarketsPages, 1000)
* @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 rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("limit".into())]), &[]);
let mut userLimit: Value = self.safe_integer_k(params, "limit", &[]);
let mut pageLimit: Value = self.safe_integer_k(self.options.clone(), "marketsPageLimit", &[Value::Int(20)]);
let mut maxPages: Value = self.safe_integer_k(self.options.clone(), "maxMarketsPages", &[Value::Int(50)]);
let mut flatMarkets: Vec<Value> = Vec::new();
// seen-guard keyed by the event handle; the events themselves go through setEvents below
// so the cache gets the base indexing (id + handle + slug) instead of a raw assignment
let mut seenEvents: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut eventsList: Vec<Value> = Vec::new();
// every raw (unflattened) row fetched so far, so its length is the raw fetched count
let mut fetchedRawRows: Vec<Value> = Vec::new();
{
let mut page: Value = Value::Int(1);
let mut __for_first_1388: bool = true;
while { if !__for_first_1388 { if let Value::Int(n) = &mut page { *n += 1; } } __for_first_1388 = false; page.as_f64().unwrap_or(f64::NAN) <= maxPages.as_f64().unwrap_or(f64::NAN) } {
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketType".to_string(), Value::Int(2));
m.insert("limit".to_string(), pageLimit.clone());
m.insert("page".to_string(), page.clone());
m
});
let __ws_arg_0 = self.extend(Value::Map(request), &[rest.clone()]);
let mut response: Value = self.opinion_public_get_market(&[__ws_arg_0]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawMarkets: Vec<Value> = self.safe_list_k(result.clone(), "list", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
// categorical parents expand into several flatMarkets entries each, so the raw,
// unflattened row count in 'total' must be compared against fetchedRawCount, not
// flatMarkets.length - otherwise expansion makes the comparison meaningless
let mut total: Value = self.safe_integer_k(result, "total", &[]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1387: bool = true;
while { if !__for_first_1387 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1387 = false; i.as_f64().unwrap_or(f64::NAN) < rawMarketsLength } {
let mut raw: Value = rawMarkets.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
fetchedRawRows.push(raw.clone());
let mut marketType: Option<i64> = self.safe_integer_k(raw.clone(), "marketType", &[]).as_i64();
if (marketType == Some(1)) {
let mut event: Value = self.parse_event(raw.clone());
let mut childMarkets: Vec<Value> = self.safe_list_k(event.clone(), "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut childMarketsLength: f64 = ((childMarkets.len() as i64) as f64);
{
let mut ci: Value = Value::Int(0);
let mut __for_first_1386: bool = true;
while { if !__for_first_1386 { if let Value::Int(n) = &mut ci { *n += 1; } } __for_first_1386 = false; ci.as_f64().unwrap_or(f64::NAN) < childMarketsLength } {
flatMarkets.push(childMarkets.get(ci.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
}
}
let mut eventKey: Option<String> = self.safe_string_k_opt(event.clone(), "event", &[]);
if (eventKey.is_some()) && (eventKey.as_deref() != Some("")) && !(matches!((&seenEvents, &eventKey.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut seenEvents { std::sync::Arc::make_mut(__d).insert(eventKey.as_deref().unwrap_or("null").to_string(), Value::Bool(true)); }
eventsList.push(event);
}
} else {
flatMarkets.push(self.parse_opinion_market(raw, &[]));
}
}
}
let mut collectedLength: f64 = ((flatMarkets.len() as i64) as f64);
let mut fetchedRawCount: f64 = ((fetchedRawRows.len() as i64) as f64);
if (rawMarketsLength < pageLimit.as_f64().unwrap_or(f64::NAN)) || (page.as_f64().unwrap_or(f64::NAN) >= maxPages.as_f64().unwrap_or(f64::NAN)) || ((total != Value::Null) && (fetchedRawCount >= total.as_f64().unwrap_or(f64::NAN))) || ((userLimit != Value::Null) && (collectedLength >= userLimit.as_f64().unwrap_or(f64::NAN))) {
break;
}
}
}
self.set_events(Value::from(eventsList));
let mut flatMarketsLength: f64 = ((flatMarkets.len() as i64) as f64);
if (userLimit != Value::Null) && (flatMarketsLength > userLimit.as_f64().unwrap_or(f64::NAN)) {
return self.array_slice(Value::from(flatMarkets), Value::Int(0), &[userLimit]);
}
return Value::from(flatMarkets);
Value::Null
}
/*
* @ignore
* @method
* @name opinion#fetchOutcome
* @description resolves a single outcome; a bare numeric token id carries no search text for
* the base's fetchEvents-driven resolution (opinion has no per-id lookup endpoint, unlike
* kalshi/polymarket), so bulk-warm the outcome cache via loadOutcomes() first for id-form input
* @param {string} outcomeSymbol the outcome handle or token id
* @returns {object} the outcome cache
*/
pub async fn fetch_outcome(&mut self, mut outcomeSymbol: Value) -> Value {
if (self.outcome_search_query(outcomeSymbol.clone()) == Value::Null) {
self.load_outcomes(&[]).await;
if self.has_outcome(outcomeSymbol.clone()).as_bool() == Some(true) {
return self.safe_outcome(outcomeSymbol.clone(), &[]);
}
}
return self.super_fetch_outcome(outcomeSymbol).await;
Value::Null
}
/*
* @ignore
* @method
* @name opinion#parseOpinionMarket
* @description converts a single raw opinion market into one ccxt market with yes/no outcomes
* @param {object} raw the raw opinion 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_opinion_market(&self, mut raw: Value, optional_args: &[Value]) -> Value {
let mut eventSlug = get_arg(optional_args, 0, Value::Null);
// {
// "chainId": "56",
// "conditionId": "469db44df1309dac7cf9fcaa142562f3c89719d47277e095d021c1561166539a",
// "createdAt": 1778750719,
// "cutoffAt": 0,
// "isResolvableByAI": true,
// "marketId": 16565,
// "marketTitle": "10–15s",
// "noLabel": "No",
// "noTokenId": "48641131337815600205538397357674754469573755318952418769815647071528778171134",
// "questionId": "63907f471c045499f69b5ea157bdea1942f9d53b6e5e767ae69f4d148aeeefae",
// "quoteToken": "0x55d398326f99059fF775485246999027B3197955",
// "rebate": {
// "maker": 0.5
// },
// "resolvedAt": 1779342061,
// "resultTokenId": "107063188116504514729209026208703521982564071792212276771696073817845504321279",
// "rules": "",
// "slug": "how-long-will-trump-and-xi-shake-hands-when-they-meet-10-15s",
// "status": 4,
// "statusEnum": "Resolved",
// "volume": "50",
// "yesLabel": "Yes",
// "yesTokenId": "107063188116504514729209026208703521982564071792212276771696073817845504321279"
// }
let mut marketId: Option<String> = self.safe_string_k_opt(raw.clone(), "marketId", &[]);
let mut slug: Option<String> = self.safe_string_k_opt(raw.clone(), "slug", &[]);
let mut effectiveEventSlug: Value = eventSlug.clone();
if (eventSlug != Value::Null) && (slug.is_some()) && (Value::Int(slug.as_deref().zip(eventSlug.as_str()).and_then(|(__s, __n)| __s.find(__n)).map(|__i| __i as i64).unwrap_or(-1)).as_f64() == Some(0.0)) {
effectiveEventSlug = Value::Null;
}
let mut marketSymbol: Value = self.slug_to_market_symbol(effectiveEventSlug.clone(), slug.clone().map(Value::from).unwrap_or(Value::Null));
let mut statusEnum: Option<String> = self.safe_string_k(raw.clone(), "statusEnum", &[]).as_str().map(str::to_owned);
let mut active: Value = (Value::Bool(statusEnum.as_deref() == Some("Activated")));
let mut resolved: Value = (Value::Bool(statusEnum.as_deref() == Some("Resolved")));
let mut resultTokenId: Value = self.safe_string_k(raw.clone(), "resultTokenId", &[]);
let mut hasResult: bool = matches!(&resolved, Value::Bool(true)) && (resultTokenId != Value::Null) && (resultTokenId.as_str() != Some(""));
let mut outcomeLabels: Value = Value::from(vec![self.safe_string_k(raw.clone(), "yesLabel", &[Value::Str("YES".into())]), self.safe_string_k(raw.clone(), "noLabel", &[Value::Str("NO".into())])]);
let mut outcomeTokenIds: Value = Value::from(vec![self.safe_string_k(raw.clone(), "yesTokenId", &[]), self.safe_string_k(raw.clone(), "noTokenId", &[])]);
let mut outcomes: Vec<Value> = Vec::new();
let mut resolvedOutcome: Value = Value::Null;
{
let mut i: i64 = 0;
let mut __for_first_1389: bool = true;
while { if !__for_first_1389 { i += 1; } __for_first_1389 = false; i < (outcomeLabels.len() as i64) } {
let mut label: Option<String> = self.safe_string_opt(outcomeLabels.clone(), Value::Int(i), &[]);
let mut tokenId: Value = self.safe_string(outcomeTokenIds.clone(), Value::Int(i), &[]);
let mut outcomeHandle: Value = self.slug_to_outcome_symbol(effectiveEventSlug.clone(), slug.clone().map(Value::from).unwrap_or(Value::Null), label.clone().map(Value::from).unwrap_or(Value::Null));
let mut winner: Value = Value::Null;
let mut settleFraction: Value = Value::Null;
if hasResult {
winner = (Value::Bool(tokenId == resultTokenId));
settleFraction = (if winner.as_bool() == Some(true) { Value::Int(1) } else { Value::Int(0) });
if winner.as_bool() == Some(true) {
resolvedOutcome = outcomeHandle.clone();
}
}
outcomes.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), tokenId.clone());
m.insert("outcomeId".to_string(), tokenId);
m.insert("outcome".to_string(), outcomeHandle);
m.insert("market".to_string(), marketSymbol.clone());
m.insert("label".to_string(), label.map(Value::from).unwrap_or(Value::Null));
m.insert("active".to_string(), active.clone());
m.insert("winner".to_string(), winner);
m.insert("settleFraction".to_string(), settleFraction);
m.insert("info".to_string(), raw.clone());
m
}));
}
}
let mut marketResolvedOutcome: Value = resolvedOutcome;
// the venue sends cutoffAt 0 for markets without a scheduled cutoff - map it to
// undefined instead of the epoch, same for the event-level end date
let mut expiryTimestamp: Value = Value::Null;
if (self.safe_integer_k(raw.clone(), "cutoffAt", &[Value::Int(0)]).as_f64() != Some(0.0)) {
expiryTimestamp = self.safe_timestamp_k(raw.clone(), "cutoffAt", &[]);
}
let mut created: Value = self.safe_timestamp_k(raw.clone(), "createdAt", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("market".to_string(), marketSymbol);
m.insert("base".to_string(), Value::Str("USDT".into()));
m.insert("quote".to_string(), Value::Str("USDT".into()));
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), marketId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("quoteId".to_string(), Value::Str("USDT".into()));
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("prediction".into()));
m.insert("marketType".to_string(), Value::Str("binary".into()));
m.insert("executionModel".to_string(), Value::Str("clob".into()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("active".to_string(), active);
m.insert("resolved".to_string(), resolved);
m.insert("resolvedOutcome".to_string(), marketResolvedOutcome);
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), expiryTimestamp.clone());
m.insert("expiryDatetime".to_string(), self.iso8601(expiryTimestamp));
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("taker".to_string(), self.safe_number(self.fees.as_map().and_then(|__m| __m.get("trading")).cloned().unwrap_or(Value::Null), Value::Str("taker".into()), &[]));
m.insert("maker".to_string(), self.safe_number(self.fees.as_map().and_then(|__m| __m.get("trading")).cloned().unwrap_or(Value::Null), Value::Str("maker".into()), &[]));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("feeSide".to_string(), Value::Str("get".into()));
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Null);
m.insert("price".to_string(), Value::Null);
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::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(0));
m.insert("max".to_string(), Value::Int(1));
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("outcomes".to_string(), Value::from(outcomes));
m.insert("info".to_string(), raw);
m.insert("created".to_string(), created);
m
});
Value::Null
}
/*
* @method
* @name opinion#fetchEvents
* @description fetches Opinion's categorical markets - scope required via query/queries/tags/eventId/slug/labelId
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/market
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.labelId] filter by opinion category label id
* @param {int} [params.limit] max number of events to fetch (paginated server-side; defaults to options.maxFetchEventsResults, 100)
* @returns {object[]} an array of event structures
*/
pub async fn fetch_events(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.require_event_query(&[params.clone()]);
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
let mut eventId: Option<String> = self.safe_string_k_opt(params.clone(), "eventId", &[]);
let mut slug: Option<String> = self.safe_string_k_opt(params.clone(), "slug", &[]);
if (eventId.is_some()) || (slug.is_some()) {
let mut singleRest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("query".into()), Value::Str("queries".into()), Value::Str("tags".into()), Value::Str("status".into()), Value::Str("sort".into()), Value::Str("searchIn".into()), Value::Str("limit".into())]), &[]);
let mut singleResponse: Value = Value::Null;
if (slug.is_some()) {
let __ws_arg_1 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), slug.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[singleRest.clone()]);
singleResponse = self.opinion_public_get_market_slug_slug(&[__ws_arg_1]).await;
} else {
let __ws_arg_2 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), eventId.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[singleRest]);
singleResponse = self.opinion_public_get_market_categorical_market_id(&[__ws_arg_2]).await;
}
let mut singleResult: Value = self.safe_dict_k(singleResponse, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut singleData: Value = self.safe_dict_k(singleResult, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut single: Value = self.parse_event(singleData);
self.index_event_outcomes(single.clone());
return self.apply_event_fetch_params(Value::from(vec![single]), &[params.clone(), queries.clone()]);
}
let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("query".into()), Value::Str("queries".into()), Value::Str("tags".into()), Value::Str("status".into()), Value::Str("sort".into()), Value::Str("searchIn".into()), Value::Str("limit".into())]), &[]);
let mut pageLimit: Value = self.parse_to_int(self.safe_integer_k(self.options.clone(), "defaultFetchEventsLimit", &[Value::Int(20)]));
// bound how many events are actually FETCHED: the user limit when given, otherwise
// options.maxFetchEventsResults - the scope filters keep the listing narrow, but a broad
// label can still hold more than one page
let mut fetchCap: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("maxFetchEventsResults".into()), &[Value::Int(100)])]);
let mut maxPages: Value = self.safe_integer_k(self.options.clone(), "maxEventsPages", &[Value::Int(50)]);
let mut rawEvents: Vec<Value> = Vec::new();
{
let mut page: Value = Value::Int(1);
let mut __for_first_1391: bool = true;
while { if !__for_first_1391 { if let Value::Int(n) = &mut page { *n += 1; } } __for_first_1391 = false; page.as_f64().unwrap_or(f64::NAN) <= maxPages.as_f64().unwrap_or(f64::NAN) } {
let mut fetchedSoFar: Value = Value::Int(rawEvents.len() as i64);
let mut remaining: Value = self.parse_to_int((match (&(fetchCap), &(fetchedSoFar)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }));
let mut reqLimit: Value = (if (remaining.as_f64().unwrap_or(f64::NAN) < pageLimit.as_f64().unwrap_or(f64::NAN)) { remaining } else { pageLimit.clone() });
if reqLimit.as_f64().unwrap_or(f64::NAN) <= ((0i64) as f64) {
break;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketType".to_string(), Value::Int(1));
m.insert("limit".to_string(), reqLimit.clone());
m.insert("page".to_string(), page.clone());
m
});
let __ws_arg_3 = self.extend(Value::Map(request), &[rest.clone()]);
let mut response: Value = self.opinion_public_get_market(&[__ws_arg_3]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut pageEvents: Vec<Value> = self.safe_list_k(result.clone(), "list", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut pageEventsLength: f64 = ((pageEvents.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1390: bool = true;
while { if !__for_first_1390 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1390 = false; i.as_f64().unwrap_or(f64::NAN) < pageEventsLength } {
rawEvents.push(pageEvents.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
}
}
// rawEvents holds every row fetched so far, so its length is the raw fetched count
let mut fetchedRawCount: f64 = ((rawEvents.len() as i64) as f64);
let mut total: Value = self.safe_integer_k(result, "total", &[]);
if (pageEventsLength < reqLimit.as_f64().unwrap_or(f64::NAN)) || (page.as_f64().unwrap_or(f64::NAN) >= maxPages.as_f64().unwrap_or(f64::NAN)) || ((total != Value::Null) && (fetchedRawCount >= total.as_f64().unwrap_or(f64::NAN))) || (fetchedRawCount >= fetchCap.as_f64().unwrap_or(f64::NAN)) {
break;
}
}
}
let mut rawEventsLength: f64 = ((rawEvents.len() as i64) as f64);
let mut parsedEvents: Vec<Value> = Vec::new();
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1393: bool = true;
while { if !__for_first_1393 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1393 = false; i.as_f64().unwrap_or(f64::NAN) < rawEventsLength } {
let mut event: Value = self.parse_event(rawEvents.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
parsedEvents.push(event.clone());
// register the parsed markets so populateOutcomes can index their outcomes
let mut eventMarkets: Vec<Value> = self.safe_list_k(event, "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut eventMarketsLength: f64 = ((eventMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1392: bool = true;
while { if !__for_first_1392 { if let Value::Int(n) = &mut mi { *n += 1; } } __for_first_1392 = false; mi.as_f64().unwrap_or(f64::NAN) < eventMarketsLength } {
let mut m: Value = eventMarkets.get(mi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
add_element_to_object(&mut self.markets, &crate::value::get_value_k(&m, "market"), m.clone());
}
}
}
}
self.populate_outcomes();
return self.apply_event_fetch_params(Value::from(parsedEvents), &[params, queries]);
Value::Null
}
/*
* @method
* @name opinion#fetchEvent
* @description fetches a single prediction-market event by its market id, or slug
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/market
* @param {string} id the numeric marketId, or the market slug
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction event structure](https://docs.ccxt.com/#/?id=prediction-event-structure)
*/
pub async fn fetch_event(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut isSlug: bool = id.as_str().unwrap_or("").contains("-");
let mut response: Value = Value::Null;
if isSlug {
let __ws_arg_4 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), id.clone());
m
}), &[params.clone()]);
response = self.opinion_public_get_market_slug_slug(&[__ws_arg_4]).await;
} else {
let __ws_arg_5 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), id);
m
}), &[params]);
response = self.opinion_public_get_market_categorical_market_id(&[__ws_arg_5]).await;
}
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(result, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut event: Value = self.parse_event(data);
self.index_event_outcomes(event.clone());
return event;
Value::Null
}
/*
* @ignore
* @method
* @name opinion#parseEvent
* @description parses a raw opinion categorical market (with nested childMarkets) into the unified event shape
* @param {object} rawEvent the raw opinion categorical market object
* @returns {object} an event structure
*/
pub fn parse_event(&self, mut rawEvent: Value) -> Value {
// {
// "chainId": "56",
// "childMarkets": [
// {
// "chainId": "56",
// "conditionId": "469db44df1309dac7cf9fcaa142562f3c89719d47277e095d021c1561166539a",
// "createdAt": 1778750719,
// "cutoffAt": 0,
// "isResolvableByAI": true,
// "marketId": 16565,
// "marketTitle": "10–15s",
// "noLabel": "No",
// "noTokenId": "48641131337815600205538397357674754469573755318952418769815647071528778171134",
// "questionId": "63907f471c045499f69b5ea157bdea1942f9d53b6e5e767ae69f4d148aeeefae",
// "quoteToken": "0x55d398326f99059fF775485246999027B3197955",
// "rebate": {
// "maker": 0.5
// },
// "resolvedAt": 1779342061,
// "resultTokenId": "107063188116504514729209026208703521982564071792212276771696073817845504321279",
// "rules": "",
// "slug": "how-long-will-trump-and-xi-shake-hands-when-they-meet-10-15s",
// "status": 4,
// "statusEnum": "Resolved",
// "volume": "50",
// "yesLabel": "Yes",
// "yesTokenId": "107063188116504514729209026208703521982564071792212276771696073817845504321279"
// },
// {
// "chainId": "56",
// "conditionId": "c4054e23e1afc96c93bbc05378414f8286b2f3e3107bb80944ba8a7581428812",
// "createdAt": 1778750720,
// "cutoffAt": 0,
// "isResolvableByAI": true,
// "marketId": 16566,
// "marketTitle": "15s+",
// "noLabel": "No",
// "noTokenId": "47010463515333704767569479601138504130354011266006912230152057656074556410652",
// "questionId": "3c78ac485d772b8241fd185f8b45ef9d7df9690d99ea59ed58927ade2f50b182",
// "quoteToken": "0x55d398326f99059fF775485246999027B3197955",
// "rebate": {
// "maker": 0.5
// },
// "resolvedAt": 1779342061,
// "resultTokenId": "47010463515333704767569479601138504130354011266006912230152057656074556410652",
// "rules": "",
// "slug": "how-long-will-trump-and-xi-shake-hands-when-they-meet-15s-plus",
// "status": 4,
// "statusEnum": "Resolved",
// "volume": "50",
// "yesLabel": "Yes",
// "yesTokenId": "4219962057210945760892475434030882254029819241100485445656470801524365584613"
// }
// ],
// "conditionId": "",
// "coverUrl": "",
// "createdAt": 1778750719,
// "cutoffAt": 1778803200,
// "isResolvableByAI": false,
// "labelIds": [
// 1
// ],
// "labels": [
// "Politics"
// ],
// "marketId": 788,
// "marketTitle": "How long will Trump and Xi shake hands when they meet?",
// "marketType": 1,
// "noLabel": "",
// "noTokenId": "",
// "questionId": "63907f471c045499f69b5ea157bdea1942f9d53b6e5e767ae69f4d148aeeefae",
// "quoteToken": "0x55d398326f99059fF775485246999027B3197955",
// "rebate": {
// "maker": 0.5
// },
// "resolvedAt": 0,
// "resultTokenId": "",
// "rules": "This market resolves based on the length of the longest qualifying handshake between Donald Trump and Xi Jinping on May 14, 2026 (Beijing local time), the day of their bilateral meeting at the Great Hall of the People.\nBaseline already established: Video footage from the welcome ceremony confirms a qualifying handshake within the 10–15s range. The remaining question is whether any additional handshake on the same day produces a longer measured duration.\nOutcomes:\n\n10–15s — resolves YES if no qualifying handshake on May 14, 2026 exceeds 15 seconds.\n15s+ — resolves YES if any qualifying handshake on May 14, 2026 is measured at more than 15 seconds.\n\nMeasurement: Duration is measured from the exact moment hands make initial physical contact until the exact moment either party breaks contact. Where multiple video sources exist, the highest-resolution footage is used; where measurements differ, the consensus reading across major media is applied. A duration falling exactly on the 15s boundary resolves to 15s+.\nQualifying handshake: voluntary, intentional, in-person; direct hand-to-hand contact (gloves permitted); clearly visible on video from start to finish. Fist bumps, hugs, waves, back pats, and other non-handshake contact are excluded from the measured duration even if they occur during the same greeting.\nResolution window: All qualifying handshakes occurring on May 14, 2026 in Beijing local time are eligible, including those at arrival, bilateral sessions, signing ceremonies, state dinners, and departure. Handshakes on any other date do not count.\nResolution source: video footage from May 14, 2026.",
// "slug": "how-long-will-trump-and-xi-shake-hands-when-they-meet",
// "status": 1,
// "statusEnum": "Created",
// "thumbnailUrl": "https://images.opinion.trade/0xf988d66bd9c46b69d33e2703f7264d3c2267136c/0xdf583bdff183f389d7c5d9c5d099127cabda824afd05d66059b8027ca775763d",
// "volume": "100.00",
// "volume24h": "100.00",
// "volume7d": "100.00",
// "yesLabel": "",
// "yesTokenId": ""
// }
let mut eventId: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "marketId", &[]);
let mut slug: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "slug", &[]);
let mut title: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "marketTitle", &[]);
let mut eventHandle: Value = Value::Null;
if (title.is_some()) {
eventHandle = self.shorten_slug(title.clone().map(Value::from).unwrap_or(Value::Null));
} else {
eventHandle = self.shorten_slug(slug.clone().map(Value::from).unwrap_or(Value::Null));
}
let mut rawChildren: Vec<Value> = self.safe_list_k(rawEvent.clone(), "childMarkets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rawChildrenLength: f64 = ((rawChildren.len() as i64) as f64);
let mut marketsList: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1394: bool = true;
while { if !__for_first_1394 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1394 = false; i.as_f64().unwrap_or(f64::NAN) < rawChildrenLength } {
marketsList.push(self.parse_opinion_market(rawChildren.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[slug.clone().map(Value::from).unwrap_or(Value::Null)]));
}
}
let mut statusEnum: Option<String> = self.safe_string_k(rawEvent.clone(), "statusEnum", &[]).as_str().map(str::to_owned);
let mut active: Value = (Value::Bool(statusEnum.as_deref() == Some("Activated")));
let mut resolved: Value = (Value::Bool(statusEnum.as_deref() == Some("Resolved")));
let mut end: Value = Value::Null;
if (self.safe_integer_k(rawEvent.clone(), "cutoffAt", &[Value::Int(0)]).as_f64() != Some(0.0)) {
end = self.safe_timestamp_k(rawEvent.clone(), "cutoffAt", &[]);
}
let mut created: Value = self.safe_timestamp_k(rawEvent.clone(), "createdAt", &[]);
let mut labels: Value = self.safe_list_k(rawEvent.clone(), "labels", &[Value::from(vec![])]);
let __ws_arg_6 = self.safe_string_k(rawEvent.clone(), "rules", &[]);
let __ws_arg_7 = self.safe_string(labels.clone(), Value::Int(0), &[]);
let __ws_arg_8 = self.safe_number_k(rawEvent.clone(), "volume", &[]);
let __ws_arg_9 = self.iso8601(created.clone());
let __ws_arg_10 = self.iso8601(end.clone());
let __ws_arg_11 = self.safe_string2(rawEvent.clone(), Value::Str("coverUrl".into()), Value::Str("thumbnailUrl".into()), &[]);
return self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), eventId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("event".to_string(), eventHandle);
m.insert("title".to_string(), title.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("description".to_string(), __ws_arg_6);
m.insert("slug".to_string(), slug.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("category".to_string(), __ws_arg_7);
m.insert("tags".to_string(), labels);
m.insert("markets".to_string(), Value::from(marketsList));
m.insert("active".to_string(), active);
m.insert("resolved".to_string(), resolved);
m.insert("volume".to_string(), __ws_arg_8);
m.insert("created".to_string(), created);
m.insert("createdDatetime".to_string(), __ws_arg_9);
m.insert("end".to_string(), end);
m.insert("endDatetime".to_string(), __ws_arg_10);
m.insert("image".to_string(), __ws_arg_11);
m.insert("info".to_string(), rawEvent);
m
}), &[]);
Value::Null
}
/*
* @method
* @name opinion#fetchTicker
* @description fetches the latest trade price and top of book for a single outcome token
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/token
* @param {string} outcome unified outcome or outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub async fn fetch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
let __ws_arg_12 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[params.clone()]);
let mut promises: Value = Value::from(vec![self.opinion_public_get_token_latest_price(&[__ws_arg_12]).await, self.opinion_public_get_token_orderbook(&[self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m
}), &[params])]).await]);
let priceResponsebookResponseVariable: Vec<Value> = promise_all(&promises).await.as_array().cloned().unwrap_or_default();
let mut priceResponse: Value = priceResponsebookResponseVariable.get(0).cloned().unwrap_or(Value::Null);
let mut bookResponse: Value = priceResponsebookResponseVariable.get(1).cloned().unwrap_or(Value::Null);
let mut response: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("price".to_string(), priceResponse);
m.insert("book".to_string(), bookResponse);
m
});
return self.parse_prediction_ticker(Value::Map(response), &[outcomeObj]);
Value::Null
}
/*
* @ignore
* @method
* @name opinion#parsePredictionTicker
* @description parses a raw opinion latest-price + orderbook pair into a unified ticker object
* @param {object} ticker a { price, book } dict of the two raw responses
* @param {object} [market] the outcome object the ticker belongs to
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub fn parse_prediction_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "price": {
// "errmsg": "",
// "errno": 0,
// "result": { "price": "0.002", "side": "buy-limit", "size": "205.03", "timestamp": 1766844546000, "tokenId": "..." }
// },
// "book": {
// "errmsg": "",
// "errno": 0,
// "result": { "asks": [ { "price": "0.999", "size": "5500" } ], "bids": [], "market": "...", "timestamp": ..., "tokenId": "..." }
// }
// }
//
let mut marketAny: Value = market.clone();
let mut priceResponse: Value = self.safe_dict_k(ticker.clone(), "price", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut priceResult: Value = self.safe_dict_k(priceResponse, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bookResponse: Value = self.safe_dict_k(ticker.clone(), "book", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bookResult: Value = self.safe_dict_k(bookResponse, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bids: Value = self.safe_list_k(bookResult.clone(), "bids", &[Value::from(vec![])]);
let mut asks: Value = self.safe_list_k(bookResult, "asks", &[Value::from(vec![])]);
let mut bestBid: Value = self.safe_dict(bids, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bestAsk: Value = self.safe_dict(asks, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut last: Value = self.safe_number_k(priceResult.clone(), "price", &[]);
let mut timestamp: Option<i64> = self.safe_integer_k(priceResult, "timestamp", &[]).as_i64();
if (timestamp == Some(0)) {
timestamp = None; // the venue reports timestamp 0 for outcomes that have not traded yet
}
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), self.safe_string_k(marketAny.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string2(marketAny.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("label".to_string(), self.safe_string_k(marketAny.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(marketAny, Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), self.safe_number_k(bestBid.clone(), "price", &[]));
m.insert("bidVolume".to_string(), self.safe_number_k(bestBid, "size", &[]));
m.insert("ask".to_string(), self.safe_number_k(bestAsk.clone(), "price", &[]));
m.insert("askVolume".to_string(), self.safe_number_k(bestAsk, "size", &[]));
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
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(), ticker);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name opinion#fetchTickers
* @description fetches tickers for multiple outcome tokens - opinion has no all-tickers endpoint, each token needs its own latest-price + orderbook request
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/token
* @param {string[]} outcomes unified outcomes or outcome token ids - required, opinion has no all-tickers endpoint
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [prediction ticker structures](https://docs.ccxt.com/#/?id=prediction-ticker-structure) indexed by outcome
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (outcomes == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles or token ids to fetch (discover them via fetchEvents ())".into()))));
}
self.load_outcomes(&[outcomes.clone()]).await;
let mut outcomesLength: f64 = ((outcomes.len() as i64) as f64);
let mut promises: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1395: bool = true;
while { if !__for_first_1395 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1395 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
let mut outcomeObj: Value = self.outcome(outcomes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
let __ws_arg_13 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[params.clone()]);
promises.push(self.opinion_public_get_token_latest_price(&[__ws_arg_13]).await);
let __ws_arg_14 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m
}), &[params.clone()]);
promises.push(self.opinion_public_get_token_orderbook(&[__ws_arg_14]).await);
}
}
let mut responses: Value = promise_all(&Value::from(promises)).await;
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1396: bool = true;
while { if !__for_first_1396 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1396 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
let mut outcomeObj: Value = self.outcome(outcomes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
let mut priceIndex: Value = (match (&(i), &(Value::Int(2))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut priceResponse: Value = self.safe_value(responses.clone(), priceIndex.clone(), &[]);
let mut bookResponse: Value = self.safe_value(responses.clone(), self.sum(&[priceIndex, Value::Int(1)]), &[]);
let mut response: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("price".to_string(), priceResponse);
m.insert("book".to_string(), bookResponse);
m
});
let mut ticker: Value = self.parse_prediction_ticker(Value::Map(response), &[outcomeObj]);
let mut symbolKey: Option<String> = self.safe_string_k_opt(ticker.clone(), "outcome", &[]);
if (symbolKey.is_some()) {
result.insert(symbolKey.as_deref().unwrap_or("null").to_string(), ticker);
}
}
}
return Value::Map(result);
Value::Null
}
/*
* @method
* @name opinion#fetchOrderBook
* @description fetches the order book for a single outcome token
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/token
* @param {string} outcome unified outcome or outcome token id
* @param {int} [limit] not used by opinion fetchOrderBook
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
*/
pub async fn fetch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_15 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.opinion_public_get_token_orderbook(&[__ws_arg_15]).await;
//
// {
// "errmsg": "",
// "errno": 0,
// "result": {
// "asks": [
// { "price": "0.999", "size": "5500" }
// ],
// "bids": [],
// "market": "ff7d2d935d0cce2922ea05a363e5a87439e1f8f86f01dacf7238d4c4cc542f6c",
// "timestamp": 1785488076901,
// "tokenId": "56915117085756475550546730127709511264652860289185956800398231821503615918119"
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_k(result.clone(), "timestamp", &[]);
let mut orderbook: Value = self.parse_order_book(result, self.safe_outcome_symbol(outcome, &[outcomeObj.clone()]), &[timestamp, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("size".into())]);
return self.safe_prediction_order_book(orderbook, &[outcomeObj]);
Value::Null
}
/*
* @method
* @name opinion#fetchOHLCV
* @description fetches historical candlestick data for an outcome token
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/token
* @param {string} outcome unified outcome or outcome token id
* @param {string} timeframe the length of time each candle represents - only '1h' and '1d' are supported live
* @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".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut interval: Option<String> = self.safe_string_opt(self.timeframes.clone(), timeframe.clone(), &[]);
if (interval.is_none()) {
let mut supportedKeys: Value = Value::Array(self.timeframes.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default());
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() unsupported timeframe ".into())).into()), timeframe).into()), Value::Str(", supported timeframes are ".into())).into()),
Value::Str(supportedKeys.as_array().map(|__a| __a.iter().map(|__v| __v.to_string()).collect::<Vec<String>>().join(", ")).unwrap_or_default().into()))));
}
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj, "outcomeId", &[]);
let __ws_arg_16 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("token_id".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("interval".to_string(), interval.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[params]);
let mut response: Value = self.opinion_public_get_token_price_history(&[__ws_arg_16]).await;
//
// {
// "errmsg": "",
// "errno": 0,
// "result": {
// "history": [
// { "p": "0.001", "t": 1785495600 }
// ]
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut history: Value = self.safe_list_k(result, "history", &[Value::from(vec![])]);
let mut candles: Vec<Value> = Vec::new();
let mut historyLength: f64 = ((history.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1397: bool = true;
while { if !__for_first_1397 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1397 = false; i.as_f64().unwrap_or(f64::NAN) < historyLength } {
let mut point: Value = self.safe_dict(history.clone(), i.clone(), &[]);
let mut price: Value = self.safe_number_k(point.clone(), "p", &[]);
let mut timestamp: Value = self.safe_timestamp_k(point, "t", &[]);
if (price != Value::Null) && (timestamp != Value::Null) {
candles.push(Value::from(vec![timestamp, price.clone(), price.clone(), price.clone(), price.clone(), Value::Null]));
}
}
}
let mut sorted: Value = self.sort_by(Value::from(candles), Value::Int(0), &[]);
return self.filter_by_since_limit(sorted, &[since, limit, Value::Int(0)]);
Value::Null
}
/*
* @method
* @name opinion#parseOHLCV
* @description parses a single opinion price-history point into a unified OHLCV candle
* @param {object} ohlcv the raw { p, t } 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);
// Unused: fetchOHLCV maps { p, t } points directly.
//
// { "p": "0.001", "t": 1785495600 }
//
let mut price: Value = self.safe_number_k(ohlcv.clone(), "p", &[]);
return Value::from(vec![self.safe_timestamp_k(ohlcv, "t", &[]), price.clone(), price.clone(), price.clone(), price.clone(), Value::Null]);
Value::Null
}
/*
* @ignore
* @method
* @name opinion#loadQuoteToken
* @description fetches and caches quote-token metadata needed to sign orders
* @param {string} quoteTokenAddress the on-chain quote-token contract address, read from a 'quoteToken' field
* @returns {object} the matching quote-token entry
*/
pub async fn load_quote_token(&mut self, mut quoteTokenAddress: Value) -> Value {
if (quoteTokenAddress == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" loadQuoteToken() requires a quoteTokenAddress".into()))));
}
let mut cacheKey: String = quoteTokenAddress.as_str().map(str::to_lowercase).unwrap_or_default();
let mut cached: Value = self.safe_dict_k(self.options.clone(), "quoteTokens", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut existing: Value = self.safe_dict(cached, Value::from(cacheKey.clone()), &[]);
if (existing != Value::Null) {
return existing;
}
let mut response: Value = self.opinion_public_get_quote_token(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut list: Vec<Value> = self.safe_list_k(result, "list", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut listLength: f64 = ((list.len() as i64) as f64);
let mut quoteTokens: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1398: bool = true;
while { if !__for_first_1398 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1398 = false; i.as_f64().unwrap_or(f64::NAN) < listLength } {
let mut entry: Value = list.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut address: Option<String> = self.safe_string_lower_k_opt(entry.clone(), "quoteTokenAddress", &[]);
if (address.is_some()) {
quoteTokens.insert(address.as_deref().unwrap_or("null").to_string(), entry);
}
}
}
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("quoteTokens".into(), Value::Map(quoteTokens.clone())); }
let mut quoteToken: Value = self.safe_dict(Value::Map(quoteTokens), Value::from(cacheKey), &[]);
if (quoteToken == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" loadQuoteToken() could not find quote token ".into())).into()), quoteTokenAddress)));
}
return quoteToken;
Value::Null
}
/*
* @ignore
* @method
* @name opinion#loadMultiSignAddress
* @description fetches and caches the per-wallet multi-signature address that owns order assets
* @returns {string} the multi-sig wallet address for this.walletAddress on chain 56, or this.walletAddress itself if none exists yet
*/
pub async fn load_multi_sign_address(&mut self) -> Value {
let mut cached: Value = self.safe_string_k(self.options.clone(), "multiSignAddress", &[]);
if (cached != Value::Null) {
return cached;
}
let mut response: Value = self.opinion_private_get_user_auth(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut walletUsers: Value = self.safe_dict_k(result, "walletUsers", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut multiSignAddress: Value = self.safe_string_k(walletUsers, "56", &[self.walletAddress.clone()]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("multiSignAddress".into(), multiSignAddress.clone()); }
return multiSignAddress;
Value::Null
}
pub fn sign_opinion_order(&self, mut order: Value, mut exchangeAddress: Value) -> Option<String> {
let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("OPINION CTF Exchange".into()));
m.insert("version".to_string(), Value::Str("1".into()));
m.insert("chainId".to_string(), Value::Int(56));
m.insert("verifyingContract".to_string(), exchangeAddress);
m
});
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("Order".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("salt".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("maker".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("signer".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("taker".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("tokenId".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("makerAmount".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("takerAmount".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("expiration".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("feeRateBps".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("side".into()));
m.insert("type".to_string(), Value::Str("uint8".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("signatureType".into()));
m.insert("type".to_string(), Value::Str("uint8".into()));
m
})]));
m
});
let mut encoded: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map(messageTypes), order);
let mut sig: Value = self.sign_message(encoded, self.privateKey.clone());
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), self.remove0x_prefix(self.safe_string_k(sig.clone(), "r", &[]))).into()), self.remove0x_prefix(self.safe_string_k(sig.clone(), "s", &[]))).into()), self.int_to_base16(self.safe_integer_k(sig, "v", &[]), &[])).into()).as_str().map(str::to_owned);
}
pub fn opinion_order_raw_amounts(&self, isMarket: bool, mut side: Value, mut amount: Value, mut price: Value, mut decimals: Value) -> Value {
let mut decimalsStr: Value = Value::Str("1".into());
if (decimals != Value::Null) {
let mut decimalsCount: Value = self.parse_to_int(decimals);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1399: bool = true;
while { if !__for_first_1399 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1399 = false; i.as_f64().unwrap_or(f64::NAN) < decimalsCount.as_f64().unwrap_or(f64::NAN) } {
decimalsStr = Value::Str(format!("{}{}", decimalsStr, Value::Str("0".into())).into());
}
}
}
let mut amountStr: Value = self.number_to_string(amount);
if isMarket && (side.as_str() == Some("BUY")) {
let mut marketMakerAmountWei: Value = self.decimal_to_precision(crate::precise::Precise::stringMul(&amountStr, &decimalsStr), Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("makerAmount".to_string(), marketMakerAmountWei);
m.insert("takerAmount".to_string(), Value::Str("0".into()));
m
});
}
let mut priceStr: Value = self.decimal_to_precision(self.number_to_string(price), Value::Int(crate::runtime::ROUND), Value::Int(6), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
let mut priceParts: Value = Value::Array(if let Some(__s) = priceStr.as_str() { __s.split(".").map(Value::from).collect() } else { Vec::new() });
let mut priceInt: Value = self.safe_string(priceParts.clone(), Value::Int(0), &[Value::Str("0".into())]);
let mut priceFrac: Value = self.safe_string(priceParts, Value::Int(1), &[Value::Str("".into())]);
let mut priceDenom: Value = Value::Str("1000000".into());
let mut priceNum: Value = crate::precise::Precise::stringAdd(&crate::precise::Precise::stringMul(&priceInt, &priceDenom), &priceFrac.as_str().map(|__s| Value::Str(format!("{:0<6}", __s).into())).unwrap_or(Value::Null));
if (priceNum.as_str() == Some("0")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder() invalid price ".into())).into()), priceStr)));
}
let mut makerRaw: Value = amountStr.clone();
if (side.as_str() == Some("BUY")) {
makerRaw = crate::precise::Precise::stringMul(&amountStr, &priceStr);
}
let mut makerAmountWei: Value = self.decimal_to_precision(crate::precise::Precise::stringMul(&makerRaw, &decimalsStr), Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
let mut makerAmount: Value = Value::Null;
let mut takerAmount: Value = Value::Null;
if (side.as_str() == Some("BUY")) {
let mut k: Value = crate::precise::Precise::stringDivPrec(&makerAmountWei, &priceNum, &Value::Int(0));
makerAmount = crate::precise::Precise::stringMul(&k, &priceNum);
takerAmount = crate::precise::Precise::stringMul(&k, &priceDenom);
} else {
let mut k: Value = crate::precise::Precise::stringDivPrec(&makerAmountWei, &priceDenom, &Value::Int(0));
makerAmount = crate::precise::Precise::stringMul(&k, &priceDenom);
takerAmount = crate::precise::Precise::stringMul(&k, &priceNum);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("makerAmount".to_string(), makerAmount);
m.insert("takerAmount".to_string(), takerAmount);
m
});
Value::Null
}
/*
* @method
* @name opinion#createOrder
* @description places a limit or market order on the CLOB for the given outcome token
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/order
* @param {string} outcome unified outcome or outcome token id
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount for limit orders, the number of outcome shares to trade; for market orders, the quote (USDT) to spend on a BUY or the shares to sell on a SELL
* @param {float} [price] the price per outcome token between 0 and 1; required for limit orders and market SELL orders (where it acts as the reference / worst acceptable price for the taker amount); ignored for market BUY orders (amount is already the quote to spend)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.postOnly] limit orders only - reject the order if it would cross the spread
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn create_order(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_key().await;
self.check_required_credentials(&[]);
let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
let mut isMarket: bool = type_var.as_str() == Some("market");
let mut sideStr: Value = (if let Some(__s) = side.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
if (price == Value::Null) {
if !isMarket {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price for limit orders".into()))));
}
if (sideStr.as_str() == Some("SELL")) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price for market sell orders".into()))));
}
}
let mut marketOrderPrice: Value = Value::Str("0".into());
if isMarket && (sideStr.as_str() == Some("SELL")) {
marketOrderPrice = self.number_to_string(price.clone());
}
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut topicId: Option<i64> = self.safe_integer_k(info.clone(), "marketId", &[]).as_i64();
let mut quoteTokenAddress: Option<String> = self.safe_string_k_opt(info, "quoteToken", &[]);
let mut quoteToken: Value = self.load_quote_token(quoteTokenAddress.clone().map(Value::from).unwrap_or(Value::Null)).await;
let mut amounts: Value = self.opinion_order_raw_amounts(isMarket.clone(), sideStr.clone(), amount, price.clone(), self.safe_integer_k(quoteToken.clone(), "decimal", &[Value::Int(18)]));
let mut makerAmount: Option<String> = self.safe_string_k_opt(amounts.clone(), "makerAmount", &[]);
let mut takerAmount: Option<String> = self.safe_string_k_opt(amounts, "takerAmount", &[]);
let mut sideInt: Value = (if (sideStr.as_str() == Some("BUY")) { Value::Int(0) } else { Value::Int(1) });
let mut salt: Value = self.number_to_string(self.milliseconds());
let mut postOnly: bool = self.safe_bool_k_opt(params.clone(), "postOnly", &[Value::Bool(false)]).unwrap_or(false);
let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("postOnly".into())]), &[]);
let mut maker: Value = self.load_multi_sign_address().await;
// Ethereum addresses are case-insensitive - a checksummed multiSignAddress compared
// against a differently-cased walletAddress with strict equality would pick the wrong
// signatureType (0 EOA vs 2 Gnosis Safe) and break order signing/validation
let mut makerLower: Value = (if let Some(__s) = maker.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null });
let mut walletAddressLower: Value = (if let Some(__s) = self.walletAddress.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null });
let mut signatureType: Value = (if (makerLower.as_str() == walletAddressLower.as_str()) { Value::Int(0) } else { Value::Int(2) });
let mut order: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("salt".to_string(), salt.clone());
m.insert("maker".to_string(), maker.clone());
m.insert("signer".to_string(), self.walletAddress.clone());
m.insert("taker".to_string(), Value::Str("0x0000000000000000000000000000000000000000".into()));
m.insert("tokenId".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("makerAmount".to_string(), makerAmount.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("takerAmount".to_string(), takerAmount.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("expiration".to_string(), Value::Str("0".into()));
m.insert("nonce".to_string(), Value::Str("0".into()));
m.insert("feeRateBps".to_string(), Value::Str("0".into()));
m.insert("side".to_string(), sideInt.clone());
m.insert("signatureType".to_string(), signatureType.clone());
m
});
let mut signature: Value = self.sign_opinion_order(Value::Map(order), self.safe_string_k(quoteToken, "ctfExchangeAddress", &[Value::Str("".into())])).map(Value::from).unwrap_or(Value::Null);
let mut signatureNo0x: Value = self.remove0x_prefix(signature.clone());
let __ws_arg_17 = self.number_to_string(price);
let __ws_arg_18 = self.seconds();
let mut orderBody: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("salt".to_string(), salt);
m.insert("maker".to_string(), maker);
m.insert("signer".to_string(), self.walletAddress.clone());
m.insert("taker".to_string(), Value::Str("0x0000000000000000000000000000000000000000".into()));
m.insert("tokenId".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m.insert("makerAmount".to_string(), makerAmount.map(Value::from).unwrap_or(Value::Null));
m.insert("takerAmount".to_string(), takerAmount.map(Value::from).unwrap_or(Value::Null));
m.insert("expiration".to_string(), Value::Str("0".into()));
m.insert("nonce".to_string(), Value::Str("0".into()));
m.insert("feeRateBps".to_string(), Value::Str("0".into()));
m.insert("side".to_string(), Value::Str(format!("{}", sideInt).into()));
m.insert("signatureType".to_string(), Value::Str(format!("{}", signatureType).into()));
m.insert("signature".to_string(), signature);
m.insert("sign".to_string(), signatureNo0x.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = __l.min(64); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null));
m.insert("contractAddress".to_string(), Value::Str("".into()));
m.insert("currencyAddress".to_string(), quoteTokenAddress.map(Value::from).unwrap_or(Value::Null));
m.insert("topicId".to_string(), Value::from(topicId));
m.insert("price".to_string(), (if isMarket { marketOrderPrice } else { __ws_arg_17 }));
m.insert("tradingMethod".to_string(), (if isMarket { Value::Int(1) } else { Value::Int(2) }));
m.insert("timestamp".to_string(), __ws_arg_18);
m.insert("safeRate".to_string(), Value::Str("0".into()));
m.insert("orderExpTime".to_string(), Value::Str("0".into()));
m.insert("postOnly".to_string(), Value::Bool(postOnly));
m
}), &[rest]);
let mut response: Value = self.opinion_private_post_order(&[orderBody]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderData: Value = self.safe_dict_k(result, "orderData", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_prediction_order(orderData, &[outcomeObj]);
Value::Null
}
/*
* @method
* @name opinion#cancelOrder
* @description cancels a single open order by id
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/order
* @param {string} id the order id
* @param {string} [outcome] not used by opinion cancelOrder
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_key().await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id.clone());
m
});
let __ws_arg_19 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.opinion_private_post_order_cancel(&[__ws_arg_19]).await;
let mut result: Value = self.safe_dict_k(response.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut canceled: bool = self.safe_bool_k_opt(result, "result", &[Value::Bool(false)]).unwrap_or(false);
// a false result does NOT mean the order is still open — it may already be filled,
// already cancelled, or unknown; don't invent a status the venue didn't report.
// error responses with an errno never reach this line, handleErrors throws on them
let mut status: Value = (if canceled { Value::Str("canceled".into()) } else { Value::Null });
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("status".to_string(), status);
m.insert("info".to_string(), response);
m
}), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name opinion#parseOrderStatus
* @description maps an opinion order statusEnum string to the unified status vocabulary
* @param {string} status the raw opinion order statusEnum
* @returns {string} a unified order status
*/
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("Pending".to_string(), Value::Str("open".into()));
m.insert("Finished".to_string(), Value::Str("closed".into()));
m.insert("Canceled".to_string(), Value::Str("canceled".into()));
m.insert("Expired".to_string(), Value::Str("canceled".into()));
m.insert("Failed".to_string(), Value::Str("canceled".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name opinion#parsePredictionOrder
* @description parses a raw opinion order object into a unified prediction order structure
* @param {object} order the raw opinion OrderData object
* @param {object} [market] the outcome object the order belongs to
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub fn parse_prediction_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "orderId": "...",
// "marketId": 1094,
// "side": 0,
// "sideEnum": "Buy",
// "tradingMethod": 2,
// "tradingMethodEnum": "Limit",
// "price": "0.01",
// "orderShares": "5",
// "orderAmount": "0.05",
// "filledShares": "0",
// "filledAmount": "0",
// "profit": "0",
// "status": 1,
// "statusEnum": "Pending",
// "createdAt": 1785500000,
// "expiresAt": 0,
// "postOnly": false
// }
//
let mut id: Option<String> = self.safe_string_k_opt(order.clone(), "orderId", &[]);
let mut marketAny: Value = market.clone();
let mut statusEnum: Option<String> = self.safe_string_k_opt(order.clone(), "statusEnum", &[]);
let mut status: Value = self.parse_order_status(statusEnum.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut sideEnum: Option<String> = self.safe_string_lower_k_opt(order.clone(), "sideEnum", &[]);
let mut tradingMethodEnum: Option<String> = self.safe_string_lower_k_opt(order.clone(), "tradingMethodEnum", &[]);
let mut timestamp: Value = self.safe_timestamp_k(order.clone(), "createdAt", &[]);
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), order.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("outcome".to_string(), self.safe_string_k(marketAny.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string2(marketAny.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("label".to_string(), self.safe_string_k(marketAny.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(marketAny, Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m.insert("type".to_string(), tradingMethodEnum.map(Value::from).unwrap_or(Value::Null));
m.insert("side".to_string(), sideEnum.map(Value::from).unwrap_or(Value::Null));
m.insert("price".to_string(), self.safe_number_k(order.clone(), "price", &[]));
m.insert("amount".to_string(), self.safe_number_k(order.clone(), "orderShares", &[]));
m.insert("cost".to_string(), self.safe_number_k(order.clone(), "filledAmount", &[]));
m.insert("filled".to_string(), self.safe_number_k(order, "filledShares", &[]));
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m
}), &[market]);
Value::Null
}
/*
* @method
* @name opinion#fetchOrders
* @description fetches all of the authenticated user's orders
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/order
* @param {string} [outcome] filter by unified outcome or outcome token id
* @param {int} [since] timestamp in ms of the earliest order to fetch
* @param {int} [limit] the maximum number of orders to fetch
* @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_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_key().await;
let mut outcomeObj: Value = Value::Null;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (outcome != Value::Null) {
outcomeObj = self.load_outcome(outcome, &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
request.insert("marketId".into(), self.safe_integer_k(info, "marketId", &[]));
}
let __ws_arg_20 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.opinion_private_get_order(&[__ws_arg_20]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = self.safe_list_k(result, "list", &[Value::from(vec![])]);
return self.parse_prediction_orders(orders, &[outcomeObj, since, limit]);
Value::Null
}
/*
* @method
* @name opinion#fetchOrder
* @description fetches a single order by id
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/order
* @param {string} id the order id
* @param {string} [outcome] unified outcome or outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn 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
}));
self.load_api_key().await;
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
outcomeObj = self.load_outcome(outcome, &[]).await;
}
let __ws_arg_21 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id);
m
}), &[params]);
let mut response: Value = self.opinion_private_get_order_order_id(&[__ws_arg_21]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderData: Value = self.safe_dict_k(result, "orderData", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_prediction_order(orderData, &[outcomeObj]);
Value::Null
}
/*
* @method
* @name opinion#fetchOpenOrders
* @description fetches the authenticated user's open orders
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/order
* @param {string} [outcome] filter by unified outcome or outcome token id
* @param {int} [since] timestamp in ms of the earliest order to fetch
* @param {int} [limit] the maximum number of orders to fetch
* @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
}));
// 1 = pending - open status
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("1".into()));
m
});
let __ws_arg_22 = self.extend(Value::Map(request), &[params]);
return self.fetch_orders(&[outcome, since, limit, __ws_arg_22]).await;
Value::Null
}
/*
* @method
* @name opinion#fetchClosedOrders
* @description fetches the authenticated user's closed orders
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/order
* @param {string} [outcome] filter by unified outcome or outcome token id
* @param {int} [since] timestamp in ms of the earliest order to fetch
* @param {int} [limit] the maximum number of orders to fetch
* @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
}));
// 2 = filled, 3 = canceled, 4 = expired, 5 = failed
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("2,3,4,5".into()));
m
});
let __ws_arg_23 = self.extend(Value::Map(request), &[params]);
return self.fetch_orders(&[outcome, since, limit, __ws_arg_23]).await;
Value::Null
}
/*
* @method
* @name opinion#fetchMyTrades
* @description fetches the authenticated user's trades
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/trade
* @param {string} [outcome] filter by unified outcome or outcome token id
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum number of trades to fetch
* @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
}));
if (self.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchMyTrades() requires a walletAddress".into()))));
}
self.load_api_key().await;
let mut outcomeObj: Value = Value::Null;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("walletAddress".to_string(), self.walletAddress.clone());
m
});
if (outcome != Value::Null) {
outcomeObj = self.load_outcome(outcome, &[]).await;
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
request.insert("marketId".into(), self.safe_integer_k(info.clone(), "marketId", &[]));
}
let __ws_arg_24 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.opinion_private_get_trade_user_wallet_address(&[__ws_arg_24]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut trades: Value = self.safe_list_k(result, "list", &[Value::from(vec![])]);
let mut tradesLength: f64 = ((trades.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1400: bool = true;
while { if !__for_first_1400 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1400 = false; i.as_f64().unwrap_or(f64::NAN) < tradesLength } {
let mut trade: Value = trades.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut tokenId: Option<String> = self.safe_string_k(trade.clone(), "tokenId", &[]).as_str().map(str::to_owned);
let mut marketId: Value = self.safe_integer_k(trade.clone(), "marketId", &[]);
if (tokenId.is_none()) && (marketId != Value::Null) {
let mut tradeMarket: Value = self.load_trade_market(marketId).await;
let mut info: Value = self.safe_dict_k(tradeMarket, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut isYes: bool = self.safe_string_lower_k(trade.clone(), "outcomeSideEnum", &[]).as_str() == Some("yes");
add_element_to_object(&mut trade, &Value::Str("tokenId".into()), (if isYes { self.safe_string_k(info.clone(), "yesTokenId", &[]) } else { self.safe_string_k(info, "noTokenId", &[]) }));
}
}
}
return self.parse_prediction_trades(trades, &[outcomeObj, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name opinion#loadTradeMarket
* @description fetches and caches a single market by its numeric marketId, and indexes its outcomes
* @param {int} marketId the numeric market id
* @returns {object} the parsed market
*/
pub async fn load_trade_market(&mut self, mut marketId: Value) -> Value {
let mut cacheKey: String = "tradeMarketsById".to_string();
let mut cached: indexmap::IndexMap<String, Value> = self.safe_dict(self.options.clone(), Value::from(cacheKey.clone()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).as_map().cloned().unwrap_or_default();
let mut idStr: Value = Value::Str(format!("{}", marketId).into());
let mut existing: Value = self.safe_dict(Value::Map(cached.clone()), idStr.clone(), &[]);
if (existing != Value::Null) {
return existing;
}
let mut response: Value = self.opinion_public_get_market_market_id(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), marketId);
m
})]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(result, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut market: Value = self.parse_opinion_market(data, &[]);
if (market == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" loadTradeMarket() could not parse market ".into())).into()), idStr)));
}
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut marketHandle: Value = self.safe_string_k(market.clone(), "market", &[Value::Str("".into())]);
if let Value::Dict(__d) = &mut self.markets { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketHandle), market.clone()); }
self.index_market_outcomes(market.clone());
cached.insert(crate::runtime::stringify_param(&idStr), market.clone());
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert(cacheKey.clone(), Value::Map(cached)); }
return market;
Value::Null
}
/*
* @ignore
* @method
* @name opinion#parsePredictionTrade
* @description parses a raw opinion trade object into a unified trade object
* @param {object} trade the raw opinion TradeData object
* @param {object} [market] the outcome object the trade belongs to
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut tokenId: Option<String> = self.safe_string_k_opt(trade.clone(), "tokenId", &[]);
let mut outcomeObj: Value = self.safe_outcome(tokenId.map(Value::from).unwrap_or(Value::Null), &[market]);
let mut timestamp: Value = self.safe_timestamp_k(trade.clone(), "createdAt", &[]);
let mut side: Option<String> = self.safe_string_lower_k_opt(trade.clone(), "side", &[]);
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "txHash", &[]));
m.insert("timestamp".to_string(), timestamp);
m.insert("side".to_string(), side.map(Value::from).unwrap_or(Value::Null));
m.insert("price".to_string(), self.safe_number_k(trade.clone(), "price", &[]));
m.insert("amount".to_string(), self.safe_number_k(trade.clone(), "shares", &[]));
m.insert("cost".to_string(), self.safe_number_k(trade.clone(), "amount", &[]));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_number_k(trade, "fee", &[]));
m.insert("currency".to_string(), Value::Str("USDT".into()));
m
}));
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(outcomeObj, Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m
}), &[]);
Value::Null
}
/*
* @method
* @name opinion#fetchBalance
* @description fetches the authenticated user's quote-token balances
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/quote-token
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_api_key().await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("chain_id".to_string(), Value::Str("56".into()));
m
});
let __ws_arg_25 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.opinion_private_get_user_balance(&[__ws_arg_25]).await;
let mut result: Value = self.safe_dict_k(response.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawBalances: Vec<Value> = self.safe_list_k(result, "balances", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rawBalancesLength: f64 = ((rawBalances.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1401: bool = true;
while { if !__for_first_1401 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1401 = false; i.as_f64().unwrap_or(f64::NAN) < rawBalancesLength } {
let mut rawBalance: Value = rawBalances.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut quoteTokenAddress: Option<String> = self.safe_string_k_opt(rawBalance.clone(), "quoteToken", &[]);
let mut quoteToken: Value = self.load_quote_token(quoteTokenAddress.map(Value::from).unwrap_or(Value::Null)).await;
add_element_to_object(&mut rawBalance, &Value::Str("symbol".into()), self.safe_string_k(quoteToken, "symbol", &[Value::Str("USDT".into())]));
}
}
return self.parse_balance(response);
Value::Null
}
/*
* @ignore
* @method
* @name opinion#parseBalance
* @description parses an opinion user-balance response into a unified balances object
* @param {object} response the raw user-balance response
* @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
*/
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut data: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut balances: Value = self.safe_list_k(data, "balances", &[Value::from(vec![])]);
let mut balancesLength: f64 = ((balances.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1402: bool = true;
while { if !__for_first_1402 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1402 = false; i.as_f64().unwrap_or(f64::NAN) < balancesLength } {
let mut balance: Value = self.safe_dict(balances.clone(), i.clone(), &[]);
let mut code: Value = self.safe_string_k(balance.clone(), "symbol", &[Value::Str("USDT".into())]);
result.insert(crate::runtime::stringify_param(&code), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("free".to_string(), self.safe_number_k(balance.clone(), "availableBalance", &[]));
m.insert("used".to_string(), self.safe_number_k(balance.clone(), "frozenBalance", &[]));
m.insert("total".to_string(), self.safe_number_k(balance, "totalBalance", &[]));
m
}));
}
}
return self.safe_balance(Value::Map(result));
Value::Null
}
/*
* @method
* @name opinion#fetchPositions
* @description fetches the authenticated user's open positions
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/position
* @param {string[]} [outcomes] filter by unified outcomes or outcome token ids
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction position structures](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.walletAddress.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() requires a walletAddress".into()))));
}
self.load_api_key().await;
let mut outcomesLength: i64 = 0;
if (outcomes != Value::Null) {
outcomesLength = outcomes.len() as i64;
self.load_outcomes(&[outcomes.clone()]).await;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("walletAddress".to_string(), self.walletAddress.clone());
m
});
let __ws_arg_26 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.opinion_private_get_positions_user_wallet_address(&[__ws_arg_26]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positions: Value = self.safe_list_k(result, "list", &[Value::from(vec![])]);
if (((outcomesLength as f64) == 0.0)) {
return self.parse_prediction_positions(positions.clone(), &[]);
}
let mut parsed: Vec<Value> = self.parse_prediction_positions(positions, &[]).as_array().cloned().unwrap_or_default();
let mut wantedTokenIds: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
// copy to a plain list so the strict null checks see one shape
let mut outcomesList: Value = (if (outcomes == Value::Null) { Value::from(vec![]) } else { outcomes });
{
let mut i: i64 = 0;
let mut __for_first_1403: bool = true;
while { if !__for_first_1403 { i += 1; } __for_first_1403 = false; i < (outcomesList.len() as i64) } {
let mut outcomeObj: Value = self.outcome(outcomesList.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null));
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj, "outcomeId", &[]);
if (tokenId.is_some()) {
if let Value::Dict(__d) = &mut wantedTokenIds { std::sync::Arc::make_mut(__d).insert(tokenId.as_deref().unwrap_or("null").to_string(), Value::Bool(true)); }
}
}
}
let mut filtered: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_1404: bool = true;
while { if !__for_first_1404 { i += 1; } __for_first_1404 = false; i < (parsed.len() as i64) } {
let mut position: Value = parsed.get(i as usize).cloned().unwrap_or(Value::Null);
let mut info: Value = self.safe_dict_k(position.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut tokenId: Option<String> = self.safe_string_k_opt(info, "tokenId", &[]);
if (tokenId.is_some()) && (matches!((&wantedTokenIds, &tokenId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Arr(__a) = &mut filtered { std::sync::Arc::make_mut(__a).push(position); }
}
}
}
return filtered;
Value::Null
}
/*
* @ignore
* @method
* @name opinion#parsePredictionPosition
* @description parses a raw opinion position object into a unified position object
* @param {object} position the raw opinion PositionData object
* @param {object} [market] the outcome object the position belongs to
* @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
*/
pub fn parse_prediction_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut tokenId: Option<String> = self.safe_string_k_opt(position.clone(), "tokenId", &[]);
let mut outcomeObj: Value = self.safe_outcome(tokenId.map(Value::from).unwrap_or(Value::Null), &[market]);
let mut outcomeSideEnum: Option<String> = self.safe_string_lower_k_opt(position.clone(), "outcomeSideEnum", &[]);
return self.safe_prediction_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("contracts".to_string(), self.safe_number_k(position.clone(), "sharesOwned", &[]));
m.insert("side".to_string(), outcomeSideEnum.map(Value::from).unwrap_or(Value::Null));
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "unrealizedPnl", &[]));
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "avgEntryPrice", &[]));
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string2(outcomeObj, Value::Str("market".into()), Value::Str("outcome".into()), &[]));
m.insert("info".to_string(), position);
m
}));
Value::Null
}
pub fn hash_message(&self, mut message: Value) -> Option<String> {
return Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(message, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into()).as_str().map(str::to_owned);
}
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Value {
let mut signature: Value = ecdsa(hash.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null),
privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null), Value::Str("secp256k1".into()), Value::Null);
// assign before padStart so the PHP str_pad regex matches
let mut rRaw: Value = self.safe_string_k(signature.clone(), "r", &[Value::Str("".into())]);
let mut sRaw: Value = self.safe_string_k(signature.clone(), "s", &[Value::Str("".into())]);
let mut r: Value = rRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
let mut s: Value = sRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("r".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), r).into()));
m.insert("s".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), s).into()));
m.insert("v".to_string(), self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]));
m
});
Value::Null
}
pub fn sign_message(&self, mut message: Value, mut privateKey: Value) -> Value {
return self.sign_hash(self.hash_message(message).map(Value::from).unwrap_or(Value::Null), privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null));
Value::Null
}
pub fn sign_api_key_auth(&self, mut walletAddress: Value, mut action: Value, mut timestamp: Value) -> Option<String> {
// EIP-712 signature used to create/get/delete an API key (wallet-authenticated key management)
let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("Opinion OpenAPI".into()));
m.insert("version".to_string(), Value::Str("1".into()));
m.insert("chainId".to_string(), Value::Int(56));
m
});
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("OpinionApiKeyAuth".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("walletAddress".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("action".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("timestamp".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
})]));
m
});
let mut messageData: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("walletAddress".to_string(), walletAddress);
m.insert("action".to_string(), action);
m.insert("timestamp".to_string(), timestamp);
m
});
let mut encoded: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map(messageTypes), Value::Map(messageData));
let mut sig: Value = self.sign_message(encoded, self.privateKey.clone());
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), self.remove0x_prefix(self.safe_string_k(sig.clone(), "r", &[]))).into()), self.remove0x_prefix(self.safe_string_k(sig.clone(), "s", &[]))).into()), self.int_to_base16(self.safe_integer_k(sig, "v", &[]), &[])).into()).as_str().map(str::to_owned);
}
/*
* @method
* @name opinion#createApiKey
* @description self-service creation of an Open API key linked to this.walletAddress via
* an EIP-712-signed request - there is no "generate key" button in the Opinion GUI, this is
* the only documented way to obtain a wallet-linked key
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/authentication
* @param {object} [params] extra parameters
* @returns {object} the api credentials { apiKey, walletAddress }
*/
pub async fn create_api_key(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.opinion_private_post_auth_api_key(&[params]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.set_api_credentials(result);
Value::Null
}
/*
* @method
* @name opinion#fetchApiKey
* @description fetches the currently active Open API key for this.walletAddress
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/authentication
* @param {object} [params] extra parameters
* @returns {object} the api credentials { apiKey, walletAddress }
*/
pub async fn fetch_api_key(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.opinion_private_get_auth_api_key(&[params]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.set_api_credentials(result);
Value::Null
}
/*
* @method
* @name opinion#deleteApiKey
* @description revokes the Open API key for this.walletAddress
* @see https://docs.opinion.trade/developer-guide/opinion-open-api/authentication
* @param {object} [params] extra parameters
* @returns {object} raw response, result.deleted confirms revocation
*/
pub async fn delete_api_key(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.opinion_private_delete_auth_api_key(&[params]).await;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("apiKey".into(), Value::Null); }
// sign() prefers this.apiKey over options['apiKey'] - clear it too, or a directly-set
// exchange.apiKey would keep being used for private calls after the key is revoked.
// an empty string, not undefined: the strict base types the credential as string, and
// sign() treats an empty key as absent
self.apiKey = Value::Str("".into());
return response;
Value::Null
}
/*
* @ignore
* @method
* @name opinion#loadApiKey
* @description ensures an apiKey is available before a private call - reuses a directly-set key, otherwise
* self-issues one from the walletAddress/privateKey via fetchApiKey(), falling back to createApiKey() when
* the wallet has no key yet; freshly created keys can take ~15 seconds to activate venue-side
* @returns {string} the apiKey
*/
pub async fn load_api_key(&mut self) -> Value {
let mut hasDirectApiKey: bool = !(self.is_empty_string(self.apiKey.clone()).as_bool() == Some(true));
if hasDirectApiKey {
return self.apiKey.clone();
}
let mut optionsKey: Value = self.safe_string_k(self.options.clone(), "apiKey", &[]);
if (optionsKey != Value::Null) {
return optionsKey;
}
if (self.walletAddress.clone() == Value::Null) || (self.privateKey.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" private endpoints require an apiKey, or a walletAddress and privateKey to self-issue one".into()))));
}
let mut creds: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
creds = self.fetch_api_key(&[]).await;
#[allow(unreachable_code)] { Value::Null }})).await;
if _try_result.is_err() {
// no key exists for this wallet yet (11010) - self-issue one; any other
// failure (unregistered wallet, disabled issuance) surfaces from the create call
creds = self.create_api_key(&[]).await;
}
return self.safe_string_k(creds, "apiKey", &[]);
Value::Null
}
pub fn set_api_credentials(&mut self, mut response: Value) -> Value {
let __response_empty = indexmap::IndexMap::new();
let response = response.as_map().unwrap_or(&__response_empty);
//
// { "apiKey": "...", "walletAddress": "..." }
//
let mut creds: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), (match response.get("apiKey") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("walletAddress".to_string(), (match response.get("walletAddress") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m
});
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("apiKey".into(), creds.get("apiKey").cloned().unwrap_or(Value::Null)); }
// checkRequiredCredentials() (called by createOrder()) checks this.apiKey, not
// options['apiKey'] - keep both in sync, same as deleteApiKey() clearing both
// an empty string, not undefined: the strict base types the credential as string
{ let __t = self.safe_string(Value::Map(creds.clone()), Value::Str("apiKey".into()), &[Value::Str("".into())]); self.apiKey = __t; }
return Value::Map(creds);
Value::Null
}
/*
* @ignore
* @method
* @name opinion#opinionWsUrl
* @description builds the websocket url - the venue authenticates the whole connection with the apiKey passed as a query parameter, for public and private channels alike
* @returns {string} the websocket url
*/
pub fn opinion_ws_url(&self) -> Option<String> {
let mut hasDirectApiKey: bool = !(self.is_empty_string(self.apiKey.clone()).as_bool() == Some(true));
let mut apiKey: Value = (if (hasDirectApiKey) { self.apiKey.clone() } else { self.safe_string_k(self.options.clone(), "apiKey", &[]) });
if (apiKey == Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" websocket requires an apiKey - set it directly or call createApiKey()/fetchApiKey() first".into()))));
}
let wsUrl: String = self.safe_string_opt(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("ws".into()), &[Value::Str("".into())]).unwrap_or_default();
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", wsUrl, Value::Str("?apikey=".into())).into()), apiKey).into()).as_str().map(str::to_owned);
}
pub fn ping(&self, mut client: Value) -> Value {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Str("HEARTBEAT".into()));
m
});
Value::Null
}
/*
* @ignore
* @method
* @name opinion#subscribeOpinionChannel
* @description subscribes to one venue channel scoped by the binary marketId and waits on the given message hash
* @param {string} messageHash the internal hash the awaited payload resolves on
* @param {string} channel the venue channel name (e.g. 'market.depth.diff')
* @param {int} marketId the numeric binary market id
* @returns {any} the first resolved payload
*/
pub async fn subscribe_opinion_channel(&mut self, mut messageHash: Value, mut channel: Value, mut marketId: Value) -> Value {
self.load_api_key().await;
let mut url: Value = self.opinion_ws_url().map(Value::from).unwrap_or(Value::Null);
let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Str("SUBSCRIBE".into()));
m.insert("channel".to_string(), channel.clone());
m.insert("marketId".to_string(), marketId);
m
});
let mut subscriptionKey: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), self.safe_string(Value::Map(subscribeMsg.clone()), Value::Str("marketId".into()), &[Value::Str("".into())])).into());
return self.watch(url, messageHash, &[Value::Map(subscribeMsg), subscriptionKey]).await;
Value::Null
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &message { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
// every data payload carries its channel name in msgType; frames without one -
// subscribe acks and heartbeat echoes - carry nothing to route
let mut msgType: Option<String> = (match __pro_message.get("msgType").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (msgType.is_none()) {
return;
}
if (msgType.as_deref() == Some("market.depth.diff")) {
self.handle_order_book(client.clone(), message.clone());
} else if (msgType.as_deref() == Some("market.last.price")) {
self.handle_ticker(client.clone(), message.clone());
} else if (msgType.as_deref() == Some("market.last.trade")) {
self.handle_trades(client.clone(), message.clone());
} else if (msgType.as_deref() == Some("trade.order.update")) {
self.handle_order(client.clone(), message.clone());
} else if (msgType.as_deref() == Some("trade.record.new")) {
self.handle_my_trade(client, message);
}
}
/*
* @ignore
* @method
* @name opinion#opinionOutcomeByMarketIdSide
* @description resolves a cached outcome object from the numeric marketId + outcomeSide (1 yes / 2 no) the user channels report instead of a tokenId - cache-only, returns undefined on a cold cache
* @param {int} marketId the numeric binary market id
* @param {int} outcomeSide 1 for the yes token, 2 for the no token
* @returns {object} the outcome object, or undefined
*/
pub fn opinion_outcome_by_market_id_side(&self, mut marketId: Value, mut outcomeSide: Value) -> Value {
if (marketId == Value::Null) || (self.markets.clone() == Value::Null) {
return Value::Null;
}
let mut marketKeys: Vec<Value> = Value::Array(self.markets.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).as_array().cloned().unwrap_or_default();
let mut marketKeysLength: f64 = ((marketKeys.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1405: bool = true;
while { if !__for_first_1405 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1405 = false; i.as_f64().unwrap_or(f64::NAN) < marketKeysLength } {
let mut market: Value = self.safe_dict(self.markets.clone(), marketKeys.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[]);
let mut info: Value = self.safe_dict_k(market.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.safe_integer_k(info, "marketId", &[]).as_f64() == marketId.as_f64()) {
let mut outcomes: Value = self.safe_list_k(market, "outcomes", &[Value::from(vec![])]);
let mut index: Value = (if (outcomeSide.as_f64() == Some(2.0)) { Value::Int(1) } else { Value::Int(0) });
return self.safe_dict(outcomes, index, &[]);
}
}
}
return Value::Null;
Value::Null
}
/*
* @method
* @name opinion#watchOrderBook
* @description streams the order book of an outcome token; the channel is delta-only so the live book is seeded from the REST snapshot
* @see https://docs.opinion.trade/developer-guide/opinion-websocket/market-channels
* @param {string} outcome unified outcome or outcome token id
* @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 marketId: Option<i64> = self.safe_integer_k(info, "marketId", &[]).as_i64();
let mut sym: Value = self.safe_outcome_symbol(outcome.clone(), &[outcomeObj]);
let mut channel: String = "market.depth.diff".to_string();
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook::".into()), sym).into());
self.load_api_key().await;
let mut url: Value = self.opinion_ws_url().map(Value::from).unwrap_or(Value::Null);
let mut client: Value = self.client(&[url.clone()]);
let __ch = crate::pro::ws_client::ClientHandle::from_value(client.clone());
let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Str("SUBSCRIBE".into()));
m.insert("channel".to_string(), Value::from(channel.clone()));
m.insert("marketId".to_string(), Value::from(marketId));
m
});
let mut subscriptionKey: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", channel, Value::Str(":".into())).into()), self.safe_string(Value::Map(subscribeMsg.clone()), Value::Str("marketId".into()), &[Value::Str("".into())])).into());
let mut isNewSubscription: bool = self.safe_value(__ch.subscriptions.clone(), subscriptionKey.clone(), &[]) == Value::Null;
if isNewSubscription {
self.seed_order_book(outcome, sym.clone(), &[limit.clone()]).await;
}
let mut future: Value = self.watch(url, messageHash.clone(), &[Value::Map(subscribeMsg), subscriptionKey]).await;
if isNewSubscription {
// return the freshly-seeded book immediately instead of blocking until the next delta
client.resolve(&[self.safe_value(self.orderbooks.clone(), sym, &[]), messageHash]);
}
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 depth channel streams single-level deltas only, so seed the live book from the REST snapshot
let mut snapshot: Value = self.fetch_order_book(outcome, &[limit]).await;
let mut orderbook: Value = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
orderbook.reset(snapshot);
if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&sym), orderbook); }
Value::Null
}
pub fn handle_order_book(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "marketId": 2764,
// "tokenId": "19120407572139442221452465677574895365338028945317996490376653704877573103648",
// "outcomeSide": 1,
// "side": "bids",
// "price": "0.2",
// "size": "50",
// "msgType": "market.depth.diff"
// }
//
let mut tokenId: Value = (match message.get("tokenId") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut outcomeObj: Value = self.safe_dict(self.exchange.outcomes_by_id.clone(), tokenId, &[]);
let mut sym: Option<String> = self.safe_string_k_opt(outcomeObj, "outcome", &[]);
if (sym.is_none()) {
return;
}
if !(matches!((&self.orderbooks, &sym.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
return;
}
let mut orderbook: Value = (if let (Some(__m), Some(__k)) = (self.orderbooks.as_map(), sym.as_deref()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
let mut sideStr: Option<String> = (match message.get("side") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
let mut bookSide: Value = (if (sideStr.as_deref() == Some("bids")) { orderbook.book_field("bids") } else { orderbook.book_field("asks") });
let mut price: Value = (match message.get("price") { Some(Value::Float(__f)) => Value::Float(*__f), Some(Value::Int(__n)) => Value::Float(*__n as f64), Some(Value::Str(__s)) => match __s.parse::<f64>() { Ok(__n) => Value::Float(__n), Err(_) => Value::Null }, _ => Value::Null });
let mut size: Value = (match message.get("size") { Some(Value::Float(__f)) => Value::Float(*__f), Some(Value::Int(__n)) => Value::Float(*__n as f64), Some(Value::Str(__s)) => match __s.parse::<f64>() { Ok(__n) => Value::Float(__n), Err(_) => Value::Null }, _ => Value::Null });
bookSide.store_array(Value::from(vec![price, size]));
orderbook.set_book_meta("timestamp", Value::Null);
orderbook.set_book_meta("datetime", Value::Null);
client.resolve(&[orderbook, Value::Str(format!("{}{}", Value::Str("orderbook::".into()), sym.map(Value::from).unwrap_or(Value::Null)).into())]);
}
/*
* @method
* @name opinion#watchTicker
* @description streams last-price updates of an outcome token
* @see https://docs.opinion.trade/developer-guide/opinion-websocket/market-channels
* @param {string} outcome unified outcome or outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub async fn 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 marketId: Value = self.safe_integer_k(info, "marketId", &[]);
let mut sym: Value = self.safe_outcome_symbol(outcome, &[outcomeObj]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker::".into()), sym).into());
return self.subscribe_opinion_channel(messageHash, Value::Str("market.last.price".into()), marketId).await;
Value::Null
}
pub fn handle_ticker(&self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &message { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "tokenId": "19120407572139442221452465677574895365338028945317996490376653704877573103648",
// "outcomeSide": 1,
// "price": "0.85",
// "marketId": 2764,
// "msgType": "market.last.price"
// }
//
let mut tokenId: Option<String> = match __pro_message.get("tokenId").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
let mut outcomeObj: Value = self.safe_dict(self.exchange.outcomes_by_id.clone(), tokenId.clone().map(Value::from).unwrap_or(Value::Null), &[]);
let mut sym: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcome", &[]);
if (sym.is_none()) {
return;
}
let mut last: Value = (match __pro_message.get("price").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null });
let mut ticker: Value = self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), sym.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("info".to_string(), message);
m
}), &[outcomeObj]);
let mut cachedTickers: indexmap::IndexMap<String, Value> = self.safe_dict_k(self.options.clone(), "wsTickers", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).as_map().cloned().unwrap_or_default();
cachedTickers.insert(sym.as_deref().unwrap_or("null").to_string(), ticker.clone());
if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("wsTickers".into(), Value::Map(cachedTickers)); }
client.resolve(&[ticker, Value::Str(format!("{}{}", Value::Str("ticker::".into()), sym.map(Value::from).unwrap_or(Value::Null)).into())]);
}
/*
* @method
* @name opinion#watchTrades
* @description streams public trades of an outcome token
* @see https://docs.opinion.trade/developer-guide/opinion-websocket/market-channels
* @param {string} outcome unified outcome or outcome token id
* @param {int} [since] timestamp in ms of the earliest trade to return
* @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 marketId: Value = self.safe_integer_k(info, "marketId", &[]);
let mut sym: Value = self.safe_outcome_symbol(outcome, &[outcomeObj]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trades::".into()), sym).into());
let mut trades: Value = self.subscribe_opinion_channel(messageHash, Value::Str("market.last.trade".into()), marketId).await;
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
pub fn handle_trades(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &message { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "tokenId": "19120407572139442221452465677574895365338028945317996490376653704877573103648",
// "side": "Buy",
// "outcomeSide": 1,
// "price": "0.85",
// "shares": "10",
// "amount": "8.5",
// "marketId": 2764,
// "msgType": "market.last.trade"
// }
//
let mut tokenId: Option<String> = match __pro_message.get("tokenId").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
let mut outcomeObj: Value = self.safe_dict(self.exchange.outcomes_by_id.clone(), tokenId.clone().map(Value::from).unwrap_or(Value::Null), &[]);
let mut sym: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcome", &[]);
if (sym.is_none()) {
return;
}
let mut trade: Value = self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Null);
m.insert("info".to_string(), message.clone());
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("outcome".to_string(), sym.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
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(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower_k(message, "side", &[]));
m.insert("takerOrMaker".to_string(), Value::Str("taker".into()));
m.insert("price".to_string(), (match __pro_message.get("price").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("amount".to_string(), (match __pro_message.get("shares").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("cost".to_string(), (match __pro_message.get("amount").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("fee".to_string(), Value::Null);
m
}), &[outcomeObj]);
if (self.trades.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.trades = __t; }
}
if (self.safe_value(self.trades.clone(), sym.clone().map(Value::from).unwrap_or(Value::Null), &[]) == Value::Null) {
let mut tradesLimit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(sym.as_deref().unwrap_or("null").to_string(), ArrayCache::new(tradesLimit)); }
}
let mut stored: Value = (if let (Some(__m), Some(__k)) = (self.trades.as_map(), sym.as_deref()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
stored.append(trade);
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("trades::".into()), sym.map(Value::from).unwrap_or(Value::Null)).into())]);
}
/*
* @method
* @name opinion#watchOrders
* @description streams the authenticated user's order updates of one market - the venue channel is per-market, so the outcome argument is required
* @see https://docs.opinion.trade/developer-guide/opinion-websocket/user-channels
* @param {string} outcome unified outcome or outcome token id whose market to watch
* @param {int} [since] timestamp in ms of the earliest order to return
* @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
}));
if (outcome == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchOrders() requires an outcome (the order update channel is per-market)".into()))));
}
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 marketId: Value = self.safe_integer_k(info, "marketId", &[]);
let mut messageHash: String = "orders".to_string();
let mut orders: Value = self.subscribe_opinion_channel(Value::from(messageHash), Value::Str("trade.order.update".into()), marketId).await;
let mut sym: Value = self.safe_outcome_symbol(outcome, &[outcomeObj]);
return self.filter_by_value_since_limit(orders, Value::Str("outcome".into()), &[sym, since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @ignore
* @method
* @name opinion#parseWsOrderStatus
* @description maps the numeric order status of the websocket order channel onto the unified vocabulary
* @param {int} status the numeric order status
* @returns {string} a unified order status, or undefined
*/
pub fn parse_ws_order_status(&self, mut status: Value) -> Option<String> {
// per the venue docs: 1 pending, 2 finished, 3 canceled, 4 expired, 5 failed
if (status.as_f64() == Some(1.0)) {
return Value::Str("open".into()).as_str().map(str::to_owned);
}
if (status.as_f64() == Some(2.0)) {
return Value::Str("closed".into()).as_str().map(str::to_owned);
}
if (status.as_f64() == Some(3.0)) {
return Value::Str("canceled".into()).as_str().map(str::to_owned);
}
if (status.as_f64() == Some(4.0)) {
return Value::Str("expired".into()).as_str().map(str::to_owned);
}
if (status.as_f64() == Some(5.0)) {
return Value::Str("rejected".into()).as_str().map(str::to_owned);
}
return None;
}
pub fn handle_order(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &message { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "orderUpdateType": "orderConfirm",
// "marketId": 2770,
// "rootMarketId": 122,
// "orderId": "a11ee07e-e22f-11f0-9714-0a58a9feac02",
// "side": 1,
// "outcomeSide": 1,
// "price": "0.150000000000000000",
// "shares": "66.66",
// "amount": "9.999000000000000000",
// "status": 1,
// "tradingMethod": 2,
// "quoteToken": "0x55d398326f99059fF775485246999027B3197955",
// "createdAt": 1766735464,
// "expiresAt": 0,
// "chainId": "56",
// "filledShares": "10.000000000000000000",
// "filledAmount": "1.500000000000000000",
// "msgType": "trade.order.update"
// }
//
let mut marketId: Value = (match __pro_message.get("marketId").cloned() {
Some(Value::Int(__n)) => Value::Int(__n),
Some(Value::Float(__f)) => Value::Int(__f as i64),
Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } },
_ => Value::Null
});
let mut outcomeSide: Value = (match __pro_message.get("outcomeSide").cloned() {
Some(Value::Int(__n)) => Value::Int(__n),
Some(Value::Float(__f)) => Value::Int(__f as i64),
Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } },
_ => Value::Null
});
let mut outcomeObj: Value = self.opinion_outcome_by_market_id_side(marketId, outcomeSide);
let mut timestamp: Value = self.safe_timestamp_k(message.clone(), "createdAt", &[]);
// unlike the REST order body (0 buy / 1 sell), the websocket channel uses 1 buy / 2 sell
// per the docs and confirmed live
let mut sideInt: Value = (match __pro_message.get("side").cloned() {
Some(Value::Int(__n)) => Value::Int(__n),
Some(Value::Float(__f)) => Value::Int(__f as i64),
Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } },
_ => Value::Null
});
let mut side: String = "sell".to_string();
if (sideInt.as_f64() == Some(1.0)) {
side = "buy".to_string();
}
let mut tradingMethod: Value = (match __pro_message.get("tradingMethod").cloned() {
Some(Value::Int(__n)) => Value::Int(__n),
Some(Value::Float(__f)) => Value::Int(__f as i64),
Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } },
_ => Value::Null
});
let mut type_var: String = "limit".to_string();
if (tradingMethod.as_f64() == Some(1.0)) {
type_var = "market".to_string();
}
let mut order: Value = self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), (match __pro_message.get("orderId").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), message);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("status".to_string(), self.parse_ws_order_status((match __pro_message.get("status").cloned() { Some(Value::Int(__n)) => Value::Int(__n), Some(Value::Float(__f)) => Value::Int(__f as i64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n),
Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null })).map(Value::from).unwrap_or(Value::Null));
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
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(), Value::from(type_var));
m.insert("side".to_string(), Value::from(side));
m.insert("price".to_string(), (match __pro_message.get("price").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("amount".to_string(), (match __pro_message.get("shares").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("cost".to_string(), (match __pro_message.get("filledAmount").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("filled".to_string(), (match __pro_message.get("filledShares").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m
}), &[outcomeObj]);
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheByOutcomeById::new(limit);
}
let mut stored: Value = self.orders.clone();
stored.append(order);
client.resolve(&[stored, Value::Str("orders".into())]);
}
/*
* @method
* @name opinion#watchMyTrades
* @description streams the authenticated user's executed trades of one market - the venue channel is per-market, so the outcome argument is required
* @see https://docs.opinion.trade/developer-guide/opinion-websocket/user-channels
* @param {string} outcome unified outcome or outcome token id whose market to watch
* @param {int} [since] timestamp in ms of the earliest trade to return
* @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 (outcome == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" watchMyTrades() requires an outcome (the trade record channel is per-market)".into()))));
}
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 marketId: Value = self.safe_integer_k(info, "marketId", &[]);
let mut messageHash: String = "myTrades".to_string();
let mut trades: Value = self.subscribe_opinion_channel(Value::from(messageHash), Value::Str("trade.record.new".into()), marketId).await;
let mut sym: Value = self.safe_outcome_symbol(outcome, &[outcomeObj]);
return self.filter_by_value_since_limit(trades, Value::Str("outcome".into()), &[sym, since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
pub fn handle_my_trade(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &message { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "orderId": "3c7af25f-e21f-11f0-9714-0a58a9feac02",
// "tradeNo": "e1403840-e22f-11f0-83af-0a58a9feac02",
// "marketId": 2770,
// "rootMarketId": 122,
// "txHash": "0x272c...4195",
// "side": "Buy",
// "outcomeSide": 2,
// "price": "0.100000000000000000",
// "shares": "9.44444",
// "amount": "0.944444",
// "profit": "0.000000000000000000",
// "status": 2,
// "quoteToken": "0x55d398326f99059fF775485246999027B3197955",
// "fee": "0.000000000000000000",
// "chainId": "56",
// "createdAt": 1766735571,
// "msgType": "trade.record.new"
// }
//
let mut marketId: Value = (match __pro_message.get("marketId").cloned() {
Some(Value::Int(__n)) => Value::Int(__n),
Some(Value::Float(__f)) => Value::Int(__f as i64),
Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } },
_ => Value::Null
});
let mut outcomeSide: Value = (match __pro_message.get("outcomeSide").cloned() {
Some(Value::Int(__n)) => Value::Int(__n),
Some(Value::Float(__f)) => Value::Int(__f as i64),
Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } },
_ => Value::Null
});
let mut outcomeObj: Value = self.opinion_outcome_by_market_id_side(marketId, outcomeSide);
let mut sym: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcome", &[]);
let mut timestamp: Value = self.safe_timestamp_k(message.clone(), "createdAt", &[]);
let mut trade: Value = self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), (match __pro_message.get("tradeNo").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("info".to_string(), message.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("outcome".to_string(), sym.map(Value::from).unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
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(), (match __pro_message.get("orderId").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower_k(message, "side", &[]));
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("price".to_string(), (match __pro_message.get("price").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("amount".to_string(), (match __pro_message.get("shares").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("cost".to_string(), (match __pro_message.get("amount").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match __pro_message.get("fee").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null }));
m.insert("currency".to_string(), Value::Str("USDT".into()));
m
}));
m
}), &[outcomeObj]);
if (self.myTrades.clone() == Value::Null) {
let mut myTradesLimit: Value = self.safe_integer_k(self.options.clone(), "myTradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheByOutcomeById::new(myTradesLimit);
}
let mut stored: Value = self.myTrades.clone();
stored.append(trade);
client.resolve(&[stored, Value::Str("myTrades".into())]);
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
let mut errno: Value = self.safe_integer_k(response.clone(), "errno", &[]);
if (errno != Value::Null) && (errno.as_f64() != Some(0.0)) {
let mut errmsg: Value = self.safe_string_k(response, "errmsg", &[Value::Str("".into())]);
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), self.number_to_string(errno), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errmsg, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
/*
* @ignore
* @method
* @name opinion#sign
* @description builds the request url and attaches the apikey/EIP-712 authentication headers for private endpoints
* @param {string} path the endpoint path
* @param {string[]} api the api group and access level
* @param {string} method the http method
* @param {object} params the request parameters
* @returns {object} a dict with url, method, body and headers
*/
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("opinion".into())]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiGroup: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut access: Option<String> = api.get(1).and_then(Value::as_str).map(str::to_owned);
let mut baseUrls: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null);
let mut baseUrl: Value = self.safe_string(baseUrls.clone(), apiGroup, &[baseUrls.as_map().and_then(|__m| __m.get("opinion")).cloned().unwrap_or(Value::Null)]);
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseUrl, Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
let mut query: Value = self.omit(params, self.extract_params(path.clone()), &[]);
let mut existingHeaders: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut headersExtended: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Accept".to_string(), Value::Str("application/json".into()));
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m
}), &[Value::Map(existingHeaders)]);
if (access.as_deref() == Some("private")) {
if (path.as_str() == Some("auth/api-key")) {
// wallet-signature scheme: no apiKey involved, the signature itself is the credential
if (self.walletAddress.clone() == Value::Null) || (self.privateKey.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), path).into()), Value::Str(" requires a walletAddress and privateKey".into()))));
}
let mut actionByMethod: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("POST".to_string(), Value::Str("create".into()));
m.insert("GET".to_string(), Value::Str("get".into()));
m.insert("DELETE".to_string(), Value::Str("delete".into()));
m
});
let mut timestamp: Value = self.number_to_string(self.seconds());
add_element_to_object(&mut headersExtended, &Value::Str("OPINION_ADDRESS".into()), self.walletAddress.clone());
add_element_to_object(&mut headersExtended, &Value::Str("OPINION_SIGNATURE".into()), self.sign_api_key_auth(self.walletAddress.clone(), self.safe_string(Value::Map(actionByMethod), method.clone(), &[Value::Str("get".into())]), timestamp.clone()).map(Value::from).unwrap_or(Value::Null));
add_element_to_object(&mut headersExtended, &Value::Str("OPINION_TIMESTAMP".into()), timestamp);
} else {
// an empty this.apiKey counts as absent - deleteApiKey clears it to '' (the
// strict base types the credential as string, undefined can not be assigned)
let mut hasDirectApiKey: bool = !(self.is_empty_string(self.apiKey.clone()).as_bool() == Some(true));
let mut apiKey: Value = (if (hasDirectApiKey) { self.apiKey.clone() } else { self.safe_string_k(self.options.clone(), "apiKey", &[]) });
if (apiKey == Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), path).into()), Value::Str(" requires an apiKey - set it directly or call createApiKey()/fetchApiKey() first".into()))));
}
add_element_to_object(&mut headersExtended, &Value::Str("apikey".into()), apiKey);
}
}
let mut bodyValue: Value = Value::Null;
if (method.as_str() == Some("GET")) {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
}
} else {
bodyValue = json_stringify(&query);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), bodyValue);
m.insert("headers".to_string(), headersExtended);
m
});
Value::Null
}
}