okx_swap_handle.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. use std::str::FromStr;
  2. use rust_decimal::Decimal;
  3. use rust_decimal::prelude::FromPrimitive;
  4. use serde_json::Value;
  5. use exchanges::response_base::ResponseData;
  6. use crate::{OrderBook, Trade, Record};
  7. pub fn handle_records(value: &Value) -> Vec<Record> {
  8. let symbol = value["arg"]["instId"].as_str().unwrap().to_string().replace("-", "_");
  9. let records_list = value["data"].as_array().unwrap();
  10. let mut records = vec![];
  11. for record_value in records_list {
  12. records.push(Record {
  13. time: Decimal::from_str(record_value[0].as_str().unwrap()).unwrap(),
  14. open: Decimal::from_str(record_value[1].as_str().unwrap()).unwrap(),
  15. high: Decimal::from_str(record_value[2].as_str().unwrap()).unwrap(),
  16. low: Decimal::from_str(record_value[3].as_str().unwrap()).unwrap(),
  17. close: Decimal::from_str(record_value[4].as_str().unwrap()).unwrap(),
  18. volume: Decimal::from_str(record_value[5].as_str().unwrap()).unwrap(),
  19. symbol: symbol.clone(),
  20. });
  21. }
  22. records
  23. }
  24. pub fn format_depth_items(value: &Value) -> Vec<OrderBook> {
  25. let mut depth_items: Vec<OrderBook> = vec![];
  26. for value in value.as_array().unwrap() {
  27. let price = Decimal::from_f64(value[0].as_f64().unwrap()).unwrap();
  28. let size = Decimal::from_f64(value[1].as_f64().unwrap()).unwrap();
  29. let value = price * size;
  30. depth_items.push(OrderBook {
  31. price,
  32. size,
  33. value,
  34. })
  35. }
  36. return depth_items;
  37. }
  38. pub fn format_trade_items(res_data: &ResponseData) -> Vec<Trade> {
  39. let result = res_data.data["data"].as_array().unwrap();
  40. let mut trades = vec![];
  41. for item in result {
  42. let side = item["side"].as_str().unwrap() == "buy";
  43. let size = if side {
  44. Decimal::from_str(item["sz"].as_str().unwrap()).unwrap()
  45. } else {
  46. -Decimal::from_str(item["sz"].as_str().unwrap()).unwrap()
  47. };
  48. let price = Decimal::from_str(item["px"].as_str().unwrap().to_string().as_str()).unwrap();
  49. let value = (size * price).abs();
  50. trades.push(Trade {
  51. id: item["tradeId"].as_str().unwrap().to_string(),
  52. time: Decimal::from_str(item["ts"].as_str().unwrap()).unwrap(),
  53. size,
  54. price,
  55. value,
  56. symbol: item["instId"].as_str().unwrap().to_string().replace("-", "_"),
  57. })
  58. }
  59. trades
  60. }