nautilus_trading/examples/strategies/orderbook_imbalance/
strategy.rs1use std::fmt::Debug;
19
20use nautilus_common::actor::{DataActor, DataActorNative};
21use nautilus_core::{UnixNanos, datetime::secs_to_nanos};
22use nautilus_model::{
23 data::OrderBookDeltas,
24 enums::OrderSide,
25 instruments::Instrument,
26 types::{Price, Quantity},
27};
28use rust_decimal::Decimal;
29
30use super::{config::OrderBookImbalanceConfig, state::ImbalanceState};
31use crate::{
32 nautilus_strategy,
33 strategy::{Strategy, StrategyCore},
34};
35
36pub struct OrderBookImbalance {
43 pub(super) core: StrategyCore,
44 pub(super) config: OrderBookImbalanceConfig,
45 pub(super) state: ImbalanceState,
46 trigger_interval_ns: u64,
47}
48
49impl OrderBookImbalance {
50 pub fn from_config(config: OrderBookImbalanceConfig) -> anyhow::Result<Self> {
57 config.validate()?;
58 let trigger_interval_ns = secs_to_nanos(config.min_seconds_between_triggers)?;
59 let core = StrategyCore::new_checked(config.base.clone())?;
60 Ok(Self {
61 core,
62 config,
63 state: ImbalanceState::default(),
64 trigger_interval_ns,
65 })
66 }
67}
68
69nautilus_strategy!(OrderBookImbalance);
70
71impl Debug for OrderBookImbalance {
72 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 f.debug_struct(stringify!(OrderBookImbalance))
74 .field("config", &self.config)
75 .field("state", &self.state)
76 .finish()
77 }
78}
79
80impl DataActor for OrderBookImbalance {
81 fn on_start(&mut self) -> anyhow::Result<()> {
82 let instrument_id = self.config.instrument_id;
83 let instrument = self
84 .cache()
85 .instrument(&instrument_id)
86 .ok_or_else(|| anyhow::anyhow!("Could not find instrument for {instrument_id}"))?;
87 self.state.size_precision = Some(instrument.size_precision());
88 self.subscribe_book_deltas(instrument_id, self.config.book_type, None, None, true, None);
89 Ok(())
90 }
91
92 fn on_stop(&mut self) -> anyhow::Result<()> {
93 let instrument_id = self.config.instrument_id;
94 self.unsubscribe_book_deltas(instrument_id, None, None);
95 if !self.config.dry_run {
96 self.cancel_all_orders(instrument_id, None, None, true, None)?;
97 self.close_all_positions(instrument_id, None, None, None, None, None, None, None)?;
98 }
99
100 println!(
101 "[{instrument_id}] summary: updates={} signals={} dry_run={}",
102 self.state.update_count, self.state.signal_count, self.config.dry_run
103 );
104 Ok(())
105 }
106
107 fn on_resume(&mut self) -> anyhow::Result<()> {
108 DataActor::on_start(self)
109 }
110
111 fn on_book_deltas(&mut self, deltas: &OrderBookDeltas) -> anyhow::Result<()> {
112 let instrument_id = self.config.instrument_id;
113 if deltas.instrument_id != instrument_id {
114 return Ok(());
115 }
116
117 self.state.update_count += 1;
118
119 let Some(size_precision) = self.state.size_precision else {
120 return Ok(());
121 };
122
123 let (bid_price, ask_price, bid, ask) = {
124 let cache = DataActorNative::cache_ref(self);
126
127 let Some(book) = cache.order_book(&instrument_id) else {
128 return Ok(());
129 };
130
131 let (Some(bid_price), Some(ask_price), Some(bid), Some(ask)) = (
132 book.best_bid_price(),
133 book.best_ask_price(),
134 book.best_bid_size(),
135 book.best_ask_size(),
136 ) else {
137 return Ok(());
138 };
139
140 (bid_price, ask_price, bid.as_decimal(), ask.as_decimal())
141 };
142
143 if bid_price >= ask_price || bid <= Decimal::ZERO || ask <= Decimal::ZERO {
144 return Ok(());
145 }
146
147 let smaller = bid.min(ask);
148 let larger = bid.max(ask);
149 let ratio = smaller / larger;
150
151 if self.config.log_interval > 0
152 && self
153 .state
154 .update_count
155 .is_multiple_of(self.config.log_interval)
156 {
157 println!(
158 "[{instrument_id}] update #{}: bid={bid} ask={ask} ratio={ratio}",
159 self.state.update_count
160 );
161 }
162
163 if larger <= self.config.trigger_min_size || ratio >= self.config.trigger_imbalance_ratio {
164 return Ok(());
165 }
166
167 let now = self.clock().timestamp_ns();
168
169 if self.state.last_trigger_ns.is_some_and(|last| {
170 now.as_u64().saturating_sub(last.as_u64()) < self.trigger_interval_ns
171 }) {
172 return Ok(());
173 }
174
175 if self
176 .cache()
177 .orders_inflight_count(None, None, self.strategy_id().as_ref(), None, None)
178 > 0
179 {
180 return Ok(());
181 }
182
183 let (side, price) = if bid > ask {
184 (OrderSide::Buy, ask_price)
185 } else {
186 (OrderSide::Sell, bid_price)
187 };
188
189 let size = smaller
190 .min(self.config.max_trade_size.as_decimal())
191 .trunc_with_scale(u32::from(size_precision));
192
193 if size <= Decimal::ZERO {
194 return Ok(());
195 }
196
197 let quantity = Quantity::from_decimal_dp(size, size_precision)?;
198 self.trigger(side, quantity, price, now)
199 }
200
201 fn on_reset(&mut self) -> anyhow::Result<()> {
202 self.state = ImbalanceState::default();
203 Ok(())
204 }
205}
206
207impl OrderBookImbalance {
208 fn trigger(
209 &mut self,
210 side: OrderSide,
211 quantity: Quantity,
212 price: Price,
213 now: UnixNanos,
214 ) -> anyhow::Result<()> {
215 let instrument_id = self.config.instrument_id;
216 self.state.last_trigger_ns = Some(now);
217 self.state.signal_count += 1;
218
219 if self.config.dry_run {
220 println!(
221 "[{instrument_id}] signal #{}: side={side} quantity={quantity} price={price} dry_run=true",
222 self.state.signal_count
223 );
224 return Ok(());
225 }
226
227 let order = self.order().limit(
228 instrument_id,
229 side,
230 quantity,
231 price,
232 Some(self.config.time_in_force),
233 None,
234 Some(false),
235 None,
236 None,
237 None,
238 None,
239 None,
240 None,
241 None,
242 None,
243 None,
244 );
245 self.submit_order(order, None, None, None)
246 }
247}