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/// A unified OHLCV candle: [timestamp, open, high, low, close, volume].
352pub type OHLCV = [f64; 6];
353
354/// Unified balance / account info.
355#[derive(Debug, Clone, Default)]
356pub struct Balances {
357    pub info:  Value,
358    pub free:  HashMap<String, f64>,
359    pub used:  HashMap<String, f64>,
360    pub total: HashMap<String, f64>,
361}
362
363impl Balances {
364    pub fn from_value(v: Value) -> Self {
365        use crate::value::get_value;
366        let mut b = Balances::default();
367        b.info = get_value(&v, &Value::Str("info".into()));
368        // The top-level `free`/`used`/`total` keys are dicts of
369        // `<currency-code> → number`. Walk them and collect.
370        let extract = |key: &str| -> HashMap<String, f64> {
371            let m = get_value(&v, &Value::Str(key.to_string().into()));
372            match m {
373                Value::Dict(d) => d.iter().filter_map(|(k, val)| {
374                    let n = match val {
375                        Value::Float(f) => Some(*f),
376                        Value::Int(n)   => Some(*n as f64),
377                        Value::Str(s)   => s.parse().ok(),
378                        _ => None,
379                    }?;
380                    Some((k.clone(), n))
381                }).collect(),
382                _ => HashMap::new(),
383            }
384        };
385        b.free  = extract("free");
386        b.used  = extract("used");
387        b.total = extract("total");
388        b
389    }
390}
391
392/// Unified transaction (deposit / withdrawal). Mirrors the TS `Transaction` interface.
393#[derive(Debug, Clone, Default)]
394pub struct Transaction {
395    pub id:           Option<String>,
396    pub txid:         Option<String>,
397    pub timestamp:    Option<i64>,
398    pub datetime:     Option<String>,
399    pub address:      Option<String>,
400    pub address_from: Option<String>,
401    pub address_to:   Option<String>,
402    pub tag:          Option<String>,
403    pub tag_from:     Option<String>,
404    pub tag_to:       Option<String>,
405    pub tx_type:      Option<String>,   // "deposit" | "withdrawal"
406    pub amount:       Option<f64>,
407    pub currency:     Option<String>,
408    pub status:       Option<String>,   // "pending" | "ok" | "failed" | "canceled"
409    pub updated:      Option<i64>,
410    pub fee:          Option<Fee>,
411    pub network:      Option<String>,
412    pub comment:      Option<String>,
413    pub internal:     Option<bool>,
414    pub raw:          Value,
415}
416
417impl Transaction {
418    pub fn from_value(v: Value) -> Self {
419        use crate::value::{safe_string, safe_number, safe_integer, safe_bool};
420        let mut t = Transaction::default();
421        t.id           = safe_string(&v, "id",          None);
422        t.txid         = safe_string(&v, "txid",        None);
423        t.timestamp    = safe_integer(&v, "timestamp",  None);
424        t.datetime     = safe_string(&v, "datetime",    None);
425        t.address      = safe_string(&v, "address",     None);
426        t.address_from = safe_string(&v, "addressFrom", None);
427        t.address_to   = safe_string(&v, "addressTo",   None);
428        t.tag          = safe_string(&v, "tag",         None);
429        t.tag_from     = safe_string(&v, "tagFrom",     None);
430        t.tag_to       = safe_string(&v, "tagTo",       None);
431        t.tx_type      = safe_string(&v, "type",        None);
432        t.amount       = safe_number(&v, "amount",      None);
433        t.currency     = safe_string(&v, "currency",    None);
434        t.status       = safe_string(&v, "status",      None);
435        t.updated      = safe_integer(&v, "updated",    None);
436        t.fee          = match crate::get_value(&v, &Value::Str("fee".into())) {
437            fee @ Value::Dict(_) => Some(Fee::from_value(fee)),
438            _ => None,
439        };
440        t.network      = safe_string(&v, "network",     None);
441        t.comment      = safe_string(&v, "comment",     None);
442        t.internal     = safe_bool(&v, "internal",      None);
443        t.raw = v;
444        t
445    }
446}
447
448/// Unified currency descriptor.
449#[derive(Debug, Clone, Default)]
450pub struct Currency {
451    pub id:        String,
452    pub code:      String,
453    pub name:      Option<String>,
454    pub active:    bool,
455    pub precision: Option<f64>,
456    pub raw:       Value,
457}
458
459impl Currency {
460    pub fn from_value(v: Value) -> Self {
461        use crate::value::{safe_string, safe_bool, safe_number};
462        let mut c = Currency::default();
463        c.id        = safe_string(&v, "id",   None).unwrap_or_default();
464        c.code      = safe_string(&v, "code", None).unwrap_or_default();
465        c.name      = safe_string(&v, "name", None);
466        c.active    = safe_bool(&v, "active", Some(true)).unwrap_or(true);
467        c.precision = safe_number(&v, "precision", None);
468        c.raw = v;
469        c
470    }
471}
472
473/// Unified position (derivatives). Mirrors the TS `Position` interface.
474#[derive(Debug, Clone, Default)]
475pub struct Position {
476    pub id:               Option<String>,
477    pub symbol:           String,
478    pub timestamp:        Option<i64>,
479    pub datetime:         Option<String>,
480    pub side:             Option<String>,
481    pub contracts:        Option<f64>,
482    pub contract_size:    Option<f64>,
483    pub notional:         Option<f64>,
484    pub entry_price:      Option<f64>,
485    pub mark_price:       Option<f64>,
486    pub last_price:       Option<f64>,
487    pub liquidation_price: Option<f64>,
488    pub unrealized_pnl:   Option<f64>,
489    pub realized_pnl:     Option<f64>,
490    pub collateral:       Option<f64>,
491    pub leverage:         Option<f64>,
492    /// Unified `marginMode` ("cross" | "isolated").
493    pub margin_mode:      Option<String>,
494    /// Deprecated `marginType` key still emitted by a few venues; prefer `margin_mode`.
495    pub margin_type:      Option<String>,
496    pub hedged:           Option<bool>,
497    pub maintenance_margin:            Option<f64>,
498    pub maintenance_margin_percentage: Option<f64>,
499    pub initial_margin:                Option<f64>,
500    pub initial_margin_percentage:     Option<f64>,
501    pub margin_ratio:     Option<f64>,
502    pub percentage:       Option<f64>,
503    pub last_update_timestamp: Option<i64>,
504    pub stop_loss_price:   Option<f64>,
505    pub take_profit_price: Option<f64>,
506    pub raw:              Value,
507}
508
509impl Position {
510    pub fn from_value(v: Value) -> Self {
511        use crate::value::{safe_string, safe_number, safe_integer, safe_bool};
512        let mut p = Position::default();
513        p.id             = safe_string(&v, "id",     None);
514        p.symbol         = safe_string(&v, "symbol", None).unwrap_or_default();
515        p.timestamp      = safe_integer(&v, "timestamp", None);
516        p.datetime       = safe_string(&v, "datetime",   None);
517        p.side           = safe_string(&v, "side",   None);
518        p.contracts      = safe_number(&v, "contracts",    None);
519        p.contract_size  = safe_number(&v, "contractSize", None);
520        p.notional       = safe_number(&v, "notional",     None);
521        p.entry_price    = safe_number(&v, "entryPrice",   None);
522        p.mark_price     = safe_number(&v, "markPrice",    None);
523        p.last_price     = safe_number(&v, "lastPrice",    None);
524        p.liquidation_price = safe_number(&v, "liquidationPrice", None);
525        p.unrealized_pnl = safe_number(&v, "unrealizedPnl", None);
526        p.realized_pnl   = safe_number(&v, "realizedPnl",   None);
527        p.collateral     = safe_number(&v, "collateral",   None);
528        p.leverage       = safe_number(&v, "leverage",     None);
529        p.margin_mode    = safe_string(&v, "marginMode",   None);
530        p.margin_type    = safe_string(&v, "marginType",   None);
531        p.hedged         = safe_bool(&v, "hedged",         None);
532        p.maintenance_margin            = safe_number(&v, "maintenanceMargin",           None);
533        p.maintenance_margin_percentage = safe_number(&v, "maintenanceMarginPercentage", None);
534        p.initial_margin                = safe_number(&v, "initialMargin",               None);
535        p.initial_margin_percentage     = safe_number(&v, "initialMarginPercentage",     None);
536        p.margin_ratio   = safe_number(&v, "marginRatio",  None);
537        p.percentage     = safe_number(&v, "percentage",   None);
538        p.last_update_timestamp = safe_integer(&v, "lastUpdateTimestamp", None);
539        p.stop_loss_price   = safe_number(&v, "stopLossPrice",   None);
540        p.take_profit_price = safe_number(&v, "takeProfitPrice", None);
541        p.raw = v;
542        p
543    }
544}
545
546/// Unified transfer record.
547#[derive(Debug, Clone, Default)]
548pub struct Transfer {
549    pub id:        Option<String>,
550    pub timestamp: Option<i64>,
551    pub datetime:  Option<String>,
552    pub currency:  Option<String>,
553    pub amount:    Option<f64>,
554    pub from_account: Option<String>,
555    pub to_account:   Option<String>,
556    pub status:    Option<String>,
557    pub raw:       Value,
558}
559
560impl Transfer {
561    pub fn from_value(v: Value) -> Self {
562        use crate::value::{safe_string, safe_number, safe_integer};
563        let mut t = Transfer::default();
564        t.id           = safe_string(&v, "id",        None);
565        t.timestamp    = safe_integer(&v, "timestamp", None);
566        t.datetime     = safe_string(&v, "datetime",  None);
567        t.currency     = safe_string(&v, "currency",  None);
568        t.amount       = safe_number(&v, "amount",    None);
569        t.from_account = safe_string(&v, "fromAccount", None);
570        t.to_account   = safe_string(&v, "toAccount",   None);
571        t.status       = safe_string(&v, "status",   None);
572        t.raw = v;
573        t
574    }
575}
576
577/// Unified ledger entry. Mirrors the TS `LedgerEntry` interface.
578#[derive(Debug, Clone, Default)]
579pub struct LedgerEntry {
580    pub id:        Option<String>,
581    pub timestamp: Option<i64>,
582    pub datetime:  Option<String>,
583    pub direction: Option<String>,   // "in" | "out"
584    pub account:   Option<String>,
585    pub reference_id:      Option<String>,
586    pub reference_account: Option<String>,
587    pub entry_type: Option<String>,  // "trade" | "transaction" | "fee" | …
588    pub amount:    Option<f64>,
589    pub currency:  Option<String>,
590    pub before:    Option<f64>,
591    pub after:     Option<f64>,
592    pub status:    Option<String>,
593    pub fee:       Option<Fee>,
594    pub raw:       Value,
595}
596
597impl LedgerEntry {
598    pub fn from_value(v: Value) -> Self {
599        use crate::value::{safe_string, safe_number, safe_integer};
600        let mut l = LedgerEntry::default();
601        l.id        = safe_string(&v, "id",        None);
602        l.timestamp = safe_integer(&v, "timestamp", None);
603        l.datetime  = safe_string(&v, "datetime",  None);
604        l.direction = safe_string(&v, "direction", None);
605        l.account   = safe_string(&v, "account",   None);
606        l.reference_id      = safe_string(&v, "referenceId",      None);
607        l.reference_account = safe_string(&v, "referenceAccount", None);
608        l.entry_type = safe_string(&v, "type",     None);
609        l.amount    = safe_number(&v, "amount",    None);
610        l.currency  = safe_string(&v, "currency",  None);
611        l.before    = safe_number(&v, "before",    None);
612        l.after     = safe_number(&v, "after",     None);
613        l.status    = safe_string(&v, "status",    None);
614        l.fee       = match crate::get_value(&v, &Value::Str("fee".into())) {
615            fee @ Value::Dict(_) => Some(Fee::from_value(fee)),
616            _ => None,
617        };
618        l.raw = v;
619        l
620    }
621}
622
623/// Unified funding rate. Mirrors the TS `FundingRate` interface.
624#[derive(Debug, Clone, Default)]
625pub struct FundingRate {
626    pub symbol:        String,
627    pub funding_rate:  Option<f64>,
628    pub timestamp:     Option<i64>,
629    pub datetime:      Option<String>,
630    pub mark_price:    Option<f64>,
631    pub index_price:   Option<f64>,
632    pub interest_rate: Option<f64>,
633    pub estimated_settle_price: Option<f64>,
634    pub funding_timestamp: Option<i64>,
635    pub funding_datetime:  Option<String>,
636    pub next_funding_timestamp: Option<i64>,
637    pub next_funding_datetime:  Option<String>,
638    pub next_funding_rate:      Option<f64>,
639    pub previous_funding_timestamp: Option<i64>,
640    pub previous_funding_datetime:  Option<String>,
641    pub previous_funding_rate:      Option<f64>,
642    pub interval:      Option<String>,
643    pub raw:           Value,
644}
645
646impl FundingRate {
647    pub fn from_value(v: Value) -> Self {
648        use crate::value::{safe_string, safe_number, safe_integer};
649        let mut f = FundingRate::default();
650        f.symbol       = safe_string(&v, "symbol", None).unwrap_or_default();
651        f.funding_rate = safe_number(&v, "fundingRate", None);
652        f.timestamp    = safe_integer(&v, "timestamp", None);
653        f.datetime     = safe_string(&v, "datetime", None);
654        f.mark_price    = safe_number(&v, "markPrice",    None);
655        f.index_price   = safe_number(&v, "indexPrice",   None);
656        f.interest_rate = safe_number(&v, "interestRate", None);
657        f.estimated_settle_price = safe_number(&v, "estimatedSettlePrice", None);
658        f.funding_timestamp = safe_integer(&v, "fundingTimestamp", None);
659        f.funding_datetime  = safe_string(&v, "fundingDatetime",   None);
660        f.next_funding_timestamp = safe_integer(&v, "nextFundingTimestamp", None);
661        f.next_funding_datetime  = safe_string(&v, "nextFundingDatetime",   None);
662        f.next_funding_rate      = safe_number(&v, "nextFundingRate",       None);
663        f.previous_funding_timestamp = safe_integer(&v, "previousFundingTimestamp", None);
664        f.previous_funding_datetime  = safe_string(&v, "previousFundingDatetime",   None);
665        f.previous_funding_rate      = safe_number(&v, "previousFundingRate",       None);
666        f.interval     = safe_string(&v, "interval", None);
667        f.raw = v;
668        f
669    }
670}
671
672/// Unified greeks (options). Mirrors the TS `Greeks` interface.
673#[derive(Debug, Clone, Default)]
674pub struct Greeks {
675    pub symbol:    String,
676    pub timestamp: Option<i64>,
677    pub datetime:  Option<String>,
678    pub delta:     Option<f64>,
679    pub gamma:     Option<f64>,
680    pub theta:     Option<f64>,
681    pub vega:      Option<f64>,
682    pub rho:       Option<f64>,
683    pub vanna:     Option<f64>,
684    pub volga:     Option<f64>,
685    pub charm:     Option<f64>,
686    pub bid_size:  Option<f64>,
687    pub ask_size:  Option<f64>,
688    pub bid_implied_volatility:  Option<f64>,
689    pub ask_implied_volatility:  Option<f64>,
690    pub mark_implied_volatility: Option<f64>,
691    pub bid_price:  Option<f64>,
692    pub ask_price:  Option<f64>,
693    pub mark_price: Option<f64>,
694    pub last_price: Option<f64>,
695    pub underlying_price: Option<f64>,
696    pub raw:       Value,
697}
698
699impl Greeks {
700    pub fn from_value(v: Value) -> Self {
701        use crate::value::{safe_string, safe_number, safe_integer};
702        let mut g = Greeks::default();
703        g.symbol    = safe_string(&v, "symbol", None).unwrap_or_default();
704        g.timestamp = safe_integer(&v, "timestamp", None);
705        g.datetime  = safe_string(&v, "datetime",  None);
706        g.delta  = safe_number(&v, "delta", None);
707        g.gamma  = safe_number(&v, "gamma", None);
708        g.theta  = safe_number(&v, "theta", None);
709        g.vega   = safe_number(&v, "vega",  None);
710        g.rho    = safe_number(&v, "rho",   None);
711        g.vanna  = safe_number(&v, "vanna", None);
712        g.volga  = safe_number(&v, "volga", None);
713        g.charm  = safe_number(&v, "charm", None);
714        g.bid_size = safe_number(&v, "bidSize", None);
715        g.ask_size = safe_number(&v, "askSize", None);
716        g.bid_implied_volatility  = safe_number(&v, "bidImpliedVolatility",  None);
717        g.ask_implied_volatility  = safe_number(&v, "askImpliedVolatility",  None);
718        g.mark_implied_volatility = safe_number(&v, "markImpliedVolatility", None);
719        g.bid_price  = safe_number(&v, "bidPrice",  None);
720        g.ask_price  = safe_number(&v, "askPrice",  None);
721        g.mark_price = safe_number(&v, "markPrice", None);
722        g.last_price = safe_number(&v, "lastPrice", None);
723        g.underlying_price = safe_number(&v, "underlyingPrice", None);
724        g.raw = v;
725        g
726    }
727}
728
729/// A single trading-fee descriptor (per currency or per side).
730#[derive(Debug, Clone, Default)]
731pub struct Fee {
732    pub currency: Option<String>,
733    pub cost:     Option<f64>,
734    pub rate:     Option<f64>,
735    pub raw:      Value,
736}
737
738impl Fee {
739    pub fn from_value(v: Value) -> Self {
740        use crate::value::{safe_string, safe_number};
741        let mut f = Fee::default();
742        f.currency = safe_string(&v, "currency", None);
743        f.cost     = safe_number(&v, "cost",     None);
744        f.rate     = safe_number(&v, "rate",     None);
745        f.raw = v;
746        f
747    }
748}
749
750/// Unified trading-fee descriptor (per-symbol maker / taker).
751#[derive(Debug, Clone, Default)]
752pub struct TradingFee {
753    pub symbol:     Option<String>,
754    pub maker:      Option<f64>,
755    pub taker:      Option<f64>,
756    pub percentage: Option<bool>,
757    pub tier_based: Option<bool>,
758    pub raw:        Value,
759}
760
761impl TradingFee {
762    pub fn from_value(v: Value) -> Self {
763        use crate::value::{safe_string, safe_number, safe_bool};
764        let mut t = TradingFee::default();
765        t.symbol     = safe_string(&v, "symbol", None);
766        t.maker      = safe_number(&v, "maker",  None);
767        t.taker      = safe_number(&v, "taker",  None);
768        t.percentage = safe_bool(&v, "percentage", None);
769        t.tier_based = safe_bool(&v, "tierBased",  None);
770        t.raw = v;
771        t
772    }
773}
774
775/// Unified liquidation record.
776#[derive(Debug, Clone, Default)]
777pub struct Liquidation {
778    pub symbol:    String,
779    pub timestamp: Option<i64>,
780    pub datetime:  Option<String>,
781    pub price:     Option<f64>,
782    pub base_value:  Option<f64>,
783    pub quote_value: Option<f64>,
784    pub contracts:     Option<f64>,
785    pub contract_size: Option<f64>,
786    pub side:      Option<String>,   // "buy" | "sell"
787    pub raw:       Value,
788}
789
790impl Liquidation {
791    pub fn from_value(v: Value) -> Self {
792        use crate::value::{safe_string, safe_number, safe_integer};
793        let mut l = Liquidation::default();
794        l.symbol      = safe_string(&v, "symbol", None).unwrap_or_default();
795        l.timestamp   = safe_integer(&v, "timestamp", None);
796        l.datetime    = safe_string(&v, "datetime", None);
797        l.price       = safe_number(&v, "price", None);
798        l.base_value  = safe_number(&v, "baseValue",  None);
799        l.quote_value = safe_number(&v, "quoteValue", None);
800        l.contracts     = safe_number(&v, "contracts",    None);
801        l.contract_size = safe_number(&v, "contractSize", None);
802        l.side        = safe_string(&v, "side", None);
803        l.raw = v;
804        l
805    }
806}
807
808/// Unified open-interest snapshot.
809#[derive(Debug, Clone, Default)]
810pub struct OpenInterest {
811    pub symbol:    String,
812    pub timestamp: Option<i64>,
813    pub datetime:  Option<String>,
814    pub open_interest_amount: Option<f64>,
815    pub open_interest_value:  Option<f64>,
816    pub base_volume:  Option<f64>,
817    pub quote_volume: Option<f64>,
818    pub raw:       Value,
819}
820
821impl OpenInterest {
822    pub fn from_value(v: Value) -> Self {
823        use crate::value::{safe_string, safe_number, safe_integer};
824        let mut o = OpenInterest::default();
825        o.symbol    = safe_string(&v, "symbol", None).unwrap_or_default();
826        o.timestamp = safe_integer(&v, "timestamp", None);
827        o.datetime  = safe_string(&v, "datetime",  None);
828        o.open_interest_amount = safe_number(&v, "openInterestAmount", None);
829        o.open_interest_value  = safe_number(&v, "openInterestValue",  None);
830        o.base_volume  = safe_number(&v, "baseVolume",  None);
831        o.quote_volume = safe_number(&v, "quoteVolume", None);
832        o.raw = v;
833        o
834    }
835}
836
837/// Exchange-wide status snapshot.
838#[derive(Debug, Clone, Default)]
839pub struct Status {
840    pub status:    Option<String>,
841    pub updated:   Option<i64>,
842    pub eta:       Option<i64>,
843    pub url:       Option<String>,
844    pub raw:       Value,
845}
846
847impl Status {
848    pub fn from_value(v: Value) -> Self {
849        use crate::value::{safe_string, safe_integer};
850        let mut s = Status::default();
851        s.status  = safe_string(&v, "status", None);
852        s.updated = safe_integer(&v, "updated", None);
853        s.eta     = safe_integer(&v, "eta",     None);
854        s.url     = safe_string(&v, "url",     None);
855        s.raw = v;
856        s
857    }
858}
859
860/// Unified margin mode per symbol.
861#[derive(Debug, Clone, Default)]
862pub struct MarginMode {
863    pub symbol:      Option<String>,
864    pub margin_mode: Option<String>,
865    pub raw:         Value,
866}
867
868impl MarginMode {
869    pub fn from_value(v: Value) -> Self {
870        use crate::value::safe_string;
871        let mut m = MarginMode::default();
872        m.symbol      = safe_string(&v, "symbol", None);
873        m.margin_mode = safe_string(&v, "marginMode", None);
874        m.raw = v;
875        m
876    }
877}
878
879/// Unified leverage per symbol.
880#[derive(Debug, Clone, Default)]
881pub struct Leverage {
882    pub symbol:        Option<String>,
883    pub margin_mode:   Option<String>,
884    pub long_leverage: Option<f64>,
885    pub short_leverage: Option<f64>,
886    pub raw:           Value,
887}
888
889impl Leverage {
890    pub fn from_value(v: Value) -> Self {
891        use crate::value::{safe_string, safe_number};
892        let mut l = Leverage::default();
893        l.symbol         = safe_string(&v, "symbol", None);
894        l.margin_mode    = safe_string(&v, "marginMode", None);
895        l.long_leverage  = safe_number(&v, "longLeverage", None);
896        l.short_leverage = safe_number(&v, "shortLeverage", None);
897        l.raw = v;
898        l
899    }
900}
901
902/// One bracket in a leverage-tier ladder.
903#[derive(Debug, Clone, Default)]
904pub struct LeverageTier {
905    pub tier:           Option<f64>,
906    pub symbol:         Option<String>,
907    pub currency:       Option<String>,
908    pub min_notional:   Option<f64>,
909    pub max_notional:   Option<f64>,
910    pub maintenance_margin_rate: Option<f64>,
911    pub max_leverage:   Option<f64>,
912    pub raw:            Value,
913}
914
915impl LeverageTier {
916    pub fn from_value(v: Value) -> Self {
917        use crate::value::{safe_string, safe_number};
918        let mut t = LeverageTier::default();
919        t.tier           = safe_number(&v, "tier", None);
920        t.symbol         = safe_string(&v, "symbol", None);
921        t.currency       = safe_string(&v, "currency", None);
922        t.min_notional   = safe_number(&v, "minNotional", None);
923        t.max_notional   = safe_number(&v, "maxNotional", None);
924        t.maintenance_margin_rate = safe_number(&v, "maintenanceMarginRate", None);
925        t.max_leverage   = safe_number(&v, "maxLeverage", None);
926        t.raw = v;
927        t
928    }
929}
930
931/// Unified borrow / lending rate.
932#[derive(Debug, Clone, Default)]
933pub struct BorrowRate {
934    pub currency:  Option<String>,
935    pub rate:      Option<f64>,
936    pub period:    Option<i64>,
937    pub timestamp: Option<i64>,
938    pub datetime:  Option<String>,
939    pub raw:       Value,
940}
941
942impl BorrowRate {
943    pub fn from_value(v: Value) -> Self {
944        use crate::value::{safe_string, safe_number, safe_integer};
945        let mut r = BorrowRate::default();
946        r.currency  = safe_string(&v, "currency", None);
947        r.rate      = safe_number(&v, "rate", None);
948        r.period    = safe_integer(&v, "period", None);
949        r.timestamp = safe_integer(&v, "timestamp", None);
950        r.datetime  = safe_string(&v, "datetime", None);
951        r.raw = v;
952        r
953    }
954}
955
956/// Unified borrow-interest record (margin interest accrued on a borrow).
957/// Distinct from `BorrowRate` — it carries accrued interest and the borrowed
958/// amount, not a periodic rate (review #7: `fetchBorrowInterest` was wrongly
959/// mapped to `BorrowRate`).
960#[derive(Debug, Clone, Default)]
961pub struct BorrowInterest {
962    pub symbol:          Option<String>,
963    pub currency:        Option<String>,
964    pub interest:        Option<f64>,
965    pub interest_rate:   Option<f64>,
966    pub amount_borrowed: Option<f64>,
967    pub margin_mode:     Option<String>,
968    pub timestamp:       Option<i64>,
969    pub datetime:        Option<String>,
970    pub raw:             Value,
971}
972
973impl BorrowInterest {
974    pub fn from_value(v: Value) -> Self {
975        use crate::value::{safe_string, safe_number, safe_integer};
976        let mut r = BorrowInterest::default();
977        r.symbol          = safe_string(&v, "symbol", None);
978        r.currency        = safe_string(&v, "currency", None);
979        r.interest        = safe_number(&v, "interest", None);
980        r.interest_rate   = safe_number(&v, "interestRate", None);
981        r.amount_borrowed = safe_number(&v, "amountBorrowed", None);
982        r.margin_mode     = safe_string(&v, "marginMode", None);
983        r.timestamp       = safe_integer(&v, "timestamp", None);
984        r.datetime        = safe_string(&v, "datetime", None);
985        r.raw = v;
986        r
987    }
988}
989
990/// Unified deposit address.
991#[derive(Debug, Clone, Default)]
992pub struct DepositAddress {
993    pub currency: Option<String>,
994    pub address:  Option<String>,
995    pub tag:      Option<String>,
996    pub network:  Option<String>,
997    pub raw:      Value,
998}
999
1000impl DepositAddress {
1001    pub fn from_value(v: Value) -> Self {
1002        use crate::value::safe_string;
1003        let mut d = DepositAddress::default();
1004        d.currency = safe_string(&v, "currency", None);
1005        d.address  = safe_string(&v, "address", None);
1006        d.tag      = safe_string(&v, "tag", None);
1007        d.network  = safe_string(&v, "network", None);
1008        d.raw = v;
1009        d
1010    }
1011}
1012
1013/// Unified margin modification — the result of `addMargin` / `reduceMargin` /
1014/// `setMargin`, and each row of `fetchMarginAdjustmentHistory`. Mirrors the TS
1015/// `MarginModification` interface (`ts/src/base/types.ts`).
1016#[derive(Debug, Clone, Default)]
1017pub struct MarginModification {
1018    pub symbol:      Option<String>,
1019    pub mod_type:    Option<String>,   // "add" | "reduce" | "set"
1020    pub margin_mode: Option<String>,   // "cross" | "isolated"
1021    pub amount:      Option<f64>,
1022    pub total:       Option<f64>,
1023    pub code:        Option<String>,
1024    pub status:      Option<String>,
1025    pub timestamp:   Option<i64>,
1026    pub datetime:    Option<String>,
1027    pub raw:         Value,
1028}
1029
1030impl MarginModification {
1031    pub fn from_value(v: Value) -> Self {
1032        use crate::value::{safe_string, safe_number, safe_integer};
1033        let mut m = MarginModification::default();
1034        m.symbol      = safe_string(&v, "symbol",     None);
1035        m.mod_type    = safe_string(&v, "type",       None);
1036        m.margin_mode = safe_string(&v, "marginMode", None);
1037        m.amount      = safe_number(&v, "amount",     None);
1038        m.total       = safe_number(&v, "total",      None);
1039        m.code        = safe_string(&v, "code",       None);
1040        m.status      = safe_string(&v, "status",     None);
1041        m.timestamp   = safe_integer(&v, "timestamp", None);
1042        m.datetime    = safe_string(&v, "datetime",   None);
1043        m.raw = v;
1044        m
1045    }
1046}
1047
1048/// Unified margin borrow/repay receipt returned by `borrowCrossMargin`,
1049/// `borrowIsolatedMargin`, `repayCrossMargin` and `repayIsolatedMargin`.
1050/// Mirrors the TS `MarginLoan` interface (`ts/src/base/types.ts`): every
1051/// venue's `parseMarginLoan` emits exactly `id`/`currency`/`amount`/`symbol`/
1052/// `timestamp`/`datetime` (+ `info`).
1053#[derive(Debug, Clone, Default)]
1054pub struct MarginLoan {
1055    pub id:        Option<String>,
1056    pub currency:  Option<String>,
1057    pub amount:    Option<f64>,
1058    pub symbol:    Option<String>,
1059    pub timestamp: Option<i64>,
1060    pub datetime:  Option<String>,
1061    pub raw:       Value,
1062}
1063
1064impl MarginLoan {
1065    pub fn from_value(v: Value) -> Self {
1066        use crate::value::{safe_string, safe_number, safe_integer};
1067        let mut m = MarginLoan::default();
1068        m.id        = safe_string(&v, "id",        None);
1069        m.currency  = safe_string(&v, "currency",  None);
1070        m.amount    = safe_number(&v, "amount",    None);
1071        m.symbol    = safe_string(&v, "symbol",    None);
1072        m.timestamp = safe_integer(&v, "timestamp", None);
1073        m.datetime  = safe_string(&v, "datetime",  None);
1074        m.raw = v;
1075        m
1076    }
1077}
1078
1079/// Unified currency-conversion record (`fetchConvertQuote`, `createConvertTrade`,
1080/// `fetchConvertTrade`, and each row of `fetchConvertTradeHistory`). Mirrors the
1081/// TS `Conversion` interface.
1082#[derive(Debug, Clone, Default)]
1083pub struct Conversion {
1084    pub id:            Option<String>,
1085    pub timestamp:     Option<i64>,
1086    pub datetime:      Option<String>,
1087    pub from_currency: Option<String>,
1088    pub from_amount:   Option<f64>,
1089    pub to_currency:   Option<String>,
1090    pub to_amount:     Option<f64>,
1091    pub price:         Option<f64>,
1092    pub fee:           Option<f64>,
1093    pub raw:           Value,
1094}
1095
1096impl Conversion {
1097    pub fn from_value(v: Value) -> Self {
1098        use crate::value::{safe_string, safe_number, safe_integer};
1099        let mut c = Conversion::default();
1100        c.id            = safe_string(&v, "id",           None);
1101        c.timestamp     = safe_integer(&v, "timestamp",   None);
1102        c.datetime      = safe_string(&v, "datetime",     None);
1103        c.from_currency = safe_string(&v, "fromCurrency", None);
1104        c.from_amount   = safe_number(&v, "fromAmount",   None);
1105        c.to_currency   = safe_string(&v, "toCurrency",   None);
1106        c.to_amount     = safe_number(&v, "toAmount",     None);
1107        c.price         = safe_number(&v, "price",        None);
1108        c.fee           = safe_number(&v, "fee",          None);
1109        c.raw = v;
1110        c
1111    }
1112}
1113
1114/// Unified auto-deleveraging rank (`fetchADLRank`, `fetchPositionADLRank`,
1115/// and each row of `fetchPositionsADLRank`). Mirrors the TS `ADL` interface.
1116#[derive(Debug, Clone, Default)]
1117pub struct ADL {
1118    pub symbol:     Option<String>,
1119    pub rank:       Option<i64>,
1120    pub rating:     Option<String>,
1121    pub percentage: Option<f64>,
1122    pub timestamp:  Option<i64>,
1123    pub datetime:   Option<String>,
1124    pub raw:        Value,
1125}
1126
1127impl ADL {
1128    pub fn from_value(v: Value) -> Self {
1129        use crate::value::{safe_string, safe_number, safe_integer};
1130        let mut a = ADL::default();
1131        a.symbol     = safe_string(&v, "symbol",     None);
1132        a.rank       = safe_integer(&v, "rank",      None);
1133        a.rating     = safe_string(&v, "rating",     None);
1134        a.percentage = safe_number(&v, "percentage", None);
1135        a.timestamp  = safe_integer(&v, "timestamp", None);
1136        a.datetime   = safe_string(&v, "datetime",   None);
1137        a.raw = v;
1138        a
1139    }
1140}
1141
1142/// Unified long/short ratio (`fetchLongShortRatio`, and each row of
1143/// `fetchLongShortRatioHistory`). Mirrors the TS `LongShortRatio` interface.
1144#[derive(Debug, Clone, Default)]
1145pub struct LongShortRatio {
1146    pub symbol:           Option<String>,
1147    pub timestamp:        Option<i64>,
1148    pub datetime:         Option<String>,
1149    pub timeframe:        Option<String>,
1150    pub long_short_ratio: Option<f64>,
1151    pub raw:              Value,
1152}
1153
1154impl LongShortRatio {
1155    pub fn from_value(v: Value) -> Self {
1156        use crate::value::{safe_string, safe_number, safe_integer};
1157        let mut r = LongShortRatio::default();
1158        r.symbol           = safe_string(&v, "symbol",         None);
1159        r.timestamp        = safe_integer(&v, "timestamp",     None);
1160        r.datetime         = safe_string(&v, "datetime",       None);
1161        r.timeframe        = safe_string(&v, "timeframe",      None);
1162        r.long_short_ratio = safe_number(&v, "longShortRatio", None);
1163        r.raw = v;
1164        r
1165    }
1166}
1167
1168/// One historical funding-rate sample (each row of `fetchFundingRateHistory`).
1169/// Mirrors the TS `FundingRateHistory` interface. Distinct from
1170/// [`FundingRate`], which is the live snapshot with next/previous rates.
1171#[derive(Debug, Clone, Default)]
1172pub struct FundingRateHistory {
1173    pub symbol:       Option<String>,
1174    pub funding_rate: Option<f64>,
1175    pub timestamp:    Option<i64>,
1176    pub datetime:     Option<String>,
1177    pub raw:          Value,
1178}
1179
1180impl FundingRateHistory {
1181    pub fn from_value(v: Value) -> Self {
1182        use crate::value::{safe_string, safe_number, safe_integer};
1183        let mut f = FundingRateHistory::default();
1184        f.symbol       = safe_string(&v, "symbol",      None);
1185        f.funding_rate = safe_number(&v, "fundingRate", None);
1186        f.timestamp    = safe_integer(&v, "timestamp",  None);
1187        f.datetime     = safe_string(&v, "datetime",    None);
1188        f.raw = v;
1189        f
1190    }
1191}
1192
1193/// One funding payment made or received (each row of `fetchFundingHistory`).
1194/// Mirrors the TS `FundingHistory` interface.
1195#[derive(Debug, Clone, Default)]
1196pub struct FundingHistory {
1197    pub id:        Option<String>,
1198    pub symbol:    Option<String>,
1199    pub code:      Option<String>,
1200    pub timestamp: Option<i64>,
1201    pub datetime:  Option<String>,
1202    pub amount:    Option<f64>,
1203    pub raw:       Value,
1204}
1205
1206impl FundingHistory {
1207    pub fn from_value(v: Value) -> Self {
1208        use crate::value::{safe_string, safe_number, safe_integer};
1209        let mut f = FundingHistory::default();
1210        f.id        = safe_string(&v, "id",         None);
1211        f.symbol    = safe_string(&v, "symbol",     None);
1212        f.code      = safe_string(&v, "code",       None);
1213        f.timestamp = safe_integer(&v, "timestamp", None);
1214        f.datetime  = safe_string(&v, "datetime",   None);
1215        f.amount    = safe_number(&v, "amount",     None);
1216        f.raw = v;
1217        f
1218    }
1219}
1220
1221/// One sub-account / wallet entry (each row of `fetchAccounts`). Mirrors the
1222/// TS `Account` interface.
1223#[derive(Debug, Clone, Default)]
1224pub struct Account {
1225    pub id:           Option<String>,
1226    pub account_type: Option<String>,
1227    pub code:         Option<String>,
1228    pub raw:          Value,
1229}
1230
1231impl Account {
1232    pub fn from_value(v: Value) -> Self {
1233        use crate::value::safe_string;
1234        let mut a = Account::default();
1235        a.id           = safe_string(&v, "id",   None);
1236        a.account_type = safe_string(&v, "type", None);
1237        a.code         = safe_string(&v, "code", None);
1238        a.raw = v;
1239        a
1240    }
1241}
1242
1243/// Position-mode flag (`fetchPositionMode`). Mirrors the TS `PositionModeInfo`
1244/// interface: `hedged` is `true` for hedge (dual-side) mode, `false` for one-way.
1245#[derive(Debug, Clone, Default)]
1246pub struct PositionModeInfo {
1247    pub hedged: Option<bool>,
1248    pub raw:    Value,
1249}
1250
1251impl PositionModeInfo {
1252    pub fn from_value(v: Value) -> Self {
1253        use crate::value::safe_bool;
1254        let mut p = PositionModeInfo::default();
1255        p.hedged = safe_bool(&v, "hedged", None);
1256        p.raw = v;
1257        p
1258    }
1259}
1260
1261/// Unified option-contract snapshot (`fetchOption`, and each value of
1262/// `fetchOptionChain`). Named `OptionContract` because `Option` collides with
1263/// `core::option::Option`. Mirrors the TS `Option` interface.
1264#[derive(Debug, Clone, Default)]
1265pub struct OptionContract {
1266    pub currency:           Option<String>,
1267    pub symbol:             Option<String>,
1268    pub timestamp:          Option<i64>,
1269    pub datetime:           Option<String>,
1270    pub implied_volatility: Option<f64>,
1271    pub open_interest:      Option<f64>,
1272    pub bid_price:          Option<f64>,
1273    pub ask_price:          Option<f64>,
1274    pub mid_price:          Option<f64>,
1275    pub mark_price:         Option<f64>,
1276    pub last_price:         Option<f64>,
1277    pub underlying_price:   Option<f64>,
1278    pub change:             Option<f64>,
1279    pub percentage:         Option<f64>,
1280    pub base_volume:        Option<f64>,
1281    pub quote_volume:       Option<f64>,
1282    pub raw:                Value,
1283}
1284
1285impl OptionContract {
1286    pub fn from_value(v: Value) -> Self {
1287        use crate::value::{safe_string, safe_number, safe_integer};
1288        let mut o = OptionContract::default();
1289        o.currency           = safe_string(&v, "currency",          None);
1290        o.symbol             = safe_string(&v, "symbol",            None);
1291        o.timestamp          = safe_integer(&v, "timestamp",        None);
1292        o.datetime           = safe_string(&v, "datetime",          None);
1293        o.implied_volatility = safe_number(&v, "impliedVolatility", None);
1294        o.open_interest      = safe_number(&v, "openInterest",      None);
1295        o.bid_price          = safe_number(&v, "bidPrice",          None);
1296        o.ask_price          = safe_number(&v, "askPrice",          None);
1297        o.mid_price          = safe_number(&v, "midPrice",          None);
1298        o.mark_price         = safe_number(&v, "markPrice",         None);
1299        o.last_price         = safe_number(&v, "lastPrice",         None);
1300        o.underlying_price   = safe_number(&v, "underlyingPrice",   None);
1301        o.change             = safe_number(&v, "change",            None);
1302        o.percentage         = safe_number(&v, "percentage",        None);
1303        o.base_volume        = safe_number(&v, "baseVolume",        None);
1304        o.quote_volume       = safe_number(&v, "quoteVolume",       None);
1305        o.raw = v;
1306        o
1307    }
1308}
1309
1310/// Last traded price per symbol (each value of `fetchLastPrices`). Mirrors the
1311/// TS `LastPrice` interface.
1312#[derive(Debug, Clone, Default)]
1313pub struct LastPrice {
1314    pub symbol:    Option<String>,
1315    pub timestamp: Option<i64>,
1316    pub datetime:  Option<String>,
1317    pub price:     Option<f64>,
1318    pub side:      Option<String>,   // "buy" | "sell"
1319    pub raw:       Value,
1320}
1321
1322impl LastPrice {
1323    pub fn from_value(v: Value) -> Self {
1324        use crate::value::{safe_string, safe_number, safe_integer};
1325        let mut p = LastPrice::default();
1326        p.symbol    = safe_string(&v, "symbol",    None);
1327        p.timestamp = safe_integer(&v, "timestamp", None);
1328        p.datetime  = safe_string(&v, "datetime",  None);
1329        p.price     = safe_number(&v, "price",     None);
1330        p.side      = safe_string(&v, "side",      None);
1331        p.raw = v;
1332        p
1333    }
1334}
1335
1336/// Unified isolated-margin borrow rate — one entry per symbol with a rate for
1337/// each leg (`fetchIsolatedBorrowRate`, and each value of
1338/// `fetchIsolatedBorrowRates`). Mirrors the TS `IsolatedBorrowRate` interface.
1339/// Distinct from [`BorrowRate`] (cross-margin, single `currency`/`rate`), whose
1340/// decoder would leave every field of an isolated rate `None`.
1341#[derive(Debug, Clone, Default)]
1342pub struct IsolatedBorrowRate {
1343    pub symbol:     Option<String>,
1344    pub base:       Option<String>,
1345    pub base_rate:  Option<f64>,
1346    pub quote:      Option<String>,
1347    pub quote_rate: Option<f64>,
1348    pub period:     Option<i64>,
1349    pub timestamp:  Option<i64>,
1350    pub datetime:   Option<String>,
1351    pub raw:        Value,
1352}
1353
1354impl IsolatedBorrowRate {
1355    pub fn from_value(v: Value) -> Self {
1356        use crate::value::{safe_string, safe_number, safe_integer};
1357        let mut r = IsolatedBorrowRate::default();
1358        r.symbol     = safe_string(&v, "symbol",    None);
1359        r.base       = safe_string(&v, "base",      None);
1360        r.base_rate  = safe_number(&v, "baseRate",  None);
1361        r.quote      = safe_string(&v, "quote",     None);
1362        r.quote_rate = safe_number(&v, "quoteRate", None);
1363        r.period     = safe_integer(&v, "period",   None);
1364        r.timestamp  = safe_integer(&v, "timestamp", None);
1365        r.datetime   = safe_string(&v, "datetime",  None);
1366        r.raw = v;
1367        r
1368    }
1369}
1370
1371/// One leg of a [`DepositWithdrawFee`] — the fee for a deposit or a withdrawal,
1372/// and whether it is a percentage of the amount (vs. a flat fee). Mirrors the
1373/// TS `DepositWithdrawFeeNetwork` interface.
1374#[derive(Debug, Clone, Copy, Default, PartialEq)]
1375pub struct DepositWithdrawFeeLeg {
1376    pub fee:        Option<f64>,
1377    pub percentage: Option<bool>,
1378}
1379
1380impl DepositWithdrawFeeLeg {
1381    fn from_value(v: &Value) -> Self {
1382        use crate::value::{safe_number, safe_bool};
1383        DepositWithdrawFeeLeg { fee: safe_number(v, "fee", None), percentage: safe_bool(v, "percentage", None) }
1384    }
1385}
1386
1387/// Unified deposit/withdraw fee for one currency (`fetchDepositWithdrawFee`,
1388/// and each value of `fetchDepositWithdrawFees`). Mirrors the TS
1389/// `DepositWithdrawFee` interface: a currency-level `withdraw`/`deposit` pair
1390/// plus the same pair per network under `networks`.
1391#[derive(Debug, Clone, Default)]
1392pub struct DepositWithdrawFee {
1393    pub withdraw: DepositWithdrawFeeLeg,
1394    pub deposit:  DepositWithdrawFeeLeg,
1395    pub networks: HashMap<String, DepositWithdrawFeeNetwork>,
1396    pub raw:      Value,
1397}
1398
1399/// Per-network `withdraw`/`deposit` legs inside [`DepositWithdrawFee::networks`].
1400#[derive(Debug, Clone, Copy, Default, PartialEq)]
1401pub struct DepositWithdrawFeeNetwork {
1402    pub withdraw: DepositWithdrawFeeLeg,
1403    pub deposit:  DepositWithdrawFeeLeg,
1404}
1405
1406impl DepositWithdrawFee {
1407    pub fn from_value(v: Value) -> Self {
1408        let sub = |parent: &Value, key: &str| crate::value::get_value(parent, &Value::Str(key.to_string().into()));
1409        let mut d = DepositWithdrawFee::default();
1410        d.withdraw = DepositWithdrawFeeLeg::from_value(&sub(&v, "withdraw"));
1411        d.deposit  = DepositWithdrawFeeLeg::from_value(&sub(&v, "deposit"));
1412        if let Value::Dict(networks) = sub(&v, "networks") {
1413            for (id, net) in networks.iter() {
1414                d.networks.insert(id.clone(), DepositWithdrawFeeNetwork {
1415                    withdraw: DepositWithdrawFeeLeg::from_value(&sub(net, "withdraw")),
1416                    deposit:  DepositWithdrawFeeLeg::from_value(&sub(net, "deposit")),
1417                });
1418            }
1419        }
1420        d.raw = v;
1421        d
1422    }
1423}
1424
1425// -----------------------------------------------------------------------------
1426// Collection aliases (mirror the plural names used in Go's exchange_types.go)
1427// -----------------------------------------------------------------------------
1428
1429pub type Markets       = HashMap<String, Market>;
1430pub type Currencies    = HashMap<String, Currency>;
1431pub type Tickers       = HashMap<String, Ticker>;
1432pub type OrderBooks    = HashMap<String, OrderBook>;
1433pub type FundingRates  = HashMap<String, FundingRate>;
1434pub type OpenInterests = HashMap<String, OpenInterest>;
1435pub type Leverages     = HashMap<String, Leverage>;
1436pub type MarginModes   = HashMap<String, MarginMode>;
1437pub type TradingFees   = HashMap<String, TradingFee>;
1438/// `fetchCrossBorrowRates` — currency code → [`BorrowRate`].
1439pub type CrossBorrowRates    = HashMap<String, BorrowRate>;
1440/// `fetchIsolatedBorrowRates` — symbol → [`IsolatedBorrowRate`].
1441pub type IsolatedBorrowRates = HashMap<String, IsolatedBorrowRate>;
1442/// `fetchLastPrices` — symbol → [`LastPrice`].
1443pub type LastPrices          = HashMap<String, LastPrice>;
1444/// `fetchOptionChain` — symbol → [`OptionContract`].
1445pub type OptionChain         = HashMap<String, OptionContract>;
1446/// `fetchLeverageTiers` — symbol → its ladder of [`LeverageTier`]s.
1447pub type LeverageTiers       = HashMap<String, Vec<LeverageTier>>;
1448/// `fetchDepositWithdrawFees` — currency code → [`DepositWithdrawFee`].
1449pub type DepositWithdrawFees = HashMap<String, DepositWithdrawFee>;
1450/// `fetchAllGreeks` — symbol → [`Greeks`].
1451pub type AllGreeks           = HashMap<String, Greeks>;
1452/// `fetchDepositAddresses` — currency code → [`DepositAddress`].
1453pub type DepositAddresses    = HashMap<String, DepositAddress>;
1454
1455/// Walk a `Value::Dict` of `<key> → Value` and decode each value with
1456/// the supplied `from_value` constructor. Returns an empty map on a
1457/// non-dict input — matches the lenient fallback semantics of the
1458/// individual `from_value` impls.
1459pub fn dict_from_value<T>(v: &Value, decode: fn(Value) -> T) -> HashMap<String, T> {
1460    match v {
1461        Value::Dict(d) => d.iter()
1462            .map(|(k, val)| (k.clone(), decode(val.clone())))
1463            .collect(),
1464        _ => HashMap::new(),
1465    }
1466}
1467
1468/// Walk a `Value::Arr` and decode each element with the supplied
1469/// `from_value` constructor.
1470pub fn vec_from_value<T>(v: &Value, decode: fn(Value) -> T) -> Vec<T> {
1471    match v {
1472        Value::Arr(rows) => rows.iter().map(|row| decode(row.clone())).collect(),
1473        _ => Vec::new(),
1474    }
1475}
1476
1477#[cfg(test)]
1478mod from_value_tests {
1479    use super::{Market, Order, OrderBook, MarginModification, Conversion, IsolatedBorrowRate, BorrowRate, PositionModeInfo, LastPrice, LeverageTier, DepositWithdrawFee, MarginLoan, Ticker, Trade, Position, Transaction, LedgerEntry, FundingRate, TradingFee, OpenInterest, Liquidation, Greeks};
1480    use crate::Value;
1481    use crate::value::HashMap;
1482
1483    fn dict(pairs: &[(&str, Value)]) -> Value {
1484        let mut m = HashMap::new();
1485        for (k, v) in pairs { m.insert(k.to_string(), v.clone()); }
1486        Value::Map(m)
1487    }
1488
1489    // Malformed order-book rows (non-array, too short, unparseable) must be
1490    // dropped, not emitted as [NaN, NaN] (review #7).
1491    #[test]
1492    fn order_book_drops_malformed_rows() {
1493        let row = |a: Value, b: Value| Value::Array(vec![a, b]);
1494        let bids = Value::Array(vec![
1495            row(Value::Str("100.5".into()), Value::Str("2".into())), // ok
1496            Value::Array(vec![Value::Str("bad".into()), Value::Int(1)]), // NaN price → drop
1497            Value::Array(vec![Value::Int(99)]),                          // missing amount → drop
1498            Value::Str("notarow".into()),                               // not an array → drop
1499            row(Value::Int(99), Value::Float(3.0)),                     // ok
1500        ]);
1501        let ob = OrderBook::from_value(dict(&[("bids", bids)]));
1502        assert_eq!(ob.bids.len(), 2, "malformed rows were not dropped: {:?}", ob.bids);
1503        assert_eq!(ob.bids[0], [100.5, 2.0]);
1504        assert_eq!(ob.bids[1], [99.0, 3.0]);
1505        assert!(ob.bids.iter().all(|r| !r[0].is_nan() && !r[1].is_nan()));
1506    }
1507
1508    #[test]
1509    fn market_assigns_declared_fields() {
1510        let v = dict(&[
1511            ("id", Value::Str("BTCUSDT".into())), ("symbol", Value::Str("BTC/USDT:USDT".into())),
1512            ("settle", Value::Str("USDT".into())), ("baseId", Value::Str("BTC".into())),
1513            ("quoteId", Value::Str("USDT".into())), ("margin", Value::Bool(true)),
1514            ("contract", Value::Bool(true)), ("linear", Value::Bool(true)), ("inverse", Value::Bool(false)),
1515        ]);
1516        let m = Market::from_value(v);
1517        assert_eq!(m.settle.as_deref(), Some("USDT"));
1518        assert_eq!(m.base_id, "BTC");
1519        assert_eq!(m.quote_id, "USDT");
1520        assert!(m.margin && m.contract);
1521        assert_eq!(m.linear, Some(true));
1522        assert_eq!(m.inverse, Some(false));
1523    }
1524
1525    #[test]
1526    fn order_assigns_fee() {
1527        let v = dict(&[
1528            ("id", Value::Str("1".into())),
1529            ("fee", dict(&[("currency", Value::Str("USDT".into())), ("cost", Value::Float(0.1))])),
1530        ]);
1531        let o = Order::from_value(v);
1532        let fee = o.fee.expect("fee should be assigned");
1533        assert_eq!(fee.get("currency"), Some(&Value::Str("USDT".into())));
1534    }
1535
1536    // The unified structs added for the typed-wrapper coverage push must
1537    // actually read the camelCase keys the TS parsers emit — a decoder that
1538    // reads the wrong key compiles green and silently yields all-`None`.
1539    #[test]
1540    fn margin_modification_reads_unified_keys() {
1541        let v = dict(&[
1542            ("symbol", Value::Str("BTC/USDT:USDT".into())),
1543            ("type", Value::Str("add".into())),
1544            ("marginMode", Value::Str("isolated".into())),
1545            ("amount", Value::Float(0.001)),
1546            ("code", Value::Str("USDT".into())),
1547            ("status", Value::Str("ok".into())),
1548            ("timestamp", Value::Int(1_700_000_000_000)),
1549        ]);
1550        let m = MarginModification::from_value(v);
1551        assert_eq!(m.symbol.as_deref(), Some("BTC/USDT:USDT"));
1552        assert_eq!(m.mod_type.as_deref(), Some("add"));
1553        assert_eq!(m.margin_mode.as_deref(), Some("isolated"));
1554        assert_eq!(m.amount, Some(0.001));
1555        assert_eq!(m.code.as_deref(), Some("USDT"));
1556        assert_eq!(m.status.as_deref(), Some("ok"));
1557        assert_eq!(m.timestamp, Some(1_700_000_000_000));
1558        assert_eq!(m.total, None);
1559    }
1560
1561    #[test]
1562    fn conversion_reads_unified_keys() {
1563        let v = dict(&[
1564            ("id", Value::Str("q1".into())),
1565            ("fromCurrency", Value::Str("BTC".into())),
1566            ("fromAmount", Value::Str("0.5".into())),
1567            ("toCurrency", Value::Str("USDT".into())),
1568            ("toAmount", Value::Float(20000.0)),
1569            ("price", Value::Int(40000)),
1570        ]);
1571        let c = Conversion::from_value(v);
1572        assert_eq!(c.id.as_deref(), Some("q1"));
1573        assert_eq!(c.from_currency.as_deref(), Some("BTC"));
1574        assert_eq!(c.from_amount, Some(0.5));
1575        assert_eq!(c.to_currency.as_deref(), Some("USDT"));
1576        assert_eq!(c.to_amount, Some(20000.0));
1577        assert_eq!(c.price, Some(40000.0));
1578        assert_eq!(c.fee, None);
1579    }
1580
1581    #[test]
1582    fn isolated_borrow_rate_is_not_the_cross_shape() {
1583        let v = dict(&[
1584            ("symbol", Value::Str("BTC/USDT".into())),
1585            ("base", Value::Str("BTC".into())),
1586            ("baseRate", Value::Float(0.0001)),
1587            ("quote", Value::Str("USDT".into())),
1588            ("quoteRate", Value::Float(0.0002)),
1589        ]);
1590        let r = IsolatedBorrowRate::from_value(v.clone());
1591        assert_eq!(r.symbol.as_deref(), Some("BTC/USDT"));
1592        assert_eq!(r.base_rate, Some(0.0001));
1593        assert_eq!(r.quote_rate, Some(0.0002));
1594        // The previous mapping (`IsolatedBorrowRate` → `BorrowRate`) lost every field.
1595        let wrong = BorrowRate::from_value(v);
1596        assert_eq!(wrong.currency, None);
1597        assert_eq!(wrong.rate, None);
1598    }
1599
1600    #[test]
1601    fn leverage_tiers_map_of_vec_and_deposit_withdraw_fee_nesting() {
1602        let tier = |n: f64| dict(&[("tier", Value::Float(n)), ("maxLeverage", Value::Int(20))]);
1603        let tiers = dict(&[("BTC/USDT:USDT", Value::Array(vec![tier(1.0), tier(2.0)]))]);
1604        let decoded = super::dict_from_value(&tiers, |row| super::vec_from_value(&row, LeverageTier::from_value));
1605        assert_eq!(decoded["BTC/USDT:USDT"].len(), 2);
1606        assert_eq!(decoded["BTC/USDT:USDT"][1].tier, Some(2.0));
1607        assert_eq!(decoded["BTC/USDT:USDT"][1].max_leverage, Some(20.0));
1608        let fee = DepositWithdrawFee::from_value(dict(&[
1609            ("withdraw", dict(&[("fee", Value::Float(0.0005)), ("percentage", Value::Bool(false))])),
1610            ("deposit", dict(&[("fee", Value::Null), ("percentage", Value::Null)])),
1611            ("networks", dict(&[("BTC", dict(&[
1612                ("withdraw", dict(&[("fee", Value::Str("0.0004".into())), ("percentage", Value::Bool(false))])),
1613                ("deposit", dict(&[("fee", Value::Int(0)), ("percentage", Value::Null)])),
1614            ]))])),
1615        ]));
1616        assert_eq!(fee.withdraw.fee, Some(0.0005));
1617        assert_eq!(fee.withdraw.percentage, Some(false));
1618        assert_eq!(fee.deposit.fee, None);
1619        assert_eq!(fee.networks["BTC"].withdraw.fee, Some(0.0004));
1620        assert_eq!(fee.networks["BTC"].deposit.fee, Some(0.0));
1621    }
1622
1623    #[test]
1624    fn position_mode_and_last_price_read_unified_keys() {
1625        let p = PositionModeInfo::from_value(dict(&[("hedged", Value::Bool(true))]));
1626        assert_eq!(p.hedged, Some(true));
1627        let lp = LastPrice::from_value(dict(&[
1628            ("symbol", Value::Str("ETH/USDT".into())),
1629            ("price", Value::Str("3000.5".into())),
1630            ("side", Value::Str("buy".into())),
1631        ]));
1632        assert_eq!(lp.symbol.as_deref(), Some("ETH/USDT"));
1633        assert_eq!(lp.price, Some(3000.5));
1634        assert_eq!(lp.side.as_deref(), Some("buy"));
1635    }
1636
1637    // Mirrors binance `parseMarginLoan`: `id` from `tranId`, `currency` from the
1638    // unified code, `symbol` undefined for cross margin. A decoder keyed on the
1639    // raw exchange fields (`tranId`/`asset`) would silently read all-`None`.
1640    #[test]
1641    fn margin_loan_reads_unified_keys() {
1642        let m = MarginLoan::from_value(dict(&[
1643            ("id", Value::Str("108988250265".into())),
1644            ("currency", Value::Str("USDC".into())),
1645            ("amount", Value::Int(10)),
1646            ("symbol", Value::Null),
1647            ("timestamp", Value::Int(1_727_170_761_267)),
1648            ("datetime", Value::Str("2024-09-24T09:39:21.267Z".into())),
1649            ("info", dict(&[("tranId", Value::Int(108988250265)), ("asset", Value::Str("USDC".into()))])),
1650        ]));
1651        assert_eq!(m.id.as_deref(), Some("108988250265"));
1652        assert_eq!(m.currency.as_deref(), Some("USDC"));
1653        assert_eq!(m.amount, Some(10.0));
1654        assert_eq!(m.symbol, None);
1655        assert_eq!(m.timestamp, Some(1_727_170_761_267));
1656        assert_eq!(m.datetime.as_deref(), Some("2024-09-24T09:39:21.267Z"));
1657        assert!(matches!(m.raw, Value::Dict(_)));
1658    }
1659
1660    // The core structs were narrower than their TS interfaces (Ticker lacked
1661    // `open`/`close`/`percentage`…, Trade lacked `fee`/`order`/`takerOrMaker`,
1662    // Position lacked `marginMode`/`liquidationPrice`…). Pin the widened
1663    // decoders to the unified camelCase keys the TS parsers emit.
1664    #[test]
1665    fn widened_core_structs_read_unified_keys() {
1666        let fee = dict(&[("currency", Value::Str("USDT".into())), ("cost", Value::Float(0.12)), ("rate", Value::Float(0.001))]);
1667        let t = Ticker::from_value(dict(&[
1668            ("symbol", Value::Str("BTC/USDT".into())),
1669            ("open", Value::Float(100.0)), ("close", Value::Float(110.0)),
1670            ("bidVolume", Value::Int(3)), ("askVolume", Value::Str("4.5".into())),
1671            ("vwap", Value::Float(105.0)), ("previousClose", Value::Float(99.0)),
1672            ("change", Value::Float(10.0)), ("percentage", Value::Float(10.0)),
1673            ("average", Value::Float(105.0)), ("indexPrice", Value::Float(109.0)), ("markPrice", Value::Float(109.5)),
1674        ]));
1675        assert_eq!(t.open, Some(100.0));
1676        assert_eq!(t.close, Some(110.0));
1677        assert_eq!(t.bid_volume, Some(3.0));
1678        assert_eq!(t.ask_volume, Some(4.5));
1679        assert_eq!(t.vwap, Some(105.0));
1680        assert_eq!(t.previous_close, Some(99.0));
1681        assert_eq!(t.change, Some(10.0));
1682        assert_eq!(t.percentage, Some(10.0));
1683        assert_eq!(t.average, Some(105.0));
1684        assert_eq!(t.index_price, Some(109.0));
1685        assert_eq!(t.mark_price, Some(109.5));
1686
1687        let tr = Trade::from_value(dict(&[
1688            ("id", Value::Str("t1".into())), ("order", Value::Str("o1".into())),
1689            ("type", Value::Str("limit".into())), ("takerOrMaker", Value::Str("maker".into())),
1690            ("fee", fee.clone()),
1691        ]));
1692        assert_eq!(tr.order.as_deref(), Some("o1"));
1693        assert_eq!(tr.trade_type.as_deref(), Some("limit"));
1694        assert_eq!(tr.taker_or_maker.as_deref(), Some("maker"));
1695        assert_eq!(tr.fee.as_ref().and_then(|f| f.cost), Some(0.12));
1696        assert_eq!(tr.fee.as_ref().and_then(|f| f.currency.clone()).as_deref(), Some("USDT"));
1697
1698        let o = Order::from_value(dict(&[
1699            ("id", Value::Str("o1".into())),
1700            ("timeInForce", Value::Str("GTC".into())),
1701            ("postOnly", Value::Bool(true)), ("reduceOnly", Value::Bool(false)),
1702            ("average", Value::Float(101.0)), ("triggerPrice", Value::Float(95.0)),
1703            ("stopLossPrice", Value::Float(90.0)), ("takeProfitPrice", Value::Float(120.0)),
1704            ("lastTradeTimestamp", Value::Int(1_700_000_000_001)),
1705            ("lastUpdateTimestamp", Value::Int(1_700_000_000_002)),
1706            ("trades", Value::Arr(std::sync::Arc::new(vec![dict(&[("id", Value::Str("t1".into())), ("amount", Value::Float(0.5))])]))),
1707        ]));
1708        assert_eq!(o.time_in_force.as_deref(), Some("GTC"));
1709        assert_eq!(o.post_only, Some(true));
1710        assert_eq!(o.reduce_only, Some(false));
1711        assert_eq!(o.average, Some(101.0));
1712        assert_eq!(o.trigger_price, Some(95.0));
1713        assert_eq!(o.stop_loss_price, Some(90.0));
1714        assert_eq!(o.take_profit_price, Some(120.0));
1715        assert_eq!(o.last_trade_timestamp, Some(1_700_000_000_001));
1716        assert_eq!(o.last_update_timestamp, Some(1_700_000_000_002));
1717        assert_eq!(o.trades.len(), 1);
1718        assert_eq!(o.trades[0].id.as_deref(), Some("t1"));
1719        assert_eq!(o.trades[0].amount, Some(0.5));
1720        // A missing `trades` key decodes to an empty Vec, not a panic.
1721        assert!(Order::from_value(dict(&[])).trades.is_empty());
1722
1723        let p = Position::from_value(dict(&[
1724            ("symbol", Value::Str("BTC/USDT:USDT".into())),
1725            ("marginMode", Value::Str("cross".into())), ("hedged", Value::Bool(false)),
1726            ("liquidationPrice", Value::Float(50000.0)), ("notional", Value::Float(1000.0)),
1727            ("collateral", Value::Float(100.0)), ("realizedPnl", Value::Float(1.5)),
1728            ("maintenanceMargin", Value::Float(5.0)), ("initialMargin", Value::Float(50.0)),
1729            ("marginRatio", Value::Float(0.05)), ("percentage", Value::Float(1.2)),
1730            ("lastUpdateTimestamp", Value::Int(1_700_000_000_003)),
1731        ]));
1732        assert_eq!(p.margin_mode.as_deref(), Some("cross"));
1733        assert_eq!(p.margin_type, None);
1734        assert_eq!(p.hedged, Some(false));
1735        assert_eq!(p.liquidation_price, Some(50000.0));
1736        assert_eq!(p.notional, Some(1000.0));
1737        assert_eq!(p.collateral, Some(100.0));
1738        assert_eq!(p.realized_pnl, Some(1.5));
1739        assert_eq!(p.maintenance_margin, Some(5.0));
1740        assert_eq!(p.initial_margin, Some(50.0));
1741        assert_eq!(p.margin_ratio, Some(0.05));
1742        assert_eq!(p.percentage, Some(1.2));
1743        assert_eq!(p.last_update_timestamp, Some(1_700_000_000_003));
1744
1745        let tx = Transaction::from_value(dict(&[
1746            ("type", Value::Str("withdrawal".into())), ("network", Value::Str("TRC20".into())),
1747            ("tag", Value::Str("memo".into())), ("addressTo", Value::Str("Txyz".into())),
1748            ("updated", Value::Int(1_700_000_000_004)), ("internal", Value::Bool(true)),
1749            ("comment", Value::Str("c".into())), ("fee", fee.clone()),
1750        ]));
1751        assert_eq!(tx.tx_type.as_deref(), Some("withdrawal"));
1752        assert_eq!(tx.network.as_deref(), Some("TRC20"));
1753        assert_eq!(tx.tag.as_deref(), Some("memo"));
1754        assert_eq!(tx.address_to.as_deref(), Some("Txyz"));
1755        assert_eq!(tx.updated, Some(1_700_000_000_004));
1756        assert_eq!(tx.internal, Some(true));
1757        assert_eq!(tx.comment.as_deref(), Some("c"));
1758        assert_eq!(tx.fee.as_ref().and_then(|f| f.rate), Some(0.001));
1759
1760        let le = LedgerEntry::from_value(dict(&[
1761            ("type", Value::Str("trade".into())), ("referenceId", Value::Str("r1".into())),
1762            ("before", Value::Float(10.0)), ("after", Value::Float(9.5)), ("status", Value::Str("ok".into())),
1763            ("fee", fee),
1764        ]));
1765        assert_eq!(le.entry_type.as_deref(), Some("trade"));
1766        assert_eq!(le.reference_id.as_deref(), Some("r1"));
1767        assert_eq!(le.before, Some(10.0));
1768        assert_eq!(le.after, Some(9.5));
1769        assert_eq!(le.status.as_deref(), Some("ok"));
1770        assert!(le.fee.is_some());
1771
1772        let fr = FundingRate::from_value(dict(&[
1773            ("fundingRate", Value::Float(0.0001)), ("markPrice", Value::Float(1.0)),
1774            ("nextFundingTimestamp", Value::Int(1_700_000_000_005)), ("interval", Value::Str("8h".into())),
1775            ("previousFundingRate", Value::Float(0.00005)),
1776        ]));
1777        assert_eq!(fr.mark_price, Some(1.0));
1778        assert_eq!(fr.next_funding_timestamp, Some(1_700_000_000_005));
1779        assert_eq!(fr.interval.as_deref(), Some("8h"));
1780        assert_eq!(fr.previous_funding_rate, Some(0.00005));
1781
1782        let tf = TradingFee::from_value(dict(&[("maker", Value::Float(0.001)), ("percentage", Value::Bool(true)), ("tierBased", Value::Bool(false))]));
1783        assert_eq!(tf.percentage, Some(true));
1784        assert_eq!(tf.tier_based, Some(false));
1785
1786        let oi = OpenInterest::from_value(dict(&[("baseVolume", Value::Float(12.0)), ("quoteVolume", Value::Float(1200.0))]));
1787        assert_eq!(oi.base_volume, Some(12.0));
1788        assert_eq!(oi.quote_volume, Some(1200.0));
1789
1790        let lq = Liquidation::from_value(dict(&[("contracts", Value::Float(2.0)), ("contractSize", Value::Float(0.01)), ("side", Value::Str("sell".into()))]));
1791        assert_eq!(lq.contracts, Some(2.0));
1792        assert_eq!(lq.contract_size, Some(0.01));
1793        assert_eq!(lq.side.as_deref(), Some("sell"));
1794
1795        let g = Greeks::from_value(dict(&[("bidImpliedVolatility", Value::Float(0.6)), ("underlyingPrice", Value::Float(60000.0)), ("charm", Value::Float(-0.01))]));
1796        assert_eq!(g.bid_implied_volatility, Some(0.6));
1797        assert_eq!(g.underlying_price, Some(60000.0));
1798        assert_eq!(g.charm, Some(-0.01));
1799
1800        assert_eq!(LeverageTier::from_value(dict(&[("symbol", Value::Str("ETH/USDT:USDT".into()))])).symbol.as_deref(), Some("ETH/USDT:USDT"));
1801    }
1802}