// 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;
pub struct LighterCore {
pub exchange: crate::exchange::Exchange,
}
impl LighterCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::exchange::Exchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = LighterCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for LighterCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_order(self, order, &[market])
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_funding_rate(self, rate, &[market])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_transfer(self, transfer, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_currency(self, currency)
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_margin_modification(self, data, &[market])
}
fn parse_account(&self, account: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_account(self, account)
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::parse_transaction(self, transaction, &[currency])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on LighterCore.
LighterCore::handle_errors(self, 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 {
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"approve_builder_fee" => self.approve_builder_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]).await,
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_all_orders_after" => self.cancel_all_orders_after(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"change_api_key" => self.change_api_key(&args[..]).await,
"check_if_standard_tier" => self.check_if_standard_tier(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_sub_account" => self.create_sub_account(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_accounts" => self.fetch_accounts(&args[..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_nonce" => self.fetch_nonce(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_status" => self.fetch_status(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_transfers" => self.fetch_transfers(&args[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"get_lighter_private_key" => self.get_lighter_private_key(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_account_index" => self.handle_account_index(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,
"handle_api_key_index" => self.handle_api_key_index(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())..]),
"handle_builder_fee_approval" => self.handle_builder_fee_approval(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"load_account" => self.load_account(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,
"modify_leverage_and_margin_mode" => self.modify_leverage_and_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"parse_account" => self.parse_account(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_order_time_in_force_integer" => self.parse_order_time_in_force_integer(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"pow" => self.pow(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"pre_load_lighter_library" => self.pre_load_lighter_library(&args[..]).await,
"reduce_margin" => self.reduce_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin" => self.set_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"sign_and_cancel_all_orders" => self.sign_and_cancel_all_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"sign_and_cancel_order" => self.sign_and_cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"sign_and_create_order" => self.sign_and_create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]).await,
"transfer" => self.transfer(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,
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for LighterCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for LighterCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl LighterCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.super_describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("lighter".into()));
m.insert("name".to_string(), Value::Str("Lighter".into()));
m.insert("countries".to_string(), Value::from(vec![]));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("rateLimit".to_string(), Value::Int(1000));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("dex".to_string(), Value::Bool(true));
m.insert("quoteJsonNumbers".to_string(), Value::Bool(false));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(true));
m.insert("borrowCrossMargin".to_string(), Value::Bool(false));
m.insert("borrowIsolatedMargin".to_string(), Value::Bool(false));
m.insert("borrowMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelAllOrdersAfter".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(false));
m.insert("cancelOrdersForSymbols".to_string(), Value::Bool(false));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(false));
m.insert("createPostOnlyOrder".to_string(), Value::Bool(false));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(false));
m.insert("createStopOrder".to_string(), Value::Bool(false));
m.insert("createTriggerOrder".to_string(), Value::Bool(false));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(true));
m.insert("fetchAllGreeks".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchBorrowRatesPerSymbol".to_string(), Value::Bool(false));
m.insert("fetchCanceledAndClosedOrders".to_string(), Value::Bool(false));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(false));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Bool(false));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(false));
m.insert("fetchFundingHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(false));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchGreeks".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(false));
m.insert("fetchLeverage".to_string(), Value::Bool(false));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchLiquidations".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Bool(false));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(false));
m.insert("fetchMyLiquidations".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(false));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
m.insert("fetchOpenInterests".to_string(), Value::Bool(false));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOption".to_string(), Value::Bool(false));
m.insert("fetchOptionChain".to_string(), Value::Bool(false));
m.insert("fetchOrder".to_string(), Value::Bool(false));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(false));
m.insert("fetchOrderTrades".to_string(), Value::Bool(false));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositionMode".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(false));
m.insert("fetchTradingFee".to_string(), Value::Bool(false));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTransfer".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(true));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawal".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(true));
m.insert("repayCrossMargin".to_string(), Value::Bool(false));
m.insert("repayIsolatedMargin".to_string(), Value::Bool(false));
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMargin".to_string(), Value::Bool(true));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15m".to_string(), Value::Str("15m".into()));
m.insert("30m".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m
}));
m.insert("hostname".to_string(), Value::Str("zklighter.elliot.ai".into()));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/5aa1158d-0734-49fc-9155-501d94b76a0b".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("root".to_string(), Value::Str("https://mainnet.{hostname}".into()));
m.insert("public".to_string(), Value::Str("https://mainnet.{hostname}".into()));
m.insert("private".to_string(), Value::Str("https://mainnet.{hostname}".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("root".to_string(), Value::Str("https://testnet.{hostname}".into()));
m.insert("public".to_string(), Value::Str("https://testnet.{hostname}".into()));
m.insert("private".to_string(), Value::Str("https://testnet.{hostname}".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://lighter.xyz/".into()));
m.insert("doc".to_string(), Value::Str("https://apidocs.lighter.xyz/".into()));
m.insert("fees".to_string(), Value::Str("https://docs.lighter.xyz/perpetual-futures/fees".into()));
m.insert("referral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str("https://app.lighter.xyz/?referral=715955W9".into()));
m.insert("discount".to_string(), Value::Float(0.1));
m
}));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("root".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountsByL1Address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("apikeys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("exchangeStats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("assetDetails".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orderBookDetails".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orderBookOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orderBooks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("recentTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("blockTxs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("nextNonce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tx".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("txFromL1TxHash".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("txs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("announcement".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("block".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("blocks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("currentHeight".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markPriceCandles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fundings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fastbridge/info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("funding-rates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("withdrawalDelay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("partnerStats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("syntheticSpotInfo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tokenlist".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sendTx".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sendTxBatch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountLimits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountMetadata".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("pnl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("l1Metadata".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("liquidations".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positionFunding".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("publicPoolsMetadata".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("getMakerOnlyApiKeys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountActiveOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountInactiveOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("export".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("export/historicalTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountTxs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("deposit/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("transfer/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("withdraw/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("referral/points".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("transferFeeInfo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("changeAccountTier".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("setMakerOnlyApiKeys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("notification/ack".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/respond".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/update".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("httpExceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("21146".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21500".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21501".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21502".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21503".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21504".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21505".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21506".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21507".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21508".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21511".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21512".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("21600".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21601".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21602".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21603".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21604".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21605".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21606".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21607".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21608".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21611".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21612".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21613".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21614".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21700".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21701".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21702".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21703".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21704".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21705".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21706".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21707".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21708".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21709".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21710".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21711".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21712".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21713".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21714".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21715".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21716".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21717".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21718".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21719".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21720".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21721".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21722".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21723".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21724".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21725".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21726".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21727".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21728".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21729".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21730".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21731".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21732".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21733".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21734".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21735".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21736".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21737".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21738".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21739".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21740".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21901".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21902".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21903".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21904".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21905".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("21906".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("23000".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("23001".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("23002".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("23003".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::Int(0));
m.insert("maker".to_string(), Value::Int(0));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(false));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("walletAddress".to_string(), Value::Bool(false));
m.insert("privateKey".to_string(), Value::Bool(true));
m.insert("password".to_string(), Value::Bool(false));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultType".to_string(), Value::Str("swap".into()));
m.insert("builderFee".to_string(), Value::Bool(true));
m.insert("chainId".to_string(), Value::Int(304));
m.insert("accountIndex".to_string(), Value::Null);
m.insert("apiKeyIndex".to_string(), Value::Null);
m.insert("lighterPrivateKey".to_string(), Value::Null);
m.insert("wasmExecPath".to_string(), Value::Null);
m.insert("libraryPath".to_string(), Value::Null);
m.insert("integratorAccountIndex".to_string(), Value::Int(718718));
m.insert("integratorMakerFee".to_string(), Value::Int(1000));
m.insert("integratorTakerFee".to_string(), Value::Int(1000));
m.insert("authDeadlineExpiry".to_string(), Value::Int(28800));
m.insert("authDeadlineMinimumRemaining".to_string(), Value::Int(60));
m.insert("tiersForAccountIndexes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("default".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(true));
m.insert("FOK".to_string(), Value::Bool(true));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m
}));
m
}));
m
})]);
Value::Null
}
pub async fn load_account(&mut self, mut chainId: Value, mut privateKey: Value, mut apiKeyIndex: Value, mut accountIndex: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.init_auth_object(accountIndex.clone(), apiKeyIndex.clone());
let mut cachedAuths: Value = self.safe_dict(get_value(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &accountIndex), apiKeyIndex.clone(), &[]);
let mut signer: Value = self.safe_value_k(cachedAuths, "signer", &[]);
if (signer != Value::Null) {
return signer;
}
let mut libraryPath: Value = self.handle_option_string_and_params(params, Value::Str("loadAccount".into()), Value::Str("libraryPath".into()), &[]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut lighterPrivateKeyIsSet: bool = (privateKey != Value::Null) && (privateKey.as_str() != Some(""));
if lighterPrivateKeyIsSet && (libraryPath != Value::Null) && (apiKeyIndex != Value::Null) && (accountIndex != Value::Null) {
// load lighter library, and create lighter client
signer = self.load_lighter_library(libraryPath.clone(), chainId.clone(), privateKey.clone(), self.parse_to_int(apiKeyIndex.clone()), self.parse_to_int(accountIndex.clone()), &[Value::Bool(true)]).await;
add_element_to_object(get_value_mut(get_value_mut(get_value_mut(&mut self.options, &Value::Str("auths".into())), &accountIndex), &apiKeyIndex), &Value::Str("signer".into()), signer.clone());
return signer;
}
let mut privateKeyIsSet: bool = (self.privateKey.clone() != Value::Null) && (self.privateKey.as_str() != Some(""));
if privateKeyIsSet && (apiKeyIndex != Value::Null) && (accountIndex != Value::Null) {
if ((self.privateKey.len() as i64) as f64) > ((66i64) as f64) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" after the latest update (v4.5.50), CCXT now expects the l1 private key to be provided in the credentials. Please check for more details: https://github.com/ccxt/ccxt/wiki/FAQ#how-to-use-the-lighter-exchange-in-ccxt".into()))));
}
// load lighter library without creating lighter client
signer = self.load_lighter_library(libraryPath, chainId, Value::Str("".into()), self.parse_to_int(apiKeyIndex.clone()), self.parse_to_int(accountIndex.clone()), &[Value::Bool(false)]).await;
add_element_to_object(get_value_mut(get_value_mut(get_value_mut(&mut self.options, &Value::Str("auths".into())), &accountIndex), &apiKeyIndex), &Value::Str("signer".into()), signer.clone());
let mut res: Value = Box::pin(self.change_api_key(&[])).await;
Box::pin(self.handle_builder_fee_approval(self.parse_to_int(accountIndex), self.parse_to_int(apiKeyIndex))).await;
return res;
}
return signer;
Value::Null
}
pub fn init_auth_object(&self, mut strAccountIndex: Value, mut strApiKeyIndex: Value) {
if !(matches!(&self.options, Value::Dict(__d) if __d.contains_key("auths"))) {
if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("auths".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }
}
if !(in_op(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &strAccountIndex)) {
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("auths".into())), &strAccountIndex, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
}
if !(in_op(&get_value(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &strAccountIndex), &strApiKeyIndex)) {
add_element_to_object(get_value_mut(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("auths".into())), &strAccountIndex), &strApiKeyIndex, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("signer".to_string(), Value::Null);
m.insert("lighterPrivateKey".to_string(), Value::Null);
m.insert("deadline".to_string(), Value::Null);
m.insert("token".to_string(), Value::Null);
m
}));
}
}
pub fn get_lighter_private_key(&self, mut strAccountIndex: Value, mut strApiKeyIndex: Value) -> Value {
if !(matches!(&self.options, Value::Dict(__d) if __d.contains_key("auths"))) {
return Value::Null;
}
if !(in_op(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &strAccountIndex)) {
return Value::Null;
}
if !(in_op(&get_value(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &strAccountIndex), &strApiKeyIndex)) {
return Value::Null;
}
if !(in_op(&get_value(&get_value(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &strAccountIndex), &strApiKeyIndex), &Value::Str("lighterPrivateKey".into()))) {
return Value::Null;
}
return crate::value::get_value_k(&get_value(&get_value(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &strAccountIndex), &strApiKeyIndex), "lighterPrivateKey");
Value::Null
}
/*
* @method
* @name lighter#preLoadLighterLibrary
* @description if the required credentials are available in options, it will pre-load the lighter Signer to avoid delaying sensitive calls like createOrder the first time they're executed
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {boolean} true if the signer was loaded, false otherwise
*/
pub async fn pre_load_lighter_library(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("loadAccount".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexAndParams: Value = self.handle_account_index(paramsApiKeyIndex, Value::Str("loadAccount".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexAndParams.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
if (accountIndex == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires accountIndex or account_index".into()))));
}
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
self.init_auth_object(strAccountIndex.clone(), strApiKeyIndex.clone());
let mut signer: Value = self.safe_dict(get_value(&get_value(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &strAccountIndex), &strApiKeyIndex), Value::Str("signer".into()), &[]);
if (signer != Value::Null) {
return Value::Bool(true);
}
signer = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[]).await;
self.handle_builder_fee_approval(accountIndex, apiKeyIndex).await;
return (Value::Bool(signer != Value::Null));
Value::Null
}
pub fn handle_api_key_index(&self, mut params: Value, mut methodName1: Value, mut optionName1: Value, mut optionName2: Value, optional_args: &[Value]) -> Value {
let mut defaultValue = get_arg(optional_args, 0, Value::Null);
let mut apiKeyIndexOptionparamsApiKeyIndexVariable = self.handle_option_and_params2(params, methodName1, optionName1, optionName2, &[defaultValue]);
let mut apiKeyIndexOption: Value = apiKeyIndexOptionparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexOptionparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut apiKeyIndex: Value = apiKeyIndexOption;
if (apiKeyIndex == Value::Null) || (apiKeyIndex.as_f64().unwrap_or(f64::NAN) < ((4i64) as f64)) || (apiKeyIndex.as_f64().unwrap_or(f64::NAN) > ((254i64) as f64)) {
// apiKeyIndex = this.randNumber (2);
apiKeyIndex = Value::Int(254);
if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("apiKeyIndex".into(), apiKeyIndex.clone()); }; // default to a value to avoid overriding other keys
}
return Value::from(vec![self.parse_to_int(apiKeyIndex), paramsApiKeyIndex]);
Value::Null
}
pub async fn handle_account_index(&mut self, mut params: Value, mut methodName1: Value, mut optionName1: Value, mut optionName2: Value, optional_args: &[Value]) -> Value {
let mut defaultValue = get_arg(optional_args, 0, Value::Null);
let mut accountIndexOptionparamsAccountIndexVariable = self.handle_option_and_params2(params, methodName1.clone(), optionName1.clone(), optionName2.clone(), &[defaultValue]);
let mut accountIndexOption: Value = accountIndexOptionparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexOptionparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndex: Value = accountIndexOption;
if (accountIndex == Value::Null) {
let mut walletAddress: Value = self.walletAddress.clone();
if (self.privateKey.clone() != Value::Null) {
if ((self.privateKey.len() as i64) as f64) > ((66i64) as f64) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" after the latest update (v4.5.50), CCXT now expects the l1 private key to be provided in the credentials. Please check for more details: https://github.com/ccxt/ccxt/wiki/FAQ#how-to-use-the-lighter-exchange-in-ccxt".into()))));
}
walletAddress = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
}
if (walletAddress == Value::Null) || (walletAddress.as_str() == Some("")) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName1).into()), Value::Str("() requires an ".into())).into()), optionName1).into()), Value::Str("/".into())).into()), optionName2).into()), Value::Str(" parameter or walletAddress to fetch accountIndex. Alternatively set privateKey in credentials to enable automatic walletAddress detection.".into()))));
}
let mut res: Value = self.public_get_accounts_by_l1_address(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("l1_address".to_string(), walletAddress);
m
})]).await;
//
// {
// "code": 200,
// "l1_address": "0xaaaabbbb....ccccdddd",
// "sub_accounts": [
// {
// "code": 0,
// "account_type": 0,
// "index": 666666,
// "l1_address": "0xaaaabbbb....ccccdddd",
// "cancel_all_time": 0,
// "total_order_count": 0,
// "total_isolated_order_count": 0,
// "pending_order_count": 0,
// "available_balance": "",
// "status": 0,
// "collateral": "40",
// "transaction_time": 0,
// "account_trading_mode": 0
// }
// ]
// }
//
let mut subAccounts: Value = self.safe_list_k(res, "sub_accounts", &[]);
if (matches!(&subAccounts, Value::Arr(_))) {
let mut account: Value = self.safe_dict(subAccounts.clone(), Value::Int(0), &[]);
if (account == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName1).into()), Value::Str("() requires an ".into())).into()), optionName1).into()), Value::Str(" or ".into())).into()), optionName2).into()), Value::Str(" parameter".into()))));
}
accountIndex = account.as_map().and_then(|__m| __m.get("index")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("accountIndex".into(), accountIndex.clone()); }
}
}
return Value::from(vec![self.parse_to_int(accountIndex), paramsAccountIndex]);
Value::Null
}
pub async fn create_sub_account(&mut self, mut name: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("createSubAccount".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, Value::Str("createSubAccount".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex.clone());
m.insert("account_index".to_string(), accountIndex.clone());
m
});
let mut strAccountIndex: Value = self.number_to_string(accountIndex);
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let __ws_arg_0 = self.extend(signRaw, &[paramsAccountIndex]);
let mut txTypetxInfoVariable = self.lighter_sign_create_sub_account(signer, __ws_arg_0);
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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
return self.public_post_send_tx(&[request]).await;
Value::Null
}
pub fn create_auth(&self, optional_args: &[Value]) -> Option<String> {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// don't omit [accountIndex, apiKeyIndex], request may need them
let mut apiKeyIndex: Value = self.safe_string2(params.clone(), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
if (apiKeyIndex == Value::Null) {
let mut res: Value = self.handle_option_and_params2(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), Value::Str("createAuth".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
apiKeyIndex = self.safe_string(res.clone(), Value::Int(0), &[]);
}
let mut accountIndex: Value = self.safe_string2(params, Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]);
if (accountIndex == Value::Null) {
let mut res: Value = self.handle_option_and_params2(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), Value::Str("createAuth".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]);
accountIndex = self.safe_string(res, Value::Int(0), &[]);
}
let mut auths: Value = self.safe_dict_k(self.options.clone(), "auths", &[]);
let mut accountAuths: Value = self.safe_dict(auths, accountIndex.clone(), &[]);
let mut cachedAuth: Value = self.safe_dict(accountAuths, apiKeyIndex.clone(), &[]);
let mut cachedDeadline: Value = self.safe_integer_k(cachedAuth.clone(), "deadline", &[]);
if (cachedDeadline != Value::Null) {
let mut minimumDeadline: Value = (match (&(self.seconds()), &(self.safe_integer_k(self.options.clone(), "authDeadlineMinimumRemaining", &[Value::Int(60)]))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
if cachedDeadline.as_f64().unwrap_or(f64::NAN) >= minimumDeadline.as_f64().unwrap_or(f64::NAN) {
return self.safe_string_k(cachedAuth, "token", &[]).as_str().map(str::to_owned);
}
}
let mut deadline: Value = (match (&(self.seconds()), &(self.safe_integer_k(self.options.clone(), "authDeadlineExpiry", &[Value::Int(28800)]))) { (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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deadline".to_string(), deadline.clone());
m.insert("api_key_index".to_string(), self.parse_to_int(apiKeyIndex.clone()));
m.insert("account_index".to_string(), self.parse_to_int(accountIndex.clone()));
m
});
let mut token: Value = self.lighter_create_auth_token(crate::value::get_value_k(&get_value(&get_value(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &accountIndex), &apiKeyIndex), "signer"), request);
add_element_to_object(get_value_mut(get_value_mut(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("auths".into())), &accountIndex), &apiKeyIndex), &Value::Str("deadline".into()), deadline);
add_element_to_object(get_value_mut(get_value_mut(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("auths".into())), &accountIndex), &apiKeyIndex), &Value::Str("token".into()), token.clone());
return token.as_str().map(str::to_owned);
}
pub fn pow(&self, mut n: Value, mut m: Value) -> Value {
let mut r: Value = crate::precise::Precise::stringMul(&n, &Value::Str("1".into()));
let mut c: Value = self.parse_to_int(m);
if c.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" pow() requires m > 0.".into()))));
}
if (c.as_f64() == Some(0.0)) {
return Value::Str("1".into());
}
if c.as_f64().unwrap_or(f64::NAN) > ((100i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" pow() requires m < 100.".into()))));
}
{
let mut i: Value = Value::Int(1);
let mut __for_first_925: bool = true;
while { if !__for_first_925 { 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_925 = false; i.as_f64().unwrap_or(f64::NAN) < c.as_f64().unwrap_or(f64::NAN) } {
r = crate::precise::Precise::stringMul(&r, &n);
}
}
return r;
Value::Null
}
pub fn hash_message(&self, mut message: Value) -> Option<String> {
let mut binaryMessage: Value = self.encode(message);
let mut binaryMessageLength: Value = self.binary_length(binaryMessage.clone(), &[]);
let mut x19: Value = self.base16_to_binary(Value::Str("19".into()), &[]);
let mut newline: Value = self.base16_to_binary(Value::Str("0a".into()), &[]);
let mut prefix: Value = self.binary_concat(x19, &[self.encode(Value::Str("Ethereum Signed Message:".into())), newline, self.encode(self.number_to_string(binaryMessageLength))]);
return Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(self.binary_concat(prefix, &[binaryMessage]), Value::Str("keccak".into()), &[Value::Str("hex".into())])).into()).as_str().map(str::to_owned);
}
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Option<String> {
self.check_required_credentials(&[]);
let mut signature: Value = ecdsa(slice(&hash, &Value::Int(-64), &Value::Null), slice(&privateKey, &Value::Int(-64), &Value::Null), Value::Str("secp256k1".into()), Value::Null);
let mut r: Value = signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null);
let mut s: Value = signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null);
let mut v: Value = self.int_to_base16(self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]), &[]);
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), pad_start(&r, &Value::Int(64), &Value::Str("0".into()))).into()), pad_start(&s, &Value::Int(64), &Value::Str("0".into()))).into()), v).into()).as_str().map(str::to_owned);
}
pub fn sign_l1_and_prepare_tx_info(&self, mut txInfo: Value, mut message: Value, mut privateKey: Value) -> Option<String> {
let mut hashMessage: Value = self.hash_message(message).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut signature: Value = self.sign_hash(hashMessage, privateKey).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut decTxInfo: Value = self.parse_json_value(txInfo);
add_element_to_object(&mut decTxInfo, &Value::Str("L1Sig".into()), signature);
return json_stringify(&decTxInfo).as_str().map(str::to_owned);
}
pub async fn handle_builder_fee_approval(&mut self, mut accountIndex: Value, mut apiKeyIndex: Value) -> Value {
let mut buildFee: Value = self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]);
if (buildFee.as_bool() != Some(true)) {
return Value::Bool(false);
}
let mut approvedBuilderFee: Value = self.safe_bool_k(self.options.clone(), "approvedBuilderFee", &[Value::Bool(false)]);
if (approvedBuilderFee.as_bool() == Some(true)) {
return Value::Bool(true);
}
let mut standardTier: bool = false;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut isStandardTier: Value = self.check_if_standard_tier(self.parse_to_int(accountIndex.clone())).await;
if is_true(&isStandardTier) {
standardTier = true;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("builderFee".into(), Value::Bool(false)); }
} else {
let mut builder: Value = self.safe_integer_k(self.options.clone(), "integratorAccountIndex", &[Value::Int(718718)]);
let mut takerFeeRate: Value = self.safe_integer_k(self.options.clone(), "integratorTakerFee", &[Value::Int(1000)]);
let mut makerFeeRate: Value = self.safe_integer_k(self.options.clone(), "integratorMakerFee", &[Value::Int(1000)]);
Box::pin(self.approve_builder_fee(builder, takerFeeRate, makerFeeRate, accountIndex, apiKeyIndex, &[])).await;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("approvedBuilderFee".into(), Value::Bool(true)); }
}
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("builderFee".into(), Value::Bool(false)); }
}
if standardTier {
return Value::Bool(false);
}
return Value::Bool(true);
Value::Null
}
pub async fn check_if_standard_tier(&mut self, mut accountIndex: Value) -> Value {
let mut tiersForAccountIndexes: Value = self.safe_dict_k(self.options.clone(), "tiersForAccountIndexes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut accountIndexStr: Value = to_string_val(&accountIndex);
let mut isStandardTier: Value = self.safe_bool(tiersForAccountIndexes.clone(), accountIndexStr.clone(), &[]);
if (isStandardTier != Value::Null) {
return isStandardTier;
}
let mut accountLimits: Value = self.private_get_account_limits(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_index".to_string(), accountIndex);
m
})]).await;
//
// {
// "code": 200,
// "max_llp_percentage": 100,
// "max_llp_amount": "0.000000",
// "user_tier": "standard",
// "can_create_public_pool": false,
// "user_tier_name": "standard",
// "current_maker_fee_tick": 0,
// "current_taker_fee_tick": 0,
// "leased_lit": "0.00000000",
// "effective_lit_stakes": "0.00000000",
// "user_tier_last_update": 0
// }
//
let mut tier: Option<String> = self.safe_string_k(accountLimits, "user_tier", &[]).as_str().map(str::to_owned);
let mut isStandard: Value = (Value::Bool(tier.as_deref() == Some("standard")));
if let Value::Dict(__d) = &mut tiersForAccountIndexes { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&accountIndexStr), isStandard.clone()); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("tiersForAccountIndexes".into(), tiersForAccountIndexes); }
return isStandard;
Value::Null
}
pub async fn approve_builder_fee(&mut self, mut builder: Value, mut takerFeeRate: Value, mut makerFeeRate: Value, mut accountIndex: Value, mut apiKeyIndex: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = Box::pin(self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[params.clone()])).await;
let __ws_arg_1 = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("skipNonce".to_string(), Value::Bool(false));
m
})]);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[__ws_arg_1]).await;
let mut expiry: Value = (match (&(self.milliseconds()), &((match (&(Value::Int(365)), &(Value::Int(864000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("integrator_account_index".to_string(), builder);
m.insert("integrator_taker_fee".to_string(), takerFeeRate);
m.insert("integrator_maker_fee".to_string(), makerFeeRate);
m.insert("approval_expiry".to_string(), expiry);
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_2 = self.extend(signRaw, &[params]);
let mut txTypetxInfomessageToSignVariable = self.lighter_sign_approve_integrator(signer, __ws_arg_2);
let mut txType: Value = txTypetxInfomessageToSignVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfomessageToSignVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut messageToSign: Value = txTypetxInfomessageToSignVariable.as_array().and_then(|__arr| __arr.get(2)).cloned().unwrap_or(Value::Null);
let mut newTxInfo: Value = self.sign_l1_and_prepare_tx_info(txInfo, messageToSign, self.privateKey.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), newTxInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[request]).await;
return response;
Value::Null
}
pub async fn change_api_key(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("changeApiKey".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, Value::Str("changeApiKey".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signerNotLoad: Value = crate::value::get_value_k(&get_value(&get_value(&self.options.as_map().and_then(|__m| __m.get("auths")).cloned().unwrap_or(Value::Null), &strAccountIndex), &strApiKeyIndex), "signer");
let mut privateKeypublicKeyVariable = self.lighter_generate_api_key(signerNotLoad.clone());
let mut privateKey: Value = privateKeypublicKeyVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut publicKey: Value = privateKeypublicKeyVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_3 = self.extend(paramsAccountIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("skipNonce".to_string(), Value::Bool(false));
m
})]);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[__ws_arg_3]).await;
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pubkey".to_string(), self.encode(publicKey));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex.clone());
m.insert("account_index".to_string(), accountIndex.clone());
m
});
// create lighter client
let mut signer: Value = self.lighter_create_client(signerNotLoad, self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), privateKey.clone(), apiKeyIndex.clone(), accountIndex.clone());
let __ws_arg_4 = self.extend(signRaw, &[paramsAccountIndex]);
let mut txTypetxInfomessageToSignVariable = self.lighter_sign_change_pubkey(signer.clone(), __ws_arg_4);
let mut txType: Value = txTypetxInfomessageToSignVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfomessageToSignVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut messageToSign: Value = txTypetxInfomessageToSignVariable.as_array().and_then(|__arr| __arr.get(2)).cloned().unwrap_or(Value::Null);
let mut newTxInfo: Value = self.sign_l1_and_prepare_tx_info(txInfo, messageToSign, self.privateKey.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), newTxInfo);
m
});
self.public_post_send_tx(&[request]).await;
add_element_to_object(get_value_mut(get_value_mut(get_value_mut(&mut self.options, &Value::Str("auths".into())), &strAccountIndex), &strApiKeyIndex), &Value::Str("lighterPrivateKey".into()), privateKey);
add_element_to_object(get_value_mut(get_value_mut(get_value_mut(&mut self.options, &Value::Str("auths".into())), &strAccountIndex), &strApiKeyIndex), &Value::Str("signer".into()), signer.clone()); // reassign signer in go
Box::pin(self.handle_builder_fee_approval(accountIndex, apiKeyIndex)).await;
return signer;
Value::Null
}
pub fn set_sandbox_mode(&mut self, mut enable: Value) {
self.super_set_sandbox_mode(enable.clone());
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("sandboxMode".into(), enable.clone()); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("chainId".into(), (if is_true(&enable) { Value::Int(300) } else { Value::Int(304) })); }
}
pub fn create_order_request(&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
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
/*
* @method
* @ignore
* @name lighter#createOrderRequest
* @description helper function to build the request
* @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 you want to trade in units of the base currency
* @param {float} [price] the price that 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 {int} [params.nonce] nonce for the account
* @param {int} [params.apiKeyIndex] apiKeyIndex
* @param {int} [params.accountIndex] accountIndex
* @param {int} [params.orderExpiry] orderExpiry
* @returns {any[]} request to be sent to the exchange
*/
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price argument".into()))));
}
let mut reduceOnly: Value = self.safe_bool2(params.clone(), Value::Str("reduceOnly".into()), Value::Str("reduce_only".into()), &[Value::Bool(false)]); // default false
let mut orderType: Value = to_upper(&type_var);
let mut market: Value = self.market(symbol.clone());
let mut orderSide: Value = to_upper(&side);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m
});
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("createOrder".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexparamsAccountIndexVariable = self.handle_option_and_params2(paramsApiKeyIndex, Value::Str("createOrder".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]);
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut nonceparamsNonceVariable = self.handle_option_and_params(paramsAccountIndex, Value::Str("createOrder".into()), Value::Str("nonce".into()), &[]);
let mut nonce: Value = nonceparamsNonceVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsNonce: Value = nonceparamsNonceVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut orderExpiryOptionparamsOrderExpiryVariable = self.handle_option_integer_and_params(paramsNonce, Value::Str("createOrder".into()), Value::Str("orderExpiry".into()), &[Value::Int(0)]);
let mut orderExpiryOption: Value = orderExpiryOptionparamsOrderExpiryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsOrderExpiry: Value = orderExpiryOptionparamsOrderExpiryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut orderExpiry: Value = orderExpiryOption;
if (nonce != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("nonce".into(), nonce); }
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("api_key_index".into(), apiKeyIndex); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("account_index".into(), self.parse_to_int(accountIndex)); }
let mut triggerPrice: Value = self.safe_string2(paramsOrderExpiry.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossPrice: Value = self.safe_value_k(paramsOrderExpiry.clone(), "stopLossPrice", &[triggerPrice]);
let mut takeProfitPrice: Value = self.safe_value_k(paramsOrderExpiry.clone(), "takeProfitPrice", &[]);
let mut stopLoss: Value = self.safe_dict_k(paramsOrderExpiry.clone(), "stopLoss", &[]);
let mut takeProfit: Value = self.safe_dict_k(paramsOrderExpiry.clone(), "takeProfit", &[]);
let mut hasStopLoss: bool = stopLoss != Value::Null;
let mut hasTakeProfit: bool = takeProfit != Value::Null;
let mut isConditional: bool = (stopLossPrice != Value::Null) || (takeProfitPrice != Value::Null);
let mut isMarketOrder: Value = (Value::Bool(orderType.as_str() == Some("MARKET")));
let mut timeInForce: Option<String> = self.safe_string_lower_k(paramsOrderExpiry.clone(), "timeInForce", &[Value::Str("gtt".into())]).as_str().map(str::to_owned);
let mut postOnly: Value = self.is_post_only(isMarketOrder.clone(), Value::Null, &[paramsOrderExpiry.clone()]);
let mut paramsOmitted: Value = self.omit(paramsOrderExpiry, Value::from(vec![Value::Str("stopLoss".into()), Value::Str("takeProfit".into()), Value::Str("timeInForce".into())]), &[]);
let mut orderTypeNum: Value = Value::Null;
let mut timeInForceNum: Value = Value::Null;
if matches!(&isMarketOrder, Value::Bool(true)) {
orderTypeNum = Value::Int(1);
timeInForceNum = Value::Int(0);
} else {
orderTypeNum = Value::Int(0);
}
if (orderSide.as_str() == Some("BUY")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("is_ask".into(), Value::Int(0)); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("is_ask".into(), Value::Int(1)); }
}
if is_true(&postOnly) {
timeInForceNum = Value::Int(2);
orderExpiry = Value::Int(-1);
} else {
if !(matches!(&isMarketOrder, Value::Bool(true))) {
if (timeInForce.as_deref() == Some("ioc")) {
timeInForceNum = Value::Int(0);
orderExpiry = Value::Int(0);
} else if (timeInForce.as_deref() == Some("gtt")) {
timeInForceNum = Value::Int(1);
orderExpiry = Value::Int(-1);
}
}
}
let mut marketInfo: Value = self.safe_dict_k(market, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut amountStr: Value = Value::Null;
let mut priceStr: Value = self.price_to_precision(symbol.clone(), price);
let mut amountScale: Value = self.pow(Value::Str("10".into()), marketInfo.as_map().and_then(|__m| __m.get("size_decimals")).cloned().unwrap_or(Value::Null));
let mut priceScale: Value = self.pow(Value::Str("10".into()), marketInfo.as_map().and_then(|__m| __m.get("price_decimals")).cloned().unwrap_or(Value::Null));
let mut triggerPriceStr: Value = Value::Str("0".into()); // default is 0
let mut defaultClientOrderId: Value = self.rand_number(Value::Int(9)); // c# only support int32 2147483647.
let mut clientOrderId: Value = self.safe_integer2(paramsOmitted.clone(), Value::Str("client_order_index".into()), Value::Str("clientOrderId".into()), &[defaultClientOrderId]);
let mut paramsRequest: Value = self.omit(paramsOmitted, Value::from(vec![Value::Str("reduceOnly".into()), Value::Str("reduce_only".into()), Value::Str("timeInForce".into()), Value::Str("postOnly".into()), Value::Str("nonce".into()), Value::Str("apiKeyIndex".into()), Value::Str("stopPrice".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("client_order_index".into()), Value::Str("clientOrderId".into())]), &[]);
if isConditional {
amountStr = self.number_to_string(amount.clone());
if (stopLossPrice != Value::Null) {
if matches!(&isMarketOrder, Value::Bool(true)) {
orderTypeNum = Value::Int(2);
} else {
orderTypeNum = Value::Int(3);
}
triggerPriceStr = self.price_to_precision(symbol.clone(), stopLossPrice);
} else if (takeProfitPrice != Value::Null) {
if matches!(&isMarketOrder, Value::Bool(true)) {
orderTypeNum = Value::Int(4);
} else {
orderTypeNum = Value::Int(5);
}
triggerPriceStr = self.price_to_precision(symbol.clone(), takeProfitPrice);
}
} else {
amountStr = self.amount_to_precision(symbol.clone(), amount);
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("order_expiry".into(), orderExpiry); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("order_type".into(), orderTypeNum); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("time_in_force".into(), timeInForceNum); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("reduce_only".into(), (if (reduceOnly.as_bool() == Some(true)) { Value::Int(1) } else { Value::Int(0) })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("client_order_index".into(), clientOrderId); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("base_amount".into(), self.parse_to_int(crate::precise::Precise::stringMul(&amountStr, &amountScale))); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("avg_execution_price".into(), self.parse_to_int(crate::precise::Precise::stringMul(&priceStr, &priceScale))); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("trigger_price".into(), self.parse_to_int(crate::precise::Precise::stringMul(&triggerPriceStr, &priceScale))); }
if matches!(self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]), Value::Bool(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("integrator_account_index".into(), self.options.as_map().and_then(|__m| __m.get("integratorAccountIndex")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("integrator_taker_fee".into(), self.options.as_map().and_then(|__m| __m.get("integratorTakerFee")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("integrator_maker_fee".into(), self.options.as_map().and_then(|__m| __m.get("integratorMakerFee")).cloned().unwrap_or(Value::Null)); }
}
let mut orders: Value = Value::from(vec![]);
append_to_array(&mut orders, self.extend(request, &[paramsRequest.clone()]));
if hasStopLoss || hasTakeProfit {
// group order
add_element_to_object(get_value_mut(&mut orders, &Value::Int(0)), &Value::Str("client_order_index".into()), Value::Int(0)); // client order index should be 0
let mut triggerOrderSide: Value = Value::Str("".into());
if (orderSide.as_str() == Some("BUY")) {
triggerOrderSide = Value::Str("sell".into());
} else {
triggerOrderSide = Value::Str("buy".into());
}
let mut stopLossOrderTriggerPrice: Value = self.safe_number2(stopLoss.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossOrderType: Value = self.safe_string_k(stopLoss.clone(), "type", &[Value::Str("limit".into())]);
let mut stopLossOrderLimitPrice: Value = self.safe_number2(stopLoss.clone(), Value::Str("price".into()), Value::Str("stopLossPrice".into()), &[stopLossOrderTriggerPrice.clone()]);
let mut takeProfitOrderTriggerPrice: Value = self.safe_number2(takeProfit.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut takeProfitOrderType: Value = self.safe_string_k(takeProfit.clone(), "type", &[Value::Str("limit".into())]);
let mut takeProfitOrderLimitPrice: Value = self.safe_number2(takeProfit.clone(), Value::Str("price".into()), Value::Str("takeProfitPrice".into()), &[takeProfitOrderTriggerPrice.clone()]);
// amount should be 0 for child orders
if (stopLoss != Value::Null) {
let __ws_arg_5 = self.extend(paramsRequest.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stopLossPrice".to_string(), stopLossOrderTriggerPrice);
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})]);
let mut orderObj: Value = self.create_order_request(symbol.clone(), stopLossOrderType, triggerOrderSide.clone(), Value::Int(0), &[stopLossOrderLimitPrice, __ws_arg_5]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
add_element_to_object(&mut orderObj, &Value::Str("client_order_index".into()), Value::Int(0));
append_to_array(&mut orders, orderObj.clone());
}
if (takeProfit != Value::Null) {
let __ws_arg_6 = self.extend(paramsRequest, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("takeProfitPrice".to_string(), takeProfitOrderTriggerPrice);
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})]);
let mut orderObj: Value = self.create_order_request(symbol, takeProfitOrderType, triggerOrderSide, Value::Int(0), &[takeProfitOrderLimitPrice, __ws_arg_6]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
add_element_to_object(&mut orderObj, &Value::Str("client_order_index".into()), Value::Int(0));
append_to_array(&mut orders, orderObj);
}
}
return orders;
Value::Null
}
pub async fn fetch_nonce(&mut self, mut accountIndex: Value, mut apiKeyIndex: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (accountIndex == Value::Null) || (apiKeyIndex == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchNonce() requires accountIndex and apiKeyIndex.".into()))));
}
if (matches!(¶ms, Value::Dict(__d) if __d.contains_key("nonce"))) {
return self.safe_integer_k(params.clone(), "nonce", &[]);
}
let mut nonceInOptions: Value = self.safe_integer_k(self.options.clone(), "nonce", &[]);
if (nonceInOptions != Value::Null) {
return nonceInOptions;
}
// avoid skipNonce for l1 operations
let mut skipNonce: Value = self.handle_option_bool_and_params(params, Value::Str("fetchNonce".into()), Value::Str("skipNonce".into()), &[Value::Bool(true)]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
if is_true(&skipNonce) {
return self.milliseconds();
}
let mut response: Value = self.public_get_next_nonce(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_index".to_string(), accountIndex);
m.insert("api_key_index".to_string(), apiKeyIndex);
m
})]).await;
return self.safe_integer_k(response, "nonce", &[]);
Value::Null
}
pub async fn sign_and_create_order(&mut self, mut method: Value, 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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
// non-destructively get values from opts/params
let mut accIndexAndParams: Value = self.handle_account_index(params.clone(), method.clone(), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accIndexAndParams.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut apiKeyIndexAndParams: Value = self.handle_api_key_index(params.clone(), method.clone(), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexAndParams.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
// before order-req creation, we need to know account status
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[params.clone()]).await;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut isStandardTier: Value = self.check_if_standard_tier(accountIndex.clone()).await;
if is_true(&isStandardTier) {
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("builderFee".into(), Value::Bool(false)); }
}
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("builderFee".into(), Value::Bool(false)); }
}
let mut groupingTypeparamsGroupingTypeVariable = self.handle_option_integer_and_params(params, method, Value::Str("groupingType".into()), &[Value::Int(3)]);
let mut groupingType: Value = groupingTypeparamsGroupingTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsGroupingType: Value = groupingTypeparamsGroupingTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); // default GROUPING_TYPE_ONE_TRIGGERS_A_ONE_CANCELS_THE_OTHER
let mut orderRequests: Value = self.create_order_request(symbol, type_var, side, amount, &[price, paramsGroupingType]);
let mut totalOrderRequests: f64 = ((orderRequests.len() as i64) as f64);
if totalOrderRequests > ((1i64) as f64) {
// the signer replaces a -1 expiry with now + 28 days reading the clock once per leg, and rejects
// a group whose legs differ ("OrderExpiry is invalid"), so resolve the default once for all legs
let mut groupOrderExpiry: Value = self.sum(&[self.milliseconds(), Value::Int(2419200000)]); // 28 days
{
let mut i: Value = Value::Int(0);
let mut __for_first_926: bool = true;
while { if !__for_first_926 { 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_926 = false; i.as_f64().unwrap_or(f64::NAN) < totalOrderRequests } {
if (self.safe_integer(orderRequests.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), Value::Str("order_expiry".into()), &[]).as_f64() == Value::Int(-1).as_f64()) {
add_element_to_object(get_value_mut(&mut orderRequests, &i), &Value::Str("order_expiry".into()), groupOrderExpiry.clone());
}
}
}
}
let mut order: Value = Value::Null;
if totalOrderRequests > ((0i64) as f64) {
order = orderRequests.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
}
// the nonce could be updated
if (self.safe_integer_k(order.clone(), "nonce", &[]) == Value::Null) {
add_element_to_object(&mut order, &Value::Str("nonce".into()), self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[]).await);
}
let mut txType: Value = Value::Null;
let mut txInfo: Value = Value::Null;
if totalOrderRequests < ((2i64) as f64) {
{ let __destr_tmp = self.lighter_sign_create_order(signer.clone(), order.clone()); txType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); txInfo = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
} else {
let mut signingPayload: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("grouping_type".to_string(), groupingType);
m.insert("orders".to_string(), orderRequests);
m.insert("nonce".to_string(), order.as_map().and_then(|__m| __m.get("nonce")).cloned().unwrap_or(Value::Null));
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
if matches!(self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]), Value::Bool(true)) {
if let Value::Dict(__d) = &mut signingPayload { std::sync::Arc::make_mut(__d).insert("integrator_account_index".into(), order.as_map().and_then(|__m| __m.get("integrator_account_index")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut signingPayload { std::sync::Arc::make_mut(__d).insert("integrator_taker_fee".into(), order.as_map().and_then(|__m| __m.get("integrator_taker_fee")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut signingPayload { std::sync::Arc::make_mut(__d).insert("integrator_maker_fee".into(), order.as_map().and_then(|__m| __m.get("integrator_maker_fee")).cloned().unwrap_or(Value::Null)); }
}
{ let __destr_tmp = self.lighter_sign_create_grouped_orders(signer, signingPayload); txType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); txInfo = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
}
return Value::from(vec![txType, txInfo, order]);
Value::Null
}
/*
* @method
* @name lighter#createOrder
* @description create a trade order
* @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} [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(&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 txTypetxInfoorderVariable = self.sign_and_create_order(Value::Str("createOrder".into()), symbol.clone(), type_var, side, amount, &[price, params]).await;
let mut txType: Value = txTypetxInfoorderVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoorderVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut order: Value = txTypetxInfoorderVariable.as_array().and_then(|__arr| __arr.get(2)).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[request]).await;
return self.parse_order(self.deep_extend(response, &[order]), &[market]);
Value::Null
}
/*
* @method
* @name lighter#editOrder
* @description cancels an order and places a new order
* @param {string} id order id
* @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 the currency you want to trade in units of the base currency
* @param {float} [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.accountIndex] account index
* @param {string} [params.apiKeyIndex] api key index
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("editOrder".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, Value::Str("editOrder".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut market: Value = self.market(symbol.clone());
let mut marketInfo: Value = self.safe_dict_k(market.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut amountScale: Value = self.pow(Value::Str("10".into()), marketInfo.as_map().and_then(|__m| __m.get("size_decimals")).cloned().unwrap_or(Value::Null));
let mut priceScale: Value = self.pow(Value::Str("10".into()), marketInfo.as_map().and_then(|__m| __m.get("price_decimals")).cloned().unwrap_or(Value::Null));
let mut triggerPrice: Value = self.safe_string_n(paramsAccountIndex.clone(), Value::from(vec![Value::Str("stopPrice".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]);
let mut paramsOmitted: Value = self.omit(paramsAccountIndex, Value::from(vec![Value::Str("stopPrice".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]);
let mut amountStr: Value = Value::Null;
let mut priceStr: Value = self.price_to_precision(symbol.clone(), price);
let mut triggerPriceStr: Value = Value::Str("0".into()); // default is 0
if (triggerPrice != Value::Null) {
amountStr = self.number_to_string(amount.clone());
triggerPriceStr = self.price_to_precision(symbol.clone(), triggerPrice);
} else {
amountStr = self.amount_to_precision(symbol, amount);
}
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsOmitted.clone()]).await;
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("index".to_string(), self.parse_to_int(id));
m.insert("base_amount".to_string(), self.parse_to_int(crate::precise::Precise::stringMul(&amountStr, &amountScale)));
m.insert("price".to_string(), self.parse_to_int(crate::precise::Precise::stringMul(&priceStr, &priceScale)));
m.insert("trigger_price".to_string(), self.parse_to_int(crate::precise::Precise::stringMul(&triggerPriceStr, &priceScale)));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
if matches!(self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]), Value::Bool(true)) {
if let Value::Dict(__d) = &mut signRaw { std::sync::Arc::make_mut(__d).insert("integrator_account_index".into(), self.options.as_map().and_then(|__m| __m.get("integratorAccountIndex")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut signRaw { std::sync::Arc::make_mut(__d).insert("integrator_taker_fee".into(), self.options.as_map().and_then(|__m| __m.get("integratorTakerFee")).cloned().unwrap_or(Value::Null)); }
if let Value::Dict(__d) = &mut signRaw { std::sync::Arc::make_mut(__d).insert("integrator_maker_fee".into(), self.options.as_map().and_then(|__m| __m.get("integratorMakerFee")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_7 = self.extend(signRaw, &[paramsOmitted]);
let mut txTypetxInfoVariable = self.lighter_sign_modify_order(signer, __ws_arg_7);
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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[request]).await;
return self.parse_order(response, &[market]);
Value::Null
}
/*
* @method
* @name lighter#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://apidocs.lighter.xyz/reference/status
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/?id=exchange-status-structure}
*/
pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.root_get(&[params]).await;
//
// {
// "status": "1",
// "network_id": "1",
// "timestamp": "1717777777"
// }
//
let mut status: Option<String> = self.safe_string_k(response.clone(), "status", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if (status.as_deref() == Some("200")) { Value::Str("ok".into()) } else { Value::Str("error".into()) }));
m.insert("updated".to_string(), Value::Null);
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
/*
* @method
* @name lighter#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://apidocs.lighter.xyz/reference/status
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.root_get(&[params]).await;
return self.safe_timestamp_k(response, "timestamp", &[]);
Value::Null
}
/*
* @method
* @name lighter#fetchMarkets
* @description retrieves data on all markets for lighter
* @see https://apidocs.lighter.xyz/reference/orderbookdetails
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_order_book_details(&[params]).await;
//
// {
// "code": "200",
// "message": "string",
// "order_book_details": [
// {
// "symbol": "ETH",
// "market_id": 0,
// "market_type": "perp",
// "base_asset_id": 0,
// "quote_asset_id": 0,
// "status": "active",
// "taker_fee": "0.0001",
// "maker_fee": "0.0000",
// "liquidation_fee": "0.01",
// "min_base_amount": "0.01",
// "min_quote_amount": "0.1",
// "supported_size_decimals": "4",
// "supported_price_decimals": "4",
// "supported_quote_decimals": "4",
// "order_quote_limit": "281474976.710655",
// "size_decimals": "4",
// "price_decimals": "4",
// "quote_multiplier": "10000",
// "default_initial_margin_fraction": "100",
// "min_initial_margin_fraction": "100",
// "maintenance_margin_fraction": "50",
// "closeout_margin_fraction": "100",
// "last_trade_price": "3024.66",
// "daily_trades_count": "68",
// "daily_base_token_volume": "235.25",
// "daily_quote_token_volume": "93566.25",
// "daily_price_low": "3014.66",
// "daily_price_high": "3024.66",
// "daily_price_change": "3.66",
// "open_interest": "93.0",
// "daily_chart": "{1640995200:3024.66}",
// "market_config": {
// "market_margin_mode": 0,
// "insurance_fund_account_index": 281474976710655,
// "liquidation_mode": 0,
// "force_reduce_only": false,
// "funding_fee_discounts_enabled": true,
// "trading_hours": "",
// "hidden": true
// },
// "strategy_index": 0
// }
// ],
// "spot_order_book_details": [
// {
// "symbol": "ETH/USDC",
// "market_id": 2048,
// "market_type": "spot",
// "base_asset_id": 1,
// "quote_asset_id": 3,
// "status": "active",
// "taker_fee": "0.0000",
// "maker_fee": "0.0000",
// "liquidation_fee": "0.0000",
// "min_base_amount": "0.0001",
// "min_quote_amount": "0.000001",
// "order_quote_limit": "2500000.000000",
// "supported_size_decimals": 4,
// "supported_price_decimals": 2,
// "supported_quote_decimals": 6,
// "size_decimals": 4,
// "price_decimals": 2,
// "last_trade_price": 2731.79,
// "daily_trades_count": 126993,
// "daily_base_token_volume": 1203.0962,
// "daily_quote_token_volume": 3516374.947553,
// "daily_price_low": 2717.47,
// "daily_price_high": 3044.21,
// "daily_price_change": -10.2389493724579,
// "daily_chart": "{1640995200:3024.66}"
// }
// ]
// }
//
let mut spotMarkets: Value = self.safe_list_k(response.clone(), "spot_order_book_details", &[Value::from(vec![])]);
let mut swapMarkets: Value = self.safe_list_k(response, "order_book_details", &[Value::from(vec![])]);
let mut markets: Value = self.array_concat(spotMarkets, swapMarkets);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_927: bool = true;
while { if !__for_first_927 { 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_927 = false; i.as_f64().unwrap_or(f64::NAN) < ((markets.len() as i64) as f64) } {
let mut market: Value = markets.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut id: Value = self.safe_string_k(market.clone(), "market_id", &[]);
let mut type_var: Value = self.safe_string_k(market.clone(), "market_type", &[]);
if (type_var.as_str() == Some("perp")) {
type_var = Value::Str("swap".into());
}
let mut baseId: Value = self.safe_string_k(market.clone(), "symbol", &[]);
if (baseId != Value::Null) && (Value::Int(baseId.as_str().and_then(|__s| __s.find("/")).map(|__i| __i as i64).unwrap_or(-1)).as_f64() != Value::Int(-1).as_f64()) {
baseId = split(&baseId, &Value::Str("/".into())).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
}
let mut quoteId: Value = Value::Str("USDC".into());
let mut settleId: Value = (if (type_var.as_str() == Some("swap")) { Value::Str("USDC".into()) } else { Value::Null });
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
continue;
}
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
if (settle != Value::Null) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str(":".into())).into()), settle).into());
}
let mut amountDecimals: Value = self.safe_string2(market.clone(), Value::Str("size_decimals".into()), Value::Str("supported_size_decimals".into()), &[]);
let mut priceDecimals: Value = self.safe_string2(market.clone(), Value::Str("price_decimals".into()), Value::Str("supported_price_decimals".into()), &[]);
let mut amountPrecision: Value = (if (amountDecimals == Value::Null) { Value::Null } else { self.parse_number(self.parse_precision(&[amountDecimals]), &[]) });
let mut pricePrecision: Value = (if (priceDecimals == Value::Null) { Value::Null } else { self.parse_number(self.parse_precision(&[priceDecimals]), &[]) });
let mut quoteMultiplier: Value = self.safe_number_k(market.clone(), "quote_multiplier", &[]);
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), type_var.clone());
m.insert("spot".to_string(), Value::Bool(type_var.as_str() == Some("spot")));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(type_var.as_str() == Some("swap")));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(self.safe_string_k(market.clone(), "status", &[]).as_str() == Some("active")));
m.insert("contract".to_string(), Value::Bool(type_var.as_str() == Some("swap")));
m.insert("linear".to_string(), (if (type_var.as_str() == Some("swap")) { Value::Bool(true) } else { Value::Null }));
m.insert("inverse".to_string(), (if (type_var.as_str() == Some("swap")) { Value::Bool(false) } else { Value::Null }));
m.insert("taker".to_string(), self.safe_number_k(market.clone(), "taker_fee", &[]));
m.insert("maker".to_string(), self.safe_number_k(market.clone(), "maker_fee", &[]));
m.insert("contractSize".to_string(), quoteMultiplier);
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), amountPrecision);
m.insert("price".to_string(), pricePrecision);
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(market.clone(), "min_base_amount", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(market.clone(), "min_quote_amount", &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "order_quote_limit", &[]));
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market);
m
}));
}
}
return result;
Value::Null
}
/*
* @method
* @name lighter#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://apidocs.lighter.xyz/reference/assetdetails
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_asset_details(&[params]).await;
if self.check_required_credentials(&[Value::Bool(false)]).as_bool() == Some(true) {
self.pre_load_lighter_library(&[]).await;
}
//
// {
// "code": 200,
// "asset_details": [
// {
// "asset_id": 3,
// "symbol": "USDC",
// "l1_decimals": 6,
// "decimals": 6,
// "min_transfer_amount": "1.000000",
// "min_withdrawal_amount": "1.000000",
// "margin_mode": "enabled",
// "index_price": "1.000000",
// "l1_address": "0x95Fd23d5110f9D89A4b0B7d63D78F5B5Ea5074D1"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "asset_details", &[Value::from(vec![])]);
return self.parse_currencies(data);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
let mut id: Value = self.safe_string_k(rawCurrency.clone(), "asset_id", &[]);
let mut code: Value = self.safe_currency_code(self.safe_string_k(rawCurrency.clone(), "symbol", &[]), &[]);
let mut decimals: Value = self.safe_string_k(rawCurrency.clone(), "decimals", &[]);
let mut isUSDC: Value = (Value::Bool(code.as_str() == Some("USDC")));
let mut depositMin: Value = Value::Null;
let mut withdrawMin: Value = Value::Null;
if matches!(&isUSDC, Value::Bool(true)) {
depositMin = self.safe_number_k(rawCurrency.clone(), "min_transfer_amount", &[]);
withdrawMin = self.safe_number_k(rawCurrency.clone(), "min_withdrawal_amount", &[]);
}
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("name".to_string(), code.clone());
m.insert("code".to_string(), code);
m.insert("precision".to_string(), self.parse_number(Value::Str(format!("{}{}", Value::Str("1e-".into()), decimals).into()), &[]));
m.insert("active".to_string(), Value::Bool(true));
m.insert("fee".to_string(), Value::Null);
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("deposit".to_string(), isUSDC.clone());
m.insert("withdraw".to_string(), isUSDC);
m.insert("type".to_string(), Value::Str("crypto".into()));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), depositMin);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), withdrawMin);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), rawCurrency);
m
}));
Value::Null
}
/*
* @method
* @name lighter#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://apidocs.lighter.xyz/reference/orderbookorders
* @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 fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrderBook() requires a symbol argument".into()))));
}
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("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("limit".to_string(), Value::Int(100));
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(250))); }
}
let __ws_arg_8 = self.extend(request, &[params]);
let mut response: Value = self.public_get_order_book_orders(&[__ws_arg_8]).await;
//
// {
// "code": 200,
// "total_asks": 1,
// "asks": [
// {
// "order_index": 281475565888172,
// "order_id": "281475565888172",
// "owner_account_index": 134436,
// "initial_base_amount": "0.2000",
// "remaining_base_amount": "0.2000",
// "price": "3430.00",
// "order_expiry": 1765419046808
// }
// ],
// "total_bids": 1,
// "bids": [
// {
// "order_index": 562949401225099,
// "order_id": "562949401225099",
// "owner_account_index": 314236,
// "initial_base_amount": "1.7361",
// "remaining_base_amount": "1.3237",
// "price": "3429.80",
// "order_expiry": 1765419047587
// }
// ]
// }
//
let mut result: Value = self.parse_order_book(response, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[Value::Null, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("remaining_base_amount".into())]);
return result;
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTicker, fetchTickers
// {
// "symbol": "ETH",
// "market_id": 0,
// "status": "active",
// "taker_fee": "0.0000",
// "maker_fee": "0.0000",
// "liquidation_fee": "1.0000",
// "min_base_amount": "0.0050",
// "min_quote_amount": "10.000000",
// "order_quote_limit": "",
// "supported_size_decimals": 4,
// "supported_price_decimals": 2,
// "supported_quote_decimals": 6,
// "size_decimals": 4,
// "price_decimals": 2,
// "quote_multiplier": 1,
// "default_initial_margin_fraction": 500,
// "min_initial_margin_fraction": 200,
// "maintenance_margin_fraction": 120,
// "closeout_margin_fraction": 80,
// "last_trade_price": 3550.69,
// "daily_trades_count": 1197349,
// "daily_base_token_volume": 481297.3509,
// "daily_quote_token_volume": 1671431095.263844,
// "daily_price_low": 3402.41,
// "daily_price_high": 3571.45,
// "daily_price_change": 0.5294300840859545,
// "open_interest": 39559.3278,
// "daily_chart": {},
// "market_config": {
// "market_margin_mode": 0,
// "insurance_fund_account_index": 281474976710654,
// "liquidation_mode": 0,
// "force_reduce_only": false,
// "trading_hours": ""
// }
// }
//
// watchTicker, watchTickers
// {
// "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
// }
//
let mut marketId: Value = self.safe_string_k(ticker.clone(), "market_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut last: Value = self.safe_string_k(ticker.clone(), "last_trade_price", &[]);
let mut high: Value = self.safe_string_k(ticker.clone(), "daily_price_high", &[]);
let mut low: Value = self.safe_string_k(ticker.clone(), "daily_price_low", &[]);
let mut baseVolume: Value = self.safe_string_k(ticker.clone(), "daily_base_token_volume", &[]);
let mut quoteVolume: Value = self.safe_string_k(ticker.clone(), "daily_quote_token_volume", &[]);
let mut change: Value = self.safe_string_k(ticker.clone(), "daily_price_change", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("high".to_string(), high);
m.insert("low".to_string(), low);
m.insert("bid".to_string(), Value::Null);
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), Value::Null);
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), change);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), baseVolume);
m.insert("quoteVolume".to_string(), quoteVolume);
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "mark_price", &[]));
m.insert("indexPrice".to_string(), self.safe_string_k(ticker.clone(), "index_price", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name lighter#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://apidocs.lighter.xyz/reference/orderbookdetails
* @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 fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTicker() requires a symbol argument".into()))));
}
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("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_9 = self.extend(request, &[params]);
let mut response: Value = self.public_get_order_book_details(&[__ws_arg_9]).await;
//
// {
// "code": 200,
// "order_book_details": [
// {
// "symbol": "ETH",
// "market_id": 0,
// "status": "active",
// "taker_fee": "0.0000",
// "maker_fee": "0.0000",
// "liquidation_fee": "1.0000",
// "min_base_amount": "0.0050",
// "min_quote_amount": "10.000000",
// "order_quote_limit": "",
// "supported_size_decimals": 4,
// "supported_price_decimals": 2,
// "supported_quote_decimals": 6,
// "size_decimals": 4,
// "price_decimals": 2,
// "quote_multiplier": 1,
// "default_initial_margin_fraction": 500,
// "min_initial_margin_fraction": 200,
// "maintenance_margin_fraction": 120,
// "closeout_margin_fraction": 80,
// "last_trade_price": 3550.69,
// "daily_trades_count": 1197349,
// "daily_base_token_volume": 481297.3509,
// "daily_quote_token_volume": 1671431095.263844,
// "daily_price_low": 3402.41,
// "daily_price_high": 3571.45,
// "daily_price_change": 0.5294300840859545,
// "open_interest": 39559.3278,
// "daily_chart": {},
// "market_config": {
// "market_margin_mode": 0,
// "insurance_fund_account_index": 281474976710655,
// "liquidation_mode": 0,
// "force_reduce_only": false,
// "trading_hours": ""
// }
// }
// ]
// }
//
let mut spotTickers: Value = self.safe_list_k(response.clone(), "spot_order_book_details", &[Value::from(vec![])]);
let mut swapTickers: Value = self.safe_list_k(response, "order_book_details", &[Value::from(vec![])]);
let mut tickers: Value = self.array_concat(spotTickers, swapTickers);
let mut first: Value = self.safe_dict(tickers, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(first, &[market]);
Value::Null
}
/*
* @method
* @name lighter#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://apidocs.lighter.xyz/reference/orderbookdetails
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut response: Value = self.public_get_order_book_details(&[params]).await;
let mut spotTickers: Value = self.safe_list_k(response.clone(), "spot_order_book_details", &[Value::from(vec![])]);
let mut swapTickers: Value = self.safe_list_k(response, "order_book_details", &[Value::from(vec![])]);
let mut tickers: Value = self.array_concat(spotTickers, swapTickers);
return self.parse_tickers(tickers, &[symbolsNormalized]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_integer_k(ohlcv.clone(), "t", &[]), self.safe_number_k(ohlcv.clone(), "o", &[]), self.safe_number_k(ohlcv.clone(), "h", &[]), self.safe_number_k(ohlcv.clone(), "l", &[]), self.safe_number_k(ohlcv.clone(), "c", &[]), self.safe_number_k(ohlcv, "v", &[])]);
Value::Null
}
/*
* @method
* @name lighter#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://apidocs.lighter.xyz/reference/candles
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest candle to fetch
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1h".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("until".into())]), &[]);
let mut now: Value = self.milliseconds();
let mut startTs: Value = Value::Null;
let mut endTs: Value = Value::Null;
if (since != Value::Null) {
startTs = since.clone();
if (until != Value::Null) {
endTs = until.clone();
} else if (limit != Value::Null) {
let mut duration: Value = self.parse_timeframe(timeframe.clone());
endTs = self.sum(&[since.clone(), (match (&((match (&(duration), &(limit)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
} else {
endTs = now.clone();
}
} else {
endTs = (if (until != Value::Null) { until } else { now });
let mut defaultLimit: Value = Value::Int(100);
if (limit != Value::Null) {
startTs = (match (&(endTs), &((match (&((match (&(self.parse_timeframe(timeframe.clone())), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(limit)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
} else {
startTs = (match (&(endTs), &((match (&((match (&(self.parse_timeframe(timeframe.clone())), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(defaultLimit)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("count_back".to_string(), Value::Int(0));
m.insert("resolution".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m.insert("start_timestamp".to_string(), startTs);
m.insert("end_timestamp".to_string(), endTs);
m
});
let __ws_arg_10 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.public_get_candles(&[__ws_arg_10]).await;
//
// {
// "code": 200,
// "r": "1m",
// "c": [
// {
// "t": 1767700500000,
// "o": 3236.86,
// "h": 3237.78,
// "l": 3235.36,
// "c": 3235.39,
// "v": 55.1632,
// "V": 178530.793575,
// "i": 779870452,
// "C": "string",
// "H": "string",
// "L": "string",
// "O": "string"
// }
// ]
// }
//
let mut ohlcvs: Value = self.safe_list_k(response, "c", &[Value::from(vec![])]);
return self.parse_ohlc_vs(ohlcvs, &[market, timeframe, since, limit]);
Value::Null
}
pub fn parse_funding_rate(&self, mut contract: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "market_id": 0,
// "exchange": "lighter",
// "symbol": "ETH",
// "rate": 0.00009599999999999999
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "market_id", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("fundingRate".to_string(), self.safe_number_k(contract, "rate", &[]));
m.insert("fundingTimestamp".to_string(), Value::Null);
m.insert("fundingDatetime".to_string(), Value::Null);
m.insert("nextFundingRate".to_string(), Value::Null);
m.insert("nextFundingTimestamp".to_string(), Value::Null);
m.insert("nextFundingDatetime".to_string(), Value::Null);
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name lighter#fetchFundingRates
* @description fetch the current funding rate for multiple symbols
* @see https://apidocs.lighter.xyz/reference/funding-rates
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rates(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let __ws_arg_11 = self.extend(params, &[]);
let mut response: Value = self.public_get_funding_rates(&[__ws_arg_11]).await;
//
// {
// "code": 200,
// "funding_rates": [
// {
// "market_id": 0,
// "exchange": "lighter",
// "symbol": "ETH",
// "rate": 0.00009599999999999999
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "funding_rates", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_928: bool = true;
while { if !__for_first_928 { 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_928 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut exchange: Option<String> = self.safe_string(data.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), Value::Str("exchange".into()), &[]).as_str().map(str::to_owned);
if (exchange.as_deref() == Some("lighter")) {
append_to_array(&mut result, data.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));
}
}
}
return self.parse_funding_rates(result, &[symbols]);
Value::Null
}
/*
* @method
* @name ligher#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://apidocs.lighter.xyz/reference/account-1
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.by] fetch balance by 'index' or 'l1_address', defaults to 'index'
* @param {string} [params.value] fetch balance value, account index or l1 address
* @param {string} [params.type] 'spot', 'swap', default is 'swap'
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(params, Value::Str("fetchBalance".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut defaultType: Value = self.safe_string2(self.options.clone(), Value::Str("fetchBalance".into()), Value::Str("defaultType".into()), &[Value::Str("spot".into())]);
let mut type_var: Option<String> = self.safe_string_k(paramsAccountIndex.clone(), "type", &[defaultType]).as_str().map(str::to_owned);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("by".to_string(), self.safe_string_k(paramsAccountIndex.clone(), "by", &[Value::Str("index".into())]));
m.insert("value".to_string(), accountIndex);
m
});
let __ws_arg_12 = self.extend(request, &[paramsAccountIndex]);
let mut response: Value = self.public_get_account(&[__ws_arg_12]).await;
//
// {
// "code": "200",
// "total": "1",
// "accounts": [
// {
// "code": "0",
// "account_type": "0",
// "index": "1077",
// "l1_address": "0x15f43D1f2DeE81424aFd891943262aa90F22cc2A",
// "cancel_all_time": "0",
// "total_order_count": "1",
// "total_isolated_order_count": "0",
// "pending_order_count": "0",
// "available_balance": "7996.489834",
// "status": "1",
// "collateral": "9000.000000",
// "account_index": "1077",
// "name": "",
// "description": "",
// "can_invite": true,
// "referral_points_percentage": "",
// "positions": [],
// "assets": [
// {
// "symbol": "ETH",
// "asset_id": "1",
// "balance": "3.00000000",
// "locked_balance": "0.00000000"
// },
// {
// "symbol": "USDC",
// "asset_id": "3",
// "balance": "1000.000000",
// "locked_balance": "0.000000"
// }
// ],
// "total_asset_value": "9536.789088",
// "cross_asset_value": "9536.789088",
// "shares": []
// }
// ]
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut accounts: Value = self.safe_list_k(response, "accounts", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_930: bool = true;
while { if !__for_first_930 { 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_930 = false; i.as_f64().unwrap_or(f64::NAN) < ((accounts.len() as i64) as f64) } {
let mut account: Value = self.safe_dict(accounts.clone(), i.clone(), &[]);
if (type_var.as_deref() == Some("spot")) {
let mut assets: Value = self.safe_list_k(account.clone(), "assets", &[Value::from(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_929: bool = true;
while { if !__for_first_929 { 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_929 = false; j.as_f64().unwrap_or(f64::NAN) < ((assets.len() as i64) as f64) } {
let mut asset: Value = self.safe_dict(assets.clone(), j.clone(), &[]);
let mut codeId: Value = self.safe_string_k(asset.clone(), "symbol", &[]);
let mut code: Value = self.safe_currency_code(codeId, &[]);
let mut balance: Value = self.safe_dict(result.clone(), code.clone(), &[self.account()]);
{ let __be_tmp = crate::precise::Precise::stringAdd(&crate::value::get_value_k(&balance, "total"), &self.safe_string_k(asset.clone(), "balance", &[])); add_element_to_object(&mut balance, &Value::Str("total".into()), __be_tmp); };
{ let __be_tmp = crate::precise::Precise::stringAdd(&crate::value::get_value_k(&balance, "used"), &self.safe_string_k(asset, "locked_balance", &[])); add_element_to_object(&mut balance, &Value::Str("used".into()), __be_tmp); };
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), balance); }
}
}
}
} else {
let mut perpBalance: Value = self.safe_dict_k(result.clone(), "USDC", &[self.account()]);
let mut perpTotal: Value = self.safe_string_k(perpBalance.clone(), "total", &[Value::Str("0".into())]);
let mut perpFree: Value = self.safe_string_k(perpBalance.clone(), "free", &[Value::Str("0".into())]);
let mut perpUSDCTotal: Value = self.safe_string_k(account.clone(), "collateral", &[Value::Str("0".into())]);
let mut perpUSDCFree: Value = self.safe_string_k(account, "available_balance", &[Value::Str("0".into())]);
add_element_to_object(&mut perpBalance, &Value::Str("total".into()), crate::precise::Precise::stringAdd(&perpTotal, &perpUSDCTotal));
add_element_to_object(&mut perpBalance, &Value::Str("free".into()), crate::precise::Precise::stringAdd(&perpFree, &perpUSDCFree));
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("USDC".into(), perpBalance); }
}
}
}
return self.safe_balance(result);
Value::Null
}
/*
* @method
* @name lighter#fetchPosition
* @description fetch data on an open position
* @see https://apidocs.lighter.xyz/reference/account-1
* @param {string} symbol unified market symbol of the market the position is held in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.by] fetch balance by 'index' or 'l1_address', defaults to 'index'
* @param {string} [params.value] fetch balance value, account index or l1 address
* @returns {object} a [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut positions: Value = self.fetch_positions(&[Value::from(vec![symbol]), params]).await;
return self.safe_dict(positions, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
/*
* @method
* @name lighter#fetchPositions
* @description fetch all open positions
* @see https://apidocs.lighter.xyz/reference/account-1
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.by] fetch balance by 'index' or 'l1_address', defaults to 'index'
* @param {string} [params.value] fetch balance value, account index or l1 address
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(params, Value::Str("fetchPositions".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("by".to_string(), self.safe_string_k(paramsAccountIndex.clone(), "by", &[Value::Str("index".into())]));
m.insert("value".to_string(), accountIndex);
m
});
let __ws_arg_13 = self.extend(request, &[paramsAccountIndex]);
let mut response: Value = self.public_get_account(&[__ws_arg_13]).await;
//
// {
// "code": 200,
// "total": 2,
// "accounts": [
// {
// "code": 0,
// "account_type": 0,
// "index": 1077,
// "l1_address": "0x15f43D1f2DeE81424aFd891943262aa90F22cc2A",
// "cancel_all_time": 0,
// "total_order_count": 0,
// "total_isolated_order_count": 0,
// "pending_order_count": 0,
// "available_balance": "12582.743947",
// "status": 1,
// "collateral": "9100.242706",
// "account_index": 1077,
// "name": "",
// "description": "",
// "can_invite": true,
// "referral_points_percentage": "",
// "positions": [
// {
// "market_id": 0,
// "symbol": "ETH",
// "initial_margin_fraction": "5.00",
// "open_order_count": 0,
// "pending_order_count": 0,
// "position_tied_order_count": 0,
// "sign": 1,
// "position": "18.0193",
// "avg_entry_price": "2669.84",
// "position_value": "54306.566340",
// "unrealized_pnl": "6197.829558",
// "realized_pnl": "0.000000",
// "liquidation_price": "2191.1107231380406",
// "margin_mode": 0,
// "allocated_margin": "0.000000"
// }
// ],
// "assets": [],
// "total_asset_value": "15298.072264000002",
// "cross_asset_value": "15298.072264000002",
// "shares": []
// }
// ]
// }
//
let mut allPositions: Value = Value::from(vec![]);
let mut accounts: Value = self.safe_list_k(response, "accounts", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_932: bool = true;
while { if !__for_first_932 { 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_932 = false; i.as_f64().unwrap_or(f64::NAN) < ((accounts.len() as i64) as f64) } {
let mut account: Value = self.safe_dict(accounts.clone(), i.clone(), &[]);
let mut positions: Value = self.safe_list_k(account, "positions", &[Value::from(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_931: bool = true;
while { if !__for_first_931 { 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_931 = false; j.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
append_to_array(&mut allPositions, positions.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));
}
}
}
}
return self.parse_positions(allPositions, &[symbols]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "market_id": 0,
// "symbol": "ETH",
// "initial_margin_fraction": "5.00",
// "open_order_count": 0,
// "pending_order_count": 0,
// "position_tied_order_count": 0,
// "sign": 1,
// "position": "18.0193",
// "avg_entry_price": "2669.84",
// "position_value": "54306.566340",
// "unrealized_pnl": "6197.829558",
// "realized_pnl": "0.000000",
// "liquidation_price": "2191.1107231380406",
// "margin_mode": 0,
// "allocated_margin": "0.000000"
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "market_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut sign: Option<i64> = self.safe_integer_k(position.clone(), "sign", &[]).as_i64();
let mut side: Value = Value::Null;
if (sign.is_some()) {
side = (if (sign == Some(1)) { Value::Str("long".into()) } else { Value::Str("short".into()) });
}
let mut marginModeId: Option<i64> = self.safe_integer_k(position.clone(), "margin_mode", &[]).as_i64();
let mut marginMode: Value = Value::Null;
if (marginModeId.is_some()) {
marginMode = (if (marginModeId == Some(0)) { Value::Str("cross".into()) } else { Value::Str("isolated".into()) });
}
let mut imfStr: Value = self.safe_string_k(position.clone(), "initial_margin_fraction", &[]);
let mut leverage: Value = Value::Null;
if (imfStr != Value::Null) {
let mut imf: Value = self.parse_to_int(imfStr);
if imf.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
leverage = (match ((Value::Int(100)).as_f64(), (imf).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
}
let mut contractsString: Value = self.safe_string_k(position.clone(), "position", &[]);
let mut positionValueString: Value = self.safe_string_k(position.clone(), "position_value", &[]);
let mut markPriceString: Value = crate::precise::Precise::stringDiv(&positionValueString, &contractsString);
// allocated_margin is the isolated collateral balance (0 for cross)
let mut positionMargin: Value = Value::Null;
if (marginMode.as_str() == Some("isolated")) {
positionMargin = self.safe_number_k(position.clone(), "allocated_margin", &[]);
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("isolated".to_string(), (Value::Bool(marginMode.as_str() == Some("isolated"))));
m.insert("hedged".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("contracts".to_string(), self.parse_number(contractsString, &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "avg_entry_price", &[]));
m.insert("markPrice".to_string(), self.parse_number(markPriceString, &[]));
m.insert("notional".to_string(), self.parse_number(positionValueString, &[]));
m.insert("leverage".to_string(), leverage);
m.insert("positionMargin".to_string(), positionMargin);
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "unrealized_pnl", &[]));
m.insert("liquidationPrice".to_string(), self.safe_number_k(position, "liquidation_price", &[]));
m.insert("marginMode".to_string(), marginMode);
m.insert("percentage".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name lighter#fetchAccounts
* @description fetch all the accounts associated with a profile
* @see https://apidocs.lighter.xyz/reference/account-1
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.by] fetch balance by 'index' or 'l1_address', defaults to 'index'
* @param {string} [params.value] fetch balance value, account index or l1 address
* @returns {object} a dictionary of [account structures]{@link https://docs.ccxt.com/?id=accounts-structure} indexed by the account type
*/
pub async fn fetch_accounts(&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 accountIndexparamsAccountIndexVariable = self.handle_account_index(params, Value::Str("fetchAccounts".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("by".to_string(), self.safe_string_k(paramsAccountIndex.clone(), "by", &[Value::Str("index".into())]));
m.insert("value".to_string(), accountIndex);
m
});
let __ws_arg_14 = self.extend(request, &[paramsAccountIndex.clone()]);
let mut response: Value = self.public_get_account(&[__ws_arg_14]).await;
//
// {
// "code": "200",
// "total": "1",
// "accounts": [
// {
// "code": "0",
// "account_type": "0",
// "index": "1077",
// "l1_address": "0x15f43D1f2DeE81424aFd891943262aa90F22cc2A",
// "cancel_all_time": "0",
// "total_order_count": "1",
// "total_isolated_order_count": "0",
// "pending_order_count": "0",
// "available_balance": "7996.489834",
// "status": "1",
// "collateral": "9000.000000",
// "account_index": "1077",
// "name": "",
// "description": "",
// "can_invite": true,
// "referral_points_percentage": "",
// "positions": [],
// "assets": [],
// "total_asset_value": "9536.789088",
// "cross_asset_value": "9536.789088",
// "shares": []
// }
// ]
// }
//
let mut accounts: Value = self.safe_list_k(response, "accounts", &[Value::from(vec![])]);
return self.parse_accounts(accounts, &[paramsAccountIndex]);
Value::Null
}
pub fn parse_account(&self, mut account: Value) -> Value {
//
// {
// "code": "0",
// "account_type": "0",
// "index": "1077",
// "l1_address": "0x15f43D1f2DeE81424aFd891943262aa90F22cc2A",
// "cancel_all_time": "0",
// "total_order_count": "1",
// "total_isolated_order_count": "0",
// "pending_order_count": "0",
// "available_balance": "7996.489834",
// "status": "1",
// "collateral": "9000.000000",
// "account_index": "1077",
// "name": "",
// "description": "",
// "can_invite": true,
// "referral_points_percentage": "",
// "positions": [],
// "assets": [],
// "total_asset_value": "9536.789088",
// "cross_asset_value": "9536.789088",
// "shares": []
// }
//
let mut accountType: Option<String> = self.safe_string_k(account.clone(), "account_type", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(account.clone(), "account_index", &[]));
m.insert("type".to_string(), (if (accountType.as_deref() == Some("0")) { Value::Str("main".into()) } else { Value::Str("subaccount".into()) }));
m.insert("code".to_string(), Value::Null);
m.insert("info".to_string(), account);
m
});
Value::Null
}
/*
* @method
* @name lighter#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://apidocs.lighter.xyz/reference/accountactiveorders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(params, Value::Str("fetchOpenOrders".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchOpenOrders".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_15 = self.extend(request, &[paramsApiKeyIndex]);
let mut response: Value = self.private_get_account_active_orders(&[__ws_arg_15]).await;
//
// {
// "code": 200,
// "orders": [
// {
// "order_index": 281474977354074,
// "client_order_index": 0,
// "order_id": "281474977354074",
// "client_order_id": "0",
// "market_index": 0,
// "owner_account_index": 1077,
// "initial_base_amount": "36.0386",
// "price": "2221.60",
// "nonce": 643418,
// "remaining_base_amount": "0.0000",
// "is_ask": true,
// "base_size": 0,
// "base_price": 222160,
// "filled_base_amount": "0.0000",
// "filled_quote_amount": "0.000000",
// "side": "",
// "type": "market",
// "time_in_force": "immediate-or-cancel",
// "reduce_only": false,
// "trigger_price": "0.00",
// "order_expiry": 0,
// "status": "canceled-margin-not-allowed",
// "trigger_status": "na",
// "trigger_time": 0,
// "parent_order_index": 0,
// "parent_order_id": "0",
// "to_trigger_order_id_0": "0",
// "to_trigger_order_id_1": "0",
// "to_cancel_order_id_0": "0",
// "block_height": 102202,
// "timestamp": 1766387932,
// "created_at": 1766387932,
// "updated_at": 1766387932
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name lighter#fetchClosedOrders
* @description fetch all unfilled currently closed orders
* @see https://apidocs.lighter.xyz/reference/accountinactiveorders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_closed_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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchClosedOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(params, Value::Str("fetchClosedOrders".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchClosedOrders".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("account_index".to_string(), accountIndex);
m.insert("limit".to_string(), Value::Int(100));
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(100))); }
}
let __ws_arg_16 = self.extend(request, &[paramsApiKeyIndex]);
let mut response: Value = self.private_get_account_inactive_orders(&[__ws_arg_16]).await;
//
// {
// "code": 200,
// "orders": [
// {
// "order_index": 281474977354074,
// "client_order_index": 0,
// "order_id": "281474977354074",
// "client_order_id": "0",
// "market_index": 0,
// "owner_account_index": 1077,
// "initial_base_amount": "36.0386",
// "price": "2221.60",
// "nonce": 643418,
// "remaining_base_amount": "0.0000",
// "is_ask": true,
// "base_size": 0,
// "base_price": 222160,
// "filled_base_amount": "0.0000",
// "filled_quote_amount": "0.000000",
// "side": "",
// "type": "market",
// "time_in_force": "immediate-or-cancel",
// "reduce_only": false,
// "trigger_price": "0.00",
// "order_expiry": 0,
// "status": "canceled-margin-not-allowed",
// "trigger_status": "na",
// "trigger_time": 0,
// "parent_order_index": 0,
// "parent_order_id": "0",
// "to_trigger_order_id_0": "0",
// "to_trigger_order_id_1": "0",
// "to_cancel_order_id_0": "0",
// "block_height": 102202,
// "timestamp": 1766387932,
// "created_at": 1766387932,
// "updated_at": 1766387932
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "order_index": 281474977354074,
// "client_order_index": 0,
// "order_id": "281474977354074",
// "client_order_id": "0",
// "market_index": 0,
// "owner_account_index": 1077,
// "initial_base_amount": "36.0386",
// "price": "2221.60",
// "nonce": 643418,
// "remaining_base_amount": "0.0000",
// "is_ask": true,
// "base_size": 0,
// "base_price": 222160,
// "filled_base_amount": "0.0000",
// "filled_quote_amount": "0.000000",
// "side": "",
// "type": "market",
// "time_in_force": "immediate-or-cancel",
// "reduce_only": false,
// "trigger_price": "0.00",
// "order_expiry": 0,
// "status": "canceled-margin-not-allowed",
// "trigger_status": "na",
// "trigger_time": 0,
// "parent_order_index": 0,
// "parent_order_id": "0",
// "to_trigger_order_id_0": "0",
// "to_trigger_order_id_1": "0",
// "to_cancel_order_id_0": "0",
// "block_height": 102202,
// "timestamp": 1766387932,
// "created_at": 1766387932,
// "updated_at": 1766387932
// }
//
let mut marketId: Value = self.safe_string_k(order.clone(), "market_index", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut timestamp: Value = self.safe_timestamp_k(order.clone(), "timestamp", &[]);
let mut isAsk: Value = self.safe_bool_k(order.clone(), "is_ask", &[]);
if (isAsk == Value::Null) {
let mut isAskAsInteger: Option<i64> = self.safe_integer_k(order.clone(), "is_ask", &[]).as_i64();
if (isAskAsInteger.is_some()) {
isAsk = Value::Bool(isAskAsInteger == Some(1));
}
}
let mut side: Value = Value::Null;
if (isAsk != Value::Null) {
side = (if isAsk.as_bool() == Some(true) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
}
let mut type_var: Value = self.safe_string_k(order.clone(), "type", &[]);
if (type_var == Value::Null) {
let mut typeAsInteger: Value = self.safe_integer_k(order.clone(), "order_type", &[]);
type_var = self.parse_order_type_integer(typeAsInteger).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
}
let mut triggerPrice: Value = self.parse_number(self.omit_zero(self.safe_string_k(order.clone(), "trigger_price", &[])), &[]);
let mut stopLossPrice: Value = Value::Null;
let mut takeProfitPrice: Value = Value::Null;
if (type_var != Value::Null) {
if Value::Int(type_var.as_str().and_then(|__s| __s.find("stop-loss")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
stopLossPrice = triggerPrice.clone();
}
if Value::Int(type_var.as_str().and_then(|__s| __s.find("take-profit")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
takeProfitPrice = triggerPrice.clone();
}
}
// Try to parse to integer first, because parsing an integer to a string wouldn't result in undefined
let mut tif: Value = Value::Null;
let mut tifAsInteger: Value = self.safe_integer_k(order.clone(), "time_in_force", &[]);
if (tifAsInteger != Value::Null) {
tif = self.parse_order_time_in_force_integer(tifAsInteger);
} else {
tif = self.safe_string_k(order.clone(), "time_in_force", &[]);
}
let mut reduceOnly: Value = self.safe_bool_k(order.clone(), "reduce_only", &[]);
if (reduceOnly == Value::Null) {
let mut reduceOnlyAsInteger: Option<i64> = self.safe_integer_k(order.clone(), "reduce_only", &[]).as_i64();
if (reduceOnlyAsInteger.is_some()) {
reduceOnly = Value::Bool(reduceOnlyAsInteger == Some(1));
}
}
let mut status: Value = self.safe_string_k(order.clone(), "status", &[]);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string_k(order.clone(), "order_id", &[]));
m.insert("clientOrderId".to_string(), self.omit_zero(self.safe_string2(order.clone(), Value::Str("client_order_id".into()), Value::Str("client_order_index".into()), &[])));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_timestamp_k(order.clone(), "updated_at", &[]));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), self.parse_order_type(type_var).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("timeInForce".to_string(), self.parse_order_time_in_force(tif.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("postOnly".to_string(), Value::Bool(tif.as_str() == Some("post-only")));
m.insert("reduceOnly".to_string(), reduceOnly);
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.safe_string_k(order.clone(), "price", &[]));
m.insert("triggerPrice".to_string(), triggerPrice);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("amount".to_string(), self.safe_string_k(order.clone(), "initial_base_amount", &[]));
m.insert("cost".to_string(), self.safe_string_k(order.clone(), "filled_quote_amount", &[]));
m.insert("average".to_string(), Value::Null);
m.insert("filled".to_string(), self.safe_string_k(order.clone(), "filled_base_amount", &[]));
m.insert("remaining".to_string(), self.safe_string_k(order, "remaining_base_amount", &[]));
m.insert("status".to_string(), self.parse_order_status(status));
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("in-progress".to_string(), Value::Str("open".into()));
m.insert("pending".to_string(), Value::Str("open".into()));
m.insert("open".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("canceled-post-only".to_string(), Value::Str("canceled".into()));
m.insert("canceled-reduce-only".to_string(), Value::Str("canceled".into()));
m.insert("canceled-position-not-allowed".to_string(), Value::Str("rejected".into()));
m.insert("canceled-margin-not-allowed".to_string(), Value::Str("rejected".into()));
m.insert("canceled-too-much-slippage".to_string(), Value::Str("canceled".into()));
m.insert("canceled-not-enough-liquidity".to_string(), Value::Str("canceled".into()));
m.insert("canceled-self-trade".to_string(), Value::Str("canceled".into()));
m.insert("canceled-expired".to_string(), Value::Str("expired".into()));
m.insert("canceled-oco".to_string(), Value::Str("canceled".into()));
m.insert("canceled-child".to_string(), Value::Str("canceled".into()));
m.insert("canceled-liquidation".to_string(), Value::Str("canceled".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Str("limit".into()));
m.insert("market".to_string(), Value::Str("market".into()));
m.insert("stop-loss".to_string(), Value::Str("market".into()));
m.insert("stop-loss-limit".to_string(), Value::Str("limit".into()));
m.insert("take-profit".to_string(), Value::Str("market".into()));
m.insert("take-profit-limit".to_string(), Value::Str("limit".into()));
m.insert("twap".to_string(), Value::Str("twap".into()));
m.insert("twap-sub".to_string(), Value::Str("twap".into()));
m.insert("liquidation".to_string(), Value::Str("market".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order_type_integer(&self, mut typeInteger: Value) -> Option<String> {
if (typeInteger == Value::Null) {
return None;
}
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("limit".into()));
m.insert("1".to_string(), Value::Str("market".into()));
m.insert("2".to_string(), Value::Str("stop-loss".into()));
m.insert("3".to_string(), Value::Str("stop-loss-limit".into()));
m.insert("4".to_string(), Value::Str("take-profit".into()));
m.insert("5".to_string(), Value::Str("take-profit-limit".into()));
m.insert("6".to_string(), Value::Str("twap".into()));
m.insert("7".to_string(), Value::Str("twap-sub".into()));
m.insert("8".to_string(), Value::Str("liquidation".into()));
m
});
return self.safe_string(types, to_string_val(&typeInteger), &[]).as_str().map(str::to_owned);
}
pub fn parse_order_time_in_force(&self, mut tif: Value) -> Option<String> {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("immediate-or-cancel".to_string(), Value::Str("IOC".into()));
m.insert("good-till-time".to_string(), Value::Str("GTC".into()));
m.insert("post-only".to_string(), Value::Str("PO".into()));
m.insert("Unknown".to_string(), Value::Null);
m
});
return self.safe_string(timeInForces, tif.clone(), &[tif.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order_time_in_force_integer(&self, mut tifInteger: Value) -> Value {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("immediate-or-cancel".into()));
m.insert("1".to_string(), Value::Str("good-till-time".into()));
m.insert("2".to_string(), Value::Str("post-only".into()));
m
});
return self.safe_string(timeInForces, to_string_val(&tifInteger), &[]);
Value::Null
}
/*
* @method
* @name lighter#transfer
* @description transfer currency internally between wallets on the same account
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount account to transfer from (spot, perp)
* @param {string} toAccount account to transfer to (spot, perp)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {string} [params.toAccountIndex] to account index, defaults to fromAccountIndex
* @param {string} [params.apiKeyIndex] api key index
* @param {string} [params.memo] hex encoding memo
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: 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 apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("transfer".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, Value::Str("transfer".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut toAccountIndexparamsToAccountIndexVariable = self.handle_option_and_params2(paramsAccountIndex, Value::Str("transfer".into()), Value::Str("toAccountIndex".into()), Value::Str("to_account_index".into()), &[accountIndex.clone()]);
let mut toAccountIndex: Value = toAccountIndexparamsToAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsToAccountIndex: Value = toAccountIndexparamsToAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsToAccountIndex.clone()]).await;
let mut currency: Value = self.currency(code.clone());
let mut currencyCode: Value = currency.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null);
if (currencyCode.as_str() != Some("USDC")) && (currencyCode.as_str() != Some("ETH")) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" transfer() only supports USDC and ETH transfers".into()))));
}
let mut amountDecimals: Value = (if (currencyCode.as_str() == Some("USDC")) { Value::Str("6".into()) } else { Value::Str("8".into()) });
let mut amountScaled: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.pow(Value::Str("10".into()), amountDecimals), &self.currency_to_precision(code, amount, &[])));
let mut fromRouteType: Value = (if (fromAccount.as_str() == Some("perp")) { Value::Int(0) } else { Value::Int(1) }); // 0: perp, 1: spot
let mut toRouteType: Value = (if (toAccount.as_str() == Some("perp")) { Value::Int(0) } else { Value::Int(1) });
let mut memo: Value = self.safe_string_k(paramsToAccountIndex.clone(), "memo", &[Value::Str("0x000000000000000000000000000000".into())]);
let mut paramsOmitted: Value = self.omit(paramsToAccountIndex, Value::from(vec![Value::Str("memo".into())]), &[]);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsOmitted.clone()]).await;
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("to_account_index".to_string(), toAccountIndex);
m.insert("asset_index".to_string(), self.parse_to_int(currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("from_route_type".to_string(), fromRouteType);
m.insert("to_route_type".to_string(), toRouteType);
m.insert("amount".to_string(), amountScaled);
m.insert("usdc_fee".to_string(), Value::Int(0));
m.insert("memo".to_string(), memo);
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_17 = self.extend(signRaw, &[paramsOmitted]);
let mut txTypetxInfoVariable = self.lighter_sign_transfer(signer, __ws_arg_17);
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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[request]).await;
return self.parse_transfer(response, &[]);
Value::Null
}
/*
* @method
* @name lighter#fetchTransfers
* @description fetch a history of internal transfers made on an account
* @see https://apidocs.lighter.xyz/reference/transfer_history
* @param {string} code unified currency code of the currency transferred
* @param {int} [since] the earliest time in ms to fetch transfers for
* @param {int} [limit] the maximum number of transfers structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn fetch_transfers(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchTransfers".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchTransfers".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(50)]).await;
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsPaginate, Value::Str("fetchTransfers".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_index".to_string(), accountIndex.clone());
m
});
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchTransfers".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex);
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
}
let __ws_arg_18 = self.extend(request, &[paramsApiKeyIndex.clone()]);
let mut response: Value = self.private_get_transfer_history(&[__ws_arg_18]).await;
//
// {
// "code": 200,
// "transfers": [
// {
// "id": "3085014",
// "asset_id": 3,
// "amount": "11.000000",
// "fee": "0.000000",
// "timestamp": 1766387292752,
// "type": "L2TransferOutflow",
// "from_l1_address": "0x15f43D1f2DeE81424aFd891943262aa90F22cc2A",
// "to_l1_address": "0x15f43D1f2DeE81424aFd891943262aa90F22cc2A",
// "from_account_index": 1077,
// "to_account_index": 281474976710608,
// "from_route": "spot",
// "to_route": "spot",
// "tx_hash": "d8e96178273d0938f9ede556edffc0aab8def9ec70c46a65791905291a2f5792af18625406102c80"
// }
// ],
// "cursor": "eyJpbmRleCI6MzA4NDkxNX0="
// }
//
let mut rows: Value = self.safe_list_k(response.clone(), "transfers", &[Value::from(vec![])]);
let mut cursor: Value = self.safe_string_k(response, "cursor", &[]);
let mut first: Value = self.safe_dict(rows.clone(), Value::Int(0), &[]);
if (first != Value::Null) && (cursor != Value::Null) {
add_element_to_object(get_value_mut(&mut rows, &Value::Int(0)), &Value::Str("cursor".into()), cursor);
}
return self.parse_transfers(rows, &[currency, since, limit, paramsApiKeyIndex]);
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "id": "3085014",
// "asset_id": 3,
// "amount": "11.000000",
// "fee": "0.000000",
// "timestamp": 1766387292752,
// "type": "L2TransferOutflow",
// "from_l1_address": "0x15f43D1f2DeE81424aFd891943262aa90F22cc2A",
// "to_l1_address": "0x15f43D1f2DeE81424aFd891943262aa90F22cc2A",
// "from_account_index": 1077,
// "to_account_index": 281474976710608,
// "from_route": "spot",
// "to_route": "spot",
// "tx_hash": "d8e96178273d0938f9ede556edffc0aab8def9ec70c46a65791905291a2f5792af18625406102c80"
// }
//
let mut currencyId: Value = self.safe_string_k(transfer.clone(), "asset_id", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[currency]);
let mut timestamp: Value = self.safe_integer_k(transfer.clone(), "timestamp", &[]);
let mut fromAccount: Value = self.safe_dict_k(transfer.clone(), "from", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut toAccount: Value = self.safe_dict_k(transfer.clone(), "to", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(transfer.clone(), "id", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), self.safe_number_k(transfer.clone(), "amount", &[]));
m.insert("fromAccount".to_string(), self.safe_string_k(fromAccount, "from_account_index", &[]));
m.insert("toAccount".to_string(), self.safe_string_k(toAccount, "to_account_index", &[]));
m.insert("status".to_string(), Value::Null);
m.insert("info".to_string(), transfer);
m
});
Value::Null
}
/*
* @method
* @name lighter#fetchDeposits
* @description fetch all deposits made to an account
* @see https://apidocs.lighter.xyz/reference/deposit_history
* @param {string} [code] unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {string} [params.address] l1_address
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchDeposits".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchDeposits".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(50)]).await;
}
let mut addressparamsAddressVariable = self.handle_option_string_and_params2(paramsPaginate, Value::Str("fetchDeposits".into()), Value::Str("address".into()), Value::Str("l1_address".into()), &[]);
let mut address: Value = addressparamsAddressVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAddress: Value = addressparamsAddressVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (address == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchDeposits() requires an address parameter".into()))));
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsAddress, Value::Str("fetchDeposits".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_index".to_string(), accountIndex.clone());
m.insert("l1_address".to_string(), address);
m
});
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchDeposits".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex);
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("coin".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_19 = self.extend(request, &[paramsApiKeyIndex]);
let mut response: Value = self.private_get_deposit_history(&[__ws_arg_19]).await;
//
// {
// "code": 200,
// "deposits": [
// {
// "id": "2901843",
// "asset_id": 5,
// "amount": "100000.0",
// "timestamp": 1766112729741,
// "status": "completed",
// "l1_tx_hash": "0xa24d83d58e1fd72b2a44a12d1ec766fb061fa0b806de2fed940b5d8ecd50744d"
// }
// ],
// "cursor": "eyJpbmRleCI6MjkwMTg0MH0="
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "deposits", &[Value::from(vec![])]);
let mut cursor: Value = self.safe_string_k(response, "cursor", &[]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
if (first != Value::Null) && (cursor != Value::Null) {
add_element_to_object(get_value_mut(&mut data, &Value::Int(0)), &Value::Str("cursor".into()), cursor);
}
return self.parse_transactions(data, &[currency, since, limit]);
Value::Null
}
/*
* @method
* @name lighter#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://apidocs.lighter.xyz/reference/withdraw_history
* @param {string} [code] unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchWithdrawals".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchWithdrawals".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(50)]).await;
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsPaginate, Value::Str("fetchWithdrawals".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_index".to_string(), accountIndex.clone());
m
});
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchWithdrawals".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex);
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("coin".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_20 = self.extend(request, &[paramsApiKeyIndex]);
let mut response: Value = self.private_get_withdraw_history(&[__ws_arg_20]).await;
//
// {
// "code": "200",
// "message": "string",
// "withdraws": [
// {
// "id": "string",
// "amount": "0.1",
// "timestamp": "1640995200",
// "status": "failed",
// "type": "secure",
// "l1_tx_hash": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8"
// }
// ],
// "cursor": "string"
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "withdraws", &[Value::from(vec![])]);
let mut cursor: Value = self.safe_string_k(response, "cursor", &[]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
if (first != Value::Null) && (cursor != Value::Null) {
add_element_to_object(get_value_mut(&mut data, &Value::Int(0)), &Value::Str("cursor".into()), cursor);
}
return self.parse_transactions(data, &[currency, since, limit]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// fetchDeposits
// {
// "id": "2901843",
// "asset_id": 5,
// "amount": "100000.0",
// "timestamp": 1766112729741,
// "status": "completed",
// "l1_tx_hash": "0xa24d83d58e1fd72b2a44a12d1ec766fb061fa0b806de2fed940b5d8ecd50744d",
// }
//
// fetchWithdrawals
// {
// "id": "string",
// "amount": "0.1",
// "timestamp": "1640995200",
// "status": "failed",
// "type": "secure",
// "l1_tx_hash": "0x70997970C51812dc3A010C7d01b50e0d17dc79C8"
// }
//
let mut type_var: Value = self.safe_string_k(transaction.clone(), "type", &[]);
if (type_var == Value::Null) {
type_var = Value::Str("deposit".into());
} else {
type_var = Value::Str("withdrawal".into());
}
let mut timestamp: Value = self.safe_integer_k(transaction.clone(), "timestamp", &[]);
let mut status: Value = self.safe_string_k(transaction.clone(), "status", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), self.safe_string_k(transaction.clone(), "id", &[]));
m.insert("txid".to_string(), self.safe_string_k(transaction.clone(), "l1_tx_hash", &[]));
m.insert("type".to_string(), type_var);
m.insert("currency".to_string(), self.safe_currency_code(self.safe_string_k(transaction.clone(), "asset_id", &[]), &[currency]));
m.insert("network".to_string(), Value::Null);
m.insert("amount".to_string(), self.safe_number_k(transaction, "amount", &[]));
m.insert("status".to_string(), self.parse_transaction_status(status));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("address".to_string(), Value::Null);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("addressTo".to_string(), Value::Null);
m.insert("tag".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("internal".to_string(), Value::Null);
m
});
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("failed".to_string(), Value::Str("failed".into()));
m.insert("pending".to_string(), Value::Str("pending".into()));
m.insert("completed".to_string(), Value::Str("ok".into()));
m.insert("claimable".to_string(), Value::Str("ok".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
/*
* @method
* @name lighter#withdraw
* @description make a withdrawal
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.tag] memo / destination tag, required for currencies in options['withdrawTagRequiredCurrencies']
* @param {string} [params.accountIndex] account index
* @param {string} [params.apiKeyIndex] api key index
* @param {int} [params.routeType] wallet type, 0: perp, 1: spot, default is 0
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("withdraw".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, Value::Str("withdraw".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut currency: Value = self.currency(code.clone());
let mut currencyCode: Value = currency.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null);
if (currencyCode.as_str() != Some("USDC")) && (currencyCode.as_str() != Some("ETH")) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" withdraw() only supports USDC and ETH transfers".into()))));
}
let mut amountDecimals: Value = (if (currencyCode.as_str() == Some("USDC")) { Value::Str("6".into()) } else { Value::Str("8".into()) });
let mut amountScaled: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.pow(Value::Str("10".into()), amountDecimals), &self.currency_to_precision(code, amount, &[])));
let mut routeType: Value = self.safe_integer_k(paramsAccountIndex.clone(), "routeType", &[Value::Int(0)]); // 0: perp, 1: spot
let mut paramsOmitted: Value = self.omit(paramsAccountIndex, Value::Str("routeType".into()), &[]);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsOmitted.clone()]).await;
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset_index".to_string(), self.parse_to_int(currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("route_type".to_string(), routeType);
m.insert("amount".to_string(), amountScaled);
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_21 = self.extend(signRaw, &[paramsOmitted]);
let mut txTypetxInfoVariable = self.lighter_sign_withdraw(signer, __ws_arg_21);
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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[request]).await;
return self.parse_transaction(response, &[]);
Value::Null
}
/*
* @method
* @name lighter#fetchMyTrades
* @description fetch all trades made by the user
* @see https://apidocs.lighter.xyz/reference/trades
* @param {string} [symbol] unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @param {int} [params.until] timestamp in ms of the latest trade to fetch
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchMyTrades".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchMyTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("next_cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(50)]).await;
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsPaginate, Value::Str("fetchMyTrades".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchMyTrades".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sort_by".to_string(), Value::Str("timestamp".into()));
m.insert("limit".to_string(), Value::Int(100));
m.insert("account_index".to_string(), accountIndex.clone());
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(100))); }
}
let mut untilparamsUntilVariable = self.handle_option_integer_and_params2(paramsApiKeyIndex, Value::Str("fetchMyTrades".into()), Value::Str("until".into()), Value::Str("from".into()), &[]);
let mut until: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("from".into(), until); }
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("market_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_22 = self.extend(request, &[paramsUntil.clone()]);
let mut response: Value = self.private_get_trades(&[__ws_arg_22]).await;
//
// {
// "code": 200,
// "trades": [
// {
// "trade_id": 17609,
// "tx_hash": "99ffeaa3899fbaa51043840ddf762fd18c182a33b5125092105bee57af11fab04edf5fd90e969abd",
// "type": "trade",
// "market_id": 0,
// "size": "10.2304",
// "price": "2958.75",
// "usd_amount": "30269.196000",
// "ask_id": 281474977339869,
// "bid_id": 562949952870533,
// "ask_client_id": 0,
// "bid_client_id": 0,
// "ask_account_id": 20,
// "bid_account_id": 1077,
// "is_maker_ask": true,
// "block_height": 102070,
// "timestamp": 1766386112741,
// "taker_position_size_before": "0.0000",
// "taker_entry_quote_before": "0.000000",
// "taker_position_sign_changed": true,
// "maker_position_size_before": "-1856.8547",
// "maker_entry_quote_before": "5491685.069325",
// "maker_initial_margin_fraction_before": 500
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "trades", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_933: bool = true;
while { if !__for_first_933 { 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_933 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
add_element_to_object(get_value_mut(&mut data, &i), &Value::Str("account_index".into()), accountIndex.clone());
}
}
let mut nextCursor: Value = self.safe_string_k(response, "next_cursor", &[]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
if (first != Value::Null) && (nextCursor != Value::Null) {
add_element_to_object(get_value_mut(&mut data, &Value::Int(0)), &Value::Str("next_cursor".into()), nextCursor);
}
return self.parse_trades(data, &[market, since, limit, paramsUntil]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "trade_id": 17609,
// "tx_hash": "99ffeaa3899fbaa51043840ddf762fd18c182a33b5125092105bee57af11fab04edf5fd90e969abd",
// "type": "trade",
// "market_id": 0,
// "size": "10.2304",
// "price": "2958.75",
// "usd_amount": "30269.196000",
// "ask_id": 281474977339869,
// "bid_id": 562949952870533,
// "ask_client_id": 0,
// "bid_client_id": 0,
// "ask_account_id": 20,
// "bid_account_id": 1077,
// "is_maker_ask": true,
// "block_height": 102070,
// "timestamp": 1766386112741,
// "taker_position_size_before": "0.0000",
// "taker_entry_quote_before": "0.000000",
// "taker_position_sign_changed": true,
// "maker_position_size_before": "-1856.8547",
// "maker_entry_quote_before": "5491685.069325",
// "maker_initial_margin_fraction_before": 500
// }
//
let mut marketId: Value = self.safe_string_k(trade.clone(), "market_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "timestamp", &[]);
let mut accountIndex: Value = self.safe_string_k(trade.clone(), "account_index", &[]);
let mut askAccountId: Value = self.safe_string_k(trade.clone(), "ask_account_id", &[]);
let mut bidAccountId: Value = self.safe_string_k(trade.clone(), "bid_account_id", &[]);
let mut isMakerAsk: Value = self.safe_bool_k(trade.clone(), "is_maker_ask", &[]);
let mut side: Value = Value::Null;
let mut orderId: Value = Value::Null;
if (accountIndex != Value::Null) {
if (accountIndex.as_str() == askAccountId.as_str()) {
side = Value::Str("sell".into());
orderId = self.safe_string_k(trade.clone(), "ask_id", &[]);
} else if (accountIndex.as_str() == bidAccountId.as_str()) {
side = Value::Str("buy".into());
orderId = self.safe_string_k(trade.clone(), "bid_id", &[]);
}
}
let mut takerOrMaker: Value = Value::Null;
if (side != Value::Null) && (isMakerAsk != Value::Null) {
let mut isMaker: Value = (if (side.as_str() == Some("sell")) { isMakerAsk.clone() } else { Value::Bool(!(isMakerAsk.as_bool() == Some(true))) });
takerOrMaker = (if is_true(&isMaker) { Value::Str("maker".into()) } else { Value::Str("taker".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(), self.safe_string_k(trade.clone(), "trade_id", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("order".to_string(), orderId);
m.insert("type".to_string(), self.safe_string_k(trade.clone(), "type", &[]));
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), self.safe_string_k(trade.clone(), "price", &[]));
m.insert("amount".to_string(), self.safe_string_k(trade.clone(), "size", &[]));
m.insert("cost".to_string(), self.safe_string_k(trade, "usd_amount", &[]));
m.insert("fee".to_string(), Value::Null);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name lighter#setLeverage
* @description set the level of leverage for a market
* @param {float} leverage the rate of leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {string} [params.apiKeyIndex] api key index
* @param {string} [params.marginMode] margin mode, 'cross' or 'isolated'
* @returns {object} response from the exchange
*/
pub async fn set_leverage(&mut self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a symbol argument".into()))));
}
let mut marginModeparamsMarginModeVariable = self.handle_option_string_and_params2(params, Value::Str("setLeverage".into()), Value::Str("marginMode".into()), Value::Str("margin_mode".into()), &[]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marginMode == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires an marginMode parameter".into()))));
}
return self.modify_leverage_and_margin_mode(leverage, marginMode, &[symbol, paramsMarginMode]).await;
Value::Null
}
/*
* @method
* @name lighter#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {string} [params.apiKeyIndex] api key index
* @param {int} [params.leverage] required leverage
* @returns {object} response from the exchange
*/
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (marginMode == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires an marginMode parameter".into()))));
}
let mut leverageparamsLeverageVariable = self.handle_option_and_params(params, Value::Str("setMarginMode".into()), Value::Str("leverage".into()), &[]);
let mut leverage: Value = leverageparamsLeverageVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsLeverage: Value = leverageparamsLeverageVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (leverage == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires an leverage parameter".into()))));
}
return self.modify_leverage_and_margin_mode(leverage, marginMode, &[symbol, paramsLeverage]).await;
Value::Null
}
pub async fn modify_leverage_and_margin_mode(&mut self, mut leverage: Value, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (marginMode.as_str() != Some("cross")) && (marginMode.as_str() != Some("isolated")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" modifyLeverageAndMarginMode() requires a marginMode parameter that must be either cross or isolated".into()))));
}
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("modifyLeverageAndMarginMode".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" modifyLeverageAndMarginMode() requires a symbol argument".into()))));
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, Value::Str("modifyLeverageAndMarginMode".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut market: Value = self.market(symbol);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("initial_margin_fraction".to_string(), self.parse_to_int((match ((Value::Int(10000)).as_f64(), (leverage).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })));
m.insert("margin_mode".to_string(), (if (marginMode.as_str() == Some("cross")) { Value::Int(0) } else { Value::Int(1) }));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_23 = self.extend(signRaw, &[paramsAccountIndex]);
let mut txTypetxInfoVariable = self.lighter_sign_update_leverage(signer, __ws_arg_23);
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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
return self.public_post_send_tx(&[request]).await;
Value::Null
}
pub async fn sign_and_cancel_order(&mut self, mut method: Value, 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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), method).into()), Value::Str(" requires a symbol argument".into()))));
}
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, method.clone(), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, method.clone(), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol);
let mut clientOrderId: Value = self.safe_string2(paramsAccountIndex.clone(), Value::Str("client_order_index".into()), Value::Str("clientOrderId".into()), &[]);
let mut paramsOmitted: Value = self.omit(paramsAccountIndex, Value::from(vec![Value::Str("client_order_index".into()), Value::Str("clientOrderId".into())]), &[]);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsOmitted.clone()]).await;
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsOmitted.clone()]).await;
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut signRaw { std::sync::Arc::make_mut(__d).insert("order_index".into(), self.parse_to_int(clientOrderId)); }
} else if (id != Value::Null) {
if let Value::Dict(__d) = &mut signRaw { std::sync::Arc::make_mut(__d).insert("order_index".into(), self.parse_to_int(id.clone())); }
} else {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), method).into()), Value::Str(" requires order id or client order id".into()))));
}
let __ws_arg_24 = self.extend(signRaw, &[paramsOmitted]);
let mut txTypetxInfoVariable = self.lighter_sign_cancel_order(signer, __ws_arg_24);
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);
return Value::from(vec![txType, txInfo]);
Value::Null
}
/*
* @method
* @name lighter#cancelOrder
* @description cancels an open order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made 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} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut txTypetxInfoVariable = self.sign_and_cancel_order(Value::Str("cancelOrder".into()), id, &[symbol.clone(), 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 market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[request]).await;
return self.parse_order(response, &[market]);
Value::Null
}
pub async fn sign_and_cancel_all_orders(&mut self, mut method: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, method.clone(), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, method, Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("time_in_force".to_string(), Value::Int(0));
m.insert("time".to_string(), Value::Int(0));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
if (symbol != Value::Null) {
let mut market: Value = self.market(symbol);
if let Value::Dict(__d) = &mut signRaw { std::sync::Arc::make_mut(__d).insert("cancel_all_market_index".into(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null))); }
}
let __ws_arg_25 = self.extend(signRaw, &[paramsAccountIndex]);
let mut txTypetxInfoVariable = self.lighter_sign_cancel_all_orders(signer, __ws_arg_25);
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);
return Value::from(vec![txType, txInfo]);
Value::Null
}
/*
* @method
* @name lighter#cancelAllOrders
* @description cancel all open orders
* @param {string} [symbol] unified market symbol, only orders in the market of this symbol are cancelled when symbol is not 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[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut txTypetxInfoVariable = self.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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[request]).await;
return self.parse_orders(Value::from(vec![response]), &[]);
Value::Null
}
/*
* @method
* @name lighter#cancelAllOrdersAfter
* @description dead man's switch, cancel all orders after the given timeout
* @param {number} timeout time in milliseconds, 0 represents cancel the timer
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the api result
*/
pub async fn cancel_all_orders_after(&mut self, mut timeout: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (timeout == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrdersAfter() requires a timeout argument".into()))));
}
let mut isScheduled: bool = timeout.as_f64() != Some(0.0);
if isScheduled && ((timeout.as_f64().unwrap_or(f64::NAN) < ((300000i64) as f64)) || (timeout.as_f64().unwrap_or(f64::NAN) > ((1296000000i64) as f64))) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" timeout should be between 5 minutes and 15 days, or 0 to cancel the timer.".into()))));
}
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("cancelOrder".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, Value::Str("cancelAllOrdersAfter".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut timeInForce: Value = Value::Int(2); // 0: IMMEDIATE 1: SCHEDULED 2: ABORT
let mut cancelTime: Value = Value::Int(0);
if isScheduled {
timeInForce = Value::Int(1);
cancelTime = self.sum(&[self.milliseconds(), timeout]);
}
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("time_in_force".to_string(), timeInForce);
m.insert("time".to_string(), cancelTime);
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_26 = self.extend(signRaw, &[paramsAccountIndex]);
let mut txTypetxInfoVariable = self.lighter_sign_cancel_all_orders(signer, __ws_arg_26);
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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[request]).await;
return response;
Value::Null
}
/*
* @method
* @name lighter#addMargin
* @description add margin
* @param {string} symbol unified market symbol
* @param {float} amount amount of margin to add
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=add-margin-structure}
*/
pub async fn add_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("direction".to_string(), Value::Int(1));
m
});
let __ws_arg_27 = self.extend(request, &[params]);
return self.set_margin(symbol, amount, &[__ws_arg_27]).await;
Value::Null
}
/*
* @method
* @name lighter#reduceMargin
* @description remove margin from a position
* @param {string} symbol unified market symbol
* @param {float} amount the amount of margin to remove
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=reduce-margin-structure}
*/
pub async fn reduce_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("direction".to_string(), Value::Int(0));
m
});
let __ws_arg_28 = self.extend(request, &[params]);
return self.set_margin(symbol, amount, &[__ws_arg_28]).await;
Value::Null
}
/*
* @method
* @name lighter#setMargin
* @description Either adds or reduces margin in an isolated position in order to set the margin to a specific value
* @param {string} symbol unified market symbol of the market to set margin in
* @param {float} amount the amount to set the margin to
* @param {object} [params] parameters specific to the exchange API endpoint
* @param {string} [params.accountIndex] account index
* @param {string} [params.apiKeyIndex] api key index
* @returns {object} A [margin structure]{@link https://docs.ccxt.com/?id=add-margin-structure}
*/
pub async fn set_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut apiKeyIndexparamsApiKeyIndexVariable = self.handle_api_key_index(params, Value::Str("setMargin".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut direction: Value = self.safe_integer_k(paramsApiKeyIndex.clone(), "direction", &[]); // 1 increase margin 0 decrease margin
if (direction == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMargin() requires a direction parameter either 1 (increase margin) or 0 (decrease margin)".into()))));
}
if !(self.in_array(direction.clone(), Value::from(vec![Value::Int(0), Value::Int(1)])).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMargin() requires a direction parameter either 1 (increase margin) or 0 (decrease margin)".into()))));
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMargin() requires a symbol argument".into()))));
}
let mut accountIndexparamsAccountIndexVariable = self.handle_account_index(paramsApiKeyIndex, Value::Str("setMargin".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.options.as_map().and_then(|__m| __m.get("chainId")).cloned().unwrap_or(Value::Null), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut market: Value = self.market(symbol);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut signRaw: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("usdc_amount".to_string(), self.parse_to_int(crate::precise::Precise::stringMul(&self.pow(Value::Str("10".into()), Value::Str("6".into())), &self.currency_to_precision(Value::Str("USDC".into()), amount, &[]))));
m.insert("direction".to_string(), direction);
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_29 = self.extend(signRaw, &[paramsAccountIndex]);
let mut txTypetxInfoVariable = self.lighter_sign_update_margin(signer, __ws_arg_29);
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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[request]).await;
return self.parse_margin_modification(response, &[market]);
Value::Null
}
pub fn parse_margin_modification(&self, mut data: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Value = self.safe_integer_k(data.clone(), "predicted_execution_time_ms", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data);
m.insert("symbol".to_string(), self.safe_string_k(market, "symbol", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Null);
m.insert("amount".to_string(), Value::Null);
m.insert("total".to_string(), Value::Null);
m.insert("code".to_string(), Value::Str("USDC".into()));
m.insert("status".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
});
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("public".into())]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiName: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut url: Value = Value::Null;
if (apiName.as_str() == Some("root")) {
let mut baseApiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("public".into()), &[]);
if (baseApiUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
url = self.implode_hostname(baseApiUrl);
} else {
let mut baseApiUrl2: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), apiName.clone(), &[]);
if (baseApiUrl2 == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
url = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.implode_hostname(baseApiUrl2), Value::Str("/api/".into())).into()), self.version.clone()).into()), Value::Str("/".into())).into()), path).into());
}
let mut authHeaders: Value = Value::Null;
if (apiName.as_str() == Some("private")) {
authHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Authorization".to_string(), self.create_auth(&[params.clone()]).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
}
if ((object_keys(¶ms).len() as i64) as f64) > ((0i64) as f64) {
if (method.as_str() == Some("POST")) {
let mut multipartHeaders: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("multipart/form-data".into()));
m
});
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), params.clone());
m.insert("headers".to_string(), multipartHeaders);
m
});
}
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.rawencode(params.clone(), &[])).into())).into());
}
if (apiName.as_str() == Some("private")) {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), Value::Null);
m.insert("headers".to_string(), authHeaders);
m
});
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), Value::Null);
m.insert("headers".to_string(), Value::Null);
m
});
Value::Null
}
pub fn handle_errors(&self, mut httpCode: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) || (response == Value::Null) {
return Value::Null;
}
//
// {
// "code": "200",
// "message": "string"
// }
//
let mut code: Value = self.safe_string_k(response.clone(), "code", &[]);
let mut message: Value = self.safe_string_k(response, "msg", &[]);
if (code != Value::Null) && (code.as_str() != Some("0")) && (code.as_str() != Some("200")) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message, feedback.clone());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), code, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
}