Skip to content

Commit

Permalink
feat: add order recv hook.
Browse files Browse the repository at this point in the history
  • Loading branch information
nkaz001 committed Apr 15, 2024
1 parent 4be06ef commit 3b1064a
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 1 deletion.
60 changes: 60 additions & 0 deletions rust/examples/logging_order_latency.rs
@@ -0,0 +1,60 @@
use algo::gridtrading;
use chrono::Utc;
use hftbacktest::{
connector::binancefutures::{BinanceFutures, Endpoint},
live::bot::Bot,
Interface,
ty::Status
};
use tracing::info;

mod algo;

const ORDER_PREFIX: &str = "prefix";
const API_KEY: &str = "apikey";
const SECRET: &str = "secret";

fn prepare_live() -> Bot {
let binance_futures = BinanceFutures::builder()
.endpoint(Endpoint::Testnet)
.api_key(API_KEY)
.secret(SECRET)
.order_prefix(ORDER_PREFIX)
.build()
.unwrap();

let mut hbt = Bot::builder()
.register("binancefutures", binance_futures)
.add("binancefutures", "SOLUSDT", 0.001, 1.0)
.order_recv_hook(|req, resp| {
if (req.req == Status::New || req.req == Status::Canceled) && (resp.req == Status::None) {
info!(
req_timestamp = req.local_timestamp,
exch_timestamp = resp.exch_timestamp,
resp_timestamp = Utc::now().timestamp_nanos_opt().unwrap(),
req = ?req.req,
"Order response is received."
);
}
Ok(())
})
.build()
.unwrap();

hbt.run().unwrap();
hbt
}

fn main() {
tracing_subscriber::fmt::init();

let mut hbt = prepare_live();

let half_spread = 0.05;
let grid_interval = 0.05;
let skew = 0.004;
let order_qty = 1.0;

gridtrading(&mut hbt, half_spread, grid_interval, skew, order_qty).unwrap();
hbt.close().unwrap();
}
8 changes: 8 additions & 0 deletions rust/src/live/bot.rs
Expand Up @@ -102,6 +102,7 @@ async fn thread_main(
}

pub type ErrorHandler = Box<dyn FnMut(ErrorEvent) -> Result<(), BotError>>;
pub type OrderRecvHook = Box<dyn FnMut(&Order<()>, &Order<()>) -> Result<(), BotError>>;

pub struct Bot {
req_tx: UnboundedSender<Request>,
Expand All @@ -115,6 +116,7 @@ pub struct Bot {
conns: Option<HashMap<String, Box<dyn Connector + Send + 'static>>>,
assets: Vec<(String, AssetInfo)>,
error_handler: Option<ErrorHandler>,
order_hook: Option<OrderRecvHook>,
}

impl Bot {
Expand All @@ -123,13 +125,15 @@ impl Bot {
conns: HashMap::new(),
assets: Vec::new(),
error_handler: None,
order_hook: None,
}
}

pub fn new(
conns: HashMap<String, Box<dyn Connector + Send + 'static>>,
assets: Vec<(String, AssetInfo)>,
error_handler: Option<ErrorHandler>,
order_hook: Option<OrderRecvHook>
) -> Self {
let (ev_tx, ev_rx) = channel();
let (req_tx, req_rx) = unbounded_channel();
Expand Down Expand Up @@ -157,6 +161,7 @@ impl Bot {
assets,
trade,
error_handler,
order_hook
}
}

Expand Down Expand Up @@ -217,6 +222,9 @@ impl Bot {
{
Entry::Occupied(mut entry) => {
let ex_order = entry.get_mut();
if let Some(hook) = self.order_hook.as_mut() {
hook(ex_order, &data.order)?;
}
if data.order.exch_timestamp >= ex_order.exch_timestamp {
if ex_order.status == Status::Canceled
|| ex_order.status == Status::Expired
Expand Down
14 changes: 13 additions & 1 deletion rust/src/live/mod.rs
Expand Up @@ -6,6 +6,8 @@ use crate::{
ty::Error,
BuildError,
};
use crate::live::bot::OrderRecvHook;
use crate::ty::Order;

pub mod bot;

Expand All @@ -22,6 +24,7 @@ pub struct BotBuilder {
conns: HashMap<String, Box<dyn Connector + Send + 'static>>,
assets: Vec<(String, AssetInfo)>,
error_handler: Option<ErrorHandler>,
order_hook: Option<OrderRecvHook>,
}

impl BotBuilder {
Expand Down Expand Up @@ -67,6 +70,15 @@ impl BotBuilder {
self
}

/// Registers the order response receive hook.
pub fn order_recv_hook<Hook>(mut self, hook: Hook) -> Self
where
Hook: FnMut(&Order<()>, &Order<()>) -> Result<(), BotError> + 'static,
{
self.order_hook = Some(Box::new(hook));
self
}

/// Builds a live [`Bot`] based on the registered connectors and assets.
pub fn build(self) -> Result<Bot, BuildError> {
let mut dup = HashSet::new();
Expand All @@ -89,7 +101,7 @@ impl BotBuilder {
)?;
}

let con = Bot::new(conns, self.assets, self.error_handler);
let con = Bot::new(conns, self.assets, self.error_handler, self.order_hook);
Ok(con)
}
}

0 comments on commit 3b1064a

Please sign in to comment.