// 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
// Generated from `ts/src/base/PredictionExchange.ts` — methods below the
// "METHODS BELOW THIS LINE ARE TRANSPILED" marker. Everything
// above the marker is hand-written (src/exchange.rs / src/prediction_exchange.rs).
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::ExchangeError;
use crate::exchange::Exchange;
use crate::exchange::ExchangeRuntime;
use crate::exchange::CallDynamicChecked;
use crate::exchange_generated::ExchangeBase;
use crate::prediction_exchange::PredictionRuntime;
use crate::prediction_exchange::PredictionExchange;
use crate::runtime::*;
pub trait PredictionBase: crate::exchange_generated::ExchangeBase {
/// Borrow the PredictionExchange holding the prediction-tier fields.
fn pred(&self) -> &crate::prediction_exchange::PredictionExchange;
fn pred_mut(&mut self) -> &mut crate::prediction_exchange::PredictionExchange;
fn describe(&self) -> Value {
return self.deep_extend(self.super_describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("approve".to_string(), Value::Bool(false));
m.insert("redeem".to_string(), Value::Bool(false));
m.insert("fetchEvent".to_string(), Value::Bool(false));
m.insert("fetchEvents".to_string(), Value::Bool(false));
m.insert("fetchOutcome".to_string(), Value::Bool(false));
m.insert("fetchSettlements".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(false));
m.insert("createOrders".to_string(), Value::Bool(false));
m.insert("createLimitOrder".to_string(), Value::Bool(false));
m.insert("createMarketOrder".to_string(), Value::Bool(false));
m.insert("createMarketOrderWs".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(false));
m.insert("cancelOrder".to_string(), Value::Bool(false));
m.insert("cancelOrders".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(false));
m.insert("editOrder".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(false));
m.insert("fetchOrder".to_string(), Value::Bool(false));
m.insert("fetchOrders".to_string(), Value::Bool(false));
m.insert("fetchOrdersByIds".to_string(), Value::Bool(false));
m.insert("fetchOrderTrades".to_string(), Value::Bool(false));
m.insert("fetchOpenOrders".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(false));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(false));
m.insert("fetchPosition".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(false));
m.insert("fetchAccounts".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchTicker".to_string(), Value::Bool(false));
m.insert("fetchTickers".to_string(), Value::Bool(false));
m.insert("fetchOrderBook".to_string(), Value::Bool(false));
m.insert("fetchL2OrderBook".to_string(), Value::Bool(false));
m.insert("fetchOHLCV".to_string(), Value::Bool(false));
m.insert("fetchTrades".to_string(), Value::Bool(false));
m.insert("fetchStatus".to_string(), Value::Bool(false));
m.insert("fetchTime".to_string(), Value::Bool(false));
m.insert("fetchOpenInterest".to_string(), Value::Bool(false));
m.insert("fetchTradingFee".to_string(), Value::Bool(false));
m.insert("watchTicker".to_string(), Value::Bool(false));
m.insert("watchTickers".to_string(), Value::Bool(false));
m.insert("watchOrderBook".to_string(), Value::Bool(false));
m.insert("watchTrades".to_string(), Value::Bool(false));
m.insert("watchOrders".to_string(), Value::Bool(false));
m.insert("watchMyTrades".to_string(), Value::Bool(false));
m.insert("watchOHLCV".to_string(), Value::Bool(false));
m.insert("watchPositions".to_string(), Value::Bool(false));
m
}));
m
})]);
Value::Null
}
fn is_prediction(&self) -> Value {
return self.safe_bool_k(self.has.clone(), "prediction", &[Value::Bool(false)]);
Value::Null
}
fn parse_search_queries(&self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __params_empty = indexmap::IndexMap::new();
let params = params.as_map().unwrap_or(&__params_empty);
// accepts either `query` (a single search string) or `queries` (a list of strings)
let mut singleQuery: Value = (match params.get("query") { 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 });
if (singleQuery != Value::Null) {
return Value::from(vec![singleQuery]);
}
return (match params.get("queries") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
Value::Null
}
fn require_event_query(&self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// fetchEvents must be scoped by at least one selector — an unfiltered call would page the
// entire exchange. require one of query / queries / tags / eventId / slug, or one of the
// venue-specific scope params an exchange declares in options['eventScopeParams'],
// e.g. kalshi's category / series_ticker
let mut query: Option<String> = self.safe_string_k(params.clone(), "query", &[]).as_str().map(str::to_owned);
let mut queries: Value = self.safe_list_k(params.clone(), "queries", &[Value::from(vec![])]);
let mut tags: Value = self.safe_list_k(params.clone(), "tags", &[Value::from(vec![])]);
let mut eventId: Option<String> = self.safe_string_k(params.clone(), "eventId", &[]).as_str().map(str::to_owned);
let mut slug: Option<String> = self.safe_string_k(params.clone(), "slug", &[]).as_str().map(str::to_owned);
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
let mut tagsLength: f64 = ((tags.len() as i64) as f64);
if (query.is_some()) || (queriesLength > ((0i64) as f64)) || (tagsLength > ((0i64) as f64)) || (eventId.is_some()) || (slug.is_some()) {
return Value::Null;
}
let mut extraScopeParams: Value = self.safe_list_k(self.options.clone(), "eventScopeParams", &[Value::from(vec![])]);
let mut extraScopeParamsLength: f64 = ((extraScopeParams.len() as i64) as f64);
let mut extraNames: Value = Value::Str("".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_181: bool = true;
while { if !__for_first_181 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_181 = false; i.as_f64().unwrap_or(f64::NAN) < extraScopeParamsLength } {
let mut scopeKey: Value = extraScopeParams.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (in_op(¶ms, &scopeKey)) {
return Value::Null;
}
extraNames = add(&Value::Str(format!("{}{}", extraNames, Value::Str(", ".into())).into()), &scopeKey);
}
}
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchEvents() requires at least one of query, queries, tags, eventId, slug".into())).into()), extraNames).into()), Value::Str(" to scope the search".into()))));
Value::Null
}
fn apply_event_fetch_params(&mut self, mut events: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut queries = get_arg(optional_args, 1, Value::Null);
let __params_empty = indexmap::IndexMap::new();
let params = params.as_map().unwrap_or(&__params_empty);
// applies the unified fetchEvents options client-side (eventId/slug/status/searchIn/sort/limit)
// so exchanges whose API can't filter natively still support them consistently.
// every fetched event lands in the cache before filtering, so loadEvents()/event()
// serve them later without another request
self.set_events(events.clone());
let mut result: Value = events;
let mut eventId: Value = (match params.get("eventId") { 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 slug: Value = (match params.get("slug") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (eventId != Value::Null) || (slug != Value::Null) {
let mut filtered: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_182: bool = true;
while { if !__for_first_182 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_182 = false; i.as_f64().unwrap_or(f64::NAN) < ((result.len() as i64) as f64) } {
let mut event: Value = result.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 idMatch: bool = (eventId != Value::Null) && (self.safe_string_k(event.clone(), "id", &[]).as_str() == eventId.as_str());
let mut slugMatch: bool = (slug != Value::Null) && (self.safe_string_k(event.clone(), "slug", &[]).as_str() == slug.as_str());
if idMatch || slugMatch {
append_to_array(&mut filtered, event);
}
}
}
result = filtered;
}
result = self.filter_events_by_status(result.clone(), &[(match params.get("status") { 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 })]);
result = self.filter_events_by_tags(result.clone(), &[(match params.get("tags") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::Null })]);
// own-line length read so the regex transpiler treats `queries` as an array (count())
// and not a string (strlen()); guard undefined since the default is undefined
let mut queriesLength: Value = Value::Int(0);
if (queries != Value::Null) {
queriesLength = Value::Int(queries.len() as i64);
}
if queriesLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
result = self.filter_events_by_search_in(result.clone(), queries, &[(match params.get("searchIn") { 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 sort: Option<String> = (match params.get("sort") { 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);
if (sort.is_some()) {
let mut sortKey: Value = Value::Null;
if (sort.as_deref() == Some("volume")) {
sortKey = Value::Str("volume".into());
} else if (sort.as_deref() == Some("liquidity")) {
sortKey = Value::Str("liquidity".into());
} else if (sort.as_deref() == Some("newest")) {
sortKey = Value::Str("created".into());
}
if (sortKey != Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_183: bool = true;
while { if !__for_first_183 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_183 = false; i.as_f64().unwrap_or(f64::NAN) < ((result.len() as i64) as f64) } {
{ let __be_tmp = self.safe_number(get_value(&result, &i), sortKey.clone(), &[Value::Int(0)]); add_element_to_object(get_value_mut(&mut result, &i), &sortKey, __be_tmp); };
}
}
result = self.sort_by(result.clone(), sortKey, &[Value::Bool(true), Value::Int(0)]);
}
}
let mut limit: Value = (match params.get("limit") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
if (limit != Value::Null) {
// clamp to the result length: arraySlice(x, 0, limit) with limit > length panics in Go
// via reflect Slice, and throws in C#, unlike JS/Python which return the whole array
let mut resultLength: Value = Value::Int(result.len() as i64);
let mut sliceEnd: Value = limit;
if sliceEnd.as_f64().unwrap_or(f64::NAN) > resultLength.as_f64().unwrap_or(f64::NAN) {
sliceEnd = resultLength;
}
result = self.array_slice(result.clone(), Value::Int(0), &[sliceEnd]);
}
return result;
Value::Null
}
fn filter_events_by_status(&self, mut events: Value, optional_args: &[Value]) -> Value {
let mut status = get_arg(optional_args, 0, Value::Null);
// 'active' | 'inactive' | 'closed' | 'all' — 'inactive' and 'closed' are interchangeable
if (status == Value::Null) || (status.as_str() == Some("all")) {
return events;
}
let mut wantActive: Value = (Value::Bool(status.as_str() == Some("active")));
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_184: bool = true;
while { if !__for_first_184 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_184 = false; i.as_f64().unwrap_or(f64::NAN) < ((events.len() as i64) as f64) } {
let mut event: Value = events.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 isActive: Value = self.safe_bool_k(event.clone(), "active", &[]);
// keep events whose status is unknown (already filtered server-side, no `active` field)
if (isActive == Value::Null) || (isActive.as_bool() == wantActive.as_bool()) {
append_to_array(&mut result, event);
}
}
}
return result;
Value::Null
}
fn filter_events_by_search_in(&self, mut events: Value, mut queries: Value, optional_args: &[Value]) -> Value {
let mut searchIn = get_arg(optional_args, 0, Value::Null);
// keep events whose title and/or description contains one of the queries (searchIn defaults to 'both')
// own-line length read so the regex transpiler uses count() (array) not strlen() (string)
let mut queriesLength: Value = Value::Int(0);
if (queries != Value::Null) {
queriesLength = Value::Int(queries.len() as i64);
}
if (searchIn == Value::Null) || (queries == Value::Null) || (queriesLength.as_f64() == Some(0.0)) {
return events;
}
let mut checkTitle: bool = (searchIn.as_str() == Some("title")) || (searchIn.as_str() == Some("both"));
let mut checkDescription: bool = (searchIn.as_str() == Some("description")) || (searchIn.as_str() == Some("both"));
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_186: bool = true;
while { if !__for_first_186 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_186 = false; i.as_f64().unwrap_or(f64::NAN) < ((events.len() as i64) as f64) } {
let mut event: Value = events.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 title: Value = self.safe_string_lower_k(event.clone(), "title", &[Value::Str("".into())]);
let mut description: Value = self.safe_string_lower_k(event.clone(), "description", &[Value::Str("".into())]);
let mut matched: bool = false;
{
let mut qi: Value = Value::Int(0);
let mut __for_first_185: bool = true;
while { if !__for_first_185 { qi = (match (&(qi), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_185 = false; qi.as_f64().unwrap_or(f64::NAN) < ((queries.len() as i64) as f64) } {
let mut q: Value = to_lower(&get_value(&queries, &qi));
if (title == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" filterEventsBySearchIn() missing title".into()))));
}
if checkTitle && (get_index_of(&title, &q).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) {
matched = true;
break;
}
if (description == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" filterEventsBySearchIn() missing description".into()))));
}
if checkDescription && (get_index_of(&description, &q).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) {
matched = true;
break;
}
}
}
if matched {
append_to_array(&mut result, event);
}
}
}
return result;
Value::Null
}
fn normalize_tag_key(&self, mut tag: Value) -> Value {
// reduce a tag to lowercase alphanumeric words joined by single spaces ("Fed Rates" /
// "fed-rates" / "FED_RATES" all become "fed rates") so label, slug and handle spellings
// of the same tag compare equal — venues surface tags in different forms and callers
// pass any of them. keeping the word boundary avoids cross-word false positives that
// plain concatenation would create ("us open" vs "household")
let mut lower: Value = to_lower(&tag);
let mut allowed: Value = Value::Str("abcdefghijklmnopqrstuvwxyz0123456789".into());
let mut chars: Value = self.string_to_chars_array(lower);
let mut s: Value = Value::Str("".into());
let mut pendingSep: bool = false;
{
let mut i: Value = Value::Int(0);
let mut __for_first_187: bool = true;
while { if !__for_first_187 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_187 = false; i.as_f64().unwrap_or(f64::NAN) < ((chars.len() as i64) as f64) } {
let mut ch: Value = chars.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if get_index_of(&allowed, &ch).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
if pendingSep && (s.as_str() != Some("")) {
s = Value::Str(format!("{}{}", s, Value::Str(" ".into())).into());
}
s = Value::Str(format!("{}{}", s, ch).into());
pendingSep = false;
} else {
pendingSep = true;
}
}
}
return s;
Value::Null
}
fn filter_events_by_tags(&self, mut events: Value, optional_args: &[Value]) -> Value {
let mut tags = get_arg(optional_args, 0, Value::Null);
// keep events carrying one of the requested tags; tolerant to string tags and to
// object tags ({ slug, title, ... }) since venues differ. no-op when no tags requested
if (tags == Value::Null) || (Value::Int(tags.len() as i64).as_f64() == Some(0.0)) {
return events;
}
let mut wanted: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_188: bool = true;
while { if !__for_first_188 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_188 = false; i.as_f64().unwrap_or(f64::NAN) < ((tags.len() as i64) as f64) } {
let mut wantedKey: Value = self.normalize_tag_key(tags.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
if (wantedKey.as_str() != Some("")) {
// an empty normalized key would substring-match every tag
append_to_array(&mut wanted, wantedKey);
}
}
}
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_191: bool = true;
while { if !__for_first_191 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_191 = false; i.as_f64().unwrap_or(f64::NAN) < ((events.len() as i64) as f64) } {
let mut event: Value = events.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 eventTags: Value = self.safe_list_k(event.clone(), "tags", &[Value::from(vec![])]);
let mut matched: bool = false;
{
let mut ti: Value = Value::Int(0);
let mut __for_first_190: bool = true;
while { if !__for_first_190 { ti = (match (&(ti), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_190 = false; ti.as_f64().unwrap_or(f64::NAN) < ((eventTags.len() as i64) as f64) } {
let mut tag: Value = eventTags.as_array().and_then(|__arr| match &ti { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut tagLabel: Value = Value::Null;
if matches!(&tag, Value::Str(_)) {
tagLabel = tag.clone();
} else {
tagLabel = self.safe_string2(tag, Value::Str("slug".into()), Value::Str("title".into()), &[]);
}
if (tagLabel != Value::Null) {
let mut tagKey: Value = self.normalize_tag_key(tagLabel);
{
let mut wi: Value = Value::Int(0);
let mut __for_first_189: bool = true;
while { if !__for_first_189 { wi = (match (&(wi), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_189 = false; wi.as_f64().unwrap_or(f64::NAN) < ((wanted.len() as i64) as f64) } {
if get_index_of(&tagKey, &wanted.as_array().and_then(|__arr| match &wi { 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)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
matched = true;
break;
}
}
}
}
if matched {
break;
}
}
}
if matched {
append_to_array(&mut result, event);
}
}
}
return result;
Value::Null
}
fn fetch_events(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_events", { let mut __args: Vec<crate::Value> = Vec::new(); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchEvents() is not supported yet".into()))));
Value::Null
} }
fn fetch_event(&mut self, mut id: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_event", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(id.clone()); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchEvent() is not supported yet".into()))));
Value::Null
} }
fn set_events(&mut self, mut events: Value) -> Value {
// merge (not reset) so successive scoped fetchEvents calls accumulate into the cache.
// index by the unified `event` handle too (that's the identifier every outcome's `event`
// field carries), so getEvent (handle) resolves without each exchange hand-writing it
if (self.pred().events.clone() == Value::Null) {
self.pred_mut().events = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if (self.pred().events_by_slug.clone() == Value::Null) {
self.pred_mut().events_by_slug = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_192: bool = true;
while { if !__for_first_192 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_192 = false; i.as_f64().unwrap_or(f64::NAN) < ((events.len() as i64) as f64) } {
let mut event: Value = events.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 id: Value = self.safe_string_k(event.clone(), "id", &[]);
let mut slug: Value = self.safe_string_k(event.clone(), "slug", &[]);
let mut handle: Value = self.safe_string_k(event.clone(), "event", &[]);
if (id != Value::Null) {
if let Value::Dict(__d) = &mut self.pred_mut().events { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&id), event.clone()); }
}
if (handle != Value::Null) {
if let Value::Dict(__d) = &mut self.pred_mut().events { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&handle), event.clone()); }
}
if (slug != Value::Null) {
if let Value::Dict(__d) = &mut self.pred_mut().events_by_slug { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&slug), event); }
}
}
}
return self.pred().events.clone();
Value::Null
}
fn events_list(&self) -> Value {
// the cached events as a list; empty on a cold instance (this.events is keyed by both
// id and handle, so de-duplicate by identity before returning)
if (self.pred().events.clone() == Value::Null) {
return Value::from(vec![]);
}
let mut result: Value = Value::from(vec![]);
let mut seen: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut keys: Value = object_keys(&self.pred().events);
{
let mut i: Value = Value::Int(0);
let mut __for_first_193: bool = true;
while { if !__for_first_193 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_193 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut event: Value = get_value(&self.pred().events, &keys.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 identity: Value = self.safe_string2(event.clone(), Value::Str("id".into()), Value::Str("event".into()), &[keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)]);
if !(in_op(&seen, &identity)) {
if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&identity), Value::Bool(true)); }
append_to_array(&mut result, event);
}
}
}
return result;
Value::Null
}
fn load_events_helper(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut reload = get_arg(optional_args, 0, Value::Bool(false));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// note: the cache-hit shortcut ignores params, so events fetched under one scope are
// returned for a later differently-scoped call. events are scoped (unlike global
// markets), so prefer fetchEvents (params) directly when you need a specific scope
if !is_true(&reload) && ((self.pred().events.clone() != Value::Null) && (self.pred().events.clone() != Value::Null)) {
return self.pred().events.clone();
}
let mut events: Value = self.fetch_events(&[params]).await;
return self.set_events(events);
Value::Null
} }
fn load_events(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut reload = get_arg(optional_args, 0, Value::Bool(false));
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.load_events_helper(&[reload, params]).await;
Value::Null
} }
fn get_event(&self, mut eventIdOrSlug: Value) -> Value {
// cache-only event resolver (the event analogue of this.outcome) - the cache fills
// through fetchEvents; this never fetches
if (self.pred().events.clone() != Value::Null) && (in_op(&self.pred().events, &eventIdOrSlug)) {
return get_value(&self.pred().events, &eventIdOrSlug);
}
if (self.pred().events_by_slug.clone() != Value::Null) && (in_op(&self.pred().events_by_slug, &eventIdOrSlug)) {
return get_value(&self.pred().events_by_slug, &eventIdOrSlug);
}
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" has no cached event ".into())).into()), eventIdOrSlug).into()), Value::Str(" - call fetchEvents ({ 'query': ... }) first".into()))));
Value::Null
}
fn outcome(&self, mut outcomeSymbol: Value) -> Value {
if (outcomeSymbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" outcome() requires an outcomeSymbol argument".into()))));
}
if (self.pred().outcomes.clone() == Value::Null) || self.is_empty(self.pred().outcomes.clone()).as_bool() == Some(true) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" outcomes not loaded - call loadOutcomes () or an outcome-addressed method first".into()))));
}
if (in_op(&self.pred().outcomes, &outcomeSymbol)) {
return get_value(&self.pred().outcomes, &outcomeSymbol);
}
if (self.pred().outcomes_by_id.clone() != Value::Null) && (in_op(&self.pred().outcomes_by_id, &outcomeSymbol)) {
return get_value(&self.pred().outcomes_by_id, &outcomeSymbol);
}
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" does not have outcome ".into())).into()), outcomeSymbol).into()), Value::Str(" - pass a known outcome handle or outcomeId, or call fetchEvents ()/loadOutcomes () first".into()))));
Value::Null
}
fn has_outcome(&self, mut outcomeIdOrSymbol: Value) -> Value {
// sync cache-only membership probe — never throws and never fetches. this is the predicate
// behind loadOutcome's fast path and loadOutcomes' miss filter; safeOutcome (stub on miss)
// and outcome (throws on miss) are the accessors
if (outcomeIdOrSymbol == Value::Null) {
return Value::Bool(false);
}
if (self.pred().outcomes.clone() != Value::Null) && (in_op(&self.pred().outcomes, &outcomeIdOrSymbol)) {
return Value::Bool(true);
}
if (self.pred().outcomes_by_id.clone() != Value::Null) && (in_op(&self.pred().outcomes_by_id, &outcomeIdOrSymbol)) {
return Value::Bool(true);
}
return Value::Bool(false);
Value::Null
}
fn safe_outcome(&self, mut outcomeIdOrSymbol: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = get_arg(optional_args, 0, Value::Null);
if (outcomeIdOrSymbol != Value::Null) {
if (self.pred().outcomes.clone() != Value::Null) && (in_op(&self.pred().outcomes, &outcomeIdOrSymbol)) {
return get_value(&self.pred().outcomes, &outcomeIdOrSymbol);
}
if (self.pred().outcomes_by_id.clone() != Value::Null) && (in_op(&self.pred().outcomes_by_id, &outcomeIdOrSymbol)) {
return get_value(&self.pred().outcomes_by_id, &outcomeIdOrSymbol);
}
}
if (outcomeObj != Value::Null) {
return outcomeObj;
}
// stub for an unknown handle; it only carries the identity keys, not the market fields
let mut outcomeObjValue: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), outcomeIdOrSymbol.clone());
m.insert("outcomeId".to_string(), outcomeIdOrSymbol);
m.insert("market".to_string(), Value::Null);
m.insert("label".to_string(), Value::Null);
m.insert("event".to_string(), Value::Null);
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
});
return outcomeObjValue;
Value::Null
}
fn safe_outcome_symbol(&self, mut outcomeIdOrSymbol: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = get_arg(optional_args, 0, Value::Null);
let mut outcomeObjValue: Value = self.safe_outcome(outcomeIdOrSymbol, &[outcomeObj]);
return crate::value::get_value_k(&outcomeObjValue, "outcome");
Value::Null
}
fn shorten_slug(&self, mut slug: Value) -> Value {
let mut replacements: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("federal-reserve".to_string(), Value::Str("fed".into()));
m.insert("interest-rates".to_string(), Value::Str("rates".into()));
m.insert("interest-rate".to_string(), Value::Str("rate".into()));
m.insert("basis-points".to_string(), Value::Str("bps".into()));
m.insert("basis-point".to_string(), Value::Str("bp".into()));
m.insert("executive-order".to_string(), Value::Str("eo".into()));
m.insert("united-states".to_string(), Value::Str("us".into()));
m.insert("united-kingdom".to_string(), Value::Str("uk".into()));
m.insert("european-union".to_string(), Value::Str("eu".into()));
m.insert("artificial-intelligence".to_string(), Value::Str("ai".into()));
m.insert("republican-party".to_string(), Value::Str("gop".into()));
m.insert("democratic-party".to_string(), Value::Str("dems".into()));
m.insert("stock-market".to_string(), Value::Str("market".into()));
m.insert("price-target".to_string(), Value::Str("pt".into()));
m.insert("market-cap".to_string(), Value::Str("mcap".into()));
m.insert("increase".to_string(), Value::Str("hike".into()));
m.insert("decrease".to_string(), Value::Str("cut".into()));
m.insert("higher".to_string(), Value::Str("up".into()));
m.insert("lower".to_string(), Value::Str("down".into()));
m.insert("greater".to_string(), Value::Str("gt".into()));
m.insert("less".to_string(), Value::Str("lt".into()));
m.insert("million".to_string(), Value::Str("M".into()));
m.insert("billion".to_string(), Value::Str("B".into()));
m.insert("trillion".to_string(), Value::Str("T".into()));
m.insert("percent".to_string(), Value::Str("pct".into()));
m
});
let mut stopWords: Value = Value::from(vec![Value::Str("will".into()), Value::Str("the".into()), Value::Str("a".into()), Value::Str("an".into()), Value::Str("after".into()), Value::Str("before".into()), Value::Str("in".into()), Value::Str("at".into()), Value::Str("by".into()), Value::Str("of".into()), Value::Str("there".into()), Value::Str("be".into()), Value::Str("to".into()), Value::Str("or".into()), Value::Str("and".into()), Value::Str("for".into()), Value::Str("on".into()), Value::Str("its".into()), Value::Str("that".into()), Value::Str("this".into()), Value::Str("from".into()), Value::Str("with".into()), Value::Str("as".into()), Value::Str("is".into()), Value::Str("are".into()), Value::Str("was".into()), Value::Str("were".into()), Value::Str("?".into()), Value::Str("how".into()), Value::Str("many".into()), Value::Str("who".into()), Value::Str("what".into()), Value::Str("when".into()), Value::Str("where".into()), Value::Str("which".into()), Value::Str("much".into())]);
let mut lower: Value = (if (slug == Value::Null) { Value::Str("".into()) } else { to_lower(&slug) });
let mut allowed: Value = Value::Str("abcdefghijklmnopqrstuvwxyz0123456789".into());
let mut chars: Value = self.string_to_chars_array(lower);
let mut s: Value = Value::Str("".into());
let mut lastDash: bool = true; // start true to drop leading separators
{
let mut i: Value = Value::Int(0);
let mut __for_first_194: bool = true;
while { if !__for_first_194 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_194 = false; i.as_f64().unwrap_or(f64::NAN) < ((chars.len() as i64) as f64) } {
let mut ch: Value = chars.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if get_index_of(&allowed, &ch).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
s = Value::Str(format!("{}{}", s, ch).into());
lastDash = false;
} else if !lastDash {
s = Value::Str(format!("{}{}", s, Value::Str("-".into())).into());
lastDash = true;
}
}
}
let mut replacementKeys: Value = object_keys(&replacements);
{
let mut i: Value = Value::Int(0);
let mut __for_first_195: bool = true;
while { if !__for_first_195 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_195 = false; i.as_f64().unwrap_or(f64::NAN) < ((replacementKeys.len() as i64) as f64) } {
let mut replacementKey: Value = replacementKeys.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 replacementValue: Value = self.safe_string(replacements.clone(), replacementKey.clone(), &[]);
if (replacementValue != Value::Null) {
s = replace_all_str(&s, &replacementKey, &replacementValue);
}
}
}
let mut rawParts: Value = split(&s, &Value::Str("-".into()));
let mut parts: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_196: bool = true;
while { if !__for_first_196 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_196 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawParts.len() as i64) as f64) } {
let mut w: Value = rawParts.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if ((w.len() as i64) as f64) > ((0i64) as f64) && !(self.in_array(w.clone(), stopWords.clone()).as_bool() == Some(true)) {
append_to_array(&mut parts, w);
}
}
}
let mut joined: Value = join(&parts, &Value::Str("_".into()));
return to_upper(&joined);
Value::Null
}
fn slug_to_market_symbol(&self, mut eventSlug: Value, mut marketSlug: Value) -> Value {
// eventSlug is nullable (Str): markets without a parent event (e.g. myriad's 1:1 markets)
// pass undefined — the body already collapses an absent event to just the market part.
// a strict `string` param would make PHP/typed transpilers throw on null before the body runs.
// qualify the market handle with its event so two events that share a market label
// — e.g. kalshi's KXFEDDECISION-28JAN and -27OCT both list "Cut 25bps" — do NOT collapse
// to the same handle — a collision silently overwrites markets in this.markets and would
// resolve an outcome to the wrong event (wrong-market trade). skip the prefix when the
// event slug is absent or identical to the market slug (e.g. myriad's 1:1 markets), so
// already-unique handles stay clean.
let mut marketPart: Value = self.shorten_slug(marketSlug);
let mut eventPart: Value = self.shorten_slug(eventSlug);
if (eventPart == Value::Null) || (eventPart.as_str() == Some("")) || (eventPart.as_str() == marketPart.as_str()) {
return marketPart;
}
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", eventPart, Value::Str("_".into())).into()), marketPart).into());
Value::Null
}
fn slug_to_outcome_symbol(&self, mut eventSlug: Value, mut marketSlug: Value, mut outcome: Value) -> Value {
// build on slugToMarketSymbol so the outcome handle stays consistent with the market symbol
// — both event-qualified or both not — otherwise a qualified market + unqualified outcome mismatch.
// the label gets a light slug treatment (uppercase alphanumerics joined by '_', no stop-word
// removal so labels like "UP OR DOWN" survive intact) — venue labels with spaces or
// currency symbols ("JD Vance", a dollar-sign price) yield clean handles (JD_VANCE, 120)
// instead of leaking raw text into the outcome handle
let mut outcomeValue: Value = (if (outcome == Value::Null) { Value::Str("".into()) } else { outcome });
let mut upper: Value = to_upper(&outcomeValue);
let mut allowed: Value = Value::Str("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".into());
let mut chars: Value = self.string_to_chars_array(upper.clone());
let mut label: Value = Value::Str("".into());
let mut pendingSep: bool = false;
{
let mut i: Value = Value::Int(0);
let mut __for_first_197: bool = true;
while { if !__for_first_197 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_197 = false; i.as_f64().unwrap_or(f64::NAN) < ((chars.len() as i64) as f64) } {
let mut ch: Value = chars.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if get_index_of(&allowed, &ch).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
if pendingSep && (label.as_str() != Some("")) {
label = Value::Str(format!("{}{}", label, Value::Str("_".into())).into());
}
label = Value::Str(format!("{}{}", label, ch).into());
pendingSep = false;
} else {
pendingSep = true;
}
}
}
if (label.as_str() == Some("")) {
// a label with no alphanumerics at all (unrealistic, but keep the :LABEL contract)
label = upper;
}
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.slug_to_market_symbol(eventSlug, marketSlug), Value::Str(":".into())).into()), label).into());
Value::Null
}
fn set_markets(&mut self, mut markets: Value, optional_args: &[Value]) -> Value {
let mut currencies = get_arg(optional_args, 0, Value::Null);
// prediction market rows carry only the unified `market` handle — `symbol` is
// deprecated there. the base indexer keys this.markets/this.symbols by 'symbol',
// so alias the handle onto a shallow copy per row; the caller's rows stay symbol-free
let mut marketsList: Value = self.to_array(markets);
let mut aliased: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_198: bool = true;
while { if !__for_first_198 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_198 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketsList.len() as i64) as f64) } {
let mut row: Value = marketsList.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 copy: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[row.clone()]);
add_element_to_object(&mut copy, &Value::Str("symbol".into()), self.safe_string2(row, Value::Str("market".into()), Value::Str("symbol".into()), &[]));
append_to_array(&mut aliased, copy);
}
}
let mut stored: Value = self.super_set_markets(aliased, currencies);
// strip the alias back off the stored rows — venues assemble user-visible event
// structures from this.markets (hyperliquid groups its outcome markets that way),
// so a leftover 'symbol' key would leak the deprecated field back to the caller
let mut marketKeys: Value = object_keys(&stored);
{
let mut i: Value = Value::Int(0);
let mut __for_first_199: bool = true;
while { if !__for_first_199 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_199 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketKeys.len() as i64) as f64) } {
let mut key: Value = marketKeys.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 __be_tmp = self.omit(get_value(&stored, &key), Value::Str("symbol".into()), &[]); add_element_to_object(&mut stored, &key, __be_tmp); };
}
}
self.populate_outcomes();
return stored;
Value::Null
}
fn index_market_outcomes(&mut self, mut market: Value) {
// index one market's outcome tokens into this.outcomes / this.outcomes_by_id,
// normalizing each to the canonical identity keys (outcome / outcomeId / market) so
// consumers and the safe* helpers stay uniform even when an exchange's parseMarket
// still emits the legacy symbol / id / marketSymbol keys. used both by populateOutcomes
// for a full rebuild and by on-demand single-market fetches (kalshi fetchOutcome), so a
// cache miss doesn't force a full O(markets x outcomes) rebuild per new outcome
if (self.pred().outcomes.clone() == Value::Null) {
self.pred_mut().outcomes = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
if (self.pred().outcomes_by_id.clone() == Value::Null) {
self.pred_mut().outcomes_by_id = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
let mut outcomesList: Value = self.safe_list_k(market, "outcomes", &[Value::from(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_200: bool = true;
while { if !__for_first_200 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_200 = false; j.as_f64().unwrap_or(f64::NAN) < ((outcomesList.len() as i64) as f64) } {
let mut oc: Value = outcomesList.as_array().and_then(|__arr| match &j { 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 ocSymbol: Value = self.safe_string2(oc.clone(), Value::Str("outcome".into()), Value::Str("symbol".into()), &[]);
let mut ocId: Value = self.safe_string2(oc.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]);
// assign unconditionally — safeString2 keeps the canonical key when present
// and falls back to the legacy one, so this never clobbers and avoids a
// missing-key access that throws in Python/PHP, unlike TS undefined
add_element_to_object(&mut oc, &Value::Str("outcomeId".into()), ocId.clone());
{ let __be_tmp = self.safe_string2(oc.clone(), Value::Str("market".into()), Value::Str("marketSymbol".into()), &[]); add_element_to_object(&mut oc, &Value::Str("market".into()), __be_tmp); };
if (ocSymbol != Value::Null) {
// shortenSlug is lossy, so two different markets can produce the same handle.
// on a real collision of same handle but different outcomeId, disambiguate the
// second one deterministically instead of silently overwriting the first —
// trading the wrong market would otherwise be indistinguishable
let mut existing: Value = self.safe_value(self.pred().outcomes.clone(), ocSymbol.clone(), &[]);
if (existing != Value::Null) {
let mut existingId: Value = self.safe_string_k(existing, "outcomeId", &[]);
if (existingId != Value::Null) && (ocId != Value::Null) && (existingId.as_str() != ocId.as_str()) {
let mut idLen: Value = Value::Int(ocId.len() as i64);
let mut suffix: Value = ocId.clone();
if idLen.as_f64().unwrap_or(f64::NAN) > ((6i64) as f64) {
suffix = slice(&ocId, &(match (&(idLen), &(Value::Int(6))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &Value::Null);
}
ocSymbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", ocSymbol, Value::Str("_".into())).into()), to_upper(&suffix)).into());
}
}
add_element_to_object(&mut oc, &Value::Str("outcome".into()), ocSymbol.clone());
if let Value::Dict(__d) = &mut self.pred_mut().outcomes { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&ocSymbol), oc.clone()); }
} else {
add_element_to_object(&mut oc, &Value::Str("outcome".into()), ocSymbol);
}
if (ocId != Value::Null) {
if let Value::Dict(__d) = &mut self.pred_mut().outcomes_by_id { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&ocId), oc); }
}
}
}
}
fn populate_outcomes(&mut self) {
// rebuild the whole outcome lookup cache from this.markets (each market carries its
// outcome tokens under the outcomes key) so cached market data works offline. no-op on
// a cold instance where markets are not loaded yet (avoids a null-access crash on the
// eventId/slug-only fetchEvents path)
self.pred_mut().outcomes = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
self.pred_mut().outcomes_by_id = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (self.markets.clone() == Value::Null) {
return;
}
let mut marketKeys: Value = object_keys(&self.markets);
{
let mut i: Value = Value::Int(0);
let mut __for_first_201: bool = true;
while { if !__for_first_201 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_201 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketKeys.len() as i64) as f64) } {
self.index_market_outcomes(get_value(&self.markets, &marketKeys.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)));
}
}
}
fn index_event_outcomes(&mut self, mut event: Value) {
// register a single event's markets into this.markets and rebuild the outcome cache so the
// handles fetchEvent() returns resolve immediately in outcome-addressed methods (fetchTicker,
// createOrder, ...). without this, on a cold instance or a loadAllOutcomes:false venue
// such as kalshi, the returned handles are unusable — fetchTicker(ev.markets[0].outcomes[0].outcome)
// BadSymbols because the outcome was never cached
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut markets: Value = self.safe_list_k(event, "markets", &[Value::from(vec![])]);
let mut marketsLength: f64 = ((markets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_202: bool = true;
while { if !__for_first_202 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_202 = false; i.as_f64().unwrap_or(f64::NAN) < marketsLength } {
let mut m: Value = markets.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 marketHandle: Value = self.safe_string2(m.clone(), Value::Str("market".into()), Value::Str("symbol".into()), &[]);
if (marketHandle != Value::Null) {
if let Value::Dict(__d) = &mut self.markets { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&marketHandle), m); }
}
}
}
self.populate_outcomes();
}
fn load_outcomes<'ccxt_rec>(&'ccxt_rec mut self, optional_args: &'ccxt_rec [Value]) -> ::std::pin::Pin<Box<dyn ::std::future::Future<Output = Value> + Send + 'ccxt_rec>> { Box::pin(async move {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut reload = get_arg(optional_args, 1, Value::Bool(false));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// outcome-addressed methods call this first, mirroring loadMarkets(). two modes:
// - an `outcomes` list (scoped): sync-filter the cache and resolve ONLY the misses through
// fetchOutcomes — venues with a batch by-id endpoint (kalshi, polymarket) override it to
// collapse all misses into one request; a warm cache returns with zero per-outcome awaits
// - no `outcomes` (bulk): load the capped markets listing once and index every outcome —
// idempotent unless reload; only worth paying on venues whose whole universe is one
// cheap request (hyperliquid), or when the user explicitly wants the top-N set
// loadMarkets()/populateOutcomes() rebuild the lookup caches explicitly (the setMarkets
// override is not dispatched by the base loadMarkets under the Go/C#/Java transpilers)
if (outcomes != Value::Null) {
let mut missing: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_203: bool = true;
while { if !__for_first_203 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_203 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomes.len() as i64) as f64) } {
if is_true(&reload) || !(self.has_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)).as_bool() == Some(true)) {
append_to_array(&mut missing, 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 missingLength: Value = Value::Int(missing.len() as i64);
let mut wasWarm: bool = (self.pred().outcomes.clone() != Value::Null) && !(self.is_empty(self.pred().outcomes.clone()).as_bool() == Some(true));
let mut loadAll: Value = self.safe_bool_k(self.options.clone(), "loadAllOutcomes", &[Value::Bool(false)]);
if (missingLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) && (loadAll.as_bool() == Some(true)) && !wasWarm && !is_true(&reload) {
// same trade-off as loadOutcome: on venues where the whole universe is one cheap
// request (hyperliquid), a cold miss bulk-warms once instead of fetching per outcome
self.load_outcomes(&[]).await;
let mut stillMissing: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_204: bool = true;
while { if !__for_first_204 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_204 = false; i.as_f64().unwrap_or(f64::NAN) < missingLength.as_f64().unwrap_or(f64::NAN) } {
if !(self.has_outcome(missing.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)).as_bool() == Some(true)) {
append_to_array(&mut stillMissing, missing.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));
}
}
}
missing = stillMissing;
missingLength = Value::Int(missing.len() as i64);
}
if missingLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
self.fetch_outcomes(missing).await;
}
return self.pred().outcomes.clone();
}
if !is_true(&reload) && (self.pred().outcomes.clone() != Value::Null) && !(self.is_empty(self.pred().outcomes.clone()).as_bool() == Some(true)) {
return self.pred().outcomes.clone();
}
self.load_markets(&[reload, params]).await;
self.populate_outcomes();
return self.pred().outcomes.clone();
Value::Null
}) }
/*
* @ignore
* @method
* @name PredictionExchange#fetchOutcomes
* @description resolves several uncached outcomes. the base has no batch by-id endpoint, so it fetches them one by one through fetchOutcome (which throws BadSymbol for an unresolvable one); venues with a batch endpoint (kalshi, polymarket) override this to collapse the list into one request
* @param {string[]} outcomeSymbols the uncached outcome handles or ids to resolve
* @returns {object} the outcome cache
*/
fn fetch_outcomes(&mut self, mut outcomeSymbols: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_outcomes", vec![outcomeSymbols.clone()]).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_205: bool = true;
while { if !__for_first_205 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_205 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomeSymbols.len() as i64) as f64) } {
self.fetch_outcome(outcomeSymbols.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)).await;
}
}
return self.pred().outcomes.clone();
Value::Null
} }
fn load_outcome(&mut self, mut outcomeSymbol: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut reload = get_arg(optional_args, 0, Value::Bool(false));
// resolve a single outcome — the per-outcome analogue of loadMarkets()+market(). a cache hit
// returns at once (pass reload=true to skip the cache and refetch the outcome's metadata).
// on a miss, fetchOutcome resolves just the requested outcome on demand — a by-id fetch on
// venues with such an endpoint (kalshi, polymarket) or the venue's scoped search otherwise.
// options.loadAllOutcomes (default false) opts back into the legacy bulk warm-up: the first
// miss loads the whole (capped) listing once so later lookups are 0-network hits — only
// sane on venues whose full universe is one cheap request (hyperliquid)
if (outcomeSymbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" loadOutcome() requires an outcomeSymbol argument".into()))));
}
if !is_true(&reload) {
if self.has_outcome(outcomeSymbol.clone()).as_bool() == Some(true) {
return self.safe_outcome(outcomeSymbol.clone(), &[]);
}
let mut wasWarm: bool = (self.pred().outcomes.clone() != Value::Null) && !(self.is_empty(self.pred().outcomes.clone()).as_bool() == Some(true));
// if markets are already loaded (offline-injected, or loaded by loadMarkets/fetchEvents)
// but the outcome cache is cold, index them for free before hitting the network — this
// makes cold-cache resolution consistent across languages regardless of loadAllOutcomes
if !wasWarm && (self.markets.clone() != Value::Null) && !(self.is_empty(self.markets.clone()).as_bool() == Some(true)) {
self.populate_outcomes();
if self.has_outcome(outcomeSymbol.clone()).as_bool() == Some(true) {
return self.safe_outcome(outcomeSymbol.clone(), &[]);
}
}
let mut loadAll: Value = self.safe_bool_k(self.options.clone(), "loadAllOutcomes", &[Value::Bool(false)]);
if (loadAll.as_bool() == Some(true)) && !wasWarm {
// a miss on a cold cache: bulk-load once so later lookups are 0-network hits.
// a miss on an already-warm cache is authoritative — the outcome genuinely isn't
// listed, so fall through to fetchOutcome (a real BadSymbol) rather than refetching
// the whole listing (which would mask typos and clobber offline-injected markets)
self.load_outcomes(&[]).await;
if self.has_outcome(outcomeSymbol.clone()).as_bool() == Some(true) {
return self.safe_outcome(outcomeSymbol.clone(), &[]);
}
}
}
return self.fetch_outcome(outcomeSymbol).await;
Value::Null
} }
fn outcome_search_query(&self, mut outcomeSymbol: Value) -> Value {
// derive a human search query from a unified outcome handle (EVENT_MARKET:LABEL) so a
// cache miss can be resolved through the venue's scoped search instead of a bulk listing
// download. returns undefined for id-like inputs (numeric token ids, 0x hashes) that
// carry no searchable words
let mut marketPart: Value = outcomeSymbol.clone();
let mut colonIndex: Value = Value::Int(outcomeSymbol.as_str().and_then(|__s| __s.find(":")).map(|__i| __i as i64).unwrap_or(-1));
if colonIndex.as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
marketPart = slice(&outcomeSymbol, &Value::Int(0), &colonIndex);
}
if (Value::Int(marketPart.as_str().and_then(|__s| __s.find("0x")).map(|__i| __i as i64).unwrap_or(-1)).as_f64() == Some(0.0)) {
return Value::Null;
}
// handles join words with '_' (slug-derived) or legacy '-' separated inputs (normalized below)
let mut normalized: Value = replace_all_str(&to_lower(&marketPart), &Value::Str("-".into()), &Value::Str("_".into()));
let mut rawWords: Value = split(&normalized, &Value::Str("_".into()));
let mut words: Value = Value::from(vec![]);
let mut hasLetters: bool = false;
let mut letters: Value = Value::Str("abcdefghijklmnopqrstuvwxyz".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_207: bool = true;
while { if !__for_first_207 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_207 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawWords.len() as i64) as f64) } {
let mut word: Value = rawWords.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);
// inline .length so the php transpiler emits strlen() — the standalone
// `const n = str.length;` statement form wrongly becomes count() (array)
if (Value::Int(word.len() as i64).as_f64() == Some(0.0)) {
continue;
}
let mut wordHasLetters: bool = false;
let mut chars: Value = self.string_to_chars_array(word.clone());
{
let mut ci: Value = Value::Int(0);
let mut __for_first_206: bool = true;
while { if !__for_first_206 { ci = (match (&(ci), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_206 = false; ci.as_f64().unwrap_or(f64::NAN) < ((chars.len() as i64) as f64) } {
if get_index_of(&letters, &chars.as_array().and_then(|__arr| match &ci { 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)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
wordHasLetters = true;
break;
}
}
}
// the query is the handle's letter-bearing words only. standalone numeric
// tokens (slug timestamps, strikes, years) are venue artifacts that title searches don't
// reliably index — and since the result is re-checked against the EXACT handle,
// a broader query only adds recall, never a wrong match
if !wordHasLetters {
continue;
}
append_to_array(&mut words, word);
hasLetters = true;
}
}
let mut wordsLength: f64 = ((words.len() as i64) as f64);
if (wordsLength == 0.0) || !hasLetters {
return Value::Null;
}
return join(&words, &Value::Str(" ".into()));
Value::Null
}
fn fetch_outcome(&mut self, mut outcomeSymbol: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_outcome", vec![outcomeSymbol.clone()]).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
// fetch just one outcome on demand — never through a bulk listing download. the base has
// no generic by-id endpoint, so it derives a search query from the handle and resolves it
// through the venue's own scoped fetchEvents (which caches everything it finds), then
// re-checks the cache. venues with a real by-id fetch (kalshi by ticker, polymarket by
// token id) override this with a cheaper single fetch and fall back to super on a miss.
let mut searchQuery: Value = self.outcome_search_query(outcomeSymbol.clone());
if (searchQuery != Value::Null) && matches!(self.safe_bool_k(self.has.clone(), "fetchEvents", &[Value::Bool(false)]), Value::Bool(true)) {
let mut searchLimit: Value = self.safe_integer_k(self.options.clone(), "fetchOutcomeSearchLimit", &[Value::Int(10)]);
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
self.fetch_events(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("query".to_string(), searchQuery);
m.insert("limit".to_string(), searchLimit);
m
})]).await;
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
// a query with zero matches surfaces as BadSymbol on some venues — treat it as a
// plain miss (the guidance-rich throw below); let real transport errors propagate
if !(matches!(&e, Value::Str(__s) if __s.contains("[BadSymbol]"))) {
panic!("{}", e);
}
}
if self.has_outcome(outcomeSymbol.clone()).as_bool() == Some(true) {
return self.safe_outcome(outcomeSymbol.clone(), &[]);
}
}
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" could not resolve outcome ".into())).into()), outcomeSymbol).into()), Value::Str(" — call fetchEvents ({ 'query': ... }) first, or pass a known outcomeId".into()))));
Value::Null
} }
/*
* @method
* @name fetchTicker
* @description fetches a price ticker for a single prediction outcome
* @param {string} outcome unified outcome handle
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [ticker structure](https://docs.ccxt.com/#/?id=ticker-structure)
*/
fn fetch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_ticker", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(outcome); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchTicker() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchTickers
* @description fetches price tickers for multiple prediction outcomes at once
* @param {string[]} [outcomes] unified outcome handles or outcome ids
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a dictionary of prediction [ticker structures](https://docs.ccxt.com/#/?id=ticker-structure) indexed by outcome
*/
fn fetch_tickers(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_tickers", { let mut __args: Vec<crate::Value> = Vec::new(); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchTickers() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchOrderBook
* @description fetches the order book for a prediction outcome
* @param {string} outcome unified outcome handle
* @param {int} [limit] the maximum number of order book entries to return
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [order book structure](https://docs.ccxt.com/#/?id=order-book-structure)
*/
fn fetch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_order_book", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(outcome); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOrderBook() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchOHLCV
* @description fetches historical candlestick data for a prediction outcome
* @param {string} outcome unified outcome handle
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum number of candles to fetch
* @param {object} [params] extra exchange-specific parameters
* @returns {int[][]} a list of candles ordered as timestamp, open, high, low, close, volume
*/
fn fetch_ohlcv(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_ohlcv", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(outcome.clone()); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.super_fetch_ohlcv(outcome, timeframe, since, limit, params).await;
Value::Null
} }
/*
* @method
* @name fetchTrades
* @description get the list of most recent trades for a prediction outcome
* @param {string} outcome unified outcome handle
* @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 exchange-specific parameters
* @returns {object[]} a list of prediction [trade structures](https://docs.ccxt.com/#/?id=public-trades)
*/
fn fetch_trades(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_trades", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(outcome); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchTrades() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name createOrder
* @description create a trade order on a prediction outcome
* @param {string} outcome unified outcome handle
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how many shares of the outcome to trade
* @param {float} [price] the price at which the order is to be filled, in cost per share
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [order structure](https://docs.ccxt.com/#/?id=order-structure)
*/
fn create_order(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("create_order", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(outcome); __args.push(type_var); __args.push(side); __args.push(amount); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name cancelOrder
* @description cancels an open order
* @param {string} id order id
* @param {string} [outcome] unified outcome handle
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [order structure](https://docs.ccxt.com/#/?id=order-structure)
*/
fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("cancel_order", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(id.clone()); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name watchTicker
* @description watches a price ticker for a single prediction outcome
* @param {string} outcome unified outcome handle
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [ticker structure](https://docs.ccxt.com/#/?id=ticker-structure)
*/
fn watch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchTicker() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name watchOrderBook
* @description watches the order book for a prediction outcome
* @param {string} outcome unified outcome handle
* @param {int} [limit] the maximum number of order book entries to return
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [order book structure](https://docs.ccxt.com/#/?id=order-book-structure)
*/
fn watch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBook() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name watchTrades
* @description watches the most recent trades for a prediction outcome
* @param {string} outcome unified outcome handle
* @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 exchange-specific parameters
* @returns {object[]} a list of prediction [trade structures](https://docs.ccxt.com/#/?id=public-trades)
*/
fn watch_trades(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchTrades() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchOrders
* @description fetches information on multiple orders made by the user
* @param {string} [outcome] unified outcome handle
* @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 exchange-specific parameters
* @returns {object[]} a list of prediction [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
fn fetch_orders(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_orders", { let mut __args: Vec<crate::Value> = Vec::new(); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOrders() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchOpenOrders
* @description fetches information on the user's open orders
* @param {string} [outcome] unified outcome handle
* @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 exchange-specific parameters
* @returns {object[]} a list of prediction [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
fn fetch_open_orders(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_open_orders", { let mut __args: Vec<crate::Value> = Vec::new(); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrders() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @param {string} [outcome] unified outcome handle
* @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 exchange-specific parameters
* @returns {object[]} a list of prediction [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_closed_orders", { let mut __args: Vec<crate::Value> = Vec::new(); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchClosedOrders() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchOrderTrades
* @description fetch all the trades made from a single order
* @param {string} id order id
* @param {string} [outcome] unified outcome handle
* @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 exchange-specific parameters
* @returns {object[]} a list of prediction [trade structures](https://docs.ccxt.com/#/?id=trade-structure)
*/
fn fetch_order_trades(&mut self, mut id: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOrderTrades() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchMyTrades
* @description fetch all trades made by the user
* @param {string} [outcome] unified outcome handle
* @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 exchange-specific parameters
* @returns {object[]} a list of prediction [trade structures](https://docs.ccxt.com/#/?id=trade-structure)
*/
fn fetch_my_trades(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_my_trades", { let mut __args: Vec<crate::Value> = Vec::new(); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchMyTrades() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchPosition
* @description fetch the open position held on a single prediction outcome
* @param {string} outcome unified outcome handle
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [position structure](https://docs.ccxt.com/#/?id=position-structure)
*/
fn fetch_position(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_position", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(outcome); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchPosition() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchPositions
* @description fetches the user's open positions
* @param {string[]} [outcomes] unified outcome handles to filter by
* @param {object} [params] extra exchange-specific parameters
* @returns {object[]} a list of prediction [position structures](https://docs.ccxt.com/#/?id=position-structure)
*/
fn fetch_positions(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_positions", { let mut __args: Vec<crate::Value> = Vec::new(); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchTradingFee
* @description fetch the trading fee for a prediction outcome
* @param {string} outcome unified outcome handle
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [fee structure](https://docs.ccxt.com/#/?id=fee-structure)
*/
fn fetch_trading_fee(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_trading_fee", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(outcome); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchTradingFee() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchOpenInterest
* @description fetch the open interest of a prediction outcome
* @param {string} outcome unified outcome handle
* @param {object} [params] extra exchange-specific parameters
* @returns {object} an [open interest structure](https://docs.ccxt.com/#/?id=open-interest-structure)
*/
fn fetch_open_interest(&mut self, mut outcome: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("fetch_open_interest", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(outcome); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterest() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name createOrders
* @description create a list of trade orders
* @param {object[]} orders a list of PredictionOrderRequest objects, each carrying an `outcome` handle
* @param {object} [params] extra exchange-specific parameters
* @returns {object[]} a list of prediction [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("create_orders", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(orders); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrders() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name cancelOrders
* @description cancel multiple orders
* @param {string[]} ids order ids
* @param {string} [outcome] unified outcome handle
* @param {object} [params] extra exchange-specific parameters
* @returns {object[]} a list of prediction [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
// async-virtual: try the derived exchange first
if let Some(__v) = self.dispatch_to_derived("cancel_orders", { let mut __args: Vec<crate::Value> = Vec::new(); __args.push(ids); __args.extend_from_slice(optional_args); __args }).await {
if !matches!(__v, crate::Value::Null) { return __v; }
}
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name createMarketBuyOrderWithCost
* @description create a market buy order on a prediction outcome by providing the cost
* @param {string} outcome unified outcome handle
* @param {float} cost how much you want to spend, in cost terms
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [order structure](https://docs.ccxt.com/#/?id=order-structure)
*/
fn create_market_buy_order_with_cost(&mut self, mut outcome: Value, mut cost: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// safeBool, not this.options['...'] — a raw missing-key access throws KeyError in Python/PHP
// when the option is undeclared (it is for every prediction exchange)
if matches!(self.safe_bool_k(self.options.clone(), "createMarketBuyOrderRequiresPrice", &[Value::Bool(false)]), Value::Bool(true)) || matches!(self.safe_bool_k(self.has.clone(), "createMarketBuyOrderWithCost", &[Value::Bool(false)]), Value::Bool(true)) {
return <Self as crate::prediction_exchange_generated::PredictionBase>::create_order(self, outcome, Value::Str("market".into()), Value::Str("buy".into()), cost, &[Value::Int(1), params]).await;
}
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createMarketBuyOrderWithCost() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name createMarketSellOrderWithCost
* @description create a market sell order on a prediction outcome by providing the cost
* @param {string} outcome unified outcome handle
* @param {float} cost how much you want to receive, in cost terms
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a prediction [order structure](https://docs.ccxt.com/#/?id=order-structure)
*/
fn create_market_sell_order_with_cost(&mut self, mut outcome: Value, mut cost: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if matches!(self.safe_bool_k(self.options.clone(), "createMarketSellOrderRequiresPrice", &[Value::Bool(false)]), Value::Bool(true)) || matches!(self.safe_bool_k(self.has.clone(), "createMarketSellOrderWithCost", &[Value::Bool(false)]), Value::Bool(true)) {
return <Self as crate::prediction_exchange_generated::PredictionBase>::create_order(self, outcome, Value::Str("market".into()), Value::Str("sell".into()), cost, &[Value::Int(1), params]).await;
}
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createMarketSellOrderWithCost() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name watchTickers
* @description watches price tickers for multiple prediction outcomes
* @param {string[]} [outcomes] unified outcome handles to watch
* @param {object} [params] extra exchange-specific parameters
* @returns {object} a dictionary of prediction [ticker structures](https://docs.ccxt.com/#/?id=ticker-structure)
*/
fn watch_tickers(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchTickers() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name watchOrders
* @description watches information on multiple orders made by the user
* @param {string} [outcome] unified outcome handle
* @param {int} [since] timestamp in ms of the earliest order to watch
* @param {int} [limit] the maximum number of orders to watch
* @param {object} [params] extra exchange-specific parameters
* @returns {object[]} a list of prediction [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
fn watch_orders(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchOrders() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name watchMyTrades
* @description watches all trades made by the user
* @param {string} [outcome] unified outcome handle
* @param {int} [since] timestamp in ms of the earliest trade to watch
* @param {int} [limit] the maximum number of trades to watch
* @param {object} [params] extra exchange-specific parameters
* @returns {object[]} a list of prediction [trade structures](https://docs.ccxt.com/#/?id=trade-structure)
*/
fn watch_my_trades(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchMyTrades() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name watchPositions
* @description watches the open positions held by the user
* @param {string[]} [outcomes] unified outcome handles to watch
* @param {int} [since] timestamp in ms of the earliest position to watch
* @param {int} [limit] the maximum number of positions to watch
* @param {object} [params] extra exchange-specific parameters
* @returns {object[]} a list of prediction [position structures](https://docs.ccxt.com/#/?id=position-structure)
*/
fn watch_positions(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchPositions() is not supported yet".into()))));
Value::Null
} }
/*
* @method
* @name fetchSettlements
* @description fetches the user's settled (resolved) positions — the "close the loop" record after
* markets resolve, with the collateral paid out and the realized pnl
* @param {string} [outcome] filter to a single unified outcome handle
* @param {int} [since] timestamp in ms of the earliest settlement to fetch
* @param {int} [limit] the maximum number of settlements to fetch
* @param {object} [params] extra exchange-specific parameters
* @returns {object[]} a list of prediction settlement structures
*/
fn fetch_settlements(&mut self, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
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
}));
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchSettlements() is not supported yet".into()))));
Value::Null
} }
fn safe_prediction_order(&self, mut outcomeOrder: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = get_arg(optional_args, 0, Value::Null);
// build the prediction order directly (do NOT delegate to the crypto safeOrder, which injects
// ~a dozen derivatives fields — stopPrice/triggerPrice/reduceOnly noise — the prediction type
// never declares, and whose parseTrades post-filters embedded fills by `symbol`, dropping every
// outcome-addressed row). prediction is always linear with a contract size of 1.
let mut amount: Value = self.omit_zero(self.safe_string_k(outcomeOrder.clone(), "amount", &[]));
let mut filled: Value = self.safe_string_k(outcomeOrder.clone(), "filled", &[]);
let mut remaining: Value = self.safe_string_k(outcomeOrder.clone(), "remaining", &[]);
let mut cost: Value = self.safe_string_k(outcomeOrder.clone(), "cost", &[]);
let mut average: Value = self.omit_zero(self.safe_string_k(outcomeOrder.clone(), "average", &[]));
let mut price: Value = self.omit_zero(self.safe_string_k(outcomeOrder.clone(), "price", &[]));
let mut side: Value = self.safe_string_k(outcomeOrder.clone(), "side", &[]);
let mut status: Value = self.safe_string_k(outcomeOrder.clone(), "status", &[]);
let mut lastTradeTimestamp: Value = self.safe_integer_k(outcomeOrder.clone(), "lastTradeTimestamp", &[]);
// parse embedded fills with the OUTCOME-aware parser (parseTrades would drop them on the symbol filter)
let mut rawTrades: Value = self.safe_list_k(outcomeOrder.clone(), "trades", &[Value::from(vec![])]);
let mut trades: Value = self.parse_prediction_trades(rawTrades, &[outcomeObj]);
let mut tradesLength: f64 = ((trades.len() as i64) as f64);
let mut feeList: Value = Value::from(vec![]);
if tradesLength > ((0i64) as f64) {
if (filled == Value::Null) {
filled = Value::Str("0".into());
}
if (cost == Value::Null) {
cost = Value::Str("0".into());
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_208: bool = true;
while { if !__for_first_208 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_208 = 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 tradeAmount: Value = self.safe_string_k(trade.clone(), "amount", &[]);
if (tradeAmount != Value::Null) {
filled = crate::precise::Precise::stringAdd(&filled, &tradeAmount);
}
let mut tradeCost: Value = self.safe_string_k(trade.clone(), "cost", &[]);
if (tradeCost != Value::Null) {
cost = crate::precise::Precise::stringAdd(&cost, &tradeCost);
}
if (side == Value::Null) {
side = self.safe_string_k(trade.clone(), "side", &[]);
}
let mut tradeTimestamp: Value = self.safe_integer_k(trade.clone(), "timestamp", &[]);
if (tradeTimestamp != Value::Null) {
if (lastTradeTimestamp == Value::Null) {
lastTradeTimestamp = tradeTimestamp.clone();
} else if tradeTimestamp.as_f64().unwrap_or(f64::NAN) > lastTradeTimestamp.as_f64().unwrap_or(f64::NAN) {
lastTradeTimestamp = tradeTimestamp;
}
}
let mut tradeFee: Value = self.safe_dict_k(trade, "fee", &[]);
if (tradeFee != Value::Null) {
append_to_array(&mut feeList, tradeFee);
}
}
}
}
// fill any totals the venue left undefined (linear, contract size 1)
if (filled == Value::Null) && (amount != Value::Null) && (remaining != Value::Null) {
filled = crate::precise::Precise::stringSub(&amount, &remaining);
}
if (remaining == Value::Null) && (amount != Value::Null) && (filled != Value::Null) {
remaining = crate::precise::Precise::stringSub(&amount, &filled);
}
if (amount == Value::Null) && (filled != Value::Null) && (remaining != Value::Null) {
amount = crate::precise::Precise::stringAdd(&filled, &remaining);
}
if (average == Value::Null) && (filled != Value::Null) && (cost != Value::Null) && is_true(&crate::precise::Precise::stringGt(&filled, &Value::Str("0".into()))) {
average = crate::precise::Precise::stringDiv(&cost, &filled);
}
if (cost == Value::Null) && (filled != Value::Null) {
let mut multiplyPrice: Value = (if (average != Value::Null) { average.clone() } else { price.clone() });
if (multiplyPrice != Value::Null) {
cost = crate::precise::Precise::stringMul(&filled, &multiplyPrice);
}
}
let mut fee: Value = self.safe_dict_k(outcomeOrder.clone(), "fee", &[]);
// own-line length reads so the regex transpiler emits count() (array), not strlen()
let mut feeListLength: f64 = ((feeList.len() as i64) as f64);
if (fee == Value::Null) && (feeListLength > ((0i64) as f64)) {
let mut reduced: Value = self.reduce_fees_by_currency(feeList);
let mut reducedLength: f64 = ((reduced.len() as i64) as f64);
if reducedLength > ((0i64) as f64) {
fee = reduced.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
}
}
// derive timeInForce/postOnly the same way the crypto safeOrder does (prediction has no
// trigger orders, so the isTriggerOrSLTp guard collapses): a market order defaults to IOC
let mut orderType: Value = self.safe_string_k(outcomeOrder.clone(), "type", &[]);
let mut timeInForce: Value = self.safe_string_k(outcomeOrder.clone(), "timeInForce", &[]);
let mut postOnly: Value = self.safe_bool_k(outcomeOrder.clone(), "postOnly", &[]);
if (timeInForce == Value::Null) {
if (orderType.as_str() == Some("market")) {
timeInForce = Value::Str("IOC".into());
}
if (postOnly.as_bool() == Some(true)) {
timeInForce = Value::Str("PO".into());
}
} else if (postOnly == Value::Null) {
postOnly = (Value::Bool(timeInForce.as_str() == Some("PO")));
}
let mut timestamp: Value = self.safe_integer_k(outcomeOrder.clone(), "timestamp", &[]);
let mut datetime: Value = self.safe_string_k(outcomeOrder.clone(), "datetime", &[]);
if (datetime == Value::Null) {
datetime = self.iso8601(timestamp.clone());
}
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(outcomeOrder.clone(), "id", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(outcomeOrder.clone(), "clientOrderId", &[]));
m.insert("timestamp".to_string(), timestamp);
m.insert("datetime".to_string(), datetime);
m.insert("lastTradeTimestamp".to_string(), lastTradeTimestamp);
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(outcomeOrder.clone(), "lastUpdateTimestamp", &[]));
m.insert("status".to_string(), status);
m.insert("type".to_string(), orderType);
m.insert("timeInForce".to_string(), timeInForce);
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.parse_number(price, &[]));
m.insert("average".to_string(), self.parse_number(average, &[]));
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("filled".to_string(), self.parse_number(filled, &[]));
m.insert("remaining".to_string(), self.parse_number(remaining, &[]));
m.insert("cost".to_string(), self.parse_number(cost, &[]));
m.insert("fee".to_string(), fee);
m.insert("reduceOnly".to_string(), self.safe_bool_k(outcomeOrder.clone(), "reduceOnly", &[]));
m.insert("postOnly".to_string(), postOnly);
m.insert("trades".to_string(), trades);
m.insert("outcome".to_string(), self.safe_string_k(outcomeOrder.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeOrder.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeOrder.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeOrder.clone(), "market", &[]));
m.insert("event".to_string(), self.safe_string_k(outcomeOrder.clone(), "event", &[]));
m.insert("info".to_string(), self.safe_value_k(outcomeOrder.clone(), "info", &[outcomeOrder.clone()]));
m
});
return result;
Value::Null
}
fn safe_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = get_arg(optional_args, 0, Value::Null);
// build the prediction trade directly (no crypto safeTrade, which leaks fields the type omits)
let mut price: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut amount: Value = self.safe_string_k(trade.clone(), "amount", &[]);
let mut cost: Value = self.safe_string_k(trade.clone(), "cost", &[]);
if (cost == Value::Null) && (price != Value::Null) && (amount != Value::Null) {
cost = crate::precise::Precise::stringMul(&price, &amount);
}
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "timestamp", &[]);
let mut datetime: Value = self.safe_string_k(trade.clone(), "datetime", &[]);
if (datetime == Value::Null) {
datetime = self.iso8601(timestamp.clone());
}
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "id", &[]));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "order", &[]));
m.insert("timestamp".to_string(), timestamp);
m.insert("datetime".to_string(), datetime);
m.insert("type".to_string(), self.safe_string_k(trade.clone(), "type", &[]));
m.insert("side".to_string(), self.safe_string_k(trade.clone(), "side", &[]));
m.insert("takerOrMaker".to_string(), self.safe_string_k(trade.clone(), "takerOrMaker", &[]));
m.insert("price".to_string(), self.parse_number(price, &[]));
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("cost".to_string(), self.parse_number(cost, &[]));
m.insert("fee".to_string(), self.safe_dict_k(trade.clone(), "fee", &[]));
m.insert("realizedPnl".to_string(), self.safe_number_k(trade.clone(), "realizedPnl", &[]));
m.insert("outcome".to_string(), self.safe_string_k(trade.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(trade.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(trade.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(trade.clone(), "market", &[]));
m.insert("info".to_string(), self.safe_value_k(trade.clone(), "info", &[trade.clone()]));
m
});
return result;
Value::Null
}
fn safe_prediction_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = get_arg(optional_args, 0, Value::Null);
// build the prediction ticker directly (no crypto safeTicker, which injects vwap/previousClose/
// indexPrice/markPrice the type omits). derive change/percentage/average only from open+close —
// prediction venues report those directly, so the crypto back-derivation from percentage is moot.
let mut open: Value = self.omit_zero(self.safe_string_k(ticker.clone(), "open", &[]));
let mut close: Value = self.omit_zero(self.safe_string2(ticker.clone(), Value::Str("close".into()), Value::Str("last".into()), &[]));
let mut last: Value = self.omit_zero(self.safe_string2(ticker.clone(), Value::Str("last".into()), Value::Str("close".into()), &[]));
let mut change: Value = self.safe_string_k(ticker.clone(), "change", &[]);
let mut percentage: Value = self.omit_zero(self.safe_string_k(ticker.clone(), "percentage", &[]));
let mut average: Value = self.omit_zero(self.safe_string_k(ticker.clone(), "average", &[]));
if (change == Value::Null) && (open != Value::Null) && (close != Value::Null) {
change = crate::precise::Precise::stringSub(&close, &open);
}
if (percentage == Value::Null) && (change != Value::Null) && (open != Value::Null) && is_true(&crate::precise::Precise::stringGt(&open, &Value::Str("0".into()))) {
percentage = crate::precise::Precise::stringMul(&crate::precise::Precise::stringDiv(&change, &open), &Value::Str("100".into()));
}
if (average == Value::Null) && (open != Value::Null) && (close != Value::Null) {
average = crate::precise::Precise::stringDiv(&crate::precise::Precise::stringAdd(&open, &close), &Value::Str("2".into()));
}
let mut timestamp: Value = self.safe_integer_k(ticker.clone(), "timestamp", &[]);
let mut datetime: Value = self.safe_string_k(ticker.clone(), "datetime", &[]);
if (datetime == Value::Null) {
datetime = self.iso8601(timestamp.clone());
}
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timestamp".to_string(), timestamp);
m.insert("datetime".to_string(), datetime);
m.insert("high".to_string(), self.safe_number_k(ticker.clone(), "high", &[]));
m.insert("low".to_string(), self.safe_number_k(ticker.clone(), "low", &[]));
m.insert("bid".to_string(), self.parse_number(self.omit_zero(self.safe_string_k(ticker.clone(), "bid", &[])), &[]));
m.insert("bidVolume".to_string(), self.safe_number_k(ticker.clone(), "bidVolume", &[]));
m.insert("ask".to_string(), self.parse_number(self.omit_zero(self.safe_string_k(ticker.clone(), "ask", &[])), &[]));
m.insert("askVolume".to_string(), self.safe_number_k(ticker.clone(), "askVolume", &[]));
m.insert("open".to_string(), self.parse_number(open, &[]));
m.insert("close".to_string(), self.parse_number(close, &[]));
m.insert("last".to_string(), self.parse_number(last, &[]));
m.insert("change".to_string(), self.parse_number(change, &[]));
m.insert("percentage".to_string(), self.parse_number(percentage, &[]));
m.insert("average".to_string(), self.parse_number(average, &[]));
m.insert("baseVolume".to_string(), self.safe_number_k(ticker.clone(), "baseVolume", &[]));
m.insert("quoteVolume".to_string(), self.safe_number_k(ticker.clone(), "quoteVolume", &[]));
m.insert("openInterest".to_string(), self.safe_number_k(ticker.clone(), "openInterest", &[]));
m.insert("outcome".to_string(), self.safe_string_k(ticker.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(ticker.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(ticker.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(ticker.clone(), "market", &[]));
m.insert("event".to_string(), self.safe_string_k(ticker.clone(), "event", &[]));
m.insert("info".to_string(), self.safe_value_k(ticker.clone(), "info", &[ticker.clone()]));
m
});
return result;
Value::Null
}
fn safe_prediction_position(&self, mut position: Value) -> Value {
// build the prediction position directly (no crypto safePosition, which carries the whole
// leverage/marginMode/liquidation block the prediction type omits)
let mut timestamp: Value = self.safe_integer_k(position.clone(), "timestamp", &[]);
let mut datetime: Value = self.safe_string_k(position.clone(), "datetime", &[]);
if (datetime == Value::Null) {
datetime = self.iso8601(timestamp.clone());
}
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(position.clone(), "id", &[]));
m.insert("timestamp".to_string(), timestamp);
m.insert("datetime".to_string(), datetime);
m.insert("contracts".to_string(), self.safe_number_k(position.clone(), "contracts", &[]));
m.insert("contractSize".to_string(), self.safe_number_k(position.clone(), "contractSize", &[]));
m.insert("side".to_string(), self.safe_string_k(position.clone(), "side", &[]));
m.insert("notional".to_string(), self.safe_number_k(position.clone(), "notional", &[]));
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "unrealizedPnl", &[]));
m.insert("realizedPnl".to_string(), self.safe_number_k(position.clone(), "realizedPnl", &[]));
m.insert("collateral".to_string(), self.safe_number_k(position.clone(), "collateral", &[]));
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "entryPrice", &[]));
m.insert("markPrice".to_string(), self.safe_number_k(position.clone(), "markPrice", &[]));
m.insert("lastPrice".to_string(), self.safe_number_k(position.clone(), "lastPrice", &[]));
m.insert("percentage".to_string(), self.safe_number_k(position.clone(), "percentage", &[]));
m.insert("resolved".to_string(), self.safe_bool_k(position.clone(), "resolved", &[]));
m.insert("won".to_string(), self.safe_bool_k(position.clone(), "won", &[]));
m.insert("settleFraction".to_string(), self.safe_number_k(position.clone(), "settleFraction", &[]));
m.insert("payout".to_string(), self.safe_number_k(position.clone(), "payout", &[]));
m.insert("outcome".to_string(), self.safe_string_k(position.clone(), "outcome", &[]));
m.insert("outcomeId".to_string(), self.safe_string_k(position.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(position.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(position.clone(), "market", &[]));
m.insert("event".to_string(), self.safe_string_k(position.clone(), "event", &[]));
m.insert("info".to_string(), self.safe_value_k(position.clone(), "info", &[position.clone()]));
m
});
return result;
Value::Null
}
fn safe_prediction_order_book(&self, mut orderbook: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = get_arg(optional_args, 0, Value::Null);
// normalize a parsed order book to the prediction shape: replace the unified
// `symbol` with the `outcome` handle and attach the outcome identity fields
// outcomeId and market - so books match the PredictionOrderBook structure.
let mut fallback: Value = self.safe_string2(orderbook.clone(), Value::Str("outcome".into()), Value::Str("symbol".into()), &[]);
let mut identity: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), (if (outcomeObj == Value::Null) { fallback.clone() } else { self.safe_string_k(outcomeObj.clone(), "outcome", &[fallback]) }));
m.insert("outcomeId".to_string(), (if (outcomeObj == Value::Null) { self.safe_string_k(orderbook.clone(), "outcomeId", &[]) } else { self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]) }));
m.insert("market".to_string(), (if (outcomeObj == Value::Null) { self.safe_string_k(orderbook.clone(), "market", &[]) } else { self.safe_string_k(outcomeObj, "market", &[]) }));
m
});
let __ws_arg_0 = self.omit(orderbook, Value::Str("symbol".into()), &[]);
return self.extend(__ws_arg_0, &[identity]);
Value::Null
}
fn parse_prediction_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" parsePredictionTicker() is not supported yet".into()))));
Value::Null
}
fn parse_prediction_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
// virtual-dispatch (static: DerivedExchange::parse_prediction_order(self, ...))
{ let __v = crate::exchange::DerivedExchange::parse_prediction_order(self, order, crate::runtime::get_arg(optional_args, 0, crate::Value::Null)); if !matches!(__v, crate::Value::Null) { return __v; } }
let mut market = get_arg(optional_args, 0, Value::Null);
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" parsePredictionOrder() is not supported yet".into()))));
Value::Null
}
fn parse_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
// virtual-dispatch (static: DerivedExchange::parse_prediction_trade(self, ...))
{ let __v = crate::exchange::DerivedExchange::parse_prediction_trade(self, trade, crate::runtime::get_arg(optional_args, 0, crate::Value::Null)); if !matches!(__v, crate::Value::Null) { return __v; } }
let mut market = get_arg(optional_args, 0, Value::Null);
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" parsePredictionTrade() is not supported yet".into()))));
Value::Null
}
fn parse_prediction_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
// virtual-dispatch (static: DerivedExchange::parse_prediction_position(self, ...))
{ let __v = crate::exchange::DerivedExchange::parse_prediction_position(self, position, crate::runtime::get_arg(optional_args, 0, crate::Value::Null)); if !matches!(__v, crate::Value::Null) { return __v; } }
let mut market = get_arg(optional_args, 0, Value::Null);
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" parsePredictionPosition() is not supported yet".into()))));
Value::Null
}
fn parse_prediction_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" parsePredictionOpenInterest() is not supported yet".into()))));
Value::Null
}
/*
* @ignore
* @method
* @name PredictionExchange#parsePredictionTrades
* @description parses a list of raw trades with the exchange's parsePredictionTrade, sorts them and filters by the outcome handle — the prediction analogue of the base parseTrades
* @param {object[]} trades the raw trades
* @param {object} [outcomeObj] the resolved outcome object the trades belong to
* @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 fields to merge into every parsed trade
* @returns {object[]} a list of prediction [trade structures](https://docs.ccxt.com/#/?id=public-trades)
*/
fn parse_prediction_trades(&self, mut trades: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = 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
}));
// prediction-market analogue of the base parseTrades: the base aggregator post-filters
// by the market's `symbol` key, but prediction structures carry an `outcome` handle
// instead — and an outcome object rebuilt from cached markets may still hold a legacy
// `symbol` key, which would silently drop every parsed row
let mut rows: Value = self.to_array(trades);
let mut results: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_209: bool = true;
while { if !__for_first_209 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_209 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut parsed: Value = <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_trade(self, rows.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[outcomeObj.clone()]);
let mut trade: Value = self.extend(parsed, &[params.clone()]);
append_to_array(&mut results, trade);
}
}
results = self.sort_by2(results.clone(), Value::Str("timestamp".into()), Value::Str("id".into()), &[]);
let mut outcomeHandle: Value = self.safe_string_k(outcomeObj, "outcome", &[]);
return self.filter_by_outcome_since_limit(results, &[outcomeHandle, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name PredictionExchange#parsePredictionOrders
* @description parses a list of raw orders with the exchange's parsePredictionOrder, sorts them and filters by the outcome handle — the prediction analogue of the base parseOrders
* @param {object[]} orders the raw orders
* @param {object} [outcomeObj] the resolved outcome object the orders belong to
* @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 fields to merge into every parsed order
* @returns {object[]} a list of prediction [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
fn parse_prediction_orders(&self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut outcomeObj = 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
}));
// prediction-market analogue of the base parseOrders — see parsePredictionTrades
let mut rows: Value = self.to_array(orders);
let mut results: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_210: bool = true;
while { if !__for_first_210 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_210 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut parsed: Value = <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_order(self, rows.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[outcomeObj.clone()]);
let mut order: Value = self.extend(parsed, &[params.clone()]);
append_to_array(&mut results, order);
}
}
results = self.sort_by(results.clone(), Value::Str("timestamp".into()), &[]);
let mut outcomeHandle: Value = self.safe_string_k(outcomeObj, "outcome", &[]);
return self.filter_by_outcome_since_limit(results, &[outcomeHandle, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name PredictionExchange#parsePredictionPositions
* @description parses a list of raw positions with the exchange's parsePredictionPosition — the prediction analogue of the base parsePositions
* @param {object[]} positions the raw positions
* @param {object} [params] extra fields to merge into every parsed position
* @returns {object[]} a list of prediction [position structures](https://docs.ccxt.com/#/?id=position-structure)
*/
fn parse_prediction_positions(&self, mut positions: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// prediction-market analogue of the base parsePositions, which resolves its `symbols`
// argument through marketSymbols() and would throw BadSymbol on outcome handles.
// venue-specific outcome filtering stays in the exchange (position identity differs
// per venue: kalshi positions are market-level, polymarket ones are per token)
let mut rows: Value = self.to_array(positions);
let mut results: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_211: bool = true;
while { if !__for_first_211 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_211 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut parsed: Value = <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_position(self, rows.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[]);
let mut position: Value = self.extend(parsed, &[params.clone()]);
append_to_array(&mut results, position);
}
}
return results;
Value::Null
}
fn filter_by_outcome_since_limit(&self, mut array: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut tail = get_arg(optional_args, 3, Value::Bool(false));
return self.filter_by_value_since_limit(array, Value::Str("outcome".into()), &[outcome, since, limit, Value::Str("timestamp".into()), tail]);
Value::Null
}
fn filter_by_outcomes_since_limit(&self, mut array: Value, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut tail = get_arg(optional_args, 3, Value::Bool(false));
let mut result: Value = self.filter_by_array(array, Value::Str("outcome".into()), &[outcomes, Value::Bool(false)]);
return self.filter_by_since_limit(result, &[since, limit, Value::Str("timestamp".into()), tail]);
Value::Null
}
fn amount_to_prediction_precision(&self, mut outcome: Value, mut amount: Value) -> Value {
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut marketSymbol: Value = self.safe_string_k(outcomeObj, "market", &[]);
return self.amount_to_precision(marketSymbol, amount);
Value::Null
}
fn price_to_prediction_precision(&self, mut outcome: Value, mut price: Value) -> Value {
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut marketSymbol: Value = self.safe_string_k(outcomeObj, "market", &[]);
return self.price_to_precision(marketSymbol, price);
Value::Null
}
fn cost_to_prediction_precision(&self, mut outcome: Value, mut cost: Value) -> Value {
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut marketSymbol: Value = self.safe_string_k(outcomeObj, "market", &[]);
return self.cost_to_precision(marketSymbol, cost);
Value::Null
}
// ------------------------------------------------------------------------
// shared EVM helpers — RLP encoding + a minimal JSON-RPC client + raw-tx
// broadcast, used by the on-chain (EOA) trading paths of EVM prediction
// venues (limitless, myriad). signEvmTransaction stays per-exchange because
// it needs the noble crypto imports (keccak/ecdsa/secp256k1) which the
// per-language prediction base skeletons don't carry; this base
// sendEvmTransaction dispatches to the exchange's signEvmTransaction override
fn pad_hex_to_even(&self, mut hex: Value) -> Value {
if (hex == Value::Null) {
return Value::Str("".into());
}
// prepend a nibble so the hex has an even number of characters (whole bytes)
let mut hexLength: Value = Value::Int(hex.len() as i64);
if ((mod_val(&hexLength, &Value::Int(2))).as_f64() != Some(0.0)) {
return Value::Str(format!("{}{}", Value::Str("0".into()), hex).into());
}
return hex;
Value::Null
}
fn pad_hex_address(&self, mut address: Value) -> Value {
if (address == Value::Null) {
return Value::Str("".into());
}
// left-pads a 20-byte address to a 32-byte ABI word (24 leading zero bytes)
let mut stripped: Value = self.remove0x_prefix(address);
return Value::Str(format!("{}{}", Value::Str("000000000000000000000000".into()), stripped).into());
Value::Null
}
fn rlp_encode_bytes(&self, mut hex: Value) -> Value {
if (hex == Value::Null) {
return Value::Str("".into());
}
// RLP-encodes a single byte string (hex without 0x) per the Ethereum RLP spec
let mut byteLength: Value = self.parse_to_int((match ((Value::Int(hex.len() as i64)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
if (byteLength.as_f64() == Some(0.0)) {
return Value::Str("80".into());
}
if (byteLength.as_f64() == Some(1.0)) && (is_less_than(&hex, &Value::Str("80".into()))) {
return hex;
}
if byteLength.as_f64().unwrap_or(f64::NAN) < ((56i64) as f64) {
return Value::Str(format!("{}{}", self.int_to_base16((match (&(Value::Int(128)), &(byteLength)) { (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 }), &[]), hex).into());
}
let mut lengthHex: Value = self.int_to_base16(byteLength, &[]);
lengthHex = self.pad_hex_to_even(lengthHex.clone());
let mut lengthOfLength: Value = self.parse_to_int((match ((Value::Int(lengthHex.len() as i64)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.int_to_base16((match (&(Value::Int(183)), &(lengthOfLength)) { (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 }), &[]), lengthHex).into()), hex).into());
Value::Null
}
fn rlp_encode_list(&self, mut items: Value) -> Value {
let mut concatenated: Value = Value::Str("".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_212: bool = true;
while { if !__for_first_212 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_212 = false; i.as_f64().unwrap_or(f64::NAN) < ((items.len() as i64) as f64) } {
concatenated = Value::Str(format!("{}{}", concatenated, items.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)).into());
}
}
let mut byteLength: Value = self.parse_to_int((match ((Value::Int(concatenated.len() as i64)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
if byteLength.as_f64().unwrap_or(f64::NAN) < ((56i64) as f64) {
return Value::Str(format!("{}{}", self.int_to_base16((match (&(Value::Int(192)), &(byteLength)) { (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 }), &[]), concatenated).into());
}
let mut lengthHex: Value = self.int_to_base16(byteLength, &[]);
lengthHex = self.pad_hex_to_even(lengthHex.clone());
let mut lengthOfLength: Value = self.parse_to_int((match ((Value::Int(lengthHex.len() as i64)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.int_to_base16((match (&(Value::Int(247)), &(lengthOfLength)) { (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 }), &[]), lengthHex).into()), concatenated).into());
Value::Null
}
fn int_to_rlp_hex(&self, mut value: Value) -> Value {
if (value == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" intToRlpHex() requires a value argument".into()))));
}
// an integer as its minimal big-endian byte hex; 0 is the empty byte string
if (value.as_f64() == Some(0.0)) {
return Value::Str("".into());
}
let mut hex: Value = self.int_to_base16(value, &[]);
hex = self.pad_hex_to_even(hex.clone());
return hex;
Value::Null
}
fn hex_to_rlp_bytes(&self, mut hexValue: Value) -> Value {
// a hex value (e.g. an RPC result) as minimal big-endian byte hex; leading zero bytes
// are stripped and 0 becomes the empty byte string (RLP integer encoding)
if (hexValue == Value::Null) {
return Value::Str("".into());
}
let mut h: Value = self.remove0x_prefix(hexValue);
let mut start: Value = Value::Int(0);
let mut total: f64 = ((h.len() as i64) as f64);
while (start.as_f64().unwrap_or(f64::NAN) < total) && (slice(&h, &start, &(match (&(start), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null })).as_str() == Some("0")) {
start = (match (&(start), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
}
h = slice(&h, &start, &Value::Null);
if (h.as_str() == Some("")) {
return Value::Str("".into());
}
h = self.pad_hex_to_even(h.clone());
return h;
Value::Null
}
// eslint-disable-next-line no-unused-vars
fn sign_evm_transaction(&self, mut tx: Value, mut privateKey: Value) -> Value {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" signEvmTransaction() must be overridden by the exchange".into()))));
Value::Null
}
fn eth_rpc(&mut self, mut rpcUrl: Value, mut method: Value, mut rpcParams: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut payload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("jsonrpc".to_string(), Value::Str("2.0".into()));
m.insert("id".to_string(), Value::Int(1));
m.insert("method".to_string(), method.clone());
m.insert("params".to_string(), rpcParams);
m
});
let mut headers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m
});
let mut response: Value = self.fetch(rpcUrl, &[Value::Str("POST".into()), headers, json_stringify(&payload)]).await;
let mut rpcError: Value = self.safe_value_k(response.clone(), "error", &[]);
if (rpcError != Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" rpc ".into())).into()), method).into()), Value::Str(" error: ".into())).into()), json_stringify(&rpcError))));
}
return self.safe_value_k(response, "result", &[]);
Value::Null
} }
fn send_evm_transaction(&mut self, mut rpcUrl: Value, mut chainId: Value, mut fromAddress: Value, mut to: Value, mut value: Value, mut data: Value, mut gasLimit: Value) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut nonce: Value = self.eth_rpc(rpcUrl.clone(), Value::Str("eth_getTransactionCount".into()), Value::from(vec![fromAddress, Value::Str("pending".into())])).await;
let mut gasPrice: Value = self.eth_rpc(rpcUrl.clone(), Value::Str("eth_gasPrice".into()), Value::from(vec![])).await;
let mut tx: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("chainId".to_string(), chainId);
m.insert("nonce".to_string(), nonce);
m.insert("maxPriorityFeePerGas".to_string(), gasPrice.clone());
m.insert("maxFeePerGas".to_string(), gasPrice);
m.insert("gasLimit".to_string(), gasLimit);
m.insert("to".to_string(), to);
m.insert("value".to_string(), value);
m.insert("data".to_string(), data);
m
});
let mut signed: Value = self.sign_evm_transaction(tx, self.privateKey.clone());
return self.eth_rpc(rpcUrl, Value::Str("eth_sendRawTransaction".into()), Value::from(vec![signed])).await;
Value::Null
} }
fn wait_for_transaction_receipt(&mut self, mut rpcUrl: Value, mut txHash: Value, optional_args: &[Value]) -> impl ::std::future::Future<Output = Value> + Send { async move {
let mut timeout = get_arg(optional_args, 0, Value::Int(60000));
let mut start: Value = self.milliseconds();
while ((match (&(self.milliseconds()), &(start)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })).as_f64().unwrap_or(f64::NAN) < timeout.as_f64().unwrap_or(f64::NAN) {
let mut receipt: Value = self.eth_rpc(rpcUrl.clone(), Value::Str("eth_getTransactionReceipt".into()), Value::from(vec![txHash.clone()])).await;
if (receipt != Value::Null) && (receipt != Value::Null) {
return receipt;
}
self.sleep(Value::Int(2000)).await;
}
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" transaction ".into())).into()), txHash).into()), Value::Str(" not mined within timeout".into()))));
Value::Null
} }
/// Prediction-base fall-through for a prediction Core's `call_dynamic`.
fn call_dynamic_prediction_base<'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 {
"amount_to_prediction_precision" => <Self as crate::prediction_exchange_generated::PredictionBase>::amount_to_prediction_precision(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"apply_event_fetch_params" => <Self as crate::prediction_exchange_generated::PredictionBase>::apply_event_fetch_params(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"cancel_order" => <Self as crate::prediction_exchange_generated::PredictionBase>::cancel_order(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => <Self as crate::prediction_exchange_generated::PredictionBase>::cancel_orders(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cost_to_prediction_precision" => <Self as crate::prediction_exchange_generated::PredictionBase>::cost_to_prediction_precision(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"create_market_buy_order_with_cost" => <Self as crate::prediction_exchange_generated::PredictionBase>::create_market_buy_order_with_cost(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_market_sell_order_with_cost" => <Self as crate::prediction_exchange_generated::PredictionBase>::create_market_sell_order_with_cost(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_order" => <Self as crate::prediction_exchange_generated::PredictionBase>::create_order(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_orders" => <Self as crate::prediction_exchange_generated::PredictionBase>::create_orders(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"eth_rpc" => <Self as crate::prediction_exchange_generated::PredictionBase>::eth_rpc(self, 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,
"events_list" => <Self as crate::prediction_exchange_generated::PredictionBase>::events_list(self),
"fetch_closed_orders" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_closed_orders(self, &args[..]).await,
"fetch_event" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_event(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_events" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_events(self, &args[..]).await,
"fetch_my_trades" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_my_trades(self, &args[..]).await,
"fetch_ohlcv" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_ohlcv(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_open_interest(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_open_orders(self, &args[..]).await,
"fetch_order_book" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_order_book(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_trades" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_order_trades(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_orders(self, &args[..]).await,
"fetch_outcome" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_outcome(self, args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_outcomes" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_outcomes(self, args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_position" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_position(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_positions(self, &args[..]).await,
"fetch_settlements" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_settlements(self, &args[..]).await,
"fetch_ticker" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_ticker(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_tickers(self, &args[..]).await,
"fetch_trades" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_trades(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trading_fee" => <Self as crate::prediction_exchange_generated::PredictionBase>::fetch_trading_fee(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"filter_by_outcome_since_limit" => <Self as crate::prediction_exchange_generated::PredictionBase>::filter_by_outcome_since_limit(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"filter_by_outcomes_since_limit" => <Self as crate::prediction_exchange_generated::PredictionBase>::filter_by_outcomes_since_limit(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"filter_events_by_search_in" => <Self as crate::prediction_exchange_generated::PredictionBase>::filter_events_by_search_in(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]),
"filter_events_by_status" => <Self as crate::prediction_exchange_generated::PredictionBase>::filter_events_by_status(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"filter_events_by_tags" => <Self as crate::prediction_exchange_generated::PredictionBase>::filter_events_by_tags(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"get_event" => <Self as crate::prediction_exchange_generated::PredictionBase>::get_event(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"has_outcome" => <Self as crate::prediction_exchange_generated::PredictionBase>::has_outcome(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"hex_to_rlp_bytes" => <Self as crate::prediction_exchange_generated::PredictionBase>::hex_to_rlp_bytes(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"int_to_rlp_hex" => <Self as crate::prediction_exchange_generated::PredictionBase>::int_to_rlp_hex(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"is_prediction" => <Self as crate::prediction_exchange_generated::PredictionBase>::is_prediction(self),
"load_events" => <Self as crate::prediction_exchange_generated::PredictionBase>::load_events(self, &args[..]).await,
"load_events_helper" => <Self as crate::prediction_exchange_generated::PredictionBase>::load_events_helper(self, &args[..]).await,
"load_outcome" => <Self as crate::prediction_exchange_generated::PredictionBase>::load_outcome(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"normalize_tag_key" => <Self as crate::prediction_exchange_generated::PredictionBase>::normalize_tag_key(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"outcome" => <Self as crate::prediction_exchange_generated::PredictionBase>::outcome(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"outcome_search_query" => <Self as crate::prediction_exchange_generated::PredictionBase>::outcome_search_query(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"pad_hex_address" => <Self as crate::prediction_exchange_generated::PredictionBase>::pad_hex_address(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"pad_hex_to_even" => <Self as crate::prediction_exchange_generated::PredictionBase>::pad_hex_to_even(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_prediction_open_interest" => <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_open_interest(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_order" => <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_order(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_orders" => <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_orders(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_position" => <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_position(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_positions" => <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_positions(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_ticker" => <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_ticker(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_trade" => <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_trade(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_trades" => <Self as crate::prediction_exchange_generated::PredictionBase>::parse_prediction_trades(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_search_queries" => <Self as crate::prediction_exchange_generated::PredictionBase>::parse_search_queries(self, &args[..]),
"price_to_prediction_precision" => <Self as crate::prediction_exchange_generated::PredictionBase>::price_to_prediction_precision(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"require_event_query" => <Self as crate::prediction_exchange_generated::PredictionBase>::require_event_query(self, &args[..]),
"rlp_encode_bytes" => <Self as crate::prediction_exchange_generated::PredictionBase>::rlp_encode_bytes(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"rlp_encode_list" => <Self as crate::prediction_exchange_generated::PredictionBase>::rlp_encode_list(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"safe_outcome" => <Self as crate::prediction_exchange_generated::PredictionBase>::safe_outcome(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"safe_outcome_symbol" => <Self as crate::prediction_exchange_generated::PredictionBase>::safe_outcome_symbol(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"safe_prediction_order" => <Self as crate::prediction_exchange_generated::PredictionBase>::safe_prediction_order(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"safe_prediction_order_book" => <Self as crate::prediction_exchange_generated::PredictionBase>::safe_prediction_order_book(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"safe_prediction_position" => <Self as crate::prediction_exchange_generated::PredictionBase>::safe_prediction_position(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"safe_prediction_ticker" => <Self as crate::prediction_exchange_generated::PredictionBase>::safe_prediction_ticker(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"safe_prediction_trade" => <Self as crate::prediction_exchange_generated::PredictionBase>::safe_prediction_trade(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"send_evm_transaction" => <Self as crate::prediction_exchange_generated::PredictionBase>::send_evm_transaction(self, 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)).await,
"set_events" => <Self as crate::prediction_exchange_generated::PredictionBase>::set_events(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"set_markets" => <Self as crate::prediction_exchange_generated::PredictionBase>::set_markets(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"shorten_slug" => <Self as crate::prediction_exchange_generated::PredictionBase>::shorten_slug(self, args.get(0).cloned().unwrap_or(crate::Value::Null)),
"sign_evm_transaction" => <Self as crate::prediction_exchange_generated::PredictionBase>::sign_evm_transaction(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"slug_to_market_symbol" => <Self as crate::prediction_exchange_generated::PredictionBase>::slug_to_market_symbol(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"slug_to_outcome_symbol" => <Self as crate::prediction_exchange_generated::PredictionBase>::slug_to_outcome_symbol(self, 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)),
"wait_for_transaction_receipt" => <Self as crate::prediction_exchange_generated::PredictionBase>::wait_for_transaction_receipt(self, args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"watch_my_trades" => <Self as crate::prediction_exchange_generated::PredictionBase>::watch_my_trades(self, &args[..]).await,
"watch_order_book" => <Self as crate::prediction_exchange_generated::PredictionBase>::watch_order_book(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => <Self as crate::prediction_exchange_generated::PredictionBase>::watch_orders(self, &args[..]).await,
"watch_positions" => <Self as crate::prediction_exchange_generated::PredictionBase>::watch_positions(self, &args[..]).await,
"watch_ticker" => <Self as crate::prediction_exchange_generated::PredictionBase>::watch_ticker(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_tickers" => <Self as crate::prediction_exchange_generated::PredictionBase>::watch_tickers(self, &args[..]).await,
"watch_trades" => <Self as crate::prediction_exchange_generated::PredictionBase>::watch_trades(self, args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
_ => self.call_dynamic_base(method, args).await,
}
})
}
}