// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
use crate::pro::*;
pub struct LighterCore {
pub parent: crate::exchanges::lighter::LighterCore,
}
impl LighterCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { parent: crate::exchanges::lighter::LighterCore::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = LighterCore::describe(self);
self.initialize_properties(described);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for LighterCore {
fn nonce(&self, ) -> crate::Value {
crate::exchange::DerivedExchange::nonce(&self.parent)
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ticker(&self.parent, ticker, market)
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_trade(&self.parent, trade, market)
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_order(&self.parent, order, market)
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_market(&self.parent, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ohlcv(&self.parent, ohlcv, market)
}
fn parse_order_book(&self, ob: crate::Value, symbol: crate::Value, ts: crate::Value, bk: crate::Value, ak: crate::Value, pk: crate::Value, ak2: crate::Value, ck: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_order_book(&self.parent, ob, symbol, ts, bk, ak, pk, ak2, ck)
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_balance(&self.parent, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_position(&self.parent, position, market)
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_funding_rate(&self.parent, rate, market)
}
fn parse_deposit(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit(&self.parent, tx, currency)
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit_address(&self.parent, depositAddress, currency)
}
fn parse_last_price(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_last_price(&self.parent, entry, market)
}
fn parse_withdrawal(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_withdrawal(&self.parent, tx, currency)
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_ledger_entry(&self.parent, entry, currency)
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_transfer(&self.parent, transfer, currency)
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_currency(&self.parent, currency)
}
fn parse_bid_ask(&self, bidask: crate::Value, price_key: crate::Value, amount_key: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_bid_ask(&self.parent, bidask, price_key, amount_key, market)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_open_interest(&self.parent, interest, market)
}
fn parse_liquidation(&self, liquidation: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_liquidation(&self.parent, liquidation, market)
}
fn parse_funding_rate_history(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_funding_rate_history(&self.parent, entry, market)
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_margin_modification(&self.parent, data, market)
}
fn parse_account(&self, account: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_account(&self.parent, account)
}
fn parse_my_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_my_trade(&self.parent, trade, market)
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_transaction(&self.parent, transaction, currency)
}
fn parse_borrow_interest(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_borrow_interest(&self.parent, info, market)
}
fn parse_adl_rank(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_adl_rank(&self.parent, info, market)
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_income(&self.parent, info, market)
}
fn parse_greeks(&self, greeks: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_greeks(&self.parent, greeks, market)
}
fn parse_margin_mode(&self, margin_mode: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_margin_mode(&self.parent, margin_mode, market)
}
fn parse_conversion(&self, conversion: crate::Value, from_currency: crate::Value, to_currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_conversion(&self.parent, conversion, from_currency, to_currency)
}
fn parse_borrow_rate(&self, info: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_borrow_rate(&self.parent, info, currency)
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_leverage(&self.parent, leverage, market)
}
fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_market_leverage_tiers(&self.parent, info, market)
}
fn parse_deposit_withdraw_fee(&self, fee: crate::Value, currency: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_deposit_withdraw_fee(&self.parent, fee, currency)
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_trade(&self.parent, trade, market)
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_order(&self.parent, order, market)
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::parse_prediction_position(&self.parent, position, market)
}
fn create_expired_option_market(&self, symbol: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::create_expired_option_market(&self.parent, symbol)
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::sign(&self.parent, path, api, method, params, headers, body)
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
crate::exchange::DerivedExchange::handle_errors(&self.parent, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for LighterCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"cancel_all_orders_ws" => self.cancel_all_orders_ws(&args[..]).await,
"cancel_order_ws" => self.cancel_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_order_ws" => self.create_order_ws(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,
"get_message_hash" => self.get_message_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"handle_balance" => self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_my_trades" => self.handle_my_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_order_book_message" => self.handle_order_book_message(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)),
"handle_orders" => self.handle_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_subscription_status" => self.handle_subscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order_trade" => self.parse_ws_order_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"pong" => self.pong(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"request_id" => self.request_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"subscribe_private" => self.subscribe_private(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"subscribe_public" => self.subscribe_public(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"subscribe_public_multiple" => self.subscribe_public_multiple(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_mark_price" => self.un_watch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_mark_prices" => self.un_watch_mark_prices(&args[..]).await,
"un_watch_my_trades" => self.un_watch_my_trades(&args[..]).await,
"un_watch_order_book" => self.un_watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_orders" => self.un_watch_orders(&args[..]).await,
"un_watch_ticker" => self.un_watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_tickers" => self.un_watch_tickers(&args[..]).await,
"un_watch_trades" => self.un_watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"unsubscribe" => self.unsubscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_balance" => self.watch_balance(&args[..]).await,
"watch_liquidations" => self.watch_liquidations(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_mark_price" => self.watch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_mark_prices" => self.watch_mark_prices(&args[..]).await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_tickers" => self.watch_tickers(&args[..]).await,
"watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// Go-style inheritance: an un-overridden method dispatches to the parent core.
_ => crate::exchange_generated::ExchangeBase::call_dynamic(&mut self.parent, method, args).await,
}
})
}
}
impl LighterCore {
/// Synchronous WS handler dispatch — routes a handler-name string (from the
/// venue's handle_message dispatch table) to the real handler method.
#[allow(dead_code, unreachable_patterns, clippy::all)]
pub fn dispatch_ws_handler(&mut self, __name: &crate::Value, args: &[crate::Value]) -> crate::Value {
let __n = match __name { crate::Value::Str(s) => s.as_ref(), _ => return crate::Value::Null };
match __n {
"cancel_all_orders_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_all_orders_ws", args.to_vec()); crate::Value::Null },
"cancel_order_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_order_ws", args.to_vec()); crate::Value::Null },
"create_order_ws" => { crate::exchange_stubs::enqueue_spawn("create_order_ws", args.to_vec()); crate::Value::Null },
"get_message_hash" => self.get_message_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"handle_all_orders_un_subscription" => { self.handle_all_orders_un_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_balance" => self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_delta" => { self.handle_delta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_deltas" => { self.handle_deltas(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_liquidation" => { self.handle_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_my_trades" => self.handle_my_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_my_trades_un_subscription" => { self.handle_my_trades_un_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book" => { self.handle_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_order_book_message" => self.handle_order_book_message(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)),
"handle_order_book_un_subscription" => { self.handle_order_book_un_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_orders" => self.handle_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_orders_un_subscription" => { self.handle_orders_un_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ping" => { self.handle_ping(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_subscription_status" => self.handle_subscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_ticker" => { self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ticker_un_subscription" => { self.handle_ticker_un_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trades" => { self.handle_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_trades_un_subscription" => { self.handle_trades_un_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_un_subscription" => { self.handle_un_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"handle_ws_sendtx_api" => { self.handle_ws_sendtx_api(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_order_trade" => self.parse_ws_order_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ws_trade" => self.parse_ws_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"pong" => { crate::exchange_stubs::enqueue_spawn("pong", args.to_vec()); crate::Value::Null },
"request_id" => self.request_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"subscribe_private" => { crate::exchange_stubs::enqueue_spawn("subscribe_private", args.to_vec()); crate::Value::Null },
"subscribe_public" => { crate::exchange_stubs::enqueue_spawn("subscribe_public", args.to_vec()); crate::Value::Null },
"subscribe_public_multiple" => { crate::exchange_stubs::enqueue_spawn("subscribe_public_multiple", args.to_vec()); crate::Value::Null },
"un_watch_mark_price" => { crate::exchange_stubs::enqueue_spawn("un_watch_mark_price", args.to_vec()); crate::Value::Null },
"un_watch_mark_prices" => { crate::exchange_stubs::enqueue_spawn("un_watch_mark_prices", args.to_vec()); crate::Value::Null },
"un_watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_my_trades", args.to_vec()); crate::Value::Null },
"un_watch_order_book" => { crate::exchange_stubs::enqueue_spawn("un_watch_order_book", args.to_vec()); crate::Value::Null },
"un_watch_orders" => { crate::exchange_stubs::enqueue_spawn("un_watch_orders", args.to_vec()); crate::Value::Null },
"un_watch_ticker" => { crate::exchange_stubs::enqueue_spawn("un_watch_ticker", args.to_vec()); crate::Value::Null },
"un_watch_tickers" => { crate::exchange_stubs::enqueue_spawn("un_watch_tickers", args.to_vec()); crate::Value::Null },
"un_watch_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades", args.to_vec()); crate::Value::Null },
"unsubscribe" => { crate::exchange_stubs::enqueue_spawn("unsubscribe", args.to_vec()); crate::Value::Null },
"watch_balance" => { crate::exchange_stubs::enqueue_spawn("watch_balance", args.to_vec()); crate::Value::Null },
"watch_liquidations" => { crate::exchange_stubs::enqueue_spawn("watch_liquidations", args.to_vec()); crate::Value::Null },
"watch_mark_price" => { crate::exchange_stubs::enqueue_spawn("watch_mark_price", args.to_vec()); crate::Value::Null },
"watch_mark_prices" => { crate::exchange_stubs::enqueue_spawn("watch_mark_prices", args.to_vec()); crate::Value::Null },
"watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("watch_my_trades", args.to_vec()); crate::Value::Null },
"watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
"watch_orders" => { crate::exchange_stubs::enqueue_spawn("watch_orders", args.to_vec()); crate::Value::Null },
"watch_ticker" => { crate::exchange_stubs::enqueue_spawn("watch_ticker", args.to_vec()); crate::Value::Null },
"watch_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_tickers", args.to_vec()); crate::Value::Null },
"watch_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
_ => crate::Value::Null,
}
}
}
impl std::ops::Deref for LighterCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.parent) }
}
impl std::ops::DerefMut for LighterCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.parent) }
}
impl LighterCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.parent.describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchMarkPrice".to_string(), Value::Bool(true));
m.insert("watchMarkPrices".to_string(), Value::Bool(true));
m.insert("watchTickers".to_string(), Value::Bool(true));
m.insert("watchBidsAsks".to_string(), Value::Bool(false));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchTrades".to_string(), Value::Bool(true));
m.insert("watchTradesForSymbols".to_string(), Value::Bool(false));
m.insert("watchOrderBookForSymbols".to_string(), Value::Bool(false));
m.insert("watchBalance".to_string(), Value::Bool(true));
m.insert("watchLiquidations".to_string(), Value::Bool(true));
m.insert("watchLiquidationsForSymbols".to_string(), Value::Bool(false));
m.insert("watchMyLiquidations".to_string(), Value::Bool(false));
m.insert("watchMyLiquidationsForSymbols".to_string(), Value::Bool(false));
m.insert("watchOHLCV".to_string(), Value::Bool(false));
m.insert("watchOHLCVForSymbols".to_string(), Value::Bool(false));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchPositions".to_string(), Value::Bool(false));
m.insert("watchFundingRate".to_string(), Value::Bool(false));
m.insert("watchFundingRates".to_string(), Value::Bool(false));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m.insert("unWatchTicker".to_string(), Value::Bool(true));
m.insert("unWatchTickers".to_string(), Value::Bool(true));
m.insert("unWatchTrades".to_string(), Value::Bool(true));
m.insert("unWatchMyTrades".to_string(), Value::Bool(true));
m.insert("unWatchMarkPrice".to_string(), Value::Bool(true));
m.insert("unWatchMarkPrices".to_string(), Value::Bool(true));
m.insert("unWatchOrders".to_string(), Value::Bool(true));
m.insert("createOrderWs".to_string(), Value::Bool(true));
m.insert("cancelOrderWs".to_string(), Value::Bool(true));
m.insert("cancelAllOrdersWs".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Str("wss://mainnet.zklighter.elliot.ai/stream".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ws".to_string(), Value::Str("wss://testnet.zklighter.elliot.ai/stream".into()));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("requestId".to_string(), self.create_safe_dictionary(&[]));
m
}));
m
})]);
Value::Null
}
pub fn get_message_hash(&self, mut unifiedChannel: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut extra = get_arg(optional_args, 1, Value::Null);
let mut hash: Value = unifiedChannel;
if (symbol != Value::Null) {
hash = Value::Str(format!("{}{}", hash, Value::Str(format!("{}{}", Value::Str("::".into()), symbol).into())).into());
} else {
hash = Value::Str(format!("{}{}", hash, Value::Str("s".into())).into()); // tickers, orderbooks, ohlcvs ...
}
if (extra != Value::Null) {
hash = Value::Str(format!("{}{}", hash, Value::Str(format!("{}{}", Value::Str("::".into()), extra).into())).into());
}
return hash;
Value::Null
}
pub async fn subscribe_public(&mut self, mut messageHash: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subscribe".into()));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHash".to_string(), messageHash.clone());
m.insert("params".to_string(), params.clone());
m
});
let __ws_arg_0 = self.extend(request, &[params]);
return self.watch(url, messageHash.clone(), &[__ws_arg_0, messageHash.clone(), subscription]).await;
Value::Null
}
pub async fn subscribe_public_multiple(&mut self, mut messageHashes: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subscribe".into()));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHashes".to_string(), messageHashes.clone());
m.insert("params".to_string(), params.clone());
m
});
let __ws_arg_1 = self.extend(request, &[params]);
return self.watch_multiple(url, messageHashes.clone(), &[__ws_arg_1, messageHashes.clone(), subscription]).await;
Value::Null
}
pub async fn unsubscribe(&mut self, mut messageHash: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("unsubscribe".into()));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("messageHash".to_string(), messageHash.clone());
m.insert("params".to_string(), params.clone());
m
});
let __ws_arg_2 = self.extend(request, &[params]);
return self.watch(url, messageHash.clone(), &[__ws_arg_2, messageHash.clone(), subscription]).await;
Value::Null
}
pub async fn subscribe_private(&mut self, mut messageHash: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.parent.pre_load_lighter_library(&[]).await;
{ let __be_tmp = self.parent.create_auth(&[params.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null); if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("auth".into(), __be_tmp); } }
return self.subscribe_public(messageHash, &[params]).await;
Value::Null
}
pub fn handle_delta(&self, mut bookside: Value, mut delta: Value) {
let mut price: Value = self.safe_float_k(delta.clone(), "price", &[]);
let mut amount: Value = self.safe_float_k(delta, "size", &[]);
bookside.store(price, amount);
}
pub fn handle_deltas(&self, mut bookside: Value, mut deltas: Value) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_456: bool = true;
while { if !__for_first_456 { 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_456 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&deltas).as_f64().unwrap_or(f64::NAN) } {
self.handle_delta(bookside.clone(), get_value(&deltas, &i));
}
}
}
pub fn handle_order_book_message(&self, mut client: Value, mut message: Value, mut orderbook: Value) -> Value {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut data: Value = (match __pro_message.get("order_book").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
self.handle_deltas(crate::value::get_value_k(&orderbook, "asks"), self.safe_list_k(data.clone(), "asks", &[Value::from(vec![])]));
self.handle_deltas(crate::value::get_value_k(&orderbook, "bids"), self.safe_list_k(data.clone(), "bids", &[Value::from(vec![])]));
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), self.safe_integer_k(data, "offset", &[]));
let mut timestamp: Value = self.safe_integer_k(message, "timestamp", &[]);
add_element_to_object(&mut orderbook, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut orderbook, &Value::Str("datetime".into()), self.iso8601(timestamp));
return orderbook;
Value::Null
}
pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "channel": "order_book:0",
// "offset": 11413309,
// "order_book": {
// "code": 0,
// "asks": [
// {
// "price": "2979.64",
// "size": "61.9487"
// }
// ],
// "bids": [
// {
// "price": "2979.36",
// "size": "0.0000"
// }
// ],
// "offset": 11413309,
// "nonce": 3107818665
// },
// "timestamp": 1763448665923,
// "type": "update/order_book"
// }
//
let mut data: Value = (match __pro_message.get("order_book").cloned() { Some(__v) if matches!(__v, Value::Dict(_)) => __v, _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut channel: Value = (match __pro_message.get("channel").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut parts: Value = split(&channel, &Value::Str(":".into()));
let mut marketId: Value = parts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_k(message.clone(), "timestamp", &[]);
if !(in_op(&self.orderbooks, &symbol)) {
{ let __be_tmp = self.order_book(&[]); if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), __be_tmp); } }
}
let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
let mut type_var: Option<String> = (match __pro_message.get("type").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) }).as_str().map(str::to_owned);
if (type_var.as_deref() == Some("subscribed/order_book")) {
let mut parsed: Value = self.parse_order_book(data.clone(), symbol.clone(), &[timestamp, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("size".into())]);
add_element_to_object(&mut parsed, &Value::Str("nonce".into()), self.safe_integer_k(data, "offset", &[]));
orderbook.reset(parsed);
} else if (type_var.as_deref() == Some("update/order_book")) {
self.handle_order_book_message(client.clone(), message, orderbook.clone());
}
let mut messageHash: Value = self.get_message_hash(Value::Str("orderbook".into()), &[symbol]);
client.resolve(&[orderbook, messageHash]);
}
/*
* @method
* @name lighter#watchOrderBook
* @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://apidocs.lighter.xyz/docs/websocket-reference#order-book
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str(format!("{}{}", Value::Str("order_book/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
m
});
let mut messageHash: Value = self.get_message_hash(Value::Str("orderbook".into()), &[symbol]);
let __ws_arg_3 = self.extend(request, &[params]);
let mut orderbook: Value = self.subscribe_public(messageHash, &[__ws_arg_3]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name lighter#unWatchOrderBook
* @description unWatches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://apidocs.lighter.xyz/docs/websocket-reference#order-book
* @param {string} symbol unified symbol of the market
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn un_watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str(format!("{}{}", Value::Str("order_book/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
m
});
let mut subMessageHash: Value = self.get_message_hash(Value::Str("orderbook".into()), &[symbol]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let __ws_arg_4 = self.extend(request, &[params]);
return self.unsubscribe(messageHash, &[__ws_arg_4]).await;
Value::Null
}
pub fn handle_ticker(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// watchTicker
// {
// "channel": "market_stats:0",
// "market_stats": {
// "market_id": 0,
// "index_price": "3015.56",
// "mark_price": "3013.91",
// "open_interest": "122736286.659423",
// "open_interest_limit": "72057594037927936.000000",
// "funding_clamp_small": "0.0500",
// "funding_clamp_big": "4.0000",
// "last_trade_price": "3013.13",
// "current_funding_rate": "0.0012",
// "funding_rate": "0.0012",
// "funding_timestamp": 1763532000004,
// "daily_base_token_volume": 643235.2763,
// "daily_quote_token_volume": 1983505435.673896,
// "daily_price_low": 2977.42,
// "daily_price_high": 3170.81,
// "daily_price_change": -0.3061987051035322
// },
// "type": "update/market_stats"
// }
//
// watchTickers
// {
// "channel": "market_stats:all",
// "market_stats": {
// "96": {
// "market_id": 96,
// "index_price": "1.15901",
// "mark_price": "1.15954",
// "open_interest": "19392952.260530",
// "open_interest_limit": "50000000000000.000000",
// "funding_clamp_small": "0.0500",
// "funding_clamp_big": "4.0000",
// "last_trade_price": "1.15955",
// "current_funding_rate": "0.0000",
// "funding_rate": "0.0000",
// "funding_timestamp": 1763532000004,
// "daily_base_token_volume": 117634224.1,
// "daily_quote_token_volume": 136339744.383989,
// "daily_price_low": 1.15774,
// "daily_price_high": 1.16105,
// "daily_price_change": -0.004311757299805109
// }
// },
// "type": "update/market_stats"
// }
//
let mut data: Value = (match message.get("market_stats") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut channel: Option<String> = (match message.get("channel") { 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 (channel.as_deref() == Some("market_stats:all")) {
let mut marketIds: Value = object_keys(&data);
{
let mut i: Value = Value::Int(0);
let mut __for_first_457: bool = true;
while { if !__for_first_457 { 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_457 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketIds.len() as i64) as f64) } {
let mut marketId: Value = marketIds.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 market: Value = self.safe_market(&[marketId.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut ticker: Value = self.parse_ticker(data.as_map().and_then(|__m| marketId.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null), &[market.clone()]);
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker.clone()); }
client.resolve(&[ticker.clone(), self.get_message_hash(Value::Str("ticker".into()), &[symbol.clone()])]);
client.resolve(&[ticker.clone(), self.get_message_hash(Value::Str("ticker".into()), &[])]);
}
}
} else {
let mut marketId: Value = self.safe_string_k(data.clone(), "market_id", &[]);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut ticker: Value = self.parse_ticker(data, &[market]);
if let Value::Dict(__d) = &mut self.tickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), ticker.clone()); }
client.resolve(&[ticker, self.get_message_hash(Value::Str("ticker".into()), &[symbol])]);
}
}
/*
* @method
* @name lighter#watchTicker
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://apidocs.lighter.xyz/docs/websocket-reference#market-stats
* @param {string} symbol unified symbol of the market to fetch the ticker for, swap markets only, the market_stats channel does not serve spot markets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchTicker() is only supported for swap markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str(format!("{}{}", Value::Str("market_stats/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
m
});
let mut messageHash: Value = self.get_message_hash(Value::Str("ticker".into()), &[symbol]);
let __ws_arg_5 = self.extend(request, &[params]);
return self.subscribe_public(messageHash, &[__ws_arg_5]).await;
Value::Null
}
/*
* @method
* @name lighter#unWatchTicker
* @description unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
* @see https://apidocs.lighter.xyz/docs/websocket-reference#market-stats
* @param {string} symbol unified symbol of the market to fetch the ticker for, swap markets only, the market_stats channel does not serve spot markets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" unWatchTicker() is only supported for swap markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str(format!("{}{}", Value::Str("market_stats/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
m
});
let mut subMessageHash: Value = self.get_message_hash(Value::Str("ticker".into()), &[symbol]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let __ws_arg_6 = self.extend(request, &[params]);
return self.unsubscribe(messageHash, &[__ws_arg_6]).await;
Value::Null
}
/*
* @method
* @name lighter#watchTickers
* @see https://apidocs.lighter.xyz/docs/websocket-reference#market-stats
* @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, swap markets only, the market_stats channel does not serve spot markets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(true)]);
let mut firstMarket: Value = self.get_market_from_symbols(&[symbols.clone()]);
if (firstMarket != Value::Null) && (firstMarket.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" watchTickers() is only supported for swap markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str("market_stats/all".into()));
m
});
let mut messageHashes: Value = Value::from(vec![]);
let mut symbolsLength: Value = Value::Int(0);
if (symbols != Value::Null) {
symbolsLength = Value::Int(symbols.len() as i64);
}
if (symbols == Value::Null) || (symbolsLength.as_f64() == Some(0.0)) {
append_to_array(&mut messageHashes, self.get_message_hash(Value::Str("ticker".into()), &[]));
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_458: bool = true;
while { if !__for_first_458 { 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_458 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.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);
append_to_array(&mut messageHashes, self.get_message_hash(Value::Str("ticker".into()), &[symbol]));
}
}
}
let __ws_arg_7 = self.extend(request, &[params]);
let mut newTicker: Value = self.subscribe_public_multiple(messageHashes, &[__ws_arg_7]).await;
if is_true(&self.newUpdates) {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
add_element_to_object(&mut result, &crate::value::get_value_k(&newTicker, "symbol"), newTicker.clone());
return result;
}
return self.filter_by_array(self.tickers.clone(), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
/*
* @method
* @name lighter#unWatchTickers
* @description unWatches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
* @see https://apidocs.lighter.xyz/docs/websocket-reference#market-stats
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, swap markets only, the market_stats channel does not serve spot markets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(true)]);
let mut firstMarket: Value = self.get_market_from_symbols(&[symbols]);
if (firstMarket != Value::Null) && (firstMarket.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" unWatchTickers() is only supported for swap markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str("market_stats/all".into()));
m
});
let mut subMessageHash: Value = self.get_message_hash(Value::Str("ticker".into()), &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let __ws_arg_8 = self.extend(request, &[params]);
return self.unsubscribe(messageHash, &[__ws_arg_8]).await;
Value::Null
}
/*
* @method
* @name lighter#watchMarkPrice
* @see https://apidocs.lighter.xyz/docs/websocket-reference#market-stats
* @description watches a mark price
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_mark_price(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.watch_ticker(symbol, &[params]).await;
Value::Null
}
/*
* @method
* @name lighter#watchMarkPrices
* @see https://apidocs.lighter.xyz/docs/websocket-reference#market-stats
* @description watches mark prices
* @param {string[]} [symbols] unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn watch_mark_prices(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.watch_tickers(&[symbols, params]).await;
Value::Null
}
/*
* @method
* @name lighter#unWatchMarkPrice
* @see https://apidocs.lighter.xyz/docs/websocket-reference#market-stats
* @description unWatches a mark price
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_mark_price(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.un_watch_ticker(symbol, &[params]).await;
Value::Null
}
/*
* @method
* @name lighter#unWatchMarkPrices
* @see https://apidocs.lighter.xyz/docs/websocket-reference#market-stats
* @description unWatches mark prices
* @param {string[]} [symbols] unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn un_watch_mark_prices(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.un_watch_tickers(&[symbols, params]).await;
Value::Null
}
pub fn parse_ws_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "trade_id": 526801155,
// "tx_hash": "1998d9df580acb7540aa141cc369d6ef926d003b3062196d2007bca15f978ab208e0caae4ac5872b",
// "type": "trade",
// "market_id": 0,
// "size": "0.0346",
// "price": "3028.85",
// "usd_amount": "104.798210",
// "ask_id": 281475673670566,
// "bid_id": 562949291740362,
// "ask_client_id": 76303170,
// "bid_client_id": 27601,
// "ask_account_id": 99349,
// "bid_account_id": 243008,
// "is_maker_ask": false,
// "block_height": 102322769,
// "timestamp": 1763623734215,
// "taker_position_size_before": "0.0346",
// "taker_entry_quote_before": "104.359926",
// "taker_initial_margin_fraction_before": 500,
// "taker_position_sign_changed": true,
// "maker_fee": 20,
// "maker_position_size_before": "2.1277",
// "maker_entry_quote_before": "6444.179555",
// "maker_initial_margin_fraction_before": 200
// }
//
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "timestamp", &[]);
let mut tradeId: Value = self.safe_string_k(trade.clone(), "trade_id", &[]);
let mut priceString: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut amountString: Value = self.safe_string_k(trade.clone(), "size", &[]);
let mut isMakerAsk: Value = self.safe_bool_k(trade.clone(), "is_maker_ask", &[]);
let mut side: Value = (if (isMakerAsk.as_bool() == Some(true)) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), tradeId);
m.insert("order".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), Value::Str("taker".into()));
m.insert("price".to_string(), priceString);
m.insert("amount".to_string(), amountString);
m.insert("cost".to_string(), self.safe_string_k(trade, "usd_amount", &[]));
m.insert("fee".to_string(), Value::Null);
m
}), &[market]);
Value::Null
}
pub fn handle_trades(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {
// "channel": "trade:0",
// "liquidation_trades": [],
// "nonce": 3159738569,
// "trades": [
// {
// "trade_id": 526801155,
// "tx_hash": "1998d9df580acb7540aa141cc369d6ef926d003b3062196d2007bca15f978ab208e0caae4ac5872b",
// "type": "trade",
// "market_id": 0,
// "size": "0.0346",
// "price": "3028.85",
// "usd_amount": "104.798210",
// "ask_id": 281475673670566,
// "bid_id": 562949291740362,
// "ask_client_id": 76303170,
// "bid_client_id": 27601,
// "ask_account_id": 99349,
// "bid_account_id": 243008,
// "is_maker_ask": false,
// "block_height": 102322769,
// "timestamp": 1763623734215,
// "taker_position_size_before": "0.0346",
// "taker_entry_quote_before": "104.359926",
// "taker_initial_margin_fraction_before": 500,
// "taker_position_sign_changed": true,
// "maker_fee": 20,
// "maker_position_size_before": "2.1277",
// "maker_entry_quote_before": "6444.179555",
// "maker_initial_margin_fraction_before": 200
// }
// ],
// "type": "subscribed/trade"
// }
//
let mut liquidationData: Value = (match __pro_message.get("liquidation_trades").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut liquidationDataLength: f64 = ((liquidationData.len() as i64) as f64);
if liquidationDataLength > ((0i64) as f64) {
self.handle_liquidation(client.clone(), message);
}
let mut data: Value = (match __pro_message.get("trades").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut channel: Value = (match __pro_message.get("channel").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut parts: Value = split(&channel, &Value::Str(":".into()));
let mut marketId: Value = parts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut stored: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
stored = ArrayCache::new(limit);
if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), stored.clone()); }
}
let mut dataLength: Value = Value::Int(data.len() as i64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_459: bool = true;
while { if !__for_first_459 { 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_459 = false; i.as_f64().unwrap_or(f64::NAN) < dataLength.as_f64().unwrap_or(f64::NAN) } {
let mut iReversed: Value = (match (&((match (&(dataLength), &(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 })), &(i)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut trade: Value = self.parse_ws_trade(get_value(&data, &iReversed), &[market.clone()]);
stored.append(trade);
}
}
let mut messageHash: Value = self.get_message_hash(Value::Str("trade".into()), &[symbol]);
client.resolve(&[stored, messageHash]);
}
/*
* @method
* @name lighter#watchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://apidocs.lighter.xyz/docs/websocket-reference#trade
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str(format!("{}{}", Value::Str("trade/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
m
});
let mut messageHash: Value = self.get_message_hash(Value::Str("trade".into()), &[market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)]);
let __ws_arg_9 = self.extend(request, &[params]);
let mut trades: Value = self.subscribe_public(messageHash, &[__ws_arg_9]).await;
return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name lighter#unWatchTrades
* @description unsubscribe from the trades channel
* @see https://apidocs.lighter.xyz/docs/websocket-reference#trade
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn un_watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str(format!("{}{}", Value::Str("trade/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
m
});
let mut subMessageHash: Value = self.get_message_hash(Value::Str("trade".into()), &[market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let __ws_arg_10 = self.extend(request, &[params]);
return self.unsubscribe(messageHash, &[__ws_arg_10]).await;
Value::Null
}
pub fn parse_ws_order_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "trade_id": 526801155,
// "tx_hash": "1998d9df580acb7540aa141cc369d6ef926d003b3062196d2007bca15f978ab208e0caae4ac5872b",
// "type": "trade",
// "market_id": 0,
// "size": "0.0346",
// "price": "3028.85",
// "usd_amount": "104.798210",
// "ask_id": 281475673670566,
// "bid_id": 562949291740362,
// "ask_client_id": 76303170,
// "bid_client_id": 27601,
// "ask_account_id": 99349,
// "bid_account_id": 243008,
// "is_maker_ask": false,
// "block_height": 102322769,
// "timestamp": 1763623734215,
// "taker_position_size_before": "0.0346",
// "taker_entry_quote_before": "104.359926",
// "taker_initial_margin_fraction_before": 500,
// "taker_position_sign_changed": true,
// "maker_fee": 20,
// "maker_position_size_before": "2.1277",
// "maker_entry_quote_before": "6444.179555",
// "maker_initial_margin_fraction_before": 200
// }
//
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "timestamp", &[]);
let mut tradeId: Value = self.safe_string_k(trade.clone(), "trade_id", &[]);
let mut priceString: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut amountString: Value = self.safe_string_k(trade.clone(), "size", &[]);
let mut costString: Value = self.safe_string_k(trade.clone(), "usd_amount", &[]);
let mut isMakerAsk: Value = self.safe_bool_k(trade.clone(), "is_maker_ask", &[]);
let mut accountIndex: Value = self.safe_integer_k(trade.clone(), "accountIndex", &[]);
let mut bidAccountId: Value = self.safe_integer_k(trade.clone(), "bid_account_id", &[]);
let mut askAccountId: Value = self.safe_integer_k(trade.clone(), "ask_account_id", &[]);
let mut side: Value = Value::Null;
let mut order: Value = Value::Null;
let mut takerOrMaker: Value = Value::Null;
if (accountIndex != Value::Null) {
if (bidAccountId.as_f64() == accountIndex.as_f64()) {
// Own trades should use the account's order side
side = Value::Str("buy".into());
order = self.safe_string_k(trade.clone(), "bid_id", &[]);
takerOrMaker = (if (isMakerAsk.as_bool() == Some(true)) { Value::Str("taker".into()) } else { Value::Str("maker".into()) });
} else if (askAccountId.as_f64() == accountIndex.as_f64()) {
side = Value::Str("sell".into());
order = self.safe_string_k(trade.clone(), "ask_id", &[]);
takerOrMaker = (if (isMakerAsk.as_bool() == Some(true)) { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
}
}
// public trades use Lighter's taker-side convention
if (side == Value::Null) {
side = (if (isMakerAsk.as_bool() == Some(true)) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
}
let mut fee: Value = Value::Null;
if (takerOrMaker != Value::Null) {
let mut feeRateRaw: Value = (if (takerOrMaker.as_str() == Some("maker")) { self.safe_string_k(trade.clone(), "maker_fee", &[]) } else { self.safe_string_k(trade.clone(), "taker_fee", &[]) });
let mut feeRate: Value = (if (feeRateRaw != Value::Null) { crate::precise::Precise::stringDiv(&feeRateRaw, &Value::Str("1000000".into())) } else { Value::Str("0".into()) });
let mut feeAmount: Value = crate::precise::Precise::stringMul(&costString, &feeRate);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeAmount);
m.insert("currency".to_string(), Value::Str("USDC".into()));
m.insert("rate".to_string(), feeRate);
m
});
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade);
m.insert("id".to_string(), tradeId);
m.insert("order".to_string(), order);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), priceString);
m.insert("amount".to_string(), amountString);
m.insert("cost".to_string(), costString);
m.insert("fee".to_string(), fee);
m
}), &[market]);
Value::Null
}
pub fn handle_my_trades(&mut self, mut client: Value, mut message: Value) -> Value {
//
// {
// "channel": "account_all_trades:723310",
// "trades": {
// 13: [{
// "trade_id": 526801155,
// "tx_hash": "1998d9df580acb7540aa141cc369d6ef926d003b3062196d2007bca15f978ab208e0caae4ac5872b",
// "type": "trade",
// "market_id": 0,
// "size": "0.0346",
// "price": "3028.85",
// "usd_amount": "104.798210",
// "ask_id": 281475673670566,
// "bid_id": 562949291740362,
// "ask_client_id": 76303170,
// "bid_client_id": 27601,
// "ask_account_id": 99349,
// "bid_account_id": 243008,
// "is_maker_ask": false,
// "block_height": 102322769,
// "timestamp": 1763623734215,
// "taker_position_size_before": "0.0346",
// "taker_entry_quote_before": "104.359926",
// "taker_initial_margin_fraction_before": 500,
// "taker_position_sign_changed": true,
// "maker_fee": 20,
// "maker_position_size_before": "2.1277",
// "maker_entry_quote_before": "6444.179555",
// "maker_initial_margin_fraction_before": 200
// }]
// },
// "type": "update/account_all_trades"
// }
//
let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[Value::Str("".into())]);
let mut parts: Value = split(&channel, &Value::Str(":".into()));
let mut accountIndex: Value = parts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut data: Value = self.safe_dict_k(message, "trades", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketIds: Value = object_keys(&data);
let mut idsLength: f64 = ((marketIds.len() as i64) as f64);
if (idsLength == 0.0) {
return Value::Bool(false);
}
if (self.myTrades.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCache::new(limit);
}
let mut stored: Value = self.myTrades.clone();
let mut messageHash: Value = self.get_message_hash(Value::Str("myTrades".into()), &[]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_461: bool = true;
while { if !__for_first_461 { 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_461 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketIds.len() as i64) as f64) } {
let mut marketId: Value = marketIds.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 market: Value = self.safe_market(&[marketId.clone()]);
let mut trades: Value = self.safe_list(data.clone(), marketId, &[Value::from(vec![])]);
let mut tradesLength: Value = Value::Int(trades.len() as i64);
{
let mut j: Value = Value::Int(0);
let mut __for_first_460: bool = true;
while { if !__for_first_460 { 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_460 = false; j.as_f64().unwrap_or(f64::NAN) < tradesLength.as_f64().unwrap_or(f64::NAN) } {
let mut jReversed: Value = (match (&((match (&(tradesLength), &(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 })), &(j)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut tradeRaw: Value = get_value(&trades, &jReversed);
add_element_to_object(&mut tradeRaw, &Value::Str("accountIndex".into()), accountIndex.clone());
crate::set_value(&mut trades, &jReversed, tradeRaw.clone());
let mut trade: Value = self.parse_ws_order_trade(tradeRaw, &[market.clone()]);
stored.append(trade.clone());
let mut symbol: Value = trade.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol != Value::Null) {
let mut symbolSpecificMessageHash: Value = self.get_message_hash(Value::Str("myTrades".into()), &[symbol]);
client.resolve(&[stored.clone(), symbolSpecificMessageHash]);
}
}
}
}
}
client.resolve(&[stored, messageHash]);
return Value::Bool(true);
Value::Null
}
/*
* @method
* @name lighter#watchMyTrades
* @description subscribe to recent trades of an account.
* @see https://apidocs.lighter.xyz/docs/websocket-reference#account-all-trades
* @param {string} [symbol] unified market symbol
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut accountIndex: Value = Value::Null;
{ let __destr_tmp = self.parent.handle_account_index(params.clone(), Value::Str("watchMyTrades".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await; accountIndex = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut messageHash: Value = self.get_message_hash(Value::Str("myTrades".into()), &[]);
if (symbol != Value::Null) {
let mut market: Value = self.market(symbol.clone());
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
messageHash = self.get_message_hash(Value::Str("myTrades".into()), &[symbol.clone()]);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str(format!("{}{}", Value::Str("account_all_trades/".into()), self.number_to_string(accountIndex)).into()));
m
});
let __ws_arg_11 = self.extend(request, &[params]);
let mut trades: Value = self.subscribe_public(messageHash, &[__ws_arg_11]).await;
if is_true(&self.newUpdates) {
limit = trades.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(trades, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name lighter#unWatchMyTrades
* @description unsubscribe from the account trades channel
* @see https://apidocs.lighter.xyz/docs/websocket-reference#account-all-trades
* @param {string} [symbol] not supported by lighter.unWatchMyTrades, the account trades channel covers every market
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @returns {any} status of the unwatch request
*/
pub async fn un_watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol != Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" unWatchMyTrades() does not support a symbol argument, the account trades channel covers every market, unWatch from all markets only".into()))));
}
let mut accountIndex: Value = Value::Null;
{ let __destr_tmp = self.parent.handle_account_index(params.clone(), Value::Str("unWatchMyTrades".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await; accountIndex = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut subMessageHash: Value = self.get_message_hash(Value::Str("myTrades".into()), &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str(format!("{}{}", Value::Str("account_all_trades/".into()), self.number_to_string(accountIndex)).into()));
m
});
let __ws_arg_12 = self.extend(request, &[params]);
return self.unsubscribe(messageHash, &[__ws_arg_12]).await;
Value::Null
}
pub fn parse_ws_liquidation(&self, mut liquidation: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "trade_id": 526801155,
// "tx_hash": "1998d9df580acb7540aa141cc369d6ef926d003b3062196d2007bca15f978ab208e0caae4ac5872b",
// "type": "liquidation",
// "market_id": 0,
// "size": "0.0346",
// "price": "3028.85",
// "usd_amount": "104.798210",
// "ask_id": 281475673670566,
// "bid_id": 562949291740362,
// "ask_client_id": 76303170,
// "bid_client_id": 27601,
// "ask_account_id": 99349,
// "bid_account_id": 243008,
// "is_maker_ask": false,
// "block_height": 102322769,
// "timestamp": 1763623734215,
// "taker_position_size_before": "0.0346",
// "taker_entry_quote_before": "104.359926",
// "taker_initial_margin_fraction_before": 500,
// "taker_position_sign_changed": true,
// "maker_fee": 20,
// "maker_position_size_before": "2.1277",
// "maker_entry_quote_before": "6444.179555",
// "maker_initial_margin_fraction_before": 200
// }
//
let mut timestamp: Value = self.safe_integer_k(liquidation.clone(), "timestamp", &[]);
let mut isMakerAsk: Value = self.safe_bool_k(liquidation.clone(), "is_maker_ask", &[]);
let mut side: Value = (if (isMakerAsk.as_bool() == Some(true)) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
let mut contracts: Value = self.safe_string_k(liquidation.clone(), "size", &[]);
let mut contractSize: Value = self.safe_string_k(market.clone(), "contractSize", &[]);
let mut price: Value = self.safe_string_k(liquidation.clone(), "price", &[]);
let mut baseValue: Value = crate::precise::Precise::stringMul(&contracts, &contractSize);
let mut quoteValue: Value = crate::precise::Precise::stringMul(&baseValue, &price);
if (market == Value::Null) {
return Value::Null;
}
return self.safe_liquidation(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), liquidation);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("contracts".to_string(), contracts);
m.insert("contractSize".to_string(), contractSize);
m.insert("price".to_string(), price);
m.insert("side".to_string(), side);
m.insert("baseValue".to_string(), baseValue);
m.insert("quoteValue".to_string(), quoteValue);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
}), &[]);
Value::Null
}
pub fn handle_liquidation(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "channel": "trade:0",
// "liquidation_trades": [],
// "nonce": 3159738569,
// "trades": [
// {
// "trade_id": 526801155,
// "tx_hash": "1998d9df580acb7540aa141cc369d6ef926d003b3062196d2007bca15f978ab208e0caae4ac5872b",
// "type": "trade",
// "market_id": 0,
// "size": "0.0346",
// "price": "3028.85",
// "usd_amount": "104.798210",
// "ask_id": 281475673670566,
// "bid_id": 562949291740362,
// "ask_client_id": 76303170,
// "bid_client_id": 27601,
// "ask_account_id": 99349,
// "bid_account_id": 243008,
// "is_maker_ask": false,
// "block_height": 102322769,
// "timestamp": 1763623734215,
// "taker_position_size_before": "0.0346",
// "taker_entry_quote_before": "104.359926",
// "taker_initial_margin_fraction_before": 500,
// "taker_position_sign_changed": true,
// "maker_fee": 20,
// "maker_position_size_before": "2.1277",
// "maker_entry_quote_before": "6444.179555",
// "maker_initial_margin_fraction_before": 200
// }
// ],
// "type": "subscribed/trade"
// }
//
let mut data: Value = (match message.get("liquidation_trades") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
let mut channel: Value = (match message.get("channel") { 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::Str("".into()) });
let mut parts: Value = split(&channel, &Value::Str(":".into()));
let mut marketId: Value = parts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut market: Value = self.safe_market(&[marketId]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut stored: Value = self.safe_value(self.liquidations.clone(), symbol.clone(), &[]);
if (stored == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "liquidationsLimit", &[Value::Int(1000)]);
self.liquidations = ArrayCache::new(limit);
stored = self.liquidations.clone();
}
let mut dataLength: Value = Value::Int(data.len() as i64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_462: bool = true;
while { if !__for_first_462 { 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_462 = false; i.as_f64().unwrap_or(f64::NAN) < dataLength.as_f64().unwrap_or(f64::NAN) } {
let mut iReversed: Value = (match (&((match (&(dataLength), &(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 })), &(i)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut liquidation: Value = self.parse_ws_liquidation(get_value(&data, &iReversed), &[market.clone()]);
stored.append(liquidation);
}
}
let mut messageHash: Value = self.get_message_hash(Value::Str("liquidations".into()), &[symbol]);
client.resolve(&[stored, messageHash]);
}
/*
* @method
* @name lighter#watchLiquidations
* @description watch the public liquidations of a trading pair
* @see https://apidocs.lighter.xyz/docs/websocket-reference#trade
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn watch_liquidations(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("channel".to_string(), Value::Str(format!("{}{}", Value::Str("trade/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()));
m
});
let mut messageHash: Value = self.get_message_hash(Value::Str("liquidations".into()), &[symbol]);
let __ws_arg_13 = self.extend(request, &[params]);
return self.subscribe_public(messageHash, &[__ws_arg_13]).await;
Value::Null
}
/*
* @method
* @name lighter#watchBalance
* @description watch balance and get the amount of funds available for trading or funds locked in orders
* @see https://apidocs.lighter.xyz/docs/websocket-reference#account-all-assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'spot' or 'swap', default is 'swap'
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn watch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut defaultType: Value = self.safe_string2(self.options.clone(), Value::Str("watchBalance".into()), Value::Str("defaultType".into()), &[Value::Str("spot".into())]);
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_param_string(params.clone(), Value::Str("type".into()), &[defaultType]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut accountIndex: Value = Value::Null;
{ let __destr_tmp = self.parent.handle_account_index(params.clone(), Value::Str("watchBalance".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await; accountIndex = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut messageHash: Value = self.get_message_hash(Value::Str("balances".into()), &[Value::Null, type_var.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (type_var.as_str() == Some("spot")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("channel".into(), Value::Str(format!("{}{}", Value::Str("account_all_assets/".into()), self.number_to_string(accountIndex.clone())).into())); }
let __ws_arg_14 = self.extend(request.clone(), &[params.clone()]);
return self.subscribe_private(messageHash.clone(), &[__ws_arg_14]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("channel".into(), Value::Str(format!("{}{}", Value::Str("user_stats/".into()), self.number_to_string(accountIndex)).into())); }
let __ws_arg_15 = self.extend(request, &[params]);
return self.subscribe_public(messageHash, &[__ws_arg_15]).await;
}
Value::Null
}
pub fn handle_balance(&mut self, mut client: Value, mut message: Value) -> Value {
//
// spot balance
// {
// "assets": {
// "1": {
// "symbol": "ETH",
// "asset_id": 1,
// "balance": "7.1072",
// "locked_balance": "0.0000"
// },
// "3": {
// "symbol": "USDC",
// "asset_id": 3,
// "balance": "6343.581906",
// "locked_balance": "297.000000"
// }
// },
// "channel": "account_all_assets:1234",
// "timestamp": 1773158679717,
// "type": "update/account_all_assets"
// }
//
// swap balance
// {
// "channel": "user_stats:10",
// "stats": {
// "collateral": "5000.00",
// "portfolio_value": "15000.00",
// "leverage": "3.0",
// "available_balance": "2000.00",
// "margin_usage": "0.80",
// "buying_power": "4000.00",
// "account_trading_mode": 1,
// "cross_stats":{
// "collateral":"0.000000",
// "portfolio_value":"0.000000",
// "leverage":"0.00",
// "available_balance":"0.000000",
// "margin_usage":"0.00",
// "buying_power":"0"
// },
// "total_stats":{
// "collateral":"0.000000",
// "portfolio_value":"0.000000",
// "leverage":"0.00",
// "available_balance":"0.000000",
// "margin_usage":"0.00",
// "buying_power":"0"
// }
// },
// "timestamp": 1773158679717,
// "type": "update/user_stats"
// }
//
let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[Value::Str("".into())]);
let mut type_var: Value = Value::Str("spot".into());
if Value::Int(channel.as_str().and_then(|__s| __s.find("user_stats:")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
type_var = Value::Str("swap".into());
}
let mut balance: Value = self.safe_dict(self.balance.clone(), type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (type_var.as_str() == Some("spot")) {
let mut assets: Value = self.safe_dict_k(message.clone(), "assets", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut assetIds: Value = object_keys(&assets);
{
let mut i: Value = Value::Int(0);
let mut __for_first_463: bool = true;
while { if !__for_first_463 { 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_463 = false; i.as_f64().unwrap_or(f64::NAN) < ((assetIds.len() as i64) as f64) } {
let mut assetId: Value = assetIds.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 asset: Value = assets.as_map().and_then(|__m| assetId.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
let mut codeId: Value = self.safe_string_k(asset.clone(), "symbol", &[]);
let mut code: Value = self.safe_currency_code(codeId, &[]);
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("used".into()), self.safe_string_k(asset.clone(), "locked_balance", &[]));
add_element_to_object(&mut account, &Value::Str("total".into()), self.safe_string_k(asset, "balance", &[]));
if (code != Value::Null) {
if let Value::Dict(__d) = &mut balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account.clone()); }
}
}
}
} else {
let mut stats: Value = self.safe_dict_k(message.clone(), "stats", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), self.safe_string_k(stats.clone(), "available_balance", &[]));
add_element_to_object(&mut account, &Value::Str("total".into()), self.safe_string_k(stats.clone(), "collateral", &[]));
add_element_to_object(&mut account, &Value::Str("info".into()), stats);
if let Value::Dict(__d) = &mut balance { std::sync::Arc::make_mut(__d).insert("USDC".into(), account); }
}
let mut timestamp: Value = self.safe_integer_k(message, "timestamp", &[]);
add_element_to_object(&mut balance, &Value::Str("timestamp".into()), timestamp.clone());
add_element_to_object(&mut balance, &Value::Str("datetime".into()), self.iso8601(timestamp));
{ let __be_tmp = self.safe_balance(balance.clone()); if let Value::Dict(__d) = &mut self.balance { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&type_var), __be_tmp); } }
let mut messageHash: Value = self.get_message_hash(Value::Str("balances".into()), &[Value::Null, type_var.clone()]);
client.resolve(&[get_value(&self.balance, &type_var), messageHash]);
return Value::Bool(true);
Value::Null
}
/*
* @name lighter#watchOrders
* @description watches information on multiple orders made by the user
* @see https://apidocs.lighter.xyz/docs/websocket-reference#account-all-orders
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut accountIndex: Value = Value::Null;
{ let __destr_tmp = self.parent.handle_account_index(params.clone(), Value::Str("watchOrders".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await; accountIndex = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut messageHash: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
let mut market: Value = self.market(symbol.clone());
messageHash = self.get_message_hash(Value::Str("orders".into()), &[market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("channel".into(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("account_orders/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str("/".into())).into()), self.number_to_string(accountIndex.clone())).into())); }
} else {
messageHash = self.get_message_hash(Value::Str("orders".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("channel".into(), Value::Str(format!("{}{}", Value::Str("account_all_orders/".into()), self.number_to_string(accountIndex)).into())); }
}
let __ws_arg_16 = self.extend(request, &[params]);
let mut orders: Value = self.subscribe_private(messageHash, &[__ws_arg_16]).await;
if is_true(&self.newUpdates) {
limit = orders.get_limit(symbol.clone(), limit.clone());
}
return self.filter_by_symbol_since_limit(orders, &[symbol, since, limit, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name lighter#unWatchOrders
* @description unWatches information on multiple orders made by the user
* @see https://apidocs.lighter.xyz/docs/websocket-reference#account-all-orders
* @param {string} symbol unified market symbol of the market orders were made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn un_watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut accountIndex: Value = Value::Null;
{ let __destr_tmp = self.parent.handle_account_index(params.clone(), Value::Str("unWatchOrders".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await; accountIndex = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut subMessageHash: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
let mut market: Value = self.market(symbol);
subMessageHash = self.get_message_hash(Value::Str("orders".into()), &[market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("channel".into(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("account_orders/".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into()), Value::Str("/".into())).into()), self.number_to_string(accountIndex.clone())).into())); }
} else {
subMessageHash = self.get_message_hash(Value::Str("orders".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("channel".into(), Value::Str(format!("{}{}", Value::Str("account_all_orders/".into()), self.number_to_string(accountIndex)).into())); }
}
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
let __ws_arg_17 = self.extend(request, &[params]);
return self.unsubscribe(messageHash, &[__ws_arg_17]).await;
Value::Null
}
pub fn request_id(&self, mut url: Value) -> Value {
let mut options: Value = self.safe_dict_k(self.options.clone(), "requestId", &[self.create_safe_dictionary(&[])]);
let mut previousValue: Value = self.safe_integer(options.clone(), url.clone(), &[Value::Int(0)]);
let mut newValue: Value = self.sum(&[previousValue, Value::Int(1)]);
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("requestId".into())), &url, newValue.clone());
return self.number_to_string(newValue);
Value::Null
}
/*
* @method
* @name lighter#createOrderWs
* @description create a trade order
* @see https://apidocs.lighter.xyz/docs/websocket-reference#send-tx
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float|undefined} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.timeInForce] 'GTT' or 'IOC', default is 'GTT'
* @param {int} [params.clientOrderId] client order id, should be unique for each order, default is a random number
* @param {string} [params.triggerPrice] trigger price for stop loss or take profit orders, in units of the quote currency
* @param {boolean} [params.reduceOnly] whether the order is reduce only, default false
* @param {int} [params.nonce] nonce for the account
* @param {int} [params.apiKeyIndex] apiKeyIndex
* @param {int} [params.accountIndex] accountIndex
* @param {int} [params.orderExpiry] orderExpiry
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order_ws(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("jsonapi/sendtx:".into()), requestId).into());
let mut txTypetxInfoordermarketVariable = self.parent.sign_and_create_order(Value::Str("createOrderWs".into()), symbol, type_var, side, amount, &[price, params]).await;
let mut txType: Value = txTypetxInfoordermarketVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoordermarketVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut order: Value = txTypetxInfoordermarketVariable.as_array().and_then(|__arr| __arr.get(2)).cloned().unwrap_or(Value::Null);
let mut market: Value = txTypetxInfoordermarketVariable.as_array().and_then(|__arr| __arr.get(3)).cloned().unwrap_or(Value::Null);
let mut parsedTx: Value = self.parse_json_value(txInfo);
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("jsonapi/sendtx".into()));
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), parsedTx);
m
}));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId);
m
});
let mut rawMessage: Value = self.watch(url, messageHash.clone(), &[message, messageHash.clone(), subscription]).await;
return self.parse_order(self.deep_extend(rawMessage, &[order]), &[market]);
Value::Null
}
/*
* @method
* @name lighter#cancelOrderWs
* @description cancel multiple orders
* @see https://apidocs.lighter.xyz/docs/websocket-reference#send-tx
* @param {string} id order id
* @param {string} [symbol] unified market symbol, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {string} [params.apiKeyIndex] api key index
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order_ws(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("jsonapi/sendtx:".into()), requestId).into());
let mut txTypetxInfomarketVariable = self.parent.sign_and_cancel_order(Value::Str("cancelOrderWs".into()), id, &[symbol, params]).await;
let mut txType: Value = txTypetxInfomarketVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfomarketVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut market: Value = txTypetxInfomarketVariable.as_array().and_then(|__arr| __arr.get(2)).cloned().unwrap_or(Value::Null);
let mut parsedTx: Value = self.parse_json_value(txInfo);
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("jsonapi/sendtx".into()));
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), parsedTx);
m
}));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId);
m
});
let mut rawMessage: Value = self.watch(url, messageHash.clone(), &[message, messageHash.clone(), subscription]).await;
return self.parse_order(rawMessage, &[market]);
Value::Null
}
/*
* @method
* @name lighter#cancelAllOrdersWs
* @description cancel all open orders in a market
* @see https://apidocs.lighter.xyz/docs/websocket-reference#send-tx
* @param {string} [symbol] unified market symbol of the market to cancel orders in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {string} [params.apiKeyIndex] api key index
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_all_orders_ws(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
let mut requestId: Value = self.request_id(url.clone());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("jsonapi/sendtx:".into()), requestId).into());
let mut txTypetxInfoVariable = self.parent.sign_and_cancel_all_orders(Value::Str("cancelAllOrdersWs".into()), &[symbol, params]).await;
let mut txType: Value = txTypetxInfoVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut parsedTx: Value = self.parse_json_value(txInfo);
let mut message: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("jsonapi/sendtx".into()));
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId.clone());
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), parsedTx);
m
}));
m
});
let mut subscription: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), requestId);
m
});
let mut rawMessage: Value = self.watch(url, messageHash.clone(), &[message, messageHash.clone(), subscription]).await;
return self.parse_orders(Value::from(vec![rawMessage]), &[]);
Value::Null
}
pub fn handle_ws_sendtx_api(&self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
//
// {"code":200,"id":"1786459718284","predicted_execution_time_ms":1786459719662,"tx_hash":"9959d3feb30d0a89fcfd4532f071ac99a98ee1202aa2a7f2c1299932b1e540b6ecdabd2b92616a14","type":"jsonapi/sendtx"}
//
let mut id: Value = (match __pro_message.get("id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
client.resolve(&[message, Value::Str(format!("{}{}", Value::Str("jsonapi/sendtx:".into()), id).into())]);
}
pub fn handle_orders(&mut self, mut client: Value, mut message: Value) -> Value {
//
// {
// "account": {ACCOUNT_INDEX},
// "channel": "account_orders:{MARKET_INDEX}",
// "nonce": INTEGER,
// "orders": {
// "{MARKET_INDEX}": [Order] // the only present market index will be the one provided
// },
// "type": "update/account_orders"
// }
//
// {
// "channel": "account_all_orders:{ACCOUNT_ID}",
// "orders": {
// "{MARKET_INDEX}": [Order]
// },
// "type": "update/account_all_orders"
// }
//
let mut data: Value = self.safe_dict_k(message, "orders", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketIds: Value = object_keys(&data);
let mut idsLength: f64 = ((marketIds.len() as i64) as f64);
if (idsLength == 0.0) {
return Value::Bool(false);
}
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCache::new(limit);
}
let mut stored: Value = self.orders.clone();
let mut messageHash: Value = self.get_message_hash(Value::Str("orders".into()), &[]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_465: bool = true;
while { if !__for_first_465 { 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_465 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketIds.len() as i64) as f64) } {
let mut marketId: Value = marketIds.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 market: Value = self.safe_market(&[marketId.clone()]);
let mut orders: Value = self.safe_list(data.clone(), marketId, &[Value::from(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_464: bool = true;
while { if !__for_first_464 { 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_464 = false; j.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut order: Value = self.parse_order(orders.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), &[market.clone()]);
stored.append(order.clone());
let mut symbol: Value = order.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol != Value::Null) {
let mut symbolSpecificMessageHash: Value = self.get_message_hash(Value::Str("orders".into()), &[symbol]);
client.resolve(&[stored.clone(), symbolSpecificMessageHash]);
}
}
}
}
}
client.resolve(&[stored, messageHash]);
return Value::Bool(true);
Value::Null
}
pub fn handle_error_message(&self, mut client: Value, mut message: Value) -> Value {
//
// {
// "error": {
// "code": 30005,
// "message": "Invalid Channel: (marketId)"
// }
// }
//
let mut error: Value = self.safe_dict_k(message.clone(), "error", &[]);
let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if (error != Value::Null) {
let mut code: Value = self.safe_string_k(error.clone(), "code", &[]);
let mut errorMessage: Value = self.safe_string_k(error.clone(), "message", &[]);
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), json_stringify(&message)).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), code.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorMessage.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
#[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
let mut id: Value = self.safe_string_k(message.clone(), "id", &[]);
let mut handled: bool = false;
if (id != Value::Null) {
let mut subscriptionKeys: Value = object_keys(&get_value(&client, &Value::Str("subscriptions".into())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_466: bool = true;
while { if !__for_first_466 { 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_466 = false; i.as_f64().unwrap_or(f64::NAN) < ((subscriptionKeys.len() as i64) as f64) } {
let mut subscriptionHash: Value = subscriptionKeys.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 subscriptionId: Value = self.safe_string(get_value(&get_value(&client, &Value::Str("subscriptions".into())), &subscriptionHash), Value::Str("id".into()), &[]);
let mut subscription: Value = self.safe_string(get_value(&get_value(&client, &Value::Str("subscriptions".into())), &subscriptionHash), Value::Str("subscription".into()), &[]);
if (id.as_str() == subscriptionId.as_str()) {
client.reject(&[e.clone(), subscriptionHash]);
handled = true;
if (subscription != Value::Null) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &subscription);
}
}
}
}
}
if !handled {
client.reject(&[e]);
}
}
return Value::Bool(true);
Value::Null
}
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (match &message { Value::Dict(__d) => __d.clone(), _ => std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
if !(self.handle_error_message(client.clone(), message.clone()).as_bool() == Some(true)) {
return;
}
let mut type_var: Option<String> = (match __pro_message.get("type").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) }).as_str().map(str::to_owned);
if (type_var.as_deref() == Some("ping")) {
self.handle_ping(client.clone(), message.clone());
return;
}
if (type_var.as_deref() == Some("jsonapi/sendtx")) {
self.handle_ws_sendtx_api(client.clone(), message.clone());
return;
}
if (type_var.as_deref() == Some("unsubscribed")) {
self.handle_un_subscription(client.clone(), message.clone());
return;
}
let mut channel: Value = (match __pro_message.get("channel").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
if Value::Int(channel.as_str().and_then(|__s| __s.find("order_book:")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_order_book(client.clone(), message.clone());
return;
}
if Value::Int(channel.as_str().and_then(|__s| __s.find("market_stats:")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_ticker(client.clone(), message.clone());
return;
}
if Value::Int(channel.as_str().and_then(|__s| __s.find("trade:")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_trades(client.clone(), message.clone());
return;
}
if Value::Int(channel.as_str().and_then(|__s| __s.find("account_all_trades:")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_my_trades(client.clone(), message.clone());
return;
}
if Value::Int(channel.as_str().and_then(|__s| __s.find("account_all_assets:")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_balance(client.clone(), message.clone());
return;
}
if Value::Int(channel.as_str().and_then(|__s| __s.find("user_stats:")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_balance(client.clone(), message.clone());
return;
}
if Value::Int(channel.as_str().and_then(|__s| __s.find("account_orders:")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_orders(client.clone(), message.clone());
return;
}
if Value::Int(channel.as_str().and_then(|__s| __s.find("account_all_orders:")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
self.handle_orders(client.clone(), message.clone());
return;
}
if (channel.as_str() == Some("")) {
self.handle_subscription_status(client, message.clone());
}
}
pub fn handle_subscription_status(&self, mut client: Value, mut message: Value) -> Value {
return message;
Value::Null
}
pub fn handle_un_subscription(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "type": "unsubscribed",
// "channel": "order_book:0"
// }
//
// the venue keys every ack by the channel name plus one id segment, whatever the
// subscribe arity was: "account_orders/{marketId}/{accountIndex}" acks and errors as
// "account_orders:{marketId}", so parts[1] is the market id on every family below
//
let mut channel: Value = (match message.get("channel") { 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::Str("".into()) });
let mut parts: Value = split(&channel, &Value::Str(":".into()));
let mut name: Option<String> = self.safe_string(parts.clone(), Value::Int(0), &[Value::Str("".into())]).as_str().map(str::to_owned);
let mut channelId: Value = self.safe_string(parts, Value::Int(1), &[]);
if (name.as_deref() == Some("order_book")) {
self.handle_order_book_un_subscription(client.clone(), channelId.clone());
} else if (name.as_deref() == Some("market_stats")) {
self.handle_ticker_un_subscription(client.clone(), channelId.clone());
} else if (name.as_deref() == Some("trade")) {
self.handle_trades_un_subscription(client.clone(), channelId.clone());
} else if (name.as_deref() == Some("account_all_trades")) {
self.handle_my_trades_un_subscription(client.clone());
} else if (name.as_deref() == Some("account_orders")) {
self.handle_orders_un_subscription(client.clone(), channelId);
} else if (name.as_deref() == Some("account_all_orders")) {
self.handle_all_orders_un_subscription(client);
}
}
pub fn handle_order_book_un_subscription(&mut self, mut client: Value, mut marketId: Value) {
let mut symbol: Value = self.safe_symbol(marketId, &[]);
let mut subMessageHash: Value = self.get_message_hash(Value::Str("orderbook".into()), &[symbol.clone()]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
self.clean_unsubscription(client, subMessageHash, messageHash, &[]);
if (in_op(&self.orderbooks, &symbol)) {
remove(&mut self.orderbooks, &symbol);
}
}
pub fn handle_ticker_un_subscription(&mut self, mut client: Value, mut marketId: Value) {
if (marketId.as_str() == Some("all")) {
// a ticker hash is served by the one wire channel that created its subscription
// record, so sweep by owner instead of by name prefix: a ticker::<symbol> hash
// owned by a live market_stats/<marketId> channel must survive this ack. deleting
// it here would make the next watchTicker re-subscribe a channel the venue still
// considers subscribed, and its "30003 Already Subscribed" frame carries no id,
// so handleErrorMessage rejects every future on the socket
let mut subscriptionHashes: Value = object_keys(&get_value(&client, &Value::Str("subscriptions".into())));
{
let mut i: Value = Value::Int(0);
let mut __for_first_467: bool = true;
while { if !__for_first_467 { 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_467 = false; i.as_f64().unwrap_or(f64::NAN) < ((subscriptionHashes.len() as i64) as f64) } {
let mut subscriptionHash: Value = subscriptionHashes.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 (starts_with(&subscriptionHash, &Value::Str("ticker".into()))) {
let mut subscription: Value = self.safe_dict(get_value(&client, &Value::Str("subscriptions".into())), subscriptionHash.clone(), &[]);
let mut subscriptionParams: Value = self.safe_dict_k(subscription, "params", &[]);
let mut subscribedChannel: Option<String> = self.safe_string_k(subscriptionParams, "channel", &[]).as_str().map(str::to_owned);
if (subscribedChannel.as_deref() == Some("market_stats/all")) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &subscriptionHash);
if (in_op(&get_value(&client, &Value::Str("futures".into())), &subscriptionHash)) {
let mut error = Value::from(crate::exchange_errors::unsubscribe_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), subscriptionHash)));
client.reject(&[Value::from(error.clone()), subscriptionHash.clone()]);
}
}
}
}
}
let mut allMessageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), self.get_message_hash(Value::Str("ticker".into()), &[])).into());
if (in_op(&get_value(&client, &Value::Str("subscriptions".into())), &allMessageHash)) {
remove(&mut get_value(&client, &Value::Str("subscriptions".into())), &allMessageHash);
}
client.resolve(&[Value::Bool(true), allMessageHash]);
let mut tickersStructure: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("topic".to_string(), Value::Str("ticker".into()));
m
});
self.clean_cache(tickersStructure);
return;
}
let mut symbol: Value = self.safe_symbol(marketId, &[]);
let mut subMessageHash: Value = self.get_message_hash(Value::Str("ticker".into()), &[symbol.clone()]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
self.clean_unsubscription(client, subMessageHash, messageHash, &[]);
if (in_op(&self.tickers, &symbol)) {
remove(&mut self.tickers, &symbol);
}
}
pub fn handle_trades_un_subscription(&mut self, mut client: Value, mut marketId: Value) {
let mut symbol: Value = self.safe_symbol(marketId, &[]);
let mut subMessageHash: Value = self.get_message_hash(Value::Str("trade".into()), &[symbol.clone()]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
self.clean_unsubscription(client, subMessageHash, messageHash, &[]);
if (in_op(&self.trades, &symbol)) {
remove(&mut self.trades, &symbol);
}
}
pub fn handle_my_trades_un_subscription(&mut self, mut client: Value) {
// one account-wide channel feeds the plural hash and every per-symbol hash
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), self.get_message_hash(Value::Str("myTrades".into()), &[])).into());
self.clean_unsubscription(client, Value::Str("myTrades".into()), messageHash, &[Value::Bool(true)]);
let mut myTradesStructure: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("topic".to_string(), Value::Str("myTrades".into()));
m
});
self.clean_cache(myTradesStructure);
}
pub fn handle_orders_un_subscription(&mut self, mut client: Value, mut marketId: Value) {
let mut symbol: Value = self.safe_symbol(marketId, &[]);
let mut subMessageHash: Value = self.get_message_hash(Value::Str("orders".into()), &[symbol]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
self.clean_unsubscription(client, subMessageHash, messageHash, &[]);
}
pub fn handle_all_orders_un_subscription(&mut self, mut client: Value) {
// only the plural hash is awaited on this channel, per-symbol order hashes
// belong to the account_orders/<marketId> channels and stay untouched here
let mut subMessageHash: Value = self.get_message_hash(Value::Str("orders".into()), &[]);
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe:".into()), subMessageHash).into());
self.clean_unsubscription(client, subMessageHash, messageHash, &[]);
let mut ordersStructure: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("topic".to_string(), Value::Str("orders".into()));
m
});
self.clean_cache(ordersStructure);
}
pub fn handle_ping(&mut self, mut client: Value, mut message: Value) {
//
// { "type": "ping" }
//
self.spawn(&[Value::Str("pong".into()).clone(), client, message.clone()]);
}
pub async fn pong(&mut self, mut client: Value, mut message: Value) -> Value {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("pong".into()));
m
});
client.send(&[request]);
Value::Null
}
}