use std::collections::HashMap;
use rustc_serialize::json;
use rustc_serialize::Decodable;
use core;
use core::{Currency, Pair, TickerError};
#[derive(RustcEncodable, RustcDecodable, Debug, Copy, Clone)]
pub struct Ticker {
pub high: f32,
pub low: f32,
pub avg: f32,
pub vol: f32,
pub vol_cur: f32,
buy: f32,
sell: f32,
last: f32,
pub updated: f32,
}
type Tickers = HashMap<String, Ticker>;
impl core::Ticker for Ticker {
fn last(&self) -> f32 {
self.last
}
fn bid(&self) -> f32 {
self.buy
}
fn ask(&self) -> f32 {
self.sell
}
}
pub fn ticker(pair: Pair) -> Result<Ticker, TickerError> {
let pair_str = match pair {
(Currency::BTC, Currency::USD) => "btc_usd",
(Currency::BTC, Currency::RUR) => "btc_rur",
(Currency::BTC, Currency::EUR) => "btc_eur",
(Currency::LTC, Currency::BTC) => "ltc_btc",
(Currency::LTC, Currency::USD) => "ltc_usd",
(Currency::LTC, Currency::RUR) => "ltc_rur",
(Currency::LTC, Currency::EUR) => "ltc_eur",
(Currency::NMC, Currency::BTC) => "nmc_btc",
(Currency::NMC, Currency::USD) => "nmc_usd",
(Currency::NVC, Currency::BTC) => "nvc_btc",
(Currency::NVC, Currency::USD) => "nvc_usd",
(Currency::USD, Currency::RUR) => "usd_rur",
(Currency::EUR, Currency::USD) => "eur_usd",
(Currency::EUR, Currency::RUR) => "eur_rur",
(Currency::PPC, Currency::BTC) => "ppc_btc",
(Currency::PPC, Currency::USD) => "ppc_usd",
_ => return Err(TickerError::NotSupportPair),
};
let version = 3;
let base_url = "https://btc-e.com/api";
let method = "ticker";
let url_string = format!("{}/{}/{}/{}", base_url, version, method, pair_str);
let json = core::get_json(&url_string);
match json.find(pair_str) {
Some(x) => {
let x = x.clone();
let mut decoder = json::Decoder::new(x);
let result = Ticker::decode(&mut decoder);
match result {
Ok(x) => Ok(x),
Err(e) => Err(TickerError::DecoderError(e)),
}
},
None => Err(TickerError::Other),
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::Currency;
#[test]
fn test_ticker_okay() {
let pair = (Currency::BTC, Currency::USD);
let ticker = ticker(pair);
assert!(ticker.is_ok());
println!("{:?}", ticker.ok().unwrap());
}
#[test]
fn test_ticker_invalid_pair() {
let pair = (Currency::BTC, Currency::JPY);
let ticker = ticker(pair);
assert!(ticker.is_err());
}
}