Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OHLC endpoint #3

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ pub use kraken_rest_client::*;
mod messages;
use messages::{
unpack_kraken_result, AddOrderRequest, AssetPairsRequest, CancelAllOrdersAfterRequest, CancelOrderRequest, Empty,
GetOpenOrdersRequest, KrakenResult, TickerRequest,
GetOpenOrdersRequest, KrakenResult, OHLCRequest, TickerRequest,
};
pub use messages::{
AddOrderResponse, AssetPairsResponse, AssetTickerInfo, AssetsResponse, BalanceResponse, BsType,
AddOrderResponse, AssetOHLCInfo, AssetPairsResponse, AssetTickerInfo, AssetsResponse, BalanceResponse, BsType,
CancelAllOrdersAfterResponse, CancelAllOrdersResponse, CancelOrderResponse, GetOpenOrdersResponse,
GetWebSocketsTokenResponse, OrderAdded, OrderFlag, OrderInfo, OrderStatus, OrderType, SystemStatusResponse,
TickerResponse, TimeResponse, TxId, UserRefId,
GetWebSocketsTokenResponse, OHLCResponse, OrderAdded, OrderFlag, OrderInfo, OrderStatus, OrderType,
SystemStatusResponse, TickerResponse, TimeResponse, TxId, UserRefId,
};

use core::convert::TryFrom;
Expand All @@ -25,6 +25,8 @@ use std::collections::BTreeSet;
#[cfg(feature = "ws")]
pub mod ws;

mod tests;

/// A description of a market order to place
#[derive(Debug, Clone)]
pub struct MarketOrder {
Expand Down Expand Up @@ -100,6 +102,17 @@ impl KrakenRestAPI {
result.and_then(unpack_kraken_result)
}

/// (Public) Get the ohlc data for one or more asset pairs
///
/// Arguments:
/// * pairs: A list of Kraken asset pair strings to get ticker info about
/// * interval: An integer representing time frame interval in minutes (enum: 1 5 15 30 60 240 1440 10080 21600)
/// * since: An integer representing of the epoch (in ms) that you want to get data since
pub fn ohlc(&self, pairs: Vec<String>) -> Result<OHLCResponse> {
let result: Result<KrakenResult<OHLCResponse>> = self.client.query_public("OHLC", OHLCRequest { pair: pairs.join(","), interval: None, since: None });
result.and_then(unpack_kraken_result)
}

/// (Private) Get the balance
pub fn get_account_balance(&self) -> Result<BalanceResponse> {
let result: Result<KrakenResult<BalanceResponse>> = self.client.query_private("Balance", Empty {});
Expand Down
29 changes: 29 additions & 0 deletions src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,35 @@ pub struct AssetTickerInfo {
/// Type alias for response of Ticker API call
pub type TickerResponse = HashMap<String, AssetTickerInfo>;

/// A query object to kraken public "OHLC" API call
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct OHLCRequest {
/// A comma-separated list of kraken asset pair strings
pub pair: String,
/// An integer representing time frame interval in minutes (enum: 1 5 15 30 60 240 1440 10080 21600)
#[serde(skip_serializing_if = "Option::is_none")]
pub interval: Option<i64>,
/// An integer representing of the epoch (in ms) that you want to get data since
#[serde(skip_serializing_if = "Option::is_none")]
pub since: Option<i64>,
}

/// Result of kraken public "OHLC" API call
// It's result object includes arrays containing differing types, and is somewhat complex.
// See: <https://docs.kraken.com/rest/#operation/getOHLCData>
// Array of tick data arrays [int <time>, string <open>, string <high>, string <low>, string <close>, string <vwap>, string <volume>, int <count>]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssetOHLCInfo {
/// last is an ID to be used as since when polling for new, committed OHLC data
pub last: i64,
/// Array of tick data arrays [int <time>, string <open>, string <high>, string <low>, string <close>, string <vwap>, string <volume>, int <count>]
#[serde(alias = "*", alias="XXBTZUSD", default)]
pub pair: Vec<(i64, String, String, String, String, String, String, i64)>,
}

/// Type alias for response of OHLC API call
pub type OHLCResponse = AssetOHLCInfo;

/// Type alias for response of Balance API call
pub type BalanceResponse = HashMap<String, Decimal>;

Expand Down
94 changes: 94 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
use super::*;

#[cfg(test)]
mod tests {
use super::*;

/// test_ohlc_serialization sets up dummy data and then reads it in, serializing it to the OHLCResponse.
/// A working demonstration of this technique can be found below
#[test]
fn test_ohlc_serialization() {
let ohlc_test_data_from_result = r#"
{
"LOLCOIN": [
[
1616662740,
"52591.9",
"52599.9",
"52591.8",
"52599.9",
"52599.1",
"0.11091626",
5
]
],
"last": 1616662740
}
"#;

let ohlc_info: AssetOHLCInfo = serde_json::from_str(ohlc_test_data_from_result).unwrap();
assert_eq!(ohlc_info.last, 1616662740);
}

/// It seems that when the result for AssetTickerInfo is unwrapped and serialized,
/// it's scope is smaller than the previous example.
#[test]
fn test_asset_ticker_serialization() {
let ati_test_data = r#"
{
"a": [
"52609.60000",
"1",
"1.000"
],
"b": [
"52609.50000",
"1",
"1.000"
],
"c": [
"52641.10000",
"0.00080000"
],
"v": [
"1920.83610601",
"7954.00219674"
],
"p": [
"52389.94668",
"54022.90683"
],
"t": [
23329,
80463
],
"l": [
"51513.90000",
"51513.90000"
],
"h": [
"53219.90000",
"57200.00000"
],
"o": "52280.40000"
}
"#;

let ati: AssetTickerInfo = serde_json::from_str(ati_test_data).unwrap();
assert_eq!(ati.a[0], "52609.60000");
}

#[test]
fn test_client_connection() {
let conf = KrakenRestConfig::default();
let client = KrakenRestAPI::try_from(conf).unwrap();

let ohlc_res = client.ohlc(vec!["XXBTZUSD".to_string()]).unwrap();
for candle in ohlc_res.pair {
println!("Candle: {:?}", candle);
}

// let xxbtzusd = _ohlc_res.get("XXBTZUSD").unwrap();
// assert!(xxbtzusd.pair.0 == 0);
}
}