1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! # Upbit Response Parser
//!
//! Парсинг JSON ответов от Upbit API.
//!
//! ## CRITICAL: Two Different Formats
//! - **REST API**: Returns arrays/objects directly (no wrapper)
//! - **WebSocket API**: Returns objects with different field names
//!
//! This parser handles both formats.
use serde_json::Value;
use crate::core::types::{
ExchangeError, ExchangeResult, AccountType,
Kline, OrderBook, OrderBookLevel, Ticker, Order, Balance, PublicTrade,
OrderSide, OrderType, OrderStatus, TradeSide, SymbolInfo,
UserTrade,
};
/// Парсер ответов Upbit API
pub struct UpbitParser;
impl UpbitParser {
// ═══════════════════════════════════════════════════════════════════════════════
// HELPERS
// ═══════════════════════════════════════════════════════════════════════════════
/// Check for error response
/// Upbit errors have: {"error": {"name": "...", "message": "..."}}
pub fn check_error(response: &Value) -> ExchangeResult<()> {
if let Some(error) = response.get("error") {
let name = error.get("name")
.and_then(|v| v.as_str())
.unwrap_or("unknown_error");
let message = error.get("message")
.and_then(|v| v.as_str())
.unwrap_or("Unknown error");
return Err(ExchangeError::Api {
code: 0,
message: format!("{}: {}", name, message),
});
}
Ok(())
}
/// Парсить f64 из number
fn parse_f64(value: &Value) -> Option<f64> {
value.as_f64()
}
/// Парсить f64 из поля
fn get_f64(data: &Value, key: &str) -> Option<f64> {
data.get(key).and_then(Self::parse_f64)
}
/// Парсить обязательный f64
fn require_f64(data: &Value, key: &str) -> ExchangeResult<f64> {
Self::get_f64(data, key)
.ok_or_else(|| ExchangeError::Parse(format!("Missing or invalid '{}'", key)))
}
/// Парсить строку из поля
fn get_str<'a>(data: &'a Value, key: &str) -> Option<&'a str> {
data.get(key).and_then(|v| v.as_str())
}
/// Парсить обязательную строку
fn require_str<'a>(data: &'a Value, key: &str) -> ExchangeResult<&'a str> {
Self::get_str(data, key)
.ok_or_else(|| ExchangeError::Parse(format!("Missing '{}'", key)))
}
/// Parse ISO 8601 timestamp string to milliseconds since Unix epoch.
///
/// Upbit format: `"2024-06-19T08:31:43+09:00"` (RFC 3339 / ISO 8601 with offset).
fn parse_iso_timestamp(iso_str: &str) -> Option<i64> {
chrono::DateTime::parse_from_rfc3339(iso_str)
.ok()
.map(|dt| dt.timestamp_millis())
}
// ═══════════════════════════════════════════════════════════════════════════════
// MARKET DATA (REST)
// ═══════════════════════════════════════════════════════════════════════════════
/// Парсить price from ticker
/// Upbit returns array of tickers, we take first one
pub fn parse_price(response: &Value) -> ExchangeResult<f64> {
Self::check_error(response)?;
let arr = response.as_array()
.ok_or_else(|| ExchangeError::Parse("Expected array of tickers".to_string()))?;
let ticker = arr.first()
.ok_or_else(|| ExchangeError::Parse("Empty ticker array".to_string()))?;
Self::require_f64(ticker, "trade_price")
}
/// Парсить klines
/// Upbit returns array of candles (newest first)
pub fn parse_klines(response: &Value) -> ExchangeResult<Vec<Kline>> {
Self::check_error(response)?;
let arr = response.as_array()
.ok_or_else(|| ExchangeError::Parse("Expected array of candles".to_string()))?;
let mut klines = Vec::with_capacity(arr.len());
for item in arr {
// Upbit fields:
// - candle_date_time_utc (string)
// - opening_price, high_price, low_price, trade_price (close)
// - timestamp (milliseconds - last trade in candle)
// - candle_acc_trade_volume, candle_acc_trade_price
let open_time = item.get("timestamp")
.and_then(|t| t.as_i64())
.unwrap_or(0);
klines.push(Kline {
open_time,
open: Self::get_f64(item, "opening_price").unwrap_or(0.0),
high: Self::get_f64(item, "high_price").unwrap_or(0.0),
low: Self::get_f64(item, "low_price").unwrap_or(0.0),
close: Self::get_f64(item, "trade_price").unwrap_or(0.0),
volume: Self::get_f64(item, "candle_acc_trade_volume").unwrap_or(0.0),
quote_volume: Self::get_f64(item, "candle_acc_trade_price"),
close_time: None,
trades: None,
});
}
// Upbit returns newest first, reverse to oldest first
klines.reverse();
Ok(klines)
}
/// Парсить orderbook
/// Upbit returns array with one orderbook object
pub fn parse_orderbook(response: &Value) -> ExchangeResult<OrderBook> {
Self::check_error(response)?;
let arr = response.as_array()
.ok_or_else(|| ExchangeError::Parse("Expected array of orderbooks".to_string()))?;
let data = arr.first()
.ok_or_else(|| ExchangeError::Parse("Empty orderbook array".to_string()))?;
// Parse orderbook_units array
let units = data.get("orderbook_units")
.and_then(|v| v.as_array())
.ok_or_else(|| ExchangeError::Parse("Missing orderbook_units".to_string()))?;
let mut bids = Vec::new();
let mut asks = Vec::new();
for unit in units {
// Each unit has: bid_price, bid_size, ask_price, ask_size
if let (Some(bid_price), Some(bid_size)) = (
Self::get_f64(unit, "bid_price"),
Self::get_f64(unit, "bid_size")
) {
bids.push(OrderBookLevel::new(bid_price, bid_size));
}
if let (Some(ask_price), Some(ask_size)) = (
Self::get_f64(unit, "ask_price"),
Self::get_f64(unit, "ask_size")
) {
asks.push(OrderBookLevel::new(ask_price, ask_size));
}
}
Ok(OrderBook {
timestamp: data.get("timestamp")
.and_then(|t| t.as_i64())
.unwrap_or(0),
bids,
asks,
sequence: None,
last_update_id: None,
first_update_id: None,
prev_update_id: None,
event_time: None,
transaction_time: None,
checksum: None,
})
}
/// Парсить ticker
/// Upbit returns array of tickers, we take first one
pub fn parse_ticker(response: &Value) -> ExchangeResult<Ticker> {
Self::check_error(response)?;
let arr = response.as_array()
.ok_or_else(|| ExchangeError::Parse("Expected array of tickers".to_string()))?;
let data = arr.first()
.ok_or_else(|| ExchangeError::Parse("Empty ticker array".to_string()))?;
Ok(Ticker {
last_price: Self::get_f64(data, "trade_price").unwrap_or(0.0),
bid_price: None, // Upbit ticker doesn't include bid/ask
ask_price: None,
high_24h: Self::get_f64(data, "high_price"),
low_24h: Self::get_f64(data, "low_price"),
volume_24h: Self::get_f64(data, "acc_trade_volume_24h"),
quote_volume_24h: Self::get_f64(data, "acc_trade_price_24h"),
price_change_24h: Self::get_f64(data, "change_price"),
price_change_percent_24h: Self::get_f64(data, "change_rate")
.map(|r| r * 100.0), // Convert decimal to percentage
timestamp: data.get("timestamp")
.and_then(|t| t.as_i64())
.unwrap_or(0),
})
}
/// Parse recent trades
pub fn parse_recent_trades(response: &Value) -> ExchangeResult<Vec<PublicTrade>> {
Self::check_error(response)?;
let arr = response.as_array()
.ok_or_else(|| ExchangeError::Parse("Expected array of trades".to_string()))?;
let mut trades = Vec::with_capacity(arr.len());
for item in arr {
let side = match Self::get_str(item, "ask_bid") {
Some("ASK") => TradeSide::Sell,
Some("BID") => TradeSide::Buy,
_ => TradeSide::Buy,
};
trades.push(PublicTrade {
id: item.get("sequential_id")
.and_then(|v| v.as_i64())
.map(|id| id.to_string())
.unwrap_or_default(),
price: Self::get_f64(item, "trade_price").unwrap_or(0.0),
quantity: Self::get_f64(item, "trade_volume").unwrap_or(0.0),
timestamp: item.get("timestamp")
.and_then(|t| t.as_i64())
.unwrap_or(0),
side,
});
}
Ok(trades)
}
// ═══════════════════════════════════════════════════════════════════════════════
// TRADING (REST)
// ═══════════════════════════════════════════════════════════════════════════════
/// Парсить order из response
pub fn parse_order(response: &Value, symbol: &str) -> ExchangeResult<Order> {
Self::check_error(response)?;
Self::parse_order_data(response, symbol)
}
/// Парсить order из data object
pub fn parse_order_data(data: &Value, symbol: &str) -> ExchangeResult<Order> {
// Upbit order fields:
// - uuid: order ID
// - side: "bid" (buy) or "ask" (sell)
// - ord_type: "limit", "price" (market buy), "market" (market sell)
// - state: "wait", "watch", "done", "cancel"
// - price, volume, remaining_volume, executed_volume
// - created_at (ISO 8601 string)
let side = match Self::get_str(data, "side") {
Some("ask") => OrderSide::Sell,
_ => OrderSide::Buy,
};
let order_type = match Self::get_str(data, "ord_type") {
Some("limit") => OrderType::Limit { price: 0.0 },
_ => OrderType::Market,
};
let status = Self::parse_order_status(data);
// Parse price (may be string in Upbit)
let price = data.get("price")
.and_then(|v| {
v.as_str()
.and_then(|s| s.parse::<f64>().ok())
.or_else(|| v.as_f64())
});
// Parse volumes (may be strings)
let quantity = data.get("volume")
.and_then(|v| {
v.as_str()
.and_then(|s| s.parse::<f64>().ok())
.or_else(|| v.as_f64())
})
.unwrap_or(0.0);
let filled_quantity = data.get("executed_volume")
.and_then(|v| {
v.as_str()
.and_then(|s| s.parse::<f64>().ok())
.or_else(|| v.as_f64())
})
.unwrap_or(0.0);
// Calculate average price
let average_price = if filled_quantity > 0.0 {
// TODO: Need trades_count and total value to calculate
None
} else {
None
};
Ok(Order {
id: Self::get_str(data, "uuid").unwrap_or("").to_string(),
client_order_id: Self::get_str(data, "identifier").map(String::from),
symbol: Some(Self::get_str(data, "market").unwrap_or(symbol).to_string()),
side,
order_type,
status,
price,
stop_price: None,
quantity,
filled_quantity,
average_price,
commission: None,
commission_asset: None,
created_at: data
.get("created_at")
.and_then(|v| v.as_str())
.and_then(Self::parse_iso_timestamp)
.unwrap_or(0),
updated_at: None,
time_in_force: crate::core::TimeInForce::Gtc,
})
}
/// Парсить статус ордера
fn parse_order_status(data: &Value) -> OrderStatus {
match Self::get_str(data, "state") {
Some("wait") => OrderStatus::New,
Some("watch") => OrderStatus::New, // Conditional orders
Some("done") => {
// Check if partially or fully filled
let volume = data.get("volume")
.and_then(|v| v.as_str().and_then(|s| s.parse::<f64>().ok()))
.unwrap_or(1.0);
let executed = data.get("executed_volume")
.and_then(|v| v.as_str().and_then(|s| s.parse::<f64>().ok()))
.unwrap_or(0.0);
if executed >= volume {
OrderStatus::Filled
} else {
OrderStatus::PartiallyFilled
}
},
Some("cancel") => OrderStatus::Canceled,
_ => OrderStatus::New,
}
}
/// Парсить список ордеров
pub fn parse_orders(response: &Value) -> ExchangeResult<Vec<Order>> {
Self::check_error(response)?;
let arr = response.as_array()
.ok_or_else(|| ExchangeError::Parse("Expected array of orders".to_string()))?;
arr.iter()
.map(|item| Self::parse_order_data(item, ""))
.collect()
}
/// Парсить order ID из create order response
pub fn parse_order_id(response: &Value) -> ExchangeResult<String> {
Self::check_error(response)?;
Self::require_str(response, "uuid").map(String::from)
}
/// Extract fills (`trades` array) from a single order detail response.
///
/// Upbit's `GET /v1/order?uuid=...` returns an order object that includes
/// a `trades` array when the order has been (partially) filled.
///
/// Each trade element looks like:
/// ```json
/// {"market":"KRW-BTC","uuid":"trade-uuid","price":"50000000","volume":"0.001",
/// "funds":"50000","side":"bid","created_at":"2024-01-01T00:00:00+09:00"}
/// ```
pub fn parse_order_trades(response: &Value) -> ExchangeResult<Vec<UserTrade>> {
Self::check_error(response)?;
let order_id = Self::get_str(response, "uuid").unwrap_or("").to_string();
let symbol = Self::get_str(response, "market").unwrap_or("").to_string();
// Fee information is on the order level, not per-trade in Upbit
let paid_fee: f64 = response.get("paid_fee")
.and_then(|v| {
v.as_str()
.and_then(|s| s.parse::<f64>().ok())
.or_else(|| v.as_f64())
})
.unwrap_or(0.0);
let reserved_fee_currency = Self::get_str(response, "market")
.and_then(|m| m.split('-').next())
.unwrap_or("")
.to_string();
let trades_arr = match response.get("trades").and_then(|v| v.as_array()) {
Some(arr) => arr,
None => return Ok(vec![]),
};
let trade_count = trades_arr.len();
// Distribute fee evenly across trades (Upbit does not give per-trade fee)
let fee_per_trade = if trade_count > 0 {
paid_fee / trade_count as f64
} else {
0.0
};
let mut trades = Vec::with_capacity(trade_count);
for item in trades_arr {
let side = match Self::get_str(item, "side") {
Some("ask") => OrderSide::Sell,
_ => OrderSide::Buy,
};
let price: f64 = item.get("price")
.and_then(|v| {
v.as_str()
.and_then(|s| s.parse::<f64>().ok())
.or_else(|| v.as_f64())
})
.unwrap_or(0.0);
let volume: f64 = item.get("volume")
.and_then(|v| {
v.as_str()
.and_then(|s| s.parse::<f64>().ok())
.or_else(|| v.as_f64())
})
.unwrap_or(0.0);
let timestamp = item.get("created_at")
.and_then(|v| v.as_str())
.and_then(Self::parse_iso_timestamp)
.unwrap_or(0);
let trade_id = Self::get_str(item, "uuid").unwrap_or("").to_string();
trades.push(UserTrade {
id: trade_id,
order_id: order_id.clone(),
symbol: symbol.clone(),
side,
price,
quantity: volume,
commission: fee_per_trade,
commission_asset: reserved_fee_currency.clone(),
is_maker: false, // Upbit does not expose maker/taker per fill
timestamp,
});
}
Ok(trades)
}
// ═══════════════════════════════════════════════════════════════════════════════
// ACCOUNT (REST)
// ═══════════════════════════════════════════════════════════════════════════════
/// Парсить balances
pub fn parse_balances(response: &Value) -> ExchangeResult<Vec<Balance>> {
Self::check_error(response)?;
let arr = response.as_array()
.ok_or_else(|| ExchangeError::Parse("Expected array of balances".to_string()))?;
let mut balances = Vec::new();
for item in arr {
let asset = Self::get_str(item, "currency").unwrap_or("").to_string();
if asset.is_empty() { continue; }
// Upbit balance fields (strings):
// - balance: total balance
// - locked: balance locked in orders
let total = item.get("balance")
.and_then(|v| v.as_str().and_then(|s| s.parse::<f64>().ok()))
.unwrap_or(0.0);
let locked = item.get("locked")
.and_then(|v| v.as_str().and_then(|s| s.parse::<f64>().ok()))
.unwrap_or(0.0);
let free = total - locked;
balances.push(Balance {
asset,
free,
locked,
total,
});
}
Ok(balances)
}
// ═══════════════════════════════════════════════════════════════════════════════
// WEBSOCKET PARSING (DIFFERENT FORMAT!)
// ═══════════════════════════════════════════════════════════════════════════════
/// Parse WebSocket ticker message.
///
/// Upbit emits two timestamps:
/// - `trade_timestamp` — milliseconds of the last actual trade
/// - `timestamp` — server send time (always fresh)
///
/// For consumers that just want "when did this ticker update?", server
/// send time is the freshest signal. We fall back to trade_timestamp,
/// then to "now()" so DATA_VALID checks don't flag legitimate streams as
/// stale.
///
/// Bid/ask are intentionally `None` here — Upbit's ticker channel does
/// NOT carry top-of-book quotes. Callers that need bid/ask must
/// subscribe to the orderbook channel.
pub fn parse_ws_ticker(data: &Value) -> ExchangeResult<Ticker> {
let timestamp = data.get("timestamp")
.and_then(|t| t.as_i64())
.or_else(|| data.get("trade_timestamp").and_then(|t| t.as_i64()))
.unwrap_or_else(|| {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
});
Ok(Ticker {
last_price: Self::get_f64(data, "trade_price").unwrap_or(0.0),
bid_price: None,
ask_price: None,
high_24h: Self::get_f64(data, "high_price"),
low_24h: Self::get_f64(data, "low_price"),
volume_24h: Self::get_f64(data, "acc_trade_volume_24h")
.or_else(|| Self::get_f64(data, "acc_trade_volume")),
quote_volume_24h: Self::get_f64(data, "acc_trade_price_24h"),
price_change_24h: Self::get_f64(data, "change_price"),
price_change_percent_24h: Self::get_f64(data, "change_rate")
.map(|r| r * 100.0),
timestamp,
})
}
/// Parse WebSocket trade message
pub fn parse_ws_trade(data: &Value) -> ExchangeResult<PublicTrade> {
let side = match Self::get_str(data, "ask_bid") {
Some("ASK") => TradeSide::Sell,
Some("BID") => TradeSide::Buy,
_ => TradeSide::Buy,
};
Ok(PublicTrade {
id: data.get("sequential_id")
.and_then(|v| v.as_i64())
.map(|id| id.to_string())
.unwrap_or_default(),
price: Self::get_f64(data, "trade_price").unwrap_or(0.0),
quantity: Self::get_f64(data, "trade_volume").unwrap_or(0.0),
timestamp: data.get("trade_timestamp")
.or_else(|| data.get("timestamp"))
.and_then(|t| t.as_i64())
.unwrap_or(0),
side,
})
}
/// Synthesize a Ticker from a WebSocket orderbook frame.
///
/// Upbit's ticker channel does not carry best bid/ask. Callers subscribed
/// to `StreamType::Ticker` receive a companion orderbook subscription so
/// that bid_price / ask_price can be filled from `orderbook_units[0]`.
///
/// Returns `None` if `orderbook_units` is missing or empty (no bid/ask
/// available yet), in which case the caller should skip emitting a Ticker.
pub fn parse_ws_orderbook_as_ticker(data: &Value) -> Option<Ticker> {
let units = data.get("orderbook_units")?.as_array()?;
let best = units.first()?;
let bid_price = Self::get_f64(best, "bid_price")?;
let ask_price = Self::get_f64(best, "ask_price")?;
let timestamp = data.get("timestamp")
.and_then(|t| t.as_i64())
.unwrap_or_else(|| {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0)
});
Some(Ticker {
// Orderbook frames carry no last-trade price. Use bid/ask midpoint
// as a proxy so Ticker-validity checks (last_price > 0) pass.
// Real last_price comes from the companion ticker-channel frame.
last_price: (bid_price + ask_price) / 2.0,
bid_price: Some(bid_price),
ask_price: Some(ask_price),
high_24h: None,
low_24h: None,
volume_24h: None,
quote_volume_24h: None,
price_change_24h: None,
price_change_percent_24h: None,
timestamp,
})
}
/// Parse WebSocket orderbook message
pub fn parse_ws_orderbook(data: &Value) -> ExchangeResult<OrderBook> {
let units = data.get("orderbook_units")
.and_then(|v| v.as_array())
.ok_or_else(|| ExchangeError::Parse("Missing orderbook_units".to_string()))?;
let mut bids = Vec::new();
let mut asks = Vec::new();
for unit in units {
if let (Some(bid_price), Some(bid_size)) = (
Self::get_f64(unit, "bid_price"),
Self::get_f64(unit, "bid_size")
) {
bids.push(OrderBookLevel::new(bid_price, bid_size));
}
if let (Some(ask_price), Some(ask_size)) = (
Self::get_f64(unit, "ask_price"),
Self::get_f64(unit, "ask_size")
) {
asks.push(OrderBookLevel::new(ask_price, ask_size));
}
}
Ok(OrderBook {
timestamp: data.get("timestamp")
.and_then(|t| t.as_i64())
.unwrap_or(0),
bids,
asks,
sequence: None,
last_update_id: None,
first_update_id: None,
prev_update_id: None,
event_time: None,
transaction_time: None,
checksum: None,
})
}
// ═══════════════════════════════════════════════════════════════════════════
// EXCHANGE INFO
// ═══════════════════════════════════════════════════════════════════════════
/// Parse exchange info from Upbit /v1/market/all response.
///
/// Response format:
/// ```json
/// [{"market":"KRW-BTC","korean_name":"비트코인","english_name":"Bitcoin","market_warning":"NONE"},...]
/// ```
/// Symbol format is "QUOTE-BASE" (e.g. "KRW-BTC" means base=BTC, quote=KRW)
pub fn parse_exchange_info(response: &Value, account_type: AccountType) -> ExchangeResult<Vec<SymbolInfo>> {
let items = response.as_array()
.ok_or_else(|| ExchangeError::Parse("Expected array response".to_string()))?;
let mut symbols = Vec::with_capacity(items.len());
for item in items {
let market = match item.get("market").and_then(|v| v.as_str()) {
Some(m) => m,
None => continue,
};
// Upbit format: "QUOTE-BASE" e.g. "KRW-BTC"
let parts: Vec<&str> = market.splitn(2, '-').collect();
if parts.len() != 2 {
continue;
}
let quote_asset = parts[0].to_string();
let base_asset = parts[1].to_string();
// Filter caution symbols if they have CAUTION warning (still tradeable but flag it)
// We include all by default
let status = "TRADING".to_string();
symbols.push(SymbolInfo {
symbol: market.to_string(),
base_asset,
quote_asset,
status,
price_precision: 8,
quantity_precision: 8,
min_quantity: None,
max_quantity: None,
tick_size: None,
step_size: None,
min_notional: None,
account_type,
});
}
Ok(symbols)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_parse_price() {
let response = json!([
{
"market": "SGD-BTC",
"trade_price": 67300.0
}
]);
let price = UpbitParser::parse_price(&response).unwrap();
assert_eq!(price, 67300.0);
}
#[test]
fn test_parse_error() {
let response = json!({
"error": {
"name": "invalid_signature",
"message": "JWT signature does not match"
}
});
let result = UpbitParser::check_error(&response);
assert!(result.is_err());
}
#[test]
fn test_parse_order_status() {
let data = json!({"state": "wait"});
assert_eq!(UpbitParser::parse_order_status(&data), OrderStatus::New);
let data = json!({"state": "done", "volume": "1.0", "executed_volume": "1.0"});
assert_eq!(UpbitParser::parse_order_status(&data), OrderStatus::Filled);
let data = json!({"state": "cancel"});
assert_eq!(UpbitParser::parse_order_status(&data), OrderStatus::Canceled);
}
}