Guest User

Untitled

a guest
Nov 12th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. extern crate ws;
  2. extern crate env_logger;
  3. extern crate serde;
  4. extern crate serde_json;
  5.  
  6. #[macro_use] extern crate serde_derive;
  7. use ws::{connect, CloseCode};
  8. use std::collections::HashMap;
  9. use serde_json::{Value, Error};
  10. const WS_URL: &str = "wss://api2.poloniex.com";
  11. const HELLO_STRING: &str = r#"{ "command": "subscribe", "channel": "USDC_BTC" }"#;
  12.  
  13.  
  14. #[derive(Debug)]
  15. struct OrderBook {
  16. pair_name: String,
  17. pair_id: u64,
  18. bids: HashMap<String, String>,
  19. asks: HashMap<String, String>,
  20.  
  21. }
  22. fn parse_poloniex_full_order_book(msg: &str) -> OrderBook{
  23.  
  24. let f:Value = serde_json::from_str(msg).unwrap();
  25. let pair_id = f[0].as_u64().unwrap();
  26. let pair_name = f[2][0][1]["currencyPair"].as_str().unwrap();
  27. let asks = &f[2][0][1]["orderBook"][0].as_object().unwrap();
  28. let bids = &f[2][0][1]["orderBook"][1].as_object().unwrap();
  29. //println!("{:?}", asks);
  30. let asks: HashMap<String, String>= asks.iter().map(|(price, vol)|{
  31. (price.clone(), vol.as_str().unwrap().to_string())
  32. }).collect();
  33. let bids: HashMap<String, String>= bids.iter().map(|(price, vol)|{
  34. (price.clone(), vol.as_str().unwrap().to_string())
  35. }).collect();
  36. OrderBook {
  37. pair_name: pair_name.to_string(),
  38. pair_id,
  39. asks,
  40. bids,
  41. }
  42. }
  43.  
  44. fn main() {
  45. env_logger::init();
  46. connect(WS_URL, |out| {
  47. out.send(HELLO_STRING).unwrap();
  48.  
  49. move |msg: ws::Message| {
  50. let mut order_book = parse_poloniex_full_order_book(msg.as_text().unwrap());
  51. println!("{:?}", order_book);
  52. out.close(CloseCode::Normal)
  53. }
  54. }).unwrap()
  55. }
Add Comment
Please, Sign In to add comment