Skip to main content

ccxt_common/
types.rs

1// Native Rust – hand-written domain types.
2//
3// These mirror the unified structures in wiki/Manual.md.
4// Exchange code accesses fields via `Value` maps at runtime; these structs
5// are used for the typed wrapper layer (analogous to Go's typed wrappers).
6
7use indexmap::IndexMap as HashMap;
8use crate::Value;
9
10/// A `{ min, max }` bound from a market's `limits` block. Either side may be
11/// absent when the venue does not declare it.
12#[derive(Debug, Clone, Copy, Default, PartialEq)]
13pub struct MinMax {
14    pub min: Option<f64>,
15    pub max: Option<f64>,
16}
17
18impl MinMax {
19    fn from_value(v: &Value) -> Self {
20        use crate::value::safe_number;
21        MinMax { min: safe_number(v, "min", None), max: safe_number(v, "max", None) }
22    }
23    /// `true` when `amount` is within the bound (an absent side never fails).
24    pub fn contains(&self, amount: f64) -> bool {
25        self.min.map_or(true, |m| amount >= m) && self.max.map_or(true, |m| amount <= m)
26    }
27}
28
29/// A market's declared order limits. Check these before sending an order —
30/// it costs no request and no rate-limit weight.
31#[derive(Debug, Clone, Copy, Default, PartialEq)]
32pub struct MarketLimits {
33    pub amount:   MinMax,
34    pub price:    MinMax,
35    pub cost:     MinMax,
36    pub leverage: MinMax,
37}
38
39/// A market's tick/step sizes.
40#[derive(Debug, Clone, Copy, Default, PartialEq)]
41pub struct MarketPrecision {
42    pub amount: Option<f64>,
43    pub price:  Option<f64>,
44    pub cost:   Option<f64>,
45    pub base:   Option<f64>,
46    pub quote:  Option<f64>,
47}
48
49/// A unified market / symbol descriptor.
50#[derive(Debug, Clone, Default)]
51pub struct Market {
52    pub id:       String,
53    pub symbol:   String,
54    pub base:     String,
55    pub quote:    String,
56    pub settle:   Option<String>,
57    pub base_id:  String,
58    pub quote_id: String,
59    pub market_type: String,   // "spot" | "swap" | "future" | "option"
60    pub spot:     bool,
61    pub margin:   bool,
62    pub swap:     bool,
63    pub future:   bool,
64    pub option:   bool,
65    pub active:   bool,
66    pub contract: bool,
67    pub linear:   Option<bool>,
68    pub inverse:  Option<bool>,
69    pub taker:    Option<f64>,
70    pub maker:    Option<f64>,
71    /// Declared order bounds — amount / price / cost / leverage.
72    pub limits:   MarketLimits,
73    /// Declared tick and step sizes.
74    pub precision: MarketPrecision,
75    pub raw:      Value,
76}
77
78impl Market {
79    pub fn from_value(v: Value) -> Self {
80        use crate::value::{safe_string, safe_bool, safe_number};
81        let mut m = Market::default();
82        m.id      = safe_string(&v, "id",     None).unwrap_or_default();
83        m.symbol  = safe_string(&v, "symbol", None).unwrap_or_default();
84        m.base    = safe_string(&v, "base",   None).unwrap_or_default();
85        m.quote   = safe_string(&v, "quote",  None).unwrap_or_default();
86        m.settle  = safe_string(&v, "settle",  None);
87        m.base_id  = safe_string(&v, "baseId",  None).unwrap_or_default();
88        m.quote_id = safe_string(&v, "quoteId", None).unwrap_or_default();
89        m.market_type = safe_string(&v, "type", None).unwrap_or_else(|| "spot".to_owned());
90        m.spot    = safe_bool(&v, "spot",   Some(false)).unwrap_or(false);
91        m.margin  = safe_bool(&v, "margin", Some(false)).unwrap_or(false);
92        m.swap    = safe_bool(&v, "swap",   Some(false)).unwrap_or(false);
93        m.future  = safe_bool(&v, "future", Some(false)).unwrap_or(false);
94        m.option  = safe_bool(&v, "option", Some(false)).unwrap_or(false);
95        m.contract = safe_bool(&v, "contract", Some(false)).unwrap_or(false);
96        m.linear  = safe_bool(&v, "linear",  None);
97        m.inverse = safe_bool(&v, "inverse", None);
98        m.active  = safe_bool(&v, "active", Some(true)).unwrap_or(true);
99        m.taker   = safe_number(&v, "taker", None);
100        m.maker   = safe_number(&v, "maker", None);
101        let sub = |parent: &Value, key: &str| crate::value::get_value(parent, &Value::Str(key.to_string().into()));
102        let limits = sub(&v, "limits");
103        m.limits = MarketLimits {
104            amount:   MinMax::from_value(&sub(&limits, "amount")),
105            price:    MinMax::from_value(&sub(&limits, "price")),
106            cost:     MinMax::from_value(&sub(&limits, "cost")),
107            leverage: MinMax::from_value(&sub(&limits, "leverage")),
108        };
109        let precision = sub(&v, "precision");
110        m.precision = MarketPrecision {
111            amount: safe_number(&precision, "amount", None),
112            price:  safe_number(&precision, "price",  None),
113            cost:   safe_number(&precision, "cost",   None),
114            base:   safe_number(&precision, "base",   None),
115            quote:  safe_number(&precision, "quote",  None),
116        };
117        m.raw     = v;
118        m
119    }
120}
121
122/// A unified ticker. Mirrors the TS `Ticker` interface (`ts/src/base/types.ts`).
123#[derive(Debug, Clone, Default)]
124pub struct Ticker {
125    pub symbol:         String,
126    pub timestamp:      Option<i64>,
127    pub datetime:       Option<String>,
128    pub high:           Option<f64>,
129    pub low:            Option<f64>,
130    pub bid:            Option<f64>,
131    pub bid_volume:     Option<f64>,
132    pub ask:            Option<f64>,
133    pub ask_volume:     Option<f64>,
134    pub vwap:           Option<f64>,
135    pub open:           Option<f64>,
136    pub close:          Option<f64>,
137    pub last:           Option<f64>,
138    pub previous_close: Option<f64>,
139    pub change:         Option<f64>,
140    pub percentage:     Option<f64>,
141    pub average:        Option<f64>,
142    pub base_volume:    Option<f64>,
143    pub quote_volume:   Option<f64>,
144    pub index_price:    Option<f64>,
145    pub mark_price:     Option<f64>,
146    pub raw:            Value,
147}
148
149impl Ticker {
150    pub fn from_value(v: Value) -> Self {
151        use crate::value::{safe_string, safe_number, safe_integer};
152        let mut t = Ticker::default();
153        t.symbol         = safe_string(&v, "symbol",      None).unwrap_or_default();
154        t.timestamp      = safe_integer(&v, "timestamp",  None);
155        t.datetime       = safe_string(&v, "datetime",    None);
156        t.high           = safe_number(&v, "high",         None);
157        t.low            = safe_number(&v, "low",          None);
158        t.bid            = safe_number(&v, "bid",          None);
159        t.bid_volume     = safe_number(&v, "bidVolume",    None);
160        t.ask            = safe_number(&v, "ask",          None);
161        t.ask_volume     = safe_number(&v, "askVolume",    None);
162        t.vwap           = safe_number(&v, "vwap",         None);
163        t.open           = safe_number(&v, "open",         None);
164        t.close          = safe_number(&v, "close",        None);
165        t.last           = safe_number(&v, "last",         None);
166        t.previous_close = safe_number(&v, "previousClose", None);
167        t.change         = safe_number(&v, "change",       None);
168        t.percentage     = safe_number(&v, "percentage",   None);
169        t.average        = safe_number(&v, "average",      None);
170        t.base_volume    = safe_number(&v, "baseVolume",   None);
171        t.quote_volume   = safe_number(&v, "quoteVolume",  None);
172        t.index_price    = safe_number(&v, "indexPrice",   None);
173        t.mark_price     = safe_number(&v, "markPrice",    None);
174        t.raw = v;
175        t
176    }
177}
178
179/// A unified trade record. Mirrors the TS `Trade` interface.
180#[derive(Debug, Clone, Default)]
181pub struct Trade {
182    pub id:             Option<String>,
183    pub order:          Option<String>,
184    pub symbol:         String,
185    pub timestamp:      Option<i64>,
186    pub datetime:       Option<String>,
187    pub trade_type:     Option<String>,   // "limit" | "market"
188    pub side:           Option<String>,
189    pub taker_or_maker: Option<String>,   // "taker" | "maker"
190    pub price:          Option<f64>,
191    pub amount:         Option<f64>,
192    pub cost:           Option<f64>,
193    pub fee:            Option<Fee>,
194    pub raw:            Value,
195}
196
197impl Trade {
198    pub fn from_value(v: Value) -> Self {
199        use crate::value::{safe_string, safe_number, safe_integer};
200        let mut t = Trade::default();
201        t.id             = safe_string(&v, "id",        None);
202        t.order          = safe_string(&v, "order",     None);
203        t.symbol         = safe_string(&v, "symbol",    None).unwrap_or_default();
204        t.timestamp      = safe_integer(&v, "timestamp", None);
205        t.datetime       = safe_string(&v, "datetime",  None);
206        t.trade_type     = safe_string(&v, "type",      None);
207        t.side           = safe_string(&v, "side",      None);
208        t.taker_or_maker = safe_string(&v, "takerOrMaker", None);
209        t.price          = safe_number(&v, "price",     None);
210        t.amount         = safe_number(&v, "amount",    None);
211        t.cost           = safe_number(&v, "cost",      None);
212        t.fee            = match crate::get_value(&v, &Value::Str("fee".into())) {
213            fee @ Value::Dict(_) => Some(Fee::from_value(fee)),
214            _ => None,
215        };
216        t.raw = v;
217        t
218    }
219}
220
221/// A unified order. Mirrors the TS `Order` interface.
222#[derive(Debug, Clone, Default)]
223pub struct Order {
224    pub id:        Option<String>,
225    pub client_order_id: Option<String>,
226    pub symbol:    String,
227    pub timestamp: Option<i64>,
228    pub datetime:  Option<String>,
229    pub last_trade_timestamp:  Option<i64>,
230    pub last_update_timestamp: Option<i64>,
231    pub status:    Option<String>,   // "open" | "closed" | "canceled" | "expired"
232    pub order_type:Option<String>,   // "limit" | "market"
233    pub time_in_force: Option<String>, // "GTC" | "IOC" | "FOK" | "PO"
234    pub side:      Option<String>,   // "buy" | "sell"
235    pub price:     Option<f64>,
236    pub average:   Option<f64>,
237    pub amount:    Option<f64>,
238    pub filled:    Option<f64>,
239    pub remaining: Option<f64>,
240    pub cost:      Option<f64>,
241    pub trigger_price:     Option<f64>,
242    pub stop_price:        Option<f64>,   // deprecated alias of `trigger_price`
243    pub take_profit_price: Option<f64>,
244    pub stop_loss_price:   Option<f64>,
245    pub post_only:   Option<bool>,
246    pub reduce_only: Option<bool>,
247    pub trades:    Vec<Trade>,
248    pub fee:       Option<HashMap<String, Value>>,
249    pub raw:       Value,
250}
251
252impl Order {
253    pub fn from_value(v: Value) -> Self {
254        use crate::value::{safe_string, safe_number, safe_integer, safe_bool};
255        let mut o = Order::default();
256        o.id              = safe_string(&v, "id",            None);
257        o.client_order_id = safe_string(&v, "clientOrderId", None);
258        o.symbol          = safe_string(&v, "symbol",        None).unwrap_or_default();
259        o.timestamp       = safe_integer(&v, "timestamp",    None);
260        o.datetime        = safe_string(&v, "datetime",      None);
261        o.last_trade_timestamp  = safe_integer(&v, "lastTradeTimestamp",  None);
262        o.last_update_timestamp = safe_integer(&v, "lastUpdateTimestamp", None);
263        o.status          = safe_string(&v, "status",        None);
264        o.order_type      = safe_string(&v, "type",          None);
265        o.time_in_force   = safe_string(&v, "timeInForce",   None);
266        o.side            = safe_string(&v, "side",          None);
267        o.price           = safe_number(&v, "price",         None);
268        o.average         = safe_number(&v, "average",       None);
269        o.amount          = safe_number(&v, "amount",        None);
270        o.filled          = safe_number(&v, "filled",        None);
271        o.remaining       = safe_number(&v, "remaining",     None);
272        o.cost            = safe_number(&v, "cost",          None);
273        o.trigger_price     = safe_number(&v, "triggerPrice",    None);
274        o.stop_price        = safe_number(&v, "stopPrice",       None);
275        o.take_profit_price = safe_number(&v, "takeProfitPrice", None);
276        o.stop_loss_price   = safe_number(&v, "stopLossPrice",   None);
277        o.post_only       = safe_bool(&v, "postOnly",   None);
278        o.reduce_only     = safe_bool(&v, "reduceOnly", None);
279        o.trades          = vec_from_value(&crate::get_value(&v, &Value::Str("trades".into())), Trade::from_value);
280        o.fee             = match crate::get_value(&v, &Value::Str("fee".into())) {
281            Value::Dict(m) => Some((*m).clone()),
282            _ => None,
283        };
284        o.raw = v;
285        o
286    }
287}
288
289/// A unified order-book snapshot.
290#[derive(Debug, Clone, Default)]
291pub struct OrderBook {
292    pub symbol:    Option<String>,
293    pub timestamp: Option<i64>,
294    pub datetime:  Option<String>,
295    pub bids:      Vec<[f64; 2]>,
296    pub asks:      Vec<[f64; 2]>,
297    pub nonce:     Option<i64>,
298    pub raw:       Value,
299}
300
301impl OrderBook {
302    pub fn from_value(v: Value) -> Self {
303        use crate::value::{safe_string, safe_integer, get_value};
304        let mut ob = OrderBook::default();
305        ob.symbol    = safe_string(&v, "symbol",    None);
306        ob.timestamp = safe_integer(&v, "timestamp", None);
307        ob.datetime  = safe_string(&v, "datetime",  None);
308        ob.nonce     = safe_integer(&v, "nonce",    None);
309        // `bids`/`asks` are arrays of `[price, amount]` pairs. Walk the
310        // outer `Value::Arr` and pull the first two numeric entries of each
311        // inner row. A row that isn't a 2+ element array of parseable numbers
312        // is DROPPED rather than emitted as `[NaN, NaN]` — a NaN level is not a
313        // valid book entry and would corrupt best-bid/ask and depth math
314        // downstream (review #7).
315        let extract_side = |key: &str| -> Vec<[f64; 2]> {
316            let side = get_value(&v, &Value::Str(key.to_string().into()));
317            // A resolved WS book keeps its sides as shared markers (entries in
318            // the side store), not inline arrays — read those levels straight
319            // from the store as `[price, amount]` pairs (no intermediate Value
320            // clone). Without this the match below misses and the typed book
321            // comes back empty. Falls through to plain-array parsing otherwise.
322            if let Some(pairs) = crate::value::side_price_amounts(&side) {
323                return pairs;
324            }
325            match side {
326                Value::Arr(rows) => rows.iter().filter_map(|row| {
327                    let num = |cell: Option<&Value>| -> f64 {
328                        match cell {
329                            Some(Value::Float(f)) => *f,
330                            Some(Value::Int(n))   => *n as f64,
331                            Some(Value::Str(s))   => s.parse().unwrap_or(f64::NAN),
332                            _ => f64::NAN,
333                        }
334                    };
335                    let (price, amt) = match row {
336                        Value::Arr(r) => (num(r.first()), num(r.get(1))),
337                        _ => (f64::NAN, f64::NAN),
338                    };
339                    if price.is_nan() || amt.is_nan() { None } else { Some([price, amt]) }
340                }).collect(),
341                _ => Vec::new(),
342            }
343        };
344        ob.bids = extract_side("bids");
345        ob.asks = extract_side("asks");
346        ob.raw  = v;
347        ob
348    }
349}
350
351/// One level-3 (per-order) book entry: `[price, amount, orderId]`.
352#[derive(Debug, Clone, Default)]
353pub struct OrderBookL3Entry {
354    pub price:    f64,
355    pub amount:   f64,
356    pub order_id: Option<String>,
357}
358
359/// A unified level-3 (per-order, non-aggregated) order-book snapshot.
360#[derive(Debug, Clone, Default)]
361pub struct OrderBookL3 {
362    pub symbol:    Option<String>,
363    pub timestamp: Option<i64>,
364    pub datetime:  Option<String>,
365    pub bids:      Vec<OrderBookL3Entry>,
366    pub asks:      Vec<OrderBookL3Entry>,
367    pub nonce:     Option<i64>,
368    pub raw:       Value,
369}
370
371impl OrderBookL3 {
372    pub fn from_value(v: Value) -> Self {
373        use crate::value::{safe_string, safe_integer, get_value};
374        let mut ob = OrderBookL3::default();
375        ob.symbol    = safe_string(&v, "symbol",    None);
376        ob.timestamp = safe_integer(&v, "timestamp", None);
377        ob.datetime  = safe_string(&v, "datetime",  None);
378        ob.nonce     = safe_integer(&v, "nonce",    None);
379        // Rows are `[price, amount, orderId]`. Rows whose price/amount are not
380        // parseable numbers are dropped (same policy as `OrderBook`).
381        let extract_side = |key: &str| -> Vec<OrderBookL3Entry> {
382            let side = get_value(&v, &Value::Str(key.to_string().into()));
383            match side {
384                Value::Arr(rows) => rows.iter().filter_map(|row| {
385                    let num = |cell: Option<&Value>| -> f64 {
386                        match cell {
387                            Some(Value::Float(f)) => *f,
388                            Some(Value::Int(n))   => *n as f64,
389                            Some(Value::Str(s))   => s.parse().unwrap_or(f64::NAN),
390                            _ => f64::NAN,
391                        }
392                    };
393                    let r = match row {
394                        Value::Arr(r) => r,
395                        _ => return None,
396                    };
397                    let price  = num(r.first());
398                    let amount = num(r.get(1));
399                    if price.is_nan() || amount.is_nan() {
400                        return None;
401                    }
402                    let order_id = match r.get(2) {
403                        Some(Value::Str(s))   => Some(s.to_string()),
404                        Some(Value::Int(n))   => Some(n.to_string()),
405                        Some(Value::Float(f)) => Some(f.to_string()),
406                        _ => None,
407                    };
408                    Some(OrderBookL3Entry { price, amount, order_id })
409                }).collect(),
410                _ => Vec::new(),
411            }
412        };
413        ob.bids = extract_side("bids");
414        ob.asks = extract_side("asks");
415        ob.raw  = v;
416        ob
417    }
418}
419
420/// A unified OHLCV candle: [timestamp, open, high, low, close, volume].
421pub type OHLCV = [f64; 6];
422
423/// Unified balance / account info.
424#[derive(Debug, Clone, Default)]
425pub struct Balances {
426    pub info:  Value,
427    pub free:  HashMap<String, f64>,
428    pub used:  HashMap<String, f64>,
429    pub total: HashMap<String, f64>,
430}
431
432impl Balances {
433    pub fn from_value(v: Value) -> Self {
434        use crate::value::get_value;
435        let mut b = Balances::default();
436        b.info = get_value(&v, &Value::Str("info".into()));
437        // The top-level `free`/`used`/`total` keys are dicts of
438        // `<currency-code> → number`. Walk them and collect.
439        let extract = |key: &str| -> HashMap<String, f64> {
440            let m = get_value(&v, &Value::Str(key.to_string().into()));
441            match m {
442                Value::Dict(d) => d.iter().filter_map(|(k, val)| {
443                    let n = match val {
444                        Value::Float(f) => Some(*f),
445                        Value::Int(n)   => Some(*n as f64),
446                        Value::Str(s)   => s.parse().ok(),
447                        _ => None,
448                    }?;
449                    Some((k.clone(), n))
450                }).collect(),
451                _ => HashMap::new(),
452            }
453        };
454        b.free  = extract("free");
455        b.used  = extract("used");
456        b.total = extract("total");
457        b
458    }
459}
460
461/// Unified transaction (deposit / withdrawal). Mirrors the TS `Transaction` interface.
462#[derive(Debug, Clone, Default)]
463pub struct Transaction {
464    pub id:           Option<String>,
465    pub txid:         Option<String>,
466    pub timestamp:    Option<i64>,
467    pub datetime:     Option<String>,
468    pub address:      Option<String>,
469    pub address_from: Option<String>,
470    pub address_to:   Option<String>,
471    pub tag:          Option<String>,
472    pub tag_from:     Option<String>,
473    pub tag_to:       Option<String>,
474    pub tx_type:      Option<String>,   // "deposit" | "withdrawal"
475    pub amount:       Option<f64>,
476    pub currency:     Option<String>,
477    pub status:       Option<String>,   // "pending" | "ok" | "failed" | "canceled"
478    pub updated:      Option<i64>,
479    pub fee:          Option<Fee>,
480    pub network:      Option<String>,
481    pub comment:      Option<String>,
482    pub internal:     Option<bool>,
483    pub raw:          Value,
484}
485
486impl Transaction {
487    pub fn from_value(v: Value) -> Self {
488        use crate::value::{safe_string, safe_number, safe_integer, safe_bool};
489        let mut t = Transaction::default();
490        t.id           = safe_string(&v, "id",          None);
491        t.txid         = safe_string(&v, "txid",        None);
492        t.timestamp    = safe_integer(&v, "timestamp",  None);
493        t.datetime     = safe_string(&v, "datetime",    None);
494        t.address      = safe_string(&v, "address",     None);
495        t.address_from = safe_string(&v, "addressFrom", None);
496        t.address_to   = safe_string(&v, "addressTo",   None);
497        t.tag          = safe_string(&v, "tag",         None);
498        t.tag_from     = safe_string(&v, "tagFrom",     None);
499        t.tag_to       = safe_string(&v, "tagTo",       None);
500        t.tx_type      = safe_string(&v, "type",        None);
501        t.amount       = safe_number(&v, "amount",      None);
502        t.currency     = safe_string(&v, "currency",    None);
503        t.status       = safe_string(&v, "status",      None);
504        t.updated      = safe_integer(&v, "updated",    None);
505        t.fee          = match crate::get_value(&v, &Value::Str("fee".into())) {
506            fee @ Value::Dict(_) => Some(Fee::from_value(fee)),
507            _ => None,
508        };
509        t.network      = safe_string(&v, "network",     None);
510        t.comment      = safe_string(&v, "comment",     None);
511        t.internal     = safe_bool(&v, "internal",      None);
512        t.raw = v;
513        t
514    }
515}
516
517/// Unified currency descriptor.
518#[derive(Debug, Clone, Default)]
519pub struct Currency {
520    pub id:        String,
521    pub code:      String,
522    pub name:      Option<String>,
523    pub active:    bool,
524    pub precision: Option<f64>,
525    pub raw:       Value,
526}
527
528impl Currency {
529    pub fn from_value(v: Value) -> Self {
530        use crate::value::{safe_string, safe_bool, safe_number};
531        let mut c = Currency::default();
532        c.id        = safe_string(&v, "id",   None).unwrap_or_default();
533        c.code      = safe_string(&v, "code", None).unwrap_or_default();
534        c.name      = safe_string(&v, "name", None);
535        c.active    = safe_bool(&v, "active", Some(true)).unwrap_or(true);
536        c.precision = safe_number(&v, "precision", None);
537        c.raw = v;
538        c
539    }
540}
541
542/// Unified position (derivatives). Mirrors the TS `Position` interface.
543#[derive(Debug, Clone, Default)]
544pub struct Position {
545    pub id:               Option<String>,
546    pub symbol:           String,
547    pub timestamp:        Option<i64>,
548    pub datetime:         Option<String>,
549    pub side:             Option<String>,
550    pub contracts:        Option<f64>,
551    pub contract_size:    Option<f64>,
552    pub notional:         Option<f64>,
553    pub entry_price:      Option<f64>,
554    pub mark_price:       Option<f64>,
555    pub last_price:       Option<f64>,
556    pub liquidation_price: Option<f64>,
557    pub unrealized_pnl:   Option<f64>,
558    pub realized_pnl:     Option<f64>,
559    pub position_margin: Option<f64>,
560    pub collateral:       Option<f64>,
561    pub leverage:         Option<f64>,
562    /// Unified `marginMode` ("cross" | "isolated").
563    pub margin_mode:      Option<String>,
564    /// Deprecated `marginType` key still emitted by a few venues; prefer `margin_mode`.
565    pub margin_type:      Option<String>,
566    pub hedged:           Option<bool>,
567    pub maintenance_margin:            Option<f64>,
568    pub maintenance_margin_percentage: Option<f64>,
569    pub initial_margin:                Option<f64>,
570    pub initial_margin_percentage:     Option<f64>,
571    pub margin_ratio:     Option<f64>,
572    pub percentage:       Option<f64>,
573    pub last_update_timestamp: Option<i64>,
574    pub stop_loss_price:   Option<f64>,
575    pub take_profit_price: Option<f64>,
576    pub raw:              Value,
577}
578
579impl Position {
580    pub fn from_value(v: Value) -> Self {
581        use crate::value::{safe_string, safe_number, safe_integer, safe_bool};
582        let mut p = Position::default();
583        p.id             = safe_string(&v, "id",     None);
584        p.symbol         = safe_string(&v, "symbol", None).unwrap_or_default();
585        p.timestamp      = safe_integer(&v, "timestamp", None);
586        p.datetime       = safe_string(&v, "datetime",   None);
587        p.side           = safe_string(&v, "side",   None);
588        p.contracts      = safe_number(&v, "contracts",    None);
589        p.contract_size  = safe_number(&v, "contractSize", None);
590        p.notional       = safe_number(&v, "notional",     None);
591        p.entry_price    = safe_number(&v, "entryPrice",   None);
592        p.mark_price     = safe_number(&v, "markPrice",    None);
593        p.last_price     = safe_number(&v, "lastPrice",    None);
594        p.liquidation_price = safe_number(&v, "liquidationPrice", None);
595        p.unrealized_pnl = safe_number(&v, "unrealizedPnl", None);
596        p.realized_pnl   = safe_number(&v, "realizedPnl",   None);
597        p.position_margin = safe_number(&v, "positionMargin", None);
598        p.collateral     = safe_number(&v, "collateral",   None);
599        p.leverage       = safe_number(&v, "leverage",     None);
600        p.margin_mode    = safe_string(&v, "marginMode",   None);
601        p.margin_type    = safe_string(&v, "marginType",   None);
602        p.hedged         = safe_bool(&v, "hedged",         None);
603        p.maintenance_margin            = safe_number(&v, "maintenanceMargin",           None);
604        p.maintenance_margin_percentage = safe_number(&v, "maintenanceMarginPercentage", None);
605        p.initial_margin                = safe_number(&v, "initialMargin",               None);
606        p.initial_margin_percentage     = safe_number(&v, "initialMarginPercentage",     None);
607        p.margin_ratio   = safe_number(&v, "marginRatio",  None);
608        p.percentage     = safe_number(&v, "percentage",   None);
609        p.last_update_timestamp = safe_integer(&v, "lastUpdateTimestamp", None);
610        p.stop_loss_price   = safe_number(&v, "stopLossPrice",   None);
611        p.take_profit_price = safe_number(&v, "takeProfitPrice", None);
612        p.raw = v;
613        p
614    }
615}
616
617/// Unified transfer record.
618#[derive(Debug, Clone, Default)]
619pub struct Transfer {
620    pub id:        Option<String>,
621    pub timestamp: Option<i64>,
622    pub datetime:  Option<String>,
623    pub currency:  Option<String>,
624    pub amount:    Option<f64>,
625    pub from_account: Option<String>,
626    pub to_account:   Option<String>,
627    pub status:    Option<String>,
628    pub raw:       Value,
629}
630
631impl Transfer {
632    pub fn from_value(v: Value) -> Self {
633        use crate::value::{safe_string, safe_number, safe_integer};
634        let mut t = Transfer::default();
635        t.id           = safe_string(&v, "id",        None);
636        t.timestamp    = safe_integer(&v, "timestamp", None);
637        t.datetime     = safe_string(&v, "datetime",  None);
638        t.currency     = safe_string(&v, "currency",  None);
639        t.amount       = safe_number(&v, "amount",    None);
640        t.from_account = safe_string(&v, "fromAccount", None);
641        t.to_account   = safe_string(&v, "toAccount",   None);
642        t.status       = safe_string(&v, "status",   None);
643        t.raw = v;
644        t
645    }
646}
647
648/// Unified ledger entry. Mirrors the TS `LedgerEntry` interface.
649#[derive(Debug, Clone, Default)]
650pub struct LedgerEntry {
651    pub id:        Option<String>,
652    pub timestamp: Option<i64>,
653    pub datetime:  Option<String>,
654    pub direction: Option<String>,   // "in" | "out"
655    pub account:   Option<String>,
656    pub reference_id:      Option<String>,
657    pub reference_account: Option<String>,
658    pub entry_type: Option<String>,  // "trade" | "transaction" | "fee" | …
659    pub amount:    Option<f64>,
660    pub currency:  Option<String>,
661    pub before:    Option<f64>,
662    pub after:     Option<f64>,
663    pub status:    Option<String>,
664    pub fee:       Option<Fee>,
665    pub raw:       Value,
666}
667
668impl LedgerEntry {
669    pub fn from_value(v: Value) -> Self {
670        use crate::value::{safe_string, safe_number, safe_integer};
671        let mut l = LedgerEntry::default();
672        l.id        = safe_string(&v, "id",        None);
673        l.timestamp = safe_integer(&v, "timestamp", None);
674        l.datetime  = safe_string(&v, "datetime",  None);
675        l.direction = safe_string(&v, "direction", None);
676        l.account   = safe_string(&v, "account",   None);
677        l.reference_id      = safe_string(&v, "referenceId",      None);
678        l.reference_account = safe_string(&v, "referenceAccount", None);
679        l.entry_type = safe_string(&v, "type",     None);
680        l.amount    = safe_number(&v, "amount",    None);
681        l.currency  = safe_string(&v, "currency",  None);
682        l.before    = safe_number(&v, "before",    None);
683        l.after     = safe_number(&v, "after",     None);
684        l.status    = safe_string(&v, "status",    None);
685        l.fee       = match crate::get_value(&v, &Value::Str("fee".into())) {
686            fee @ Value::Dict(_) => Some(Fee::from_value(fee)),
687            _ => None,
688        };
689        l.raw = v;
690        l
691    }
692}
693
694/// Unified funding rate. Mirrors the TS `FundingRate` interface.
695#[derive(Debug, Clone, Default)]
696pub struct FundingRate {
697    pub symbol:        String,
698    pub funding_rate:  Option<f64>,
699    pub timestamp:     Option<i64>,
700    pub datetime:      Option<String>,
701    pub mark_price:    Option<f64>,
702    pub index_price:   Option<f64>,
703    pub interest_rate: Option<f64>,
704    pub estimated_settle_price: Option<f64>,
705    pub funding_timestamp: Option<i64>,
706    pub funding_datetime:  Option<String>,
707    pub next_funding_timestamp: Option<i64>,
708    pub next_funding_datetime:  Option<String>,
709    pub next_funding_rate:      Option<f64>,
710    pub previous_funding_timestamp: Option<i64>,
711    pub previous_funding_datetime:  Option<String>,
712    pub previous_funding_rate:      Option<f64>,
713    pub interval:      Option<String>,
714    pub raw:           Value,
715}
716
717impl FundingRate {
718    pub fn from_value(v: Value) -> Self {
719        use crate::value::{safe_string, safe_number, safe_integer};
720        let mut f = FundingRate::default();
721        f.symbol       = safe_string(&v, "symbol", None).unwrap_or_default();
722        f.funding_rate = safe_number(&v, "fundingRate", None);
723        f.timestamp    = safe_integer(&v, "timestamp", None);
724        f.datetime     = safe_string(&v, "datetime", None);
725        f.mark_price    = safe_number(&v, "markPrice",    None);
726        f.index_price   = safe_number(&v, "indexPrice",   None);
727        f.interest_rate = safe_number(&v, "interestRate", None);
728        f.estimated_settle_price = safe_number(&v, "estimatedSettlePrice", None);
729        f.funding_timestamp = safe_integer(&v, "fundingTimestamp", None);
730        f.funding_datetime  = safe_string(&v, "fundingDatetime",   None);
731        f.next_funding_timestamp = safe_integer(&v, "nextFundingTimestamp", None);
732        f.next_funding_datetime  = safe_string(&v, "nextFundingDatetime",   None);
733        f.next_funding_rate      = safe_number(&v, "nextFundingRate",       None);
734        f.previous_funding_timestamp = safe_integer(&v, "previousFundingTimestamp", None);
735        f.previous_funding_datetime  = safe_string(&v, "previousFundingDatetime",   None);
736        f.previous_funding_rate      = safe_number(&v, "previousFundingRate",       None);
737        f.interval     = safe_string(&v, "interval", None);
738        f.raw = v;
739        f
740    }
741}
742
743/// Unified greeks (options). Mirrors the TS `Greeks` interface.
744#[derive(Debug, Clone, Default)]
745pub struct Greeks {
746    pub symbol:    String,
747    pub timestamp: Option<i64>,
748    pub datetime:  Option<String>,
749    pub delta:     Option<f64>,
750    pub gamma:     Option<f64>,
751    pub theta:     Option<f64>,
752    pub vega:      Option<f64>,
753    pub rho:       Option<f64>,
754    pub vanna:     Option<f64>,
755    pub volga:     Option<f64>,
756    pub charm:     Option<f64>,
757    pub bid_size:  Option<f64>,
758    pub ask_size:  Option<f64>,
759    pub bid_implied_volatility:  Option<f64>,
760    pub ask_implied_volatility:  Option<f64>,
761    pub mark_implied_volatility: Option<f64>,
762    pub bid_price:  Option<f64>,
763    pub ask_price:  Option<f64>,
764    pub mark_price: Option<f64>,
765    pub last_price: Option<f64>,
766    pub underlying_price: Option<f64>,
767    pub raw:       Value,
768}
769
770impl Greeks {
771    pub fn from_value(v: Value) -> Self {
772        use crate::value::{safe_string, safe_number, safe_integer};
773        let mut g = Greeks::default();
774        g.symbol    = safe_string(&v, "symbol", None).unwrap_or_default();
775        g.timestamp = safe_integer(&v, "timestamp", None);
776        g.datetime  = safe_string(&v, "datetime",  None);
777        g.delta  = safe_number(&v, "delta", None);
778        g.gamma  = safe_number(&v, "gamma", None);
779        g.theta  = safe_number(&v, "theta", None);
780        g.vega   = safe_number(&v, "vega",  None);
781        g.rho    = safe_number(&v, "rho",   None);
782        g.vanna  = safe_number(&v, "vanna", None);
783        g.volga  = safe_number(&v, "volga", None);
784        g.charm  = safe_number(&v, "charm", None);
785        g.bid_size = safe_number(&v, "bidSize", None);
786        g.ask_size = safe_number(&v, "askSize", None);
787        g.bid_implied_volatility  = safe_number(&v, "bidImpliedVolatility",  None);
788        g.ask_implied_volatility  = safe_number(&v, "askImpliedVolatility",  None);
789        g.mark_implied_volatility = safe_number(&v, "markImpliedVolatility", None);
790        g.bid_price  = safe_number(&v, "bidPrice",  None);
791        g.ask_price  = safe_number(&v, "askPrice",  None);
792        g.mark_price = safe_number(&v, "markPrice", None);
793        g.last_price = safe_number(&v, "lastPrice", None);
794        g.underlying_price = safe_number(&v, "underlyingPrice", None);
795        g.raw = v;
796        g
797    }
798}
799
800/// A single trading-fee descriptor (per currency or per side).
801#[derive(Debug, Clone, Default)]
802pub struct Fee {
803    pub currency: Option<String>,
804    pub cost:     Option<f64>,
805    pub rate:     Option<f64>,
806    pub raw:      Value,
807}
808
809impl Fee {
810    pub fn from_value(v: Value) -> Self {
811        use crate::value::{safe_string, safe_number};
812        let mut f = Fee::default();
813        f.currency = safe_string(&v, "currency", None);
814        f.cost     = safe_number(&v, "cost",     None);
815        f.rate     = safe_number(&v, "rate",     None);
816        f.raw = v;
817        f
818    }
819}
820
821/// Unified trading-fee descriptor (per-symbol maker / taker).
822#[derive(Debug, Clone, Default)]
823pub struct TradingFee {
824    pub symbol:     Option<String>,
825    pub maker:      Option<f64>,
826    pub taker:      Option<f64>,
827    pub percentage: Option<bool>,
828    pub tier_based: Option<bool>,
829    pub raw:        Value,
830}
831
832impl TradingFee {
833    pub fn from_value(v: Value) -> Self {
834        use crate::value::{safe_string, safe_number, safe_bool};
835        let mut t = TradingFee::default();
836        t.symbol     = safe_string(&v, "symbol", None);
837        t.maker      = safe_number(&v, "maker",  None);
838        t.taker      = safe_number(&v, "taker",  None);
839        t.percentage = safe_bool(&v, "percentage", None);
840        t.tier_based = safe_bool(&v, "tierBased",  None);
841        t.raw = v;
842        t
843    }
844}
845
846/// Unified liquidation record.
847#[derive(Debug, Clone, Default)]
848pub struct Liquidation {
849    pub symbol:    String,
850    pub timestamp: Option<i64>,
851    pub datetime:  Option<String>,
852    pub price:     Option<f64>,
853    pub base_value:  Option<f64>,
854    pub quote_value: Option<f64>,
855    pub contracts:     Option<f64>,
856    pub contract_size: Option<f64>,
857    pub side:      Option<String>,   // "buy" | "sell"
858    pub raw:       Value,
859}
860
861impl Liquidation {
862    pub fn from_value(v: Value) -> Self {
863        use crate::value::{safe_string, safe_number, safe_integer};
864        let mut l = Liquidation::default();
865        l.symbol      = safe_string(&v, "symbol", None).unwrap_or_default();
866        l.timestamp   = safe_integer(&v, "timestamp", None);
867        l.datetime    = safe_string(&v, "datetime", None);
868        l.price       = safe_number(&v, "price", None);
869        l.base_value  = safe_number(&v, "baseValue",  None);
870        l.quote_value = safe_number(&v, "quoteValue", None);
871        l.contracts     = safe_number(&v, "contracts",    None);
872        l.contract_size = safe_number(&v, "contractSize", None);
873        l.side        = safe_string(&v, "side", None);
874        l.raw = v;
875        l
876    }
877}
878
879/// Unified open-interest snapshot.
880#[derive(Debug, Clone, Default)]
881pub struct OpenInterest {
882    pub symbol:    String,
883    pub timestamp: Option<i64>,
884    pub datetime:  Option<String>,
885    pub open_interest_amount: Option<f64>,
886    pub open_interest_value:  Option<f64>,
887    pub base_volume:  Option<f64>,
888    pub quote_volume: Option<f64>,
889    pub raw:       Value,
890}
891
892impl OpenInterest {
893    pub fn from_value(v: Value) -> Self {
894        use crate::value::{safe_string, safe_number, safe_integer};
895        let mut o = OpenInterest::default();
896        o.symbol    = safe_string(&v, "symbol", None).unwrap_or_default();
897        o.timestamp = safe_integer(&v, "timestamp", None);
898        o.datetime  = safe_string(&v, "datetime",  None);
899        o.open_interest_amount = safe_number(&v, "openInterestAmount", None);
900        o.open_interest_value  = safe_number(&v, "openInterestValue",  None);
901        o.base_volume  = safe_number(&v, "baseVolume",  None);
902        o.quote_volume = safe_number(&v, "quoteVolume", None);
903        o.raw = v;
904        o
905    }
906}
907
908/// Exchange-wide status snapshot.
909#[derive(Debug, Clone, Default)]
910pub struct Status {
911    pub status:    Option<String>,
912    pub updated:   Option<i64>,
913    pub eta:       Option<i64>,
914    pub url:       Option<String>,
915    pub raw:       Value,
916}
917
918impl Status {
919    pub fn from_value(v: Value) -> Self {
920        use crate::value::{safe_string, safe_integer};
921        let mut s = Status::default();
922        s.status  = safe_string(&v, "status", None);
923        s.updated = safe_integer(&v, "updated", None);
924        s.eta     = safe_integer(&v, "eta",     None);
925        s.url     = safe_string(&v, "url",     None);
926        s.raw = v;
927        s
928    }
929}
930
931/// Unified margin mode per symbol.
932#[derive(Debug, Clone, Default)]
933pub struct MarginMode {
934    pub symbol:      Option<String>,
935    pub margin_mode: Option<String>,
936    pub raw:         Value,
937}
938
939impl MarginMode {
940    pub fn from_value(v: Value) -> Self {
941        use crate::value::safe_string;
942        let mut m = MarginMode::default();
943        m.symbol      = safe_string(&v, "symbol", None);
944        m.margin_mode = safe_string(&v, "marginMode", None);
945        m.raw = v;
946        m
947    }
948}
949
950/// Unified leverage per symbol.
951#[derive(Debug, Clone, Default)]
952pub struct Leverage {
953    pub symbol:        Option<String>,
954    pub margin_mode:   Option<String>,
955    pub long_leverage: Option<f64>,
956    pub short_leverage: Option<f64>,
957    pub raw:           Value,
958}
959
960impl Leverage {
961    pub fn from_value(v: Value) -> Self {
962        use crate::value::{safe_string, safe_number};
963        let mut l = Leverage::default();
964        l.symbol         = safe_string(&v, "symbol", None);
965        l.margin_mode    = safe_string(&v, "marginMode", None);
966        l.long_leverage  = safe_number(&v, "longLeverage", None);
967        l.short_leverage = safe_number(&v, "shortLeverage", None);
968        l.raw = v;
969        l
970    }
971}
972
973/// One bracket in a leverage-tier ladder.
974#[derive(Debug, Clone, Default)]
975pub struct LeverageTier {
976    pub tier:           Option<f64>,
977    pub symbol:         Option<String>,
978    pub currency:       Option<String>,
979    pub min_notional:   Option<f64>,
980    pub max_notional:   Option<f64>,
981    pub maintenance_margin_rate: Option<f64>,
982    pub max_leverage:   Option<f64>,
983    pub raw:            Value,
984}
985
986impl LeverageTier {
987    pub fn from_value(v: Value) -> Self {
988        use crate::value::{safe_string, safe_number};
989        let mut t = LeverageTier::default();
990        t.tier           = safe_number(&v, "tier", None);
991        t.symbol         = safe_string(&v, "symbol", None);
992        t.currency       = safe_string(&v, "currency", None);
993        t.min_notional   = safe_number(&v, "minNotional", None);
994        t.max_notional   = safe_number(&v, "maxNotional", None);
995        t.maintenance_margin_rate = safe_number(&v, "maintenanceMarginRate", None);
996        t.max_leverage   = safe_number(&v, "maxLeverage", None);
997        t.raw = v;
998        t
999    }
1000}
1001
1002/// Unified borrow / lending rate.
1003#[derive(Debug, Clone, Default)]
1004pub struct BorrowRate {
1005    pub currency:  Option<String>,
1006    pub rate:      Option<f64>,
1007    pub period:    Option<i64>,
1008    pub timestamp: Option<i64>,
1009    pub datetime:  Option<String>,
1010    pub raw:       Value,
1011}
1012
1013impl BorrowRate {
1014    pub fn from_value(v: Value) -> Self {
1015        use crate::value::{safe_string, safe_number, safe_integer};
1016        let mut r = BorrowRate::default();
1017        r.currency  = safe_string(&v, "currency", None);
1018        r.rate      = safe_number(&v, "rate", None);
1019        r.period    = safe_integer(&v, "period", None);
1020        r.timestamp = safe_integer(&v, "timestamp", None);
1021        r.datetime  = safe_string(&v, "datetime", None);
1022        r.raw = v;
1023        r
1024    }
1025}
1026
1027/// Unified borrow-interest record (margin interest accrued on a borrow).
1028/// Distinct from `BorrowRate` — it carries accrued interest and the borrowed
1029/// amount, not a periodic rate (review #7: `fetchBorrowInterest` was wrongly
1030/// mapped to `BorrowRate`).
1031#[derive(Debug, Clone, Default)]
1032pub struct BorrowInterest {
1033    pub symbol:          Option<String>,
1034    pub currency:        Option<String>,
1035    pub interest:        Option<f64>,
1036    pub interest_rate:   Option<f64>,
1037    pub amount_borrowed: Option<f64>,
1038    pub margin_mode:     Option<String>,
1039    pub timestamp:       Option<i64>,
1040    pub datetime:        Option<String>,
1041    pub raw:             Value,
1042}
1043
1044impl BorrowInterest {
1045    pub fn from_value(v: Value) -> Self {
1046        use crate::value::{safe_string, safe_number, safe_integer};
1047        let mut r = BorrowInterest::default();
1048        r.symbol          = safe_string(&v, "symbol", None);
1049        r.currency        = safe_string(&v, "currency", None);
1050        r.interest        = safe_number(&v, "interest", None);
1051        r.interest_rate   = safe_number(&v, "interestRate", None);
1052        r.amount_borrowed = safe_number(&v, "amountBorrowed", None);
1053        r.margin_mode     = safe_string(&v, "marginMode", None);
1054        r.timestamp       = safe_integer(&v, "timestamp", None);
1055        r.datetime        = safe_string(&v, "datetime", None);
1056        r.raw = v;
1057        r
1058    }
1059}
1060
1061/// Unified deposit address.
1062#[derive(Debug, Clone, Default)]
1063pub struct DepositAddress {
1064    pub currency: Option<String>,
1065    pub address:  Option<String>,
1066    pub tag:      Option<String>,
1067    pub network:  Option<String>,
1068    pub raw:      Value,
1069}
1070
1071impl DepositAddress {
1072    pub fn from_value(v: Value) -> Self {
1073        use crate::value::safe_string;
1074        let mut d = DepositAddress::default();
1075        d.currency = safe_string(&v, "currency", None);
1076        d.address  = safe_string(&v, "address", None);
1077        d.tag      = safe_string(&v, "tag", None);
1078        d.network  = safe_string(&v, "network", None);
1079        d.raw = v;
1080        d
1081    }
1082}
1083
1084/// Unified margin modification — the result of `addMargin` / `reduceMargin` /
1085/// `setMargin`, and each row of `fetchMarginAdjustmentHistory`. Mirrors the TS
1086/// `MarginModification` interface (`ts/src/base/types.ts`).
1087#[derive(Debug, Clone, Default)]
1088pub struct MarginModification {
1089    pub symbol:      Option<String>,
1090    pub mod_type:    Option<String>,   // "add" | "reduce" | "set"
1091    pub margin_mode: Option<String>,   // "cross" | "isolated"
1092    pub amount:      Option<f64>,
1093    pub total:       Option<f64>,
1094    pub code:        Option<String>,
1095    pub status:      Option<String>,
1096    pub timestamp:   Option<i64>,
1097    pub datetime:    Option<String>,
1098    pub raw:         Value,
1099}
1100
1101impl MarginModification {
1102    pub fn from_value(v: Value) -> Self {
1103        use crate::value::{safe_string, safe_number, safe_integer};
1104        let mut m = MarginModification::default();
1105        m.symbol      = safe_string(&v, "symbol",     None);
1106        m.mod_type    = safe_string(&v, "type",       None);
1107        m.margin_mode = safe_string(&v, "marginMode", None);
1108        m.amount      = safe_number(&v, "amount",     None);
1109        m.total       = safe_number(&v, "total",      None);
1110        m.code        = safe_string(&v, "code",       None);
1111        m.status      = safe_string(&v, "status",     None);
1112        m.timestamp   = safe_integer(&v, "timestamp", None);
1113        m.datetime    = safe_string(&v, "datetime",   None);
1114        m.raw = v;
1115        m
1116    }
1117}
1118
1119/// Unified margin borrow/repay receipt returned by `borrowCrossMargin`,
1120/// `borrowIsolatedMargin`, `repayCrossMargin` and `repayIsolatedMargin`.
1121/// Mirrors the TS `MarginLoan` interface (`ts/src/base/types.ts`): every
1122/// venue's `parseMarginLoan` emits exactly `id`/`currency`/`amount`/`symbol`/
1123/// `timestamp`/`datetime` (+ `info`).
1124#[derive(Debug, Clone, Default)]
1125pub struct MarginLoan {
1126    pub id:        Option<String>,
1127    pub currency:  Option<String>,
1128    pub amount:    Option<f64>,
1129    pub symbol:    Option<String>,
1130    pub timestamp: Option<i64>,
1131    pub datetime:  Option<String>,
1132    pub raw:       Value,
1133}
1134
1135impl MarginLoan {
1136    pub fn from_value(v: Value) -> Self {
1137        use crate::value::{safe_string, safe_number, safe_integer};
1138        let mut m = MarginLoan::default();
1139        m.id        = safe_string(&v, "id",        None);
1140        m.currency  = safe_string(&v, "currency",  None);
1141        m.amount    = safe_number(&v, "amount",    None);
1142        m.symbol    = safe_string(&v, "symbol",    None);
1143        m.timestamp = safe_integer(&v, "timestamp", None);
1144        m.datetime  = safe_string(&v, "datetime",  None);
1145        m.raw = v;
1146        m
1147    }
1148}
1149
1150/// Unified currency-conversion record (`fetchConvertQuote`, `createConvertTrade`,
1151/// `fetchConvertTrade`, and each row of `fetchConvertTradeHistory`). Mirrors the
1152/// TS `Conversion` interface.
1153#[derive(Debug, Clone, Default)]
1154pub struct Conversion {
1155    pub id:            Option<String>,
1156    pub timestamp:     Option<i64>,
1157    pub datetime:      Option<String>,
1158    pub from_currency: Option<String>,
1159    pub from_amount:   Option<f64>,
1160    pub to_currency:   Option<String>,
1161    pub to_amount:     Option<f64>,
1162    pub price:         Option<f64>,
1163    pub fee:           Option<f64>,
1164    pub raw:           Value,
1165}
1166
1167impl Conversion {
1168    pub fn from_value(v: Value) -> Self {
1169        use crate::value::{safe_string, safe_number, safe_integer};
1170        let mut c = Conversion::default();
1171        c.id            = safe_string(&v, "id",           None);
1172        c.timestamp     = safe_integer(&v, "timestamp",   None);
1173        c.datetime      = safe_string(&v, "datetime",     None);
1174        c.from_currency = safe_string(&v, "fromCurrency", None);
1175        c.from_amount   = safe_number(&v, "fromAmount",   None);
1176        c.to_currency   = safe_string(&v, "toCurrency",   None);
1177        c.to_amount     = safe_number(&v, "toAmount",     None);
1178        c.price         = safe_number(&v, "price",        None);
1179        c.fee           = safe_number(&v, "fee",          None);
1180        c.raw = v;
1181        c
1182    }
1183}
1184
1185/// Unified auto-deleveraging rank (`fetchADLRank`, `fetchPositionADLRank`,
1186/// and each row of `fetchPositionsADLRank`). Mirrors the TS `ADL` interface.
1187#[derive(Debug, Clone, Default)]
1188pub struct ADL {
1189    pub symbol:     Option<String>,
1190    pub rank:       Option<i64>,
1191    pub rating:     Option<String>,
1192    pub percentage: Option<f64>,
1193    pub timestamp:  Option<i64>,
1194    pub datetime:   Option<String>,
1195    pub raw:        Value,
1196}
1197
1198impl ADL {
1199    pub fn from_value(v: Value) -> Self {
1200        use crate::value::{safe_string, safe_number, safe_integer};
1201        let mut a = ADL::default();
1202        a.symbol     = safe_string(&v, "symbol",     None);
1203        a.rank       = safe_integer(&v, "rank",      None);
1204        a.rating     = safe_string(&v, "rating",     None);
1205        a.percentage = safe_number(&v, "percentage", None);
1206        a.timestamp  = safe_integer(&v, "timestamp", None);
1207        a.datetime   = safe_string(&v, "datetime",   None);
1208        a.raw = v;
1209        a
1210    }
1211}
1212
1213/// Unified long/short ratio (`fetchLongShortRatio`, and each row of
1214/// `fetchLongShortRatioHistory`). Mirrors the TS `LongShortRatio` interface.
1215#[derive(Debug, Clone, Default)]
1216pub struct LongShortRatio {
1217    pub symbol:           Option<String>,
1218    pub timestamp:        Option<i64>,
1219    pub datetime:         Option<String>,
1220    pub timeframe:        Option<String>,
1221    pub long_short_ratio: Option<f64>,
1222    pub raw:              Value,
1223}
1224
1225impl LongShortRatio {
1226    pub fn from_value(v: Value) -> Self {
1227        use crate::value::{safe_string, safe_number, safe_integer};
1228        let mut r = LongShortRatio::default();
1229        r.symbol           = safe_string(&v, "symbol",         None);
1230        r.timestamp        = safe_integer(&v, "timestamp",     None);
1231        r.datetime         = safe_string(&v, "datetime",       None);
1232        r.timeframe        = safe_string(&v, "timeframe",      None);
1233        r.long_short_ratio = safe_number(&v, "longShortRatio", None);
1234        r.raw = v;
1235        r
1236    }
1237}
1238
1239/// One historical funding-rate sample (each row of `fetchFundingRateHistory`).
1240/// Mirrors the TS `FundingRateHistory` interface. Distinct from
1241/// [`FundingRate`], which is the live snapshot with next/previous rates.
1242#[derive(Debug, Clone, Default)]
1243pub struct FundingRateHistory {
1244    pub symbol:       Option<String>,
1245    pub funding_rate: Option<f64>,
1246    pub timestamp:    Option<i64>,
1247    pub datetime:     Option<String>,
1248    pub raw:          Value,
1249}
1250
1251impl FundingRateHistory {
1252    pub fn from_value(v: Value) -> Self {
1253        use crate::value::{safe_string, safe_number, safe_integer};
1254        let mut f = FundingRateHistory::default();
1255        f.symbol       = safe_string(&v, "symbol",      None);
1256        f.funding_rate = safe_number(&v, "fundingRate", None);
1257        f.timestamp    = safe_integer(&v, "timestamp",  None);
1258        f.datetime     = safe_string(&v, "datetime",    None);
1259        f.raw = v;
1260        f
1261    }
1262}
1263
1264/// One funding payment made or received (each row of `fetchFundingHistory`).
1265/// Mirrors the TS `FundingHistory` interface.
1266#[derive(Debug, Clone, Default)]
1267pub struct FundingHistory {
1268    pub id:        Option<String>,
1269    pub symbol:    Option<String>,
1270    pub code:      Option<String>,
1271    pub timestamp: Option<i64>,
1272    pub datetime:  Option<String>,
1273    pub amount:    Option<f64>,
1274    pub raw:       Value,
1275}
1276
1277impl FundingHistory {
1278    pub fn from_value(v: Value) -> Self {
1279        use crate::value::{safe_string, safe_number, safe_integer};
1280        let mut f = FundingHistory::default();
1281        f.id        = safe_string(&v, "id",         None);
1282        f.symbol    = safe_string(&v, "symbol",     None);
1283        f.code      = safe_string(&v, "code",       None);
1284        f.timestamp = safe_integer(&v, "timestamp", None);
1285        f.datetime  = safe_string(&v, "datetime",   None);
1286        f.amount    = safe_number(&v, "amount",     None);
1287        f.raw = v;
1288        f
1289    }
1290}
1291
1292/// One sub-account / wallet entry (each row of `fetchAccounts`). Mirrors the
1293/// TS `Account` interface.
1294#[derive(Debug, Clone, Default)]
1295pub struct Account {
1296    pub id:           Option<String>,
1297    pub account_type: Option<String>,
1298    pub code:         Option<String>,
1299    pub raw:          Value,
1300}
1301
1302impl Account {
1303    pub fn from_value(v: Value) -> Self {
1304        use crate::value::safe_string;
1305        let mut a = Account::default();
1306        a.id           = safe_string(&v, "id",   None);
1307        a.account_type = safe_string(&v, "type", None);
1308        a.code         = safe_string(&v, "code", None);
1309        a.raw = v;
1310        a
1311    }
1312}
1313
1314/// Position-mode flag (`fetchPositionMode`). Mirrors the TS `PositionModeInfo`
1315/// interface: `hedged` is `true` for hedge (dual-side) mode, `false` for one-way.
1316#[derive(Debug, Clone, Default)]
1317pub struct PositionModeInfo {
1318    pub hedged: Option<bool>,
1319    pub raw:    Value,
1320}
1321
1322impl PositionModeInfo {
1323    pub fn from_value(v: Value) -> Self {
1324        use crate::value::safe_bool;
1325        let mut p = PositionModeInfo::default();
1326        p.hedged = safe_bool(&v, "hedged", None);
1327        p.raw = v;
1328        p
1329    }
1330}
1331
1332/// Unified option-contract snapshot (`fetchOption`, and each value of
1333/// `fetchOptionChain`). Named `OptionContract` because `Option` collides with
1334/// `core::option::Option`. Mirrors the TS `Option` interface.
1335#[derive(Debug, Clone, Default)]
1336pub struct OptionContract {
1337    pub currency:           Option<String>,
1338    pub symbol:             Option<String>,
1339    pub timestamp:          Option<i64>,
1340    pub datetime:           Option<String>,
1341    pub implied_volatility: Option<f64>,
1342    pub open_interest:      Option<f64>,
1343    pub bid_price:          Option<f64>,
1344    pub ask_price:          Option<f64>,
1345    pub mid_price:          Option<f64>,
1346    pub mark_price:         Option<f64>,
1347    pub last_price:         Option<f64>,
1348    pub underlying_price:   Option<f64>,
1349    pub change:             Option<f64>,
1350    pub percentage:         Option<f64>,
1351    pub base_volume:        Option<f64>,
1352    pub quote_volume:       Option<f64>,
1353    pub raw:                Value,
1354}
1355
1356impl OptionContract {
1357    pub fn from_value(v: Value) -> Self {
1358        use crate::value::{safe_string, safe_number, safe_integer};
1359        let mut o = OptionContract::default();
1360        o.currency           = safe_string(&v, "currency",          None);
1361        o.symbol             = safe_string(&v, "symbol",            None);
1362        o.timestamp          = safe_integer(&v, "timestamp",        None);
1363        o.datetime           = safe_string(&v, "datetime",          None);
1364        o.implied_volatility = safe_number(&v, "impliedVolatility", None);
1365        o.open_interest      = safe_number(&v, "openInterest",      None);
1366        o.bid_price          = safe_number(&v, "bidPrice",          None);
1367        o.ask_price          = safe_number(&v, "askPrice",          None);
1368        o.mid_price          = safe_number(&v, "midPrice",          None);
1369        o.mark_price         = safe_number(&v, "markPrice",         None);
1370        o.last_price         = safe_number(&v, "lastPrice",         None);
1371        o.underlying_price   = safe_number(&v, "underlyingPrice",   None);
1372        o.change             = safe_number(&v, "change",            None);
1373        o.percentage         = safe_number(&v, "percentage",        None);
1374        o.base_volume        = safe_number(&v, "baseVolume",        None);
1375        o.quote_volume       = safe_number(&v, "quoteVolume",       None);
1376        o.raw = v;
1377        o
1378    }
1379}
1380
1381/// Last traded price per symbol (each value of `fetchLastPrices`). Mirrors the
1382/// TS `LastPrice` interface.
1383#[derive(Debug, Clone, Default)]
1384pub struct LastPrice {
1385    pub symbol:    Option<String>,
1386    pub timestamp: Option<i64>,
1387    pub datetime:  Option<String>,
1388    pub price:     Option<f64>,
1389    pub side:      Option<String>,   // "buy" | "sell"
1390    pub raw:       Value,
1391}
1392
1393impl LastPrice {
1394    pub fn from_value(v: Value) -> Self {
1395        use crate::value::{safe_string, safe_number, safe_integer};
1396        let mut p = LastPrice::default();
1397        p.symbol    = safe_string(&v, "symbol",    None);
1398        p.timestamp = safe_integer(&v, "timestamp", None);
1399        p.datetime  = safe_string(&v, "datetime",  None);
1400        p.price     = safe_number(&v, "price",     None);
1401        p.side      = safe_string(&v, "side",      None);
1402        p.raw = v;
1403        p
1404    }
1405}
1406
1407/// Unified isolated-margin borrow rate — one entry per symbol with a rate for
1408/// each leg (`fetchIsolatedBorrowRate`, and each value of
1409/// `fetchIsolatedBorrowRates`). Mirrors the TS `IsolatedBorrowRate` interface.
1410/// Distinct from [`BorrowRate`] (cross-margin, single `currency`/`rate`), whose
1411/// decoder would leave every field of an isolated rate `None`.
1412#[derive(Debug, Clone, Default)]
1413pub struct IsolatedBorrowRate {
1414    pub symbol:     Option<String>,
1415    pub base:       Option<String>,
1416    pub base_rate:  Option<f64>,
1417    pub quote:      Option<String>,
1418    pub quote_rate: Option<f64>,
1419    pub period:     Option<i64>,
1420    pub timestamp:  Option<i64>,
1421    pub datetime:   Option<String>,
1422    pub raw:        Value,
1423}
1424
1425impl IsolatedBorrowRate {
1426    pub fn from_value(v: Value) -> Self {
1427        use crate::value::{safe_string, safe_number, safe_integer};
1428        let mut r = IsolatedBorrowRate::default();
1429        r.symbol     = safe_string(&v, "symbol",    None);
1430        r.base       = safe_string(&v, "base",      None);
1431        r.base_rate  = safe_number(&v, "baseRate",  None);
1432        r.quote      = safe_string(&v, "quote",     None);
1433        r.quote_rate = safe_number(&v, "quoteRate", None);
1434        r.period     = safe_integer(&v, "period",   None);
1435        r.timestamp  = safe_integer(&v, "timestamp", None);
1436        r.datetime   = safe_string(&v, "datetime",  None);
1437        r.raw = v;
1438        r
1439    }
1440}
1441
1442/// One leg of a [`DepositWithdrawFee`] — the fee for a deposit or a withdrawal,
1443/// and whether it is a percentage of the amount (vs. a flat fee). Mirrors the
1444/// TS `DepositWithdrawFeeNetwork` interface.
1445#[derive(Debug, Clone, Copy, Default, PartialEq)]
1446pub struct DepositWithdrawFeeLeg {
1447    pub fee:        Option<f64>,
1448    pub percentage: Option<bool>,
1449}
1450
1451impl DepositWithdrawFeeLeg {
1452    fn from_value(v: &Value) -> Self {
1453        use crate::value::{safe_number, safe_bool};
1454        DepositWithdrawFeeLeg { fee: safe_number(v, "fee", None), percentage: safe_bool(v, "percentage", None) }
1455    }
1456}
1457
1458/// Unified deposit/withdraw fee for one currency (`fetchDepositWithdrawFee`,
1459/// and each value of `fetchDepositWithdrawFees`). Mirrors the TS
1460/// `DepositWithdrawFee` interface: a currency-level `withdraw`/`deposit` pair
1461/// plus the same pair per network under `networks`.
1462#[derive(Debug, Clone, Default)]
1463pub struct DepositWithdrawFee {
1464    pub withdraw: DepositWithdrawFeeLeg,
1465    pub deposit:  DepositWithdrawFeeLeg,
1466    pub networks: HashMap<String, DepositWithdrawFeeNetwork>,
1467    pub raw:      Value,
1468}
1469
1470/// Per-network `withdraw`/`deposit` legs inside [`DepositWithdrawFee::networks`].
1471#[derive(Debug, Clone, Copy, Default, PartialEq)]
1472pub struct DepositWithdrawFeeNetwork {
1473    pub withdraw: DepositWithdrawFeeLeg,
1474    pub deposit:  DepositWithdrawFeeLeg,
1475}
1476
1477impl DepositWithdrawFee {
1478    pub fn from_value(v: Value) -> Self {
1479        let sub = |parent: &Value, key: &str| crate::value::get_value(parent, &Value::Str(key.to_string().into()));
1480        let mut d = DepositWithdrawFee::default();
1481        d.withdraw = DepositWithdrawFeeLeg::from_value(&sub(&v, "withdraw"));
1482        d.deposit  = DepositWithdrawFeeLeg::from_value(&sub(&v, "deposit"));
1483        if let Value::Dict(networks) = sub(&v, "networks") {
1484            for (id, net) in networks.iter() {
1485                d.networks.insert(id.clone(), DepositWithdrawFeeNetwork {
1486                    withdraw: DepositWithdrawFeeLeg::from_value(&sub(net, "withdraw")),
1487                    deposit:  DepositWithdrawFeeLeg::from_value(&sub(net, "deposit")),
1488                });
1489            }
1490        }
1491        d.raw = v;
1492        d
1493    }
1494}
1495
1496// -----------------------------------------------------------------------------
1497// Collection aliases (mirror the plural names used in Go's exchange_types.go)
1498// -----------------------------------------------------------------------------
1499
1500pub type Markets       = HashMap<String, Market>;
1501pub type Currencies    = HashMap<String, Currency>;
1502pub type Tickers       = HashMap<String, Ticker>;
1503pub type OrderBooks    = HashMap<String, OrderBook>;
1504pub type FundingRates  = HashMap<String, FundingRate>;
1505pub type OpenInterests = HashMap<String, OpenInterest>;
1506pub type Leverages     = HashMap<String, Leverage>;
1507pub type MarginModes   = HashMap<String, MarginMode>;
1508pub type TradingFees   = HashMap<String, TradingFee>;
1509/// `fetchCrossBorrowRates` — currency code → [`BorrowRate`].
1510pub type CrossBorrowRates    = HashMap<String, BorrowRate>;
1511/// `fetchIsolatedBorrowRates` — symbol → [`IsolatedBorrowRate`].
1512pub type IsolatedBorrowRates = HashMap<String, IsolatedBorrowRate>;
1513/// `fetchLastPrices` — symbol → [`LastPrice`].
1514pub type LastPrices          = HashMap<String, LastPrice>;
1515/// `fetchOptionChain` — symbol → [`OptionContract`].
1516pub type OptionChain         = HashMap<String, OptionContract>;
1517/// `fetchLeverageTiers` — symbol → its ladder of [`LeverageTier`]s.
1518pub type LeverageTiers       = HashMap<String, Vec<LeverageTier>>;
1519/// `fetchDepositWithdrawFees` — currency code → [`DepositWithdrawFee`].
1520pub type DepositWithdrawFees = HashMap<String, DepositWithdrawFee>;
1521/// `fetchAllGreeks` — symbol → [`Greeks`].
1522pub type AllGreeks           = HashMap<String, Greeks>;
1523/// `fetchDepositAddresses` — currency code → [`DepositAddress`].
1524pub type DepositAddresses    = HashMap<String, DepositAddress>;
1525
1526/// Walk a `Value::Dict` of `<key> → Value` and decode each value with
1527/// the supplied `from_value` constructor. Returns an empty map on a
1528/// non-dict input — matches the lenient fallback semantics of the
1529/// individual `from_value` impls.
1530pub fn dict_from_value<T>(v: &Value, decode: fn(Value) -> T) -> HashMap<String, T> {
1531    match v {
1532        Value::Dict(d) => d.iter()
1533            .map(|(k, val)| (k.clone(), decode(val.clone())))
1534            .collect(),
1535        _ => HashMap::new(),
1536    }
1537}
1538
1539/// Walk a `Value::Arr` and decode each element with the supplied
1540/// `from_value` constructor.
1541pub fn vec_from_value<T>(v: &Value, decode: fn(Value) -> T) -> Vec<T> {
1542    match v {
1543        Value::Arr(rows) => rows.iter().map(|row| decode(row.clone())).collect(),
1544        _ => Vec::new(),
1545    }
1546}
1547
1548macro_rules! string_enum {
1549    ($(#[$m:meta])* $name:ident { $($v:ident => $s:literal),+ $(,)? }) => {
1550        $(#[$m])*
1551        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1552        pub enum $name { $($v),+ }
1553        impl $name {
1554            pub fn as_str(&self) -> &'static str { match self { $(Self::$v => $s),+ } }
1555        }
1556        impl std::fmt::Display for $name {
1557            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) }
1558        }
1559        impl std::str::FromStr for $name {
1560            type Err = String;
1561            fn from_str(s: &str) -> Result<Self, String> {
1562                match s { $($s => Ok(Self::$v),)+ _ => Err(format!("invalid {}: {}", stringify!($name), s)) }
1563            }
1564        }
1565    };
1566}
1567
1568string_enum!(
1569    /// TS `DefaultType` — `options.defaultType`.
1570    DefaultType { Spot => "spot", Margin => "margin", Option => "option", Swap => "swap", Future => "future" }
1571);
1572string_enum!(
1573    /// TS `DefaultSubType` — `options.defaultSubType`.
1574    DefaultSubType { Linear => "linear", Inverse => "inverse" }
1575);
1576
1577#[cfg(test)]
1578mod from_value_tests {
1579    use super::{Market, Order, OrderBook, MarginModification, Conversion, IsolatedBorrowRate, BorrowRate, PositionModeInfo, LastPrice, LeverageTier, DepositWithdrawFee, MarginLoan, Ticker, Trade, Position, Transaction, LedgerEntry, FundingRate, TradingFee, OpenInterest, Liquidation, Greeks};
1580    use crate::Value;
1581    use crate::value::HashMap;
1582
1583    fn dict(pairs: &[(&str, Value)]) -> Value {
1584        let mut m = HashMap::new();
1585        for (k, v) in pairs { m.insert(k.to_string(), v.clone()); }
1586        Value::Map(m)
1587    }
1588
1589    // Malformed order-book rows (non-array, too short, unparseable) must be
1590    // dropped, not emitted as [NaN, NaN] (review #7).
1591    #[test]
1592    fn order_book_drops_malformed_rows() {
1593        let row = |a: Value, b: Value| Value::Array(vec![a, b]);
1594        let bids = Value::Array(vec![
1595            row(Value::Str("100.5".into()), Value::Str("2".into())), // ok
1596            Value::Array(vec![Value::Str("bad".into()), Value::Int(1)]), // NaN price → drop
1597            Value::Array(vec![Value::Int(99)]),                          // missing amount → drop
1598            Value::Str("notarow".into()),                               // not an array → drop
1599            row(Value::Int(99), Value::Float(3.0)),                     // ok
1600        ]);
1601        let ob = OrderBook::from_value(dict(&[("bids", bids)]));
1602        assert_eq!(ob.bids.len(), 2, "malformed rows were not dropped: {:?}", ob.bids);
1603        assert_eq!(ob.bids[0], [100.5, 2.0]);
1604        assert_eq!(ob.bids[1], [99.0, 3.0]);
1605        assert!(ob.bids.iter().all(|r| !r[0].is_nan() && !r[1].is_nan()));
1606    }
1607
1608    #[test]
1609    fn market_assigns_declared_fields() {
1610        let v = dict(&[
1611            ("id", Value::Str("BTCUSDT".into())), ("symbol", Value::Str("BTC/USDT:USDT".into())),
1612            ("settle", Value::Str("USDT".into())), ("baseId", Value::Str("BTC".into())),
1613            ("quoteId", Value::Str("USDT".into())), ("margin", Value::Bool(true)),
1614            ("contract", Value::Bool(true)), ("linear", Value::Bool(true)), ("inverse", Value::Bool(false)),
1615        ]);
1616        let m = Market::from_value(v);
1617        assert_eq!(m.settle.as_deref(), Some("USDT"));
1618        assert_eq!(m.base_id, "BTC");
1619        assert_eq!(m.quote_id, "USDT");
1620        assert!(m.margin && m.contract);
1621        assert_eq!(m.linear, Some(true));
1622        assert_eq!(m.inverse, Some(false));
1623    }
1624
1625    #[test]
1626    fn order_assigns_fee() {
1627        let v = dict(&[
1628            ("id", Value::Str("1".into())),
1629            ("fee", dict(&[("currency", Value::Str("USDT".into())), ("cost", Value::Float(0.1))])),
1630        ]);
1631        let o = Order::from_value(v);
1632        let fee = o.fee.expect("fee should be assigned");
1633        assert_eq!(fee.get("currency"), Some(&Value::Str("USDT".into())));
1634    }
1635
1636    // The unified structs added for the typed-wrapper coverage push must
1637    // actually read the camelCase keys the TS parsers emit — a decoder that
1638    // reads the wrong key compiles green and silently yields all-`None`.
1639    #[test]
1640    fn margin_modification_reads_unified_keys() {
1641        let v = dict(&[
1642            ("symbol", Value::Str("BTC/USDT:USDT".into())),
1643            ("type", Value::Str("add".into())),
1644            ("marginMode", Value::Str("isolated".into())),
1645            ("amount", Value::Float(0.001)),
1646            ("code", Value::Str("USDT".into())),
1647            ("status", Value::Str("ok".into())),
1648            ("timestamp", Value::Int(1_700_000_000_000)),
1649        ]);
1650        let m = MarginModification::from_value(v);
1651        assert_eq!(m.symbol.as_deref(), Some("BTC/USDT:USDT"));
1652        assert_eq!(m.mod_type.as_deref(), Some("add"));
1653        assert_eq!(m.margin_mode.as_deref(), Some("isolated"));
1654        assert_eq!(m.amount, Some(0.001));
1655        assert_eq!(m.code.as_deref(), Some("USDT"));
1656        assert_eq!(m.status.as_deref(), Some("ok"));
1657        assert_eq!(m.timestamp, Some(1_700_000_000_000));
1658        assert_eq!(m.total, None);
1659    }
1660
1661    #[test]
1662    fn conversion_reads_unified_keys() {
1663        let v = dict(&[
1664            ("id", Value::Str("q1".into())),
1665            ("fromCurrency", Value::Str("BTC".into())),
1666            ("fromAmount", Value::Str("0.5".into())),
1667            ("toCurrency", Value::Str("USDT".into())),
1668            ("toAmount", Value::Float(20000.0)),
1669            ("price", Value::Int(40000)),
1670        ]);
1671        let c = Conversion::from_value(v);
1672        assert_eq!(c.id.as_deref(), Some("q1"));
1673        assert_eq!(c.from_currency.as_deref(), Some("BTC"));
1674        assert_eq!(c.from_amount, Some(0.5));
1675        assert_eq!(c.to_currency.as_deref(), Some("USDT"));
1676        assert_eq!(c.to_amount, Some(20000.0));
1677        assert_eq!(c.price, Some(40000.0));
1678        assert_eq!(c.fee, None);
1679    }
1680
1681    #[test]
1682    fn isolated_borrow_rate_is_not_the_cross_shape() {
1683        let v = dict(&[
1684            ("symbol", Value::Str("BTC/USDT".into())),
1685            ("base", Value::Str("BTC".into())),
1686            ("baseRate", Value::Float(0.0001)),
1687            ("quote", Value::Str("USDT".into())),
1688            ("quoteRate", Value::Float(0.0002)),
1689        ]);
1690        let r = IsolatedBorrowRate::from_value(v.clone());
1691        assert_eq!(r.symbol.as_deref(), Some("BTC/USDT"));
1692        assert_eq!(r.base_rate, Some(0.0001));
1693        assert_eq!(r.quote_rate, Some(0.0002));
1694        // The previous mapping (`IsolatedBorrowRate` → `BorrowRate`) lost every field.
1695        let wrong = BorrowRate::from_value(v);
1696        assert_eq!(wrong.currency, None);
1697        assert_eq!(wrong.rate, None);
1698    }
1699
1700    #[test]
1701    fn leverage_tiers_map_of_vec_and_deposit_withdraw_fee_nesting() {
1702        let tier = |n: f64| dict(&[("tier", Value::Float(n)), ("maxLeverage", Value::Int(20))]);
1703        let tiers = dict(&[("BTC/USDT:USDT", Value::Array(vec![tier(1.0), tier(2.0)]))]);
1704        let decoded = super::dict_from_value(&tiers, |row| super::vec_from_value(&row, LeverageTier::from_value));
1705        assert_eq!(decoded["BTC/USDT:USDT"].len(), 2);
1706        assert_eq!(decoded["BTC/USDT:USDT"][1].tier, Some(2.0));
1707        assert_eq!(decoded["BTC/USDT:USDT"][1].max_leverage, Some(20.0));
1708        let fee = DepositWithdrawFee::from_value(dict(&[
1709            ("withdraw", dict(&[("fee", Value::Float(0.0005)), ("percentage", Value::Bool(false))])),
1710            ("deposit", dict(&[("fee", Value::Null), ("percentage", Value::Null)])),
1711            ("networks", dict(&[("BTC", dict(&[
1712                ("withdraw", dict(&[("fee", Value::Str("0.0004".into())), ("percentage", Value::Bool(false))])),
1713                ("deposit", dict(&[("fee", Value::Int(0)), ("percentage", Value::Null)])),
1714            ]))])),
1715        ]));
1716        assert_eq!(fee.withdraw.fee, Some(0.0005));
1717        assert_eq!(fee.withdraw.percentage, Some(false));
1718        assert_eq!(fee.deposit.fee, None);
1719        assert_eq!(fee.networks["BTC"].withdraw.fee, Some(0.0004));
1720        assert_eq!(fee.networks["BTC"].deposit.fee, Some(0.0));
1721    }
1722
1723    #[test]
1724    fn position_mode_and_last_price_read_unified_keys() {
1725        let p = PositionModeInfo::from_value(dict(&[("hedged", Value::Bool(true))]));
1726        assert_eq!(p.hedged, Some(true));
1727        let lp = LastPrice::from_value(dict(&[
1728            ("symbol", Value::Str("ETH/USDT".into())),
1729            ("price", Value::Str("3000.5".into())),
1730            ("side", Value::Str("buy".into())),
1731        ]));
1732        assert_eq!(lp.symbol.as_deref(), Some("ETH/USDT"));
1733        assert_eq!(lp.price, Some(3000.5));
1734        assert_eq!(lp.side.as_deref(), Some("buy"));
1735    }
1736
1737    // Mirrors binance `parseMarginLoan`: `id` from `tranId`, `currency` from the
1738    // unified code, `symbol` undefined for cross margin. A decoder keyed on the
1739    // raw exchange fields (`tranId`/`asset`) would silently read all-`None`.
1740    #[test]
1741    fn margin_loan_reads_unified_keys() {
1742        let m = MarginLoan::from_value(dict(&[
1743            ("id", Value::Str("108988250265".into())),
1744            ("currency", Value::Str("USDC".into())),
1745            ("amount", Value::Int(10)),
1746            ("symbol", Value::Null),
1747            ("timestamp", Value::Int(1_727_170_761_267)),
1748            ("datetime", Value::Str("2024-09-24T09:39:21.267Z".into())),
1749            ("info", dict(&[("tranId", Value::Int(108988250265)), ("asset", Value::Str("USDC".into()))])),
1750        ]));
1751        assert_eq!(m.id.as_deref(), Some("108988250265"));
1752        assert_eq!(m.currency.as_deref(), Some("USDC"));
1753        assert_eq!(m.amount, Some(10.0));
1754        assert_eq!(m.symbol, None);
1755        assert_eq!(m.timestamp, Some(1_727_170_761_267));
1756        assert_eq!(m.datetime.as_deref(), Some("2024-09-24T09:39:21.267Z"));
1757        assert!(matches!(m.raw, Value::Dict(_)));
1758    }
1759
1760    // The core structs were narrower than their TS interfaces (Ticker lacked
1761    // `open`/`close`/`percentage`…, Trade lacked `fee`/`order`/`takerOrMaker`,
1762    // Position lacked `marginMode`/`liquidationPrice`…). Pin the widened
1763    // decoders to the unified camelCase keys the TS parsers emit.
1764    #[test]
1765    fn widened_core_structs_read_unified_keys() {
1766        let fee = dict(&[("currency", Value::Str("USDT".into())), ("cost", Value::Float(0.12)), ("rate", Value::Float(0.001))]);
1767        let t = Ticker::from_value(dict(&[
1768            ("symbol", Value::Str("BTC/USDT".into())),
1769            ("open", Value::Float(100.0)), ("close", Value::Float(110.0)),
1770            ("bidVolume", Value::Int(3)), ("askVolume", Value::Str("4.5".into())),
1771            ("vwap", Value::Float(105.0)), ("previousClose", Value::Float(99.0)),
1772            ("change", Value::Float(10.0)), ("percentage", Value::Float(10.0)),
1773            ("average", Value::Float(105.0)), ("indexPrice", Value::Float(109.0)), ("markPrice", Value::Float(109.5)),
1774        ]));
1775        assert_eq!(t.open, Some(100.0));
1776        assert_eq!(t.close, Some(110.0));
1777        assert_eq!(t.bid_volume, Some(3.0));
1778        assert_eq!(t.ask_volume, Some(4.5));
1779        assert_eq!(t.vwap, Some(105.0));
1780        assert_eq!(t.previous_close, Some(99.0));
1781        assert_eq!(t.change, Some(10.0));
1782        assert_eq!(t.percentage, Some(10.0));
1783        assert_eq!(t.average, Some(105.0));
1784        assert_eq!(t.index_price, Some(109.0));
1785        assert_eq!(t.mark_price, Some(109.5));
1786
1787        let tr = Trade::from_value(dict(&[
1788            ("id", Value::Str("t1".into())), ("order", Value::Str("o1".into())),
1789            ("type", Value::Str("limit".into())), ("takerOrMaker", Value::Str("maker".into())),
1790            ("fee", fee.clone()),
1791        ]));
1792        assert_eq!(tr.order.as_deref(), Some("o1"));
1793        assert_eq!(tr.trade_type.as_deref(), Some("limit"));
1794        assert_eq!(tr.taker_or_maker.as_deref(), Some("maker"));
1795        assert_eq!(tr.fee.as_ref().and_then(|f| f.cost), Some(0.12));
1796        assert_eq!(tr.fee.as_ref().and_then(|f| f.currency.clone()).as_deref(), Some("USDT"));
1797
1798        let o = Order::from_value(dict(&[
1799            ("id", Value::Str("o1".into())),
1800            ("timeInForce", Value::Str("GTC".into())),
1801            ("postOnly", Value::Bool(true)), ("reduceOnly", Value::Bool(false)),
1802            ("average", Value::Float(101.0)), ("triggerPrice", Value::Float(95.0)),
1803            ("stopLossPrice", Value::Float(90.0)), ("takeProfitPrice", Value::Float(120.0)),
1804            ("lastTradeTimestamp", Value::Int(1_700_000_000_001)),
1805            ("lastUpdateTimestamp", Value::Int(1_700_000_000_002)),
1806            ("trades", Value::Arr(std::sync::Arc::new(vec![dict(&[("id", Value::Str("t1".into())), ("amount", Value::Float(0.5))])]))),
1807        ]));
1808        assert_eq!(o.time_in_force.as_deref(), Some("GTC"));
1809        assert_eq!(o.post_only, Some(true));
1810        assert_eq!(o.reduce_only, Some(false));
1811        assert_eq!(o.average, Some(101.0));
1812        assert_eq!(o.trigger_price, Some(95.0));
1813        assert_eq!(o.stop_loss_price, Some(90.0));
1814        assert_eq!(o.take_profit_price, Some(120.0));
1815        assert_eq!(o.last_trade_timestamp, Some(1_700_000_000_001));
1816        assert_eq!(o.last_update_timestamp, Some(1_700_000_000_002));
1817        assert_eq!(o.trades.len(), 1);
1818        assert_eq!(o.trades[0].id.as_deref(), Some("t1"));
1819        assert_eq!(o.trades[0].amount, Some(0.5));
1820        // A missing `trades` key decodes to an empty Vec, not a panic.
1821        assert!(Order::from_value(dict(&[])).trades.is_empty());
1822
1823        let p = Position::from_value(dict(&[
1824            ("symbol", Value::Str("BTC/USDT:USDT".into())),
1825            ("marginMode", Value::Str("cross".into())), ("hedged", Value::Bool(false)),
1826            ("liquidationPrice", Value::Float(50000.0)), ("notional", Value::Float(1000.0)),
1827            ("collateral", Value::Float(100.0)), ("realizedPnl", Value::Float(1.5)),
1828            ("maintenanceMargin", Value::Float(5.0)), ("initialMargin", Value::Float(50.0)),
1829            ("marginRatio", Value::Float(0.05)), ("percentage", Value::Float(1.2)),
1830            ("lastUpdateTimestamp", Value::Int(1_700_000_000_003)),
1831        ]));
1832        assert_eq!(p.margin_mode.as_deref(), Some("cross"));
1833        assert_eq!(p.margin_type, None);
1834        assert_eq!(p.hedged, Some(false));
1835        assert_eq!(p.liquidation_price, Some(50000.0));
1836        assert_eq!(p.notional, Some(1000.0));
1837        assert_eq!(p.collateral, Some(100.0));
1838        assert_eq!(p.realized_pnl, Some(1.5));
1839        assert_eq!(p.maintenance_margin, Some(5.0));
1840        assert_eq!(p.initial_margin, Some(50.0));
1841        assert_eq!(p.margin_ratio, Some(0.05));
1842        assert_eq!(p.percentage, Some(1.2));
1843        assert_eq!(p.last_update_timestamp, Some(1_700_000_000_003));
1844
1845        let tx = Transaction::from_value(dict(&[
1846            ("type", Value::Str("withdrawal".into())), ("network", Value::Str("TRC20".into())),
1847            ("tag", Value::Str("memo".into())), ("addressTo", Value::Str("Txyz".into())),
1848            ("updated", Value::Int(1_700_000_000_004)), ("internal", Value::Bool(true)),
1849            ("comment", Value::Str("c".into())), ("fee", fee.clone()),
1850        ]));
1851        assert_eq!(tx.tx_type.as_deref(), Some("withdrawal"));
1852        assert_eq!(tx.network.as_deref(), Some("TRC20"));
1853        assert_eq!(tx.tag.as_deref(), Some("memo"));
1854        assert_eq!(tx.address_to.as_deref(), Some("Txyz"));
1855        assert_eq!(tx.updated, Some(1_700_000_000_004));
1856        assert_eq!(tx.internal, Some(true));
1857        assert_eq!(tx.comment.as_deref(), Some("c"));
1858        assert_eq!(tx.fee.as_ref().and_then(|f| f.rate), Some(0.001));
1859
1860        let le = LedgerEntry::from_value(dict(&[
1861            ("type", Value::Str("trade".into())), ("referenceId", Value::Str("r1".into())),
1862            ("before", Value::Float(10.0)), ("after", Value::Float(9.5)), ("status", Value::Str("ok".into())),
1863            ("fee", fee),
1864        ]));
1865        assert_eq!(le.entry_type.as_deref(), Some("trade"));
1866        assert_eq!(le.reference_id.as_deref(), Some("r1"));
1867        assert_eq!(le.before, Some(10.0));
1868        assert_eq!(le.after, Some(9.5));
1869        assert_eq!(le.status.as_deref(), Some("ok"));
1870        assert!(le.fee.is_some());
1871
1872        let fr = FundingRate::from_value(dict(&[
1873            ("fundingRate", Value::Float(0.0001)), ("markPrice", Value::Float(1.0)),
1874            ("nextFundingTimestamp", Value::Int(1_700_000_000_005)), ("interval", Value::Str("8h".into())),
1875            ("previousFundingRate", Value::Float(0.00005)),
1876        ]));
1877        assert_eq!(fr.mark_price, Some(1.0));
1878        assert_eq!(fr.next_funding_timestamp, Some(1_700_000_000_005));
1879        assert_eq!(fr.interval.as_deref(), Some("8h"));
1880        assert_eq!(fr.previous_funding_rate, Some(0.00005));
1881
1882        let tf = TradingFee::from_value(dict(&[("maker", Value::Float(0.001)), ("percentage", Value::Bool(true)), ("tierBased", Value::Bool(false))]));
1883        assert_eq!(tf.percentage, Some(true));
1884        assert_eq!(tf.tier_based, Some(false));
1885
1886        let oi = OpenInterest::from_value(dict(&[("baseVolume", Value::Float(12.0)), ("quoteVolume", Value::Float(1200.0))]));
1887        assert_eq!(oi.base_volume, Some(12.0));
1888        assert_eq!(oi.quote_volume, Some(1200.0));
1889
1890        let lq = Liquidation::from_value(dict(&[("contracts", Value::Float(2.0)), ("contractSize", Value::Float(0.01)), ("side", Value::Str("sell".into()))]));
1891        assert_eq!(lq.contracts, Some(2.0));
1892        assert_eq!(lq.contract_size, Some(0.01));
1893        assert_eq!(lq.side.as_deref(), Some("sell"));
1894
1895        let g = Greeks::from_value(dict(&[("bidImpliedVolatility", Value::Float(0.6)), ("underlyingPrice", Value::Float(60000.0)), ("charm", Value::Float(-0.01))]));
1896        assert_eq!(g.bid_implied_volatility, Some(0.6));
1897        assert_eq!(g.underlying_price, Some(60000.0));
1898        assert_eq!(g.charm, Some(-0.01));
1899
1900        assert_eq!(LeverageTier::from_value(dict(&[("symbol", Value::Str("ETH/USDT:USDT".into()))])).symbol.as_deref(), Some("ETH/USDT:USDT"));
1901    }
1902}