Skip to content

Commit

Permalink
Extended trade history parsing. (#240)
Browse files Browse the repository at this point in the history
- Added trade_history_from.
- Added trade_history_from_to.
  • Loading branch information
beborngod authored Jul 11, 2024
1 parent 04a78c9 commit fe58a92
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
45 changes: 44 additions & 1 deletion src/account.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use error_chain::bail;

use crate::util::build_signed_request;
use crate::util::{build_signed_request, is_start_time_valid};
use crate::model::{
AccountInformation, Balance, Empty, Order, OrderCanceled, TradeHistory, Transaction,
};
Expand Down Expand Up @@ -754,6 +754,49 @@ impl Account {
.get_signed(API::Spot(Spot::MyTrades), Some(request))
}

// Trade history starting from selected date
pub fn trade_history_from<S>(&self, symbol: S, start_time: u64) -> Result<Vec<TradeHistory>>
where
S: Into<String>,
{
if !is_start_time_valid(&start_time) {
return bail!("Start time should be less than the current time");
}

let mut parameters: BTreeMap<String, String> = BTreeMap::new();
parameters.insert("symbol".into(), symbol.into());
parameters.insert("startTime".into(), start_time.to_string());
let request = build_signed_request(parameters, self.recv_window)?;
self.client
.get_signed(API::Spot(Spot::MyTrades), Some(request))
}

// Trade history starting from selected time to some time
pub fn trade_history_from_to<S>(&self, symbol: S, start_time: u64, end_time: u64) -> Result<Vec<TradeHistory>>
where
S: Into<String>,
{
if end_time <= start_time {
return bail!("End time should be greater than start time");
}
if !is_start_time_valid(&start_time) {
return bail!("Start time should be less than the current time");
}
self.get_trades(symbol, start_time, end_time)
}

fn get_trades<S>(&self, symbol: S, start_time: u64, end_time: u64) -> Result<Vec<TradeHistory>>
where
S: Into<String>,
{
let mut trades = match self.trade_history_from(symbol, start_time) {
Ok(trades) => trades,
Err(e) => return Err(e),
};
trades.retain(|trade| trade.time <= end_time);
Ok(trades)
}

fn build_order(&self, order: OrderRequest) -> BTreeMap<String, String> {
let mut order_parameters: BTreeMap<String, String> = BTreeMap::new();

Expand Down
10 changes: 10 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,13 @@ fn get_timestamp(start: SystemTime) -> Result<u64> {
let since_epoch = start.duration_since(UNIX_EPOCH)?;
Ok(since_epoch.as_secs() * 1000 + u64::from(since_epoch.subsec_nanos()) / 1_000_000)
}

pub fn is_start_time_valid(start_time: &u64) -> bool {
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();

if start_time > &current_time {
false
} else {
true
}
}

0 comments on commit fe58a92

Please sign in to comment.