1use std::{collections::VecDeque, fmt::Debug};
19
20use ahash::AHashSet;
21use nautilus_common::{
22 actor::DataActor,
23 config::{ConfigError, ConfigResult},
24};
25use nautilus_core::{DurationNanos, UnixNanos};
26use nautilus_model::{
27 data::{Bar, QuoteTick, TradeTick},
28 enums::{AggressorSide, OrderSide, PositionSide, TimeInForce},
29 events::{
30 OrderCanceled, OrderDenied, OrderExpired, OrderFilled, OrderRejected, PositionClosed,
31 PositionOpened,
32 },
33 identifiers::{ClientOrderId, PositionId},
34 orders::{Order, OrderCore},
35 types::Quantity,
36};
37
38use super::config::HurstVpinDirectionalConfig;
39use crate::{
40 nautilus_strategy,
41 strategy::{Strategy, StrategyCore},
42};
43
44pub struct HurstVpinDirectional {
55 pub(super) core: StrategyCore,
56 pub(super) config: HurstVpinDirectionalConfig,
57 pub(super) returns: VecDeque<f64>,
58 pub(super) abs_imbalances: VecDeque<f64>,
59 pub(super) signed_imbalances: VecDeque<f64>,
60 pub(super) last_close: Option<f64>,
61 pub(super) bucket_buy_volume: f64,
62 pub(super) bucket_sell_volume: f64,
63 pub(super) hurst: Option<f64>,
64 pub(super) vpin: Option<f64>,
65 pub(super) signed_vpin: Option<f64>,
66 pub(super) position_opened_ns: Option<UnixNanos>,
67 pub(super) exit_cooldown: bool,
68 pub(super) entry_order_id: Option<ClientOrderId>,
69 pub(super) exit_order_ids: AHashSet<ClientOrderId>,
70}
71
72impl HurstVpinDirectional {
73 pub fn new_checked(config: HurstVpinDirectionalConfig) -> ConfigResult<Self> {
80 config.validate()?;
81 let hurst_window = config.hurst_window;
82 let vpin_window = config.vpin_window;
83 let core = StrategyCore::new_checked(config.base.clone())
84 .map_err(|e| ConfigError::invalid_value("order_id_tag", e.to_string()))?;
85 Ok(Self {
86 core,
87 config,
88 returns: VecDeque::with_capacity(hurst_window),
89 abs_imbalances: VecDeque::with_capacity(vpin_window),
90 signed_imbalances: VecDeque::with_capacity(vpin_window),
91 last_close: None,
92 bucket_buy_volume: 0.0,
93 bucket_sell_volume: 0.0,
94 hurst: None,
95 vpin: None,
96 signed_vpin: None,
97 position_opened_ns: None,
98 exit_cooldown: false,
99 entry_order_id: None,
100 exit_order_ids: AHashSet::new(),
101 })
102 }
103
104 #[must_use]
111 pub fn new(config: HurstVpinDirectionalConfig) -> Self {
112 Self::new_checked(config).expect("invalid Hurst/VPIN config")
113 }
114
115 pub(super) fn signals_ready(&self) -> bool {
116 self.hurst.is_some()
117 && self.vpin.is_some()
118 && self.signed_vpin.is_some()
119 && self.returns.len() == self.config.hurst_window
120 && self.abs_imbalances.len() == self.config.vpin_window
121 }
122
123 pub(super) fn push_bounded(values: &mut VecDeque<f64>, capacity: usize, value: f64) {
124 if values.len() == capacity {
125 values.pop_front();
126 }
127 values.push_back(value);
128 }
129
130 pub(super) fn rolling_mean(values: &VecDeque<f64>) -> Option<f64> {
131 if values.is_empty() {
132 return None;
133 }
134 Some(values.iter().copied().sum::<f64>() / values.len() as f64)
135 }
136
137 #[allow(
138 clippy::cognitive_complexity,
139 reason = "R/S regression is inherently nested"
140 )]
141 pub(super) fn estimate_hurst(&self) -> Option<f64> {
142 if self.returns.len() < self.config.hurst_window {
143 return None;
144 }
145
146 let returns: Vec<f64> = self.returns.iter().copied().collect();
147 let mut log_lags: Vec<f64> = Vec::new();
148 let mut log_rs: Vec<f64> = Vec::new();
149
150 for &lag in &self.config.hurst_lags {
151 if lag < 2 || lag > returns.len() {
152 continue;
153 }
154
155 let mut rs_values: Vec<f64> = Vec::new();
156
157 for start in (0..=returns.len().saturating_sub(lag)).step_by(lag) {
158 let chunk = &returns[start..start + lag];
159 let mean = chunk.iter().sum::<f64>() / lag as f64;
160
161 let mut running = 0.0f64;
162 let mut cum_min = 0.0f64;
163 let mut cum_max = 0.0f64;
164 let mut var_sum = 0.0f64;
165
166 for value in chunk {
167 let deviation = value - mean;
168 running += deviation;
169 if running < cum_min {
170 cum_min = running;
171 }
172
173 if running > cum_max {
174 cum_max = running;
175 }
176 var_sum += deviation * deviation;
177 }
178 let r_range = cum_max - cum_min;
179 let stdev = (var_sum / lag as f64).sqrt();
180 if r_range > 0.0 && stdev > 0.0 {
181 rs_values.push(r_range / stdev);
182 }
183 }
184
185 if !rs_values.is_empty() {
186 let avg_rs = rs_values.iter().copied().sum::<f64>() / rs_values.len() as f64;
187 log_lags.push((lag as f64).ln());
188 log_rs.push(avg_rs.ln());
189 }
190 }
191
192 if log_lags.len() < 2 {
193 return None;
194 }
195
196 let n = log_lags.len() as f64;
197 let sx: f64 = log_lags.iter().sum();
198 let sy: f64 = log_rs.iter().sum();
199 let sxx: f64 = log_lags.iter().map(|x| x * x).sum();
200 let sxy: f64 = log_lags.iter().zip(log_rs.iter()).map(|(x, y)| x * y).sum();
201 let denom = n * sxx - sx * sx;
202 if denom == 0.0 {
203 return None;
204 }
205 Some((n * sxy - sx * sy) / denom)
206 }
207
208 pub(super) fn try_open_position(&mut self) -> anyhow::Result<()> {
209 let (hurst, vpin, signed_vpin) = match (self.hurst, self.vpin, self.signed_vpin) {
210 (Some(h), Some(v), Some(s)) => (h, v, s),
211 _ => return Ok(()),
212 };
213
214 if hurst < self.config.hurst_enter || vpin < self.config.vpin_threshold {
215 return Ok(());
216 }
217
218 if signed_vpin > 0.0 {
219 self.submit_entry(OrderSide::Buy)?;
220 } else if signed_vpin < 0.0 {
221 self.submit_entry(OrderSide::Sell)?;
222 }
223
224 Ok(())
225 }
226
227 pub(super) fn check_regime_exit(&mut self) -> anyhow::Result<()> {
228 if !self.exit_order_ids.is_empty() {
229 return Ok(());
230 }
231 let hurst = match self.hurst {
232 Some(h) => h,
233 None => return Ok(()),
234 };
235
236 if hurst >= self.config.hurst_exit {
237 return Ok(());
238 }
239
240 let has_open_position = self.has_open_position();
241 if !has_open_position {
242 return Ok(());
243 }
244
245 log::info!("Regime decay (Hurst={hurst:.3}); closing position");
246 self.submit_close()
247 }
248
249 pub(super) fn check_holding_timeout(&mut self, tick: &QuoteTick) -> anyhow::Result<()> {
250 if !self.exit_order_ids.is_empty() {
251 return Ok(());
252 }
253 let opened_ns = match self.position_opened_ns {
254 Some(ns) => ns,
255 None => return Ok(()),
256 };
257 let held = tick.ts_event.saturating_duration_since(opened_ns);
258 if held < DurationNanos::try_from_secs(self.config.max_holding_secs)? {
259 return Ok(());
260 }
261
262 log::info!("Holding timeout reached; closing position");
263 self.submit_close()
264 }
265
266 fn submit_entry(&mut self, side: OrderSide) -> anyhow::Result<()> {
267 let instrument_id = self.config.instrument_id;
268 let trade_size = self.config.trade_size;
269 let order = self.order().market(
270 instrument_id,
271 side,
272 trade_size,
273 Some(TimeInForce::Ioc),
274 None, None, None, None, None, None, );
281 self.entry_order_id = Some(order.client_order_id());
282 if let Err(e) = self.submit_order(order, None, None, None) {
283 self.entry_order_id = None;
284 return Err(e);
285 }
286
287 Ok(())
288 }
289
290 fn submit_close(&mut self) -> anyhow::Result<()> {
291 let instrument_id = self.config.instrument_id;
292 let strategy_id = self.strategy_id().expect("Strategy must be registered");
293
294 let positions: Vec<(PositionId, Quantity, PositionSide)> = self
295 .cache()
296 .positions_open(None, Some(&instrument_id), Some(&strategy_id), None, None)
297 .iter()
298 .map(|p| (p.id, p.quantity, p.side))
299 .collect();
300
301 if positions.is_empty() {
302 return Ok(());
303 }
304
305 self.exit_cooldown = true;
306
307 for (position_id, quantity, side) in positions {
308 let Some(closing_side) = OrderCore::closing_side(side) else {
309 continue;
310 };
311 let close_order = self.order().market(
312 instrument_id,
313 closing_side,
314 quantity,
315 Some(TimeInForce::Ioc),
316 Some(true), None,
318 None,
319 None,
320 None,
321 None,
322 );
323 let client_order_id = close_order.client_order_id();
324 self.exit_order_ids.insert(client_order_id);
325 if let Err(e) = self.submit_order(close_order, Some(position_id), None, None) {
326 self.exit_order_ids.remove(&client_order_id);
327 return Err(e);
328 }
329 }
330
331 Ok(())
332 }
333
334 fn has_open_position(&self) -> bool {
335 let instrument_id = self.config.instrument_id;
336 let strategy_id = self.strategy_id().expect("Strategy must be registered");
337 !self
338 .cache()
339 .positions_open(None, Some(&instrument_id), Some(&strategy_id), None, None)
340 .is_empty()
341 }
342
343 fn refresh_position_opened_ns(&mut self) {
344 let instrument_id = self.config.instrument_id;
345 let strategy_id = self.strategy_id().expect("Strategy must be registered");
346 let cache = self.cache();
347 self.position_opened_ns = cache
348 .positions_open(None, Some(&instrument_id), Some(&strategy_id), None, None)
349 .iter()
350 .map(|position| position.ts_opened)
351 .min();
352 }
353
354 fn clear_latch_for(&mut self, client_order_id: ClientOrderId) {
355 if self.entry_order_id == Some(client_order_id) {
356 self.entry_order_id = None;
357 }
358 self.exit_order_ids.remove(&client_order_id);
359 }
360}
361
362nautilus_strategy!(HurstVpinDirectional, {
363 fn on_position_opened(&mut self, event: PositionOpened) {
364 if event.instrument_id == self.config.instrument_id {
365 self.position_opened_ns = Some(event.ts_event);
366 }
367 }
368
369 fn on_position_closed(&mut self, event: PositionClosed) {
370 if event.instrument_id == self.config.instrument_id {
371 self.refresh_position_opened_ns();
372 }
373 }
374
375 fn on_order_rejected(&mut self, event: OrderRejected) {
376 if event.instrument_id == self.config.instrument_id {
377 self.clear_latch_for(event.client_order_id);
378 }
379 }
380
381 fn on_order_expired(&mut self, event: OrderExpired) {
382 if event.instrument_id == self.config.instrument_id {
383 self.clear_latch_for(event.client_order_id);
384 }
385 }
386
387 fn on_order_denied(&mut self, event: OrderDenied) {
388 if event.instrument_id == self.config.instrument_id {
389 self.clear_latch_for(event.client_order_id);
390 }
391 }
392
393 fn on_order_filled(&mut self, event: &OrderFilled) {
394 if event.instrument_id != self.config.instrument_id {
395 return;
396 }
397
398 let closed = self
399 .cache()
400 .order(&event.client_order_id)
401 .is_some_and(|o| o.is_closed());
402
403 if closed {
404 self.clear_latch_for(event.client_order_id);
405 }
406 }
407
408 fn on_order_canceled(&mut self, event: &OrderCanceled) {
409 if event.instrument_id != self.config.instrument_id {
410 return;
411 }
412 self.clear_latch_for(event.client_order_id);
413 }
414});
415
416impl Debug for HurstVpinDirectional {
417 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
418 f.debug_struct(stringify!(HurstVpinDirectional))
419 .field("config", &self.config)
420 .field("hurst", &self.hurst)
421 .field("vpin", &self.vpin)
422 .field("signed_vpin", &self.signed_vpin)
423 .finish()
424 }
425}
426
427impl DataActor for HurstVpinDirectional {
428 fn on_start(&mut self) -> anyhow::Result<()> {
429 let instrument_id = self.config.instrument_id;
430 let bar_instrument_id = self.config.bar_type.instrument_id();
431 if bar_instrument_id != instrument_id {
432 anyhow::bail!(
433 "bar_type instrument {bar_instrument_id} does not match traded instrument {instrument_id}"
434 );
435 }
436
437 {
438 let cache = self.cache();
439 cache.try_instrument(&instrument_id)?;
440 }
441
442 self.refresh_position_opened_ns();
443
444 self.subscribe_bars(self.config.bar_type, None, None);
445 self.subscribe_quotes(instrument_id, None, None);
446 self.subscribe_trades(instrument_id, None, None);
447 Ok(())
448 }
449
450 fn on_stop(&mut self) -> anyhow::Result<()> {
451 let instrument_id = self.config.instrument_id;
452 self.cancel_all_orders(instrument_id, None, None, true, None)?;
453 self.close_all_positions(instrument_id, None, None, None, None, None, None, None)?;
454 self.unsubscribe_bars(self.config.bar_type, None, None);
455 self.unsubscribe_quotes(instrument_id, None, None);
456 self.unsubscribe_trades(instrument_id, None, None);
457 Ok(())
458 }
459
460 fn on_trade(&mut self, tick: &TradeTick) -> anyhow::Result<()> {
461 let size = tick.size.as_f64();
462 match tick.aggressor_side {
463 AggressorSide::Buy => self.bucket_buy_volume += size,
464 AggressorSide::Sell => self.bucket_sell_volume += size,
465 _ => {}
466 }
467 Ok(())
468 }
469
470 fn on_bar(&mut self, bar: &Bar) -> anyhow::Result<()> {
471 let close = bar.close.as_f64();
472
473 if let Some(prev) = self.last_close
474 && prev > 0.0
475 && close > 0.0
476 {
477 let window = self.config.hurst_window;
478 Self::push_bounded(&mut self.returns, window, (close / prev).ln());
479 }
480 self.last_close = Some(close);
481
482 let total = self.bucket_buy_volume + self.bucket_sell_volume;
483 if total > 0.0 {
484 let imbalance = (self.bucket_buy_volume - self.bucket_sell_volume) / total;
485 let vpin_window = self.config.vpin_window;
486 Self::push_bounded(&mut self.abs_imbalances, vpin_window, imbalance.abs());
487 Self::push_bounded(&mut self.signed_imbalances, vpin_window, imbalance);
488 }
489 self.bucket_buy_volume = 0.0;
490 self.bucket_sell_volume = 0.0;
491
492 self.hurst = self.estimate_hurst();
493 self.vpin = Self::rolling_mean(&self.abs_imbalances);
494 self.signed_vpin = Self::rolling_mean(&self.signed_imbalances);
495
496 if let Some(h) = self.hurst {
497 log::info!(
498 "Hurst={h:.3} VPIN={:.3} signed={:+.3} bar_close={close:.2}",
499 self.vpin.unwrap_or(0.0),
500 self.signed_vpin.unwrap_or(0.0),
501 );
502 }
503
504 self.exit_cooldown = false;
505 self.check_regime_exit()
506 }
507
508 fn on_quote(&mut self, quote: &QuoteTick) -> anyhow::Result<()> {
509 if self.has_open_position() {
510 return self.check_holding_timeout(quote);
511 }
512
513 if !self.signals_ready() {
514 return Ok(());
515 }
516
517 if self.exit_cooldown {
518 return Ok(());
519 }
520
521 if self.entry_order_id.is_some() || !self.exit_order_ids.is_empty() {
522 return Ok(());
523 }
524
525 let strategy_id = self.strategy_id().expect("Strategy must be registered");
526 let has_working = {
527 let cache = self.cache();
528 !cache
529 .orders_open(
530 None,
531 Some(&self.config.instrument_id),
532 Some(&strategy_id),
533 None,
534 None,
535 )
536 .is_empty()
537 || !cache
538 .orders_inflight(
539 None,
540 Some(&self.config.instrument_id),
541 Some(&strategy_id),
542 None,
543 None,
544 )
545 .is_empty()
546 };
547
548 if has_working {
549 return Ok(());
550 }
551
552 self.try_open_position()
553 }
554
555 fn on_reset(&mut self) -> anyhow::Result<()> {
556 self.returns.clear();
557 self.abs_imbalances.clear();
558 self.signed_imbalances.clear();
559 self.last_close = None;
560 self.bucket_buy_volume = 0.0;
561 self.bucket_sell_volume = 0.0;
562 self.hurst = None;
563 self.vpin = None;
564 self.signed_vpin = None;
565 self.position_opened_ns = None;
566 self.exit_cooldown = false;
567 self.entry_order_id = None;
568 self.exit_order_ids.clear();
569 Ok(())
570 }
571}