Skip to main content

nautilus_trading/examples/strategies/delta_neutral_vol/
strategy.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Delta-neutral short volatility hedger implementation.
17
18use std::fmt::Debug;
19
20use ahash::AHashMap;
21use anyhow::Context;
22use nautilus_common::{actor::DataActor, timer::TimeEvent};
23use nautilus_core::{DurationNanos, params::Params};
24use nautilus_model::{
25    data::{QuoteTick, black_scholes::compute_greeks, option_chain::OptionGreeks},
26    enums::{OptionKind, OrderSide, TimeInForce},
27    events::{
28        OrderCanceled, OrderDenied, OrderExpired, OrderFillVoided, OrderFilled, OrderRejected,
29    },
30    identifiers::{ClientId, ClientOrderId, InstrumentId},
31    instruments::Instrument,
32    orders::Order,
33    types::{Price, Quantity},
34};
35use rust_decimal::{Decimal, prelude::ToPrimitive};
36use serde_json::json;
37use ustr::Ustr;
38
39use super::config::DeltaNeutralVolConfig;
40use crate::{
41    nautilus_strategy,
42    strategy::{Strategy, StrategyCore},
43};
44
45const REHEDGE_TIMER: &str = "delta_rehedge";
46
47/// Delta-neutral short volatility hedger.
48///
49/// Tracks a short OTM call and put (strangle) on a configurable option
50/// family and delta-hedges the net Greek exposure with the underlying
51/// perpetual swap. Rehedges when portfolio delta exceeds a threshold
52/// or on a periodic timer.
53pub struct DeltaNeutralVol {
54    pub(super) core: StrategyCore,
55    pub(super) config: DeltaNeutralVolConfig,
56    pub(super) call_instrument_id: Option<InstrumentId>,
57    pub(super) put_instrument_id: Option<InstrumentId>,
58    pub(super) subscribed_greeks: Vec<InstrumentId>,
59    pub(super) call_delta: f64,
60    pub(super) put_delta: f64,
61    pub(super) call_mark_iv: Option<f64>,
62    pub(super) put_mark_iv: Option<f64>,
63    pub(super) call_quote: Option<QuoteTick>,
64    pub(super) put_quote: Option<QuoteTick>,
65    pub(super) call_greeks: Option<OptionGreeks>,
66    pub(super) put_greeks: Option<OptionGreeks>,
67    pub(super) call_delta_ready: bool,
68    pub(super) put_delta_ready: bool,
69    pub(super) call_position: f64,
70    pub(super) put_position: f64,
71    pub(super) hedge_position: f64,
72    pub(super) order_filled_qty: AHashMap<ClientOrderId, Decimal>,
73    pub(super) hedge_pending: bool,
74    pub(super) entry_attempted: bool,
75}
76
77impl DeltaNeutralVol {
78    /// Creates a new [`DeltaNeutralVol`] instance from config.
79    #[must_use]
80    pub fn new(config: DeltaNeutralVolConfig) -> Self {
81        Self {
82            core: StrategyCore::new(config.base.clone()),
83            call_instrument_id: None,
84            put_instrument_id: None,
85            subscribed_greeks: Vec::new(),
86            call_delta: 0.0,
87            put_delta: 0.0,
88            call_mark_iv: None,
89            put_mark_iv: None,
90            call_quote: None,
91            put_quote: None,
92            call_greeks: None,
93            put_greeks: None,
94            call_delta_ready: false,
95            put_delta_ready: false,
96            call_position: 0.0,
97            put_position: 0.0,
98            hedge_position: 0.0,
99            order_filled_qty: AHashMap::new(),
100            hedge_pending: false,
101            entry_attempted: false,
102            config,
103        }
104    }
105
106    /// Computes the net portfolio delta across option legs and hedge position.
107    #[must_use]
108    pub fn portfolio_delta(&self) -> f64 {
109        self.call_delta * self.call_position
110            + self.put_delta * self.put_position
111            + self.hedge_position
112    }
113
114    /// Returns `true` when both greeks legs have been initialized.
115    #[must_use]
116    pub fn greeks_initialized(&self) -> bool {
117        self.call_instrument_id.is_some()
118            && self.put_instrument_id.is_some()
119            && self.call_delta_ready
120            && self.put_delta_ready
121    }
122
123    /// Returns `true` when portfolio delta exceeds the rehedge threshold.
124    #[must_use]
125    pub fn should_rehedge(&self) -> bool {
126        self.greeks_initialized()
127            && self.portfolio_delta().abs() > self.config.rehedge_delta_threshold
128    }
129
130    /// Returns `true` when strangle entry can proceed.
131    #[must_use]
132    pub fn should_enter_strangle(&self) -> bool {
133        self.config.enter_strangle
134            && self.greeks_initialized()
135            && self.entry_price_data_ready()
136            && self.call_position == 0.0
137            && self.put_position == 0.0
138            && !self.entry_attempted
139            && !self.has_working_entry_orders()
140    }
141
142    /// Returns `true` when the configured entry pricing mode has enough data.
143    #[must_use]
144    pub fn entry_price_data_ready(&self) -> bool {
145        if self.config.entry_premium_offset_ticks.is_some() {
146            let Some(call_id) = self.call_instrument_id else {
147                return false;
148            };
149            let Some(put_id) = self.put_instrument_id else {
150                return false;
151            };
152
153            return self.premium_entry_data_ready(call_id, self.call_quote, self.call_greeks)
154                && self.premium_entry_data_ready(put_id, self.put_quote, self.put_greeks);
155        }
156
157        self.call_mark_iv.is_some() && self.put_mark_iv.is_some()
158    }
159
160    fn premium_entry_data_ready(
161        &self,
162        instrument_id: InstrumentId,
163        quote: Option<QuoteTick>,
164        greeks: Option<OptionGreeks>,
165    ) -> bool {
166        if quote.is_some_and(|q| q.ask_price.as_decimal() > Decimal::ZERO) {
167            return true;
168        }
169
170        let Some(greeks) = greeks else {
171            return false;
172        };
173
174        self.premium_from_greeks_ready(instrument_id, greeks)
175    }
176
177    fn premium_from_greeks_ready(&self, instrument_id: InstrumentId, greeks: OptionGreeks) -> bool {
178        let Some(underlying_price) = greeks.underlying_price else {
179            return false;
180        };
181        let Some(vol) = greeks.ask_iv.filter(|v| *v > 0.0).or(greeks.mark_iv) else {
182            return false;
183        };
184        let has_option_terms = {
185            let cache = self.cache();
186            let Some(instrument) = cache.instrument(&instrument_id) else {
187                return false;
188            };
189
190            instrument.strike_price().is_some()
191                && instrument.expiration_ns().is_some()
192                && instrument.option_kind().is_some()
193        };
194
195        underlying_price > 0.0 && vol > 0.0 && has_option_terms
196    }
197
198    /// Returns `true` when any open or in-flight orders exist on the option legs.
199    #[must_use]
200    pub fn has_working_entry_orders(&self) -> bool {
201        let cache = self.cache();
202
203        for id in [self.call_instrument_id, self.put_instrument_id]
204            .into_iter()
205            .flatten()
206        {
207            let open = cache.orders_open(None, Some(&id), None, None, None);
208            let inflight = cache.orders_inflight(None, Some(&id), None, None, None);
209
210            if !open.is_empty() || !inflight.is_empty() {
211                return true;
212            }
213        }
214        false
215    }
216
217    fn enter_strangle(&mut self) -> anyhow::Result<()> {
218        if !self.should_enter_strangle() {
219            return Ok(());
220        }
221
222        let call_id = self.call_instrument_id.unwrap();
223        let put_id = self.put_instrument_id.unwrap();
224        let contracts = self.config.contracts;
225        let tif = self.config.entry_time_in_force;
226        let client_id = self.config.client_id;
227
228        if let Some(offset_ticks) = self.config.entry_premium_offset_ticks {
229            let call_price =
230                self.entry_premium_price(call_id, self.call_quote, self.call_greeks)?;
231            let put_price = self.entry_premium_price(put_id, self.put_quote, self.put_greeks)?;
232
233            log::info!(
234                "Entering strangle: SELL {contracts} x {call_id} @ premium={call_price} \
235                 + SELL {contracts} x {put_id} @ premium={put_price} \
236                 (ask_offset_ticks={offset_ticks})",
237            );
238
239            self.submit_entry_order(call_id, contracts, call_price, tif, client_id, None)?;
240            self.submit_entry_order(put_id, contracts, put_price, tif, client_id, None)?;
241        } else {
242            let call_iv = self.call_mark_iv.unwrap();
243            let put_iv = self.put_mark_iv.unwrap();
244            let offset = self.config.entry_iv_offset;
245            let call_entry_iv = call_iv - offset;
246            let put_entry_iv = put_iv - offset;
247
248            log::info!(
249                "Entering strangle: SELL {contracts} x {call_id} @ iv={call_entry_iv:.4} \
250                 + SELL {contracts} x {put_id} @ iv={put_entry_iv:.4} (offset={offset})",
251            );
252
253            let call_params = Params::new(
254                [(
255                    self.config.iv_param_key.clone(),
256                    json!(call_entry_iv.to_string()),
257                )]
258                .into(),
259            );
260
261            self.submit_entry_order(
262                call_id,
263                contracts,
264                Price::new(call_entry_iv, 4),
265                tif,
266                client_id,
267                Some(call_params),
268            )?;
269
270            let put_params = Params::new(
271                [(
272                    self.config.iv_param_key.clone(),
273                    json!(put_entry_iv.to_string()),
274                )]
275                .into(),
276            );
277
278            self.submit_entry_order(
279                put_id,
280                contracts,
281                Price::new(put_entry_iv, 4),
282                tif,
283                client_id,
284                Some(put_params),
285            )?;
286        }
287
288        self.entry_attempted = true;
289
290        Ok(())
291    }
292
293    fn entry_premium_price(
294        &self,
295        instrument_id: InstrumentId,
296        quote: Option<QuoteTick>,
297        greeks: Option<OptionGreeks>,
298    ) -> anyhow::Result<Price> {
299        if let Some(quote) = quote
300            && quote.ask_price.as_decimal() > Decimal::ZERO
301        {
302            return self.offset_entry_price(instrument_id, quote.ask_price.as_f64());
303        }
304
305        let greeks = greeks.with_context(|| {
306            format!("missing quote and Greeks for premium entry on {instrument_id}")
307        })?;
308        let base_price = self.entry_premium_from_greeks(instrument_id, greeks)?;
309
310        self.offset_entry_price(instrument_id, base_price)
311    }
312
313    fn offset_entry_price(
314        &self,
315        instrument_id: InstrumentId,
316        base_price: f64,
317    ) -> anyhow::Result<Price> {
318        let offset_ticks = self
319            .config
320            .entry_premium_offset_ticks
321            .context("missing premium entry offset")?;
322
323        let cache = self.cache();
324        let instrument = cache.try_instrument(&instrument_id)?;
325
326        instrument
327            .next_ask_price(base_price, offset_ticks)
328            .with_context(|| {
329                format!(
330                    "failed to offset premium for {instrument_id}: price={base_price}, ticks={offset_ticks}"
331                )
332            })
333    }
334
335    fn entry_premium_from_greeks(
336        &self,
337        instrument_id: InstrumentId,
338        greeks: OptionGreeks,
339    ) -> anyhow::Result<f64> {
340        let (strike, expiration_ns, is_call) = {
341            let cache = self.cache();
342            let instrument = cache.try_instrument(&instrument_id)?;
343            let strike = instrument
344                .strike_price()
345                .with_context(|| format!("missing strike for {instrument_id}"))?
346                .as_f64();
347            let expiration_ns = instrument
348                .expiration_ns()
349                .with_context(|| format!("missing expiry for {instrument_id}"))?;
350            let option_kind = instrument
351                .option_kind()
352                .with_context(|| format!("missing option kind for {instrument_id}"))?;
353            let is_call = matches!(option_kind, OptionKind::Call);
354
355            (strike, expiration_ns, is_call)
356        };
357        let now_ns = self.clock().timestamp_ns();
358
359        if expiration_ns <= now_ns {
360            anyhow::bail!("Cannot price premium entry for expired instrument {instrument_id}");
361        }
362
363        let underlying_price = greeks
364            .underlying_price
365            .with_context(|| format!("missing underlying price for {instrument_id}"))?;
366        let (vol_source, vol) = greeks
367            .ask_iv
368            .filter(|v| *v > 0.0)
369            .map(|v| ("ask_iv", v))
370            .or_else(|| greeks.mark_iv.filter(|v| *v > 0.0).map(|v| ("mark_iv", v)))
371            .with_context(|| format!("missing positive IV for {instrument_id}"))?;
372        let years_to_expiry =
373            (expiration_ns - now_ns).as_secs_f64() / (365.25 * 24.0 * 60.0 * 60.0);
374        let price = compute_greeks(
375            underlying_price as f32,
376            strike as f32,
377            years_to_expiry as f32,
378            0.0,
379            0.0,
380            vol as f32,
381            is_call,
382        )
383        .price as f64;
384
385        if !price.is_finite() || price <= 0.0 {
386            anyhow::bail!(
387                "Computed non-positive premium for {instrument_id}: price={price}, \
388                 underlying={underlying_price}, strike={strike}, {vol_source}={vol}"
389            );
390        }
391
392        log::info!(
393            "Premium quote unavailable for {instrument_id}; using {vol_source}={vol:.4}, \
394             underlying={underlying_price:.2}, strike={strike:.2}, t={years_to_expiry:.6}"
395        );
396
397        Ok(price)
398    }
399
400    fn submit_entry_order(
401        &mut self,
402        instrument_id: InstrumentId,
403        contracts: u64,
404        price: Price,
405        tif: TimeInForce,
406        client_id: ClientId,
407        params: Option<Params>,
408    ) -> anyhow::Result<()> {
409        let order = self.order().limit(
410            instrument_id,
411            OrderSide::Sell,
412            Quantity::new(contracts as f64, 0),
413            price,
414            Some(tif),
415            None,
416            None,
417            None,
418            None,
419            None,
420            None,
421            None,
422            None,
423            None,
424            None,
425            None,
426        );
427
428        self.submit_order(order, None, Some(client_id), params)
429    }
430
431    fn check_rehedge(&mut self) -> anyhow::Result<()> {
432        let delta = self.portfolio_delta();
433
434        if !self.should_rehedge() {
435            return Ok(());
436        }
437
438        if self.hedge_pending {
439            log::info!("Hedge order already pending, skipping rehedge");
440            return Ok(());
441        }
442
443        let hedge_qty = delta.abs();
444        let side = if delta > 0.0 {
445            OrderSide::Sell
446        } else {
447            OrderSide::Buy
448        };
449
450        let hedge_id = self.config.hedge_instrument_id;
451        let size_precision = {
452            let cache = self.cache();
453            cache
454                .instrument(&hedge_id)
455                .map_or(2, |i| i.size_precision())
456        };
457
458        // A delta above the float threshold can still round to zero at the size precision.
459        let hedge_quantity = Quantity::new(hedge_qty, size_precision);
460
461        if hedge_quantity.is_zero() {
462            log::debug!(
463                "Rehedge delta {hedge_qty} rounds to zero at size precision {size_precision}, skipping"
464            );
465            return Ok(());
466        }
467
468        log::info!(
469            "Rehedging: portfolio_delta={delta:.4}, submitting {side:?} {hedge_quantity} on {hedge_id}",
470        );
471
472        let order = self.order().market(
473            hedge_id,
474            side,
475            hedge_quantity,
476            None,
477            None,
478            None,
479            None,
480            None,
481            None,
482            None,
483        );
484
485        self.hedge_pending = true;
486
487        if let Err(e) = self.submit_order(order, None, Some(self.config.client_id), None) {
488            self.hedge_pending = false;
489            return Err(e);
490        }
491
492        Ok(())
493    }
494
495    fn cached_position(&self, instrument_id: InstrumentId) -> f64 {
496        self.cache()
497            .positions_open(None, Some(&instrument_id), None, None, None)
498            .iter()
499            .map(|p| {
500                p.signed_qty
501                    .to_f64()
502                    .expect("Decimal quantity fits strategy analytics")
503            })
504            .sum()
505    }
506
507    fn position_mut(&mut self, instrument_id: InstrumentId) -> Option<&mut f64> {
508        if instrument_id == self.config.hedge_instrument_id {
509            Some(&mut self.hedge_position)
510        } else if Some(instrument_id) == self.call_instrument_id {
511            Some(&mut self.call_position)
512        } else if Some(instrument_id) == self.put_instrument_id {
513            Some(&mut self.put_position)
514        } else {
515            None
516        }
517    }
518}
519
520nautilus_strategy!(DeltaNeutralVol, {
521    fn on_order_filled(&mut self, event: &OrderFilled) {
522        let qty = event.last_qty.as_f64();
523        let signed_qty = match event.order_side {
524            OrderSide::Buy => qty,
525            OrderSide::Sell => -qty,
526        };
527
528        if let Some(position) = self.position_mut(event.instrument_id) {
529            *position += signed_qty;
530            *self
531                .order_filled_qty
532                .entry(event.client_order_id)
533                .or_default() += event.last_qty.as_decimal();
534        }
535
536        if event.instrument_id == self.config.hedge_instrument_id {
537            let is_closed = self
538                .cache()
539                .order(&event.client_order_id)
540                .is_some_and(|o| o.is_closed());
541
542            if is_closed {
543                self.hedge_pending = false;
544            }
545        }
546
547        log::info!(
548            "Fill: {} {:.4} {} | positions: call={}, put={}, hedge={}",
549            event.order_side,
550            event.last_qty,
551            event.instrument_id,
552            self.call_position,
553            self.put_position,
554            self.hedge_position,
555        );
556    }
557
558    fn on_order_fill_voided(&mut self, event: &OrderFillVoided) {
559        let Some(applied_qty) = self.order_filled_qty.get(&event.client_order_id).copied() else {
560            return;
561        };
562        let corrected_qty = {
563            let cache = self.cache();
564            let Some(order) = cache.order(&event.client_order_id) else {
565                log::warn!(
566                    "Cannot refresh voided fill, order {} missing from cache",
567                    event.client_order_id
568                );
569                return;
570            };
571            order.filled_qty().as_decimal()
572        };
573        let delta = corrected_qty - applied_qty;
574        let signed_delta = match event.order_side {
575            OrderSide::Buy => delta,
576            OrderSide::Sell => -delta,
577        };
578
579        if let Some(position) = self.position_mut(event.instrument_id) {
580            *position += signed_delta
581                .to_f64()
582                .expect("Decimal quantity fits strategy analytics");
583            self.order_filled_qty
584                .insert(event.client_order_id, corrected_qty);
585        }
586    }
587
588    fn on_order_canceled(&mut self, event: &OrderCanceled) {
589        let instrument_id = self
590            .cache()
591            .order(&event.client_order_id)
592            .map(|o| o.instrument_id());
593
594        if instrument_id == Some(self.config.hedge_instrument_id) {
595            self.hedge_pending = false;
596        }
597    }
598
599    fn on_order_rejected(&mut self, event: OrderRejected) {
600        if event.instrument_id == self.config.hedge_instrument_id {
601            self.hedge_pending = false;
602        }
603    }
604
605    fn on_order_denied(&mut self, event: OrderDenied) {
606        if event.instrument_id == self.config.hedge_instrument_id {
607            self.hedge_pending = false;
608        }
609    }
610
611    fn on_order_expired(&mut self, event: OrderExpired) {
612        if event.instrument_id == self.config.hedge_instrument_id {
613            self.hedge_pending = false;
614        }
615    }
616});
617
618impl Debug for DeltaNeutralVol {
619    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
620        f.debug_struct(stringify!(DeltaNeutralVol))
621            .field("config", &self.config)
622            .field("call_instrument_id", &self.call_instrument_id)
623            .field("put_instrument_id", &self.put_instrument_id)
624            .field("call_delta", &self.call_delta)
625            .field("put_delta", &self.put_delta)
626            .field("portfolio_delta", &self.portfolio_delta())
627            .finish()
628    }
629}
630
631impl DataActor for DeltaNeutralVol {
632    fn on_start(&mut self) -> anyhow::Result<()> {
633        let venue = self.config.hedge_instrument_id.venue;
634        let underlying = Ustr::from(&self.config.option_family);
635        let now_ns = self.clock().timestamp_ns().as_u64();
636
637        let mut calls: Vec<(InstrumentId, f64, u64)> = Vec::new();
638        let mut puts: Vec<(InstrumentId, f64, u64)> = Vec::new();
639
640        {
641            let cache = self.cache();
642            let instruments = cache.instruments(&venue, Some(&underlying));
643
644            for inst in &instruments {
645                let Some(expiry_ns) = inst.expiration_ns() else {
646                    continue;
647                };
648
649                if expiry_ns.as_u64() <= now_ns {
650                    continue;
651                }
652
653                if let Some(ref filter) = self.config.expiry_filter {
654                    let symbol = inst.symbol().inner();
655                    if !symbol.as_str().contains(filter.as_str()) {
656                        continue;
657                    }
658                }
659
660                let strike = match inst.strike_price() {
661                    Some(p) => p.as_f64(),
662                    None => continue,
663                };
664
665                match inst.option_kind() {
666                    Some(OptionKind::Call) => {
667                        calls.push((inst.id(), strike, expiry_ns.as_u64()));
668                    }
669                    Some(OptionKind::Put) => {
670                        puts.push((inst.id(), strike, expiry_ns.as_u64()));
671                    }
672                    None => {}
673                }
674            }
675        }
676
677        if calls.is_empty() || puts.is_empty() {
678            log::warn!(
679                "Insufficient options found for family '{}': {} calls, {} puts",
680                self.config.option_family,
681                calls.len(),
682                puts.len(),
683            );
684            return Ok(());
685        }
686
687        if self.config.expiry_filter.is_none() {
688            let nearest = calls
689                .iter()
690                .chain(puts.iter())
691                .map(|(_, _, exp)| *exp)
692                .min()
693                .unwrap();
694            calls.retain(|(_, _, exp)| *exp == nearest);
695            puts.retain(|(_, _, exp)| *exp == nearest);
696        }
697
698        if calls.is_empty() || puts.is_empty() {
699            log::warn!(
700                "Nearest expiry has incomplete chain: {} calls, {} puts",
701                calls.len(),
702                puts.len(),
703            );
704            return Ok(());
705        }
706
707        log::info!(
708            "Found {} calls and {} puts for family '{}'",
709            calls.len(),
710            puts.len(),
711            self.config.option_family,
712        );
713
714        // Strike price approximates delta ordering: higher strikes have
715        // lower call delta, lower strikes have more negative put delta.
716        // A production strategy would subscribe to all greeks first,
717        // then select strikes once actual deltas arrive.
718        calls.sort_by(|(_, s1, _), (_, s2, _)| s1.partial_cmp(s2).unwrap());
719        puts.sort_by(|(_, s1, _), (_, s2, _)| s1.partial_cmp(s2).unwrap());
720
721        // Select call at ~80th percentile strike (OTM, ~0.20 delta)
722        let call_idx = ((1.0 - self.config.target_call_delta) * calls.len() as f64) as usize;
723        let call_idx = call_idx.min(calls.len() - 1);
724        let (call_id, call_strike, _) = calls[call_idx];
725
726        // Select put at ~20th percentile strike (OTM, ~-0.20 delta)
727        let put_idx = (self.config.target_put_delta.abs() * puts.len() as f64) as usize;
728        let put_idx = put_idx.min(puts.len() - 1);
729        let (put_id, put_strike, _) = puts[put_idx];
730
731        self.call_instrument_id = Some(call_id);
732        self.put_instrument_id = Some(put_id);
733
734        log::info!("Selected call: {call_id} (strike={call_strike})");
735        log::info!("Selected put: {put_id} (strike={put_strike})");
736        log::info!(
737            "Strangle: {} contracts per leg, hedge on {}",
738            self.config.contracts,
739            self.config.hedge_instrument_id,
740        );
741
742        let strategy_id = self.strategy_id().expect("Registered strategy has an ID");
743        let hedge_id = self.config.hedge_instrument_id;
744        self.call_position = self.cached_position(call_id);
745        self.put_position = self.cached_position(put_id);
746        self.hedge_position = self.cached_position(hedge_id);
747        self.order_filled_qty = {
748            let cache = self.cache();
749            [call_id, put_id, hedge_id]
750                .iter()
751                .flat_map(|id| cache.orders(None, Some(id), Some(&strategy_id), None, None))
752                .map(|order| (order.client_order_id(), order.filled_qty().as_decimal()))
753                .collect()
754        };
755
756        if self.call_position != 0.0 || self.put_position != 0.0 || self.hedge_position != 0.0 {
757            log::info!(
758                "Hydrated positions: call={}, put={}, hedge={}",
759                self.call_position,
760                self.put_position,
761                self.hedge_position,
762            );
763        }
764
765        let client_id = self.config.client_id;
766
767        self.subscribe_option_greeks(call_id, Some(client_id), None);
768        self.subscribed_greeks.push(call_id);
769
770        self.subscribe_option_greeks(put_id, Some(client_id), None);
771        self.subscribed_greeks.push(put_id);
772
773        if self.config.enter_strangle && self.config.entry_premium_offset_ticks.is_some() {
774            self.subscribe_quotes(call_id, Some(client_id), None);
775            self.subscribe_quotes(put_id, Some(client_id), None);
776        }
777
778        self.subscribe_quotes(self.config.hedge_instrument_id, None, None);
779
780        let interval_ns = DurationNanos::try_from_secs(self.config.rehedge_interval_secs)?;
781        self.clock()
782            .set_timer_ns(REHEDGE_TIMER, interval_ns, None, None, None, None, None)?;
783
784        log::info!(
785            "Rehedge timer set: every {}s, threshold={}",
786            self.config.rehedge_interval_secs,
787            self.config.rehedge_delta_threshold,
788        );
789
790        if self.config.enter_strangle {
791            if let Some(offset_ticks) = self.config.entry_premium_offset_ticks {
792                log::info!(
793                    "Strangle entry enabled: SELL {} x {call_id} (call) + SELL {} x {put_id} \
794                     (put) once premium data arrives (ask_offset_ticks={offset_ticks})",
795                    self.config.contracts,
796                    self.config.contracts,
797                );
798            } else {
799                log::info!(
800                    "Strangle entry enabled: SELL {} x {call_id} (call) + SELL {} x {put_id} \
801                     (put) once Greeks arrive (iv_offset={})",
802                    self.config.contracts,
803                    self.config.contracts,
804                    self.config.entry_iv_offset,
805                );
806            }
807        } else {
808            log::info!(
809                "Strangle entry disabled: hedging externally-held positions only. \
810                 Monitoring {call_id} (call) + {put_id} (put)",
811            );
812        }
813
814        Ok(())
815    }
816
817    fn on_stop(&mut self) -> anyhow::Result<()> {
818        self.clock().cancel_timer(REHEDGE_TIMER);
819
820        let ids: Vec<InstrumentId> = std::mem::take(&mut self.subscribed_greeks);
821        let client_id = self.config.client_id;
822
823        for instrument_id in ids {
824            self.unsubscribe_option_greeks(instrument_id, Some(client_id), None);
825        }
826
827        let premium_entry_active =
828            self.config.enter_strangle && self.config.entry_premium_offset_ticks.is_some();
829
830        if let Some(call_id) = self.call_instrument_id {
831            if premium_entry_active {
832                self.unsubscribe_quotes(call_id, Some(client_id), None);
833            }
834            self.cancel_all_orders(call_id, None, None, true, None)?;
835        }
836
837        if let Some(put_id) = self.put_instrument_id {
838            if premium_entry_active {
839                self.unsubscribe_quotes(put_id, Some(client_id), None);
840            }
841            self.cancel_all_orders(put_id, None, None, true, None)?;
842        }
843
844        let hedge_id = self.config.hedge_instrument_id;
845        self.unsubscribe_quotes(hedge_id, None, None);
846        self.cancel_all_orders(hedge_id, None, None, true, None)?;
847        self.hedge_pending = false;
848
849        log::info!("Delta-neutral vol strategy stopped, positions left unchanged");
850
851        Ok(())
852    }
853
854    fn on_option_greeks(&mut self, greeks: &OptionGreeks) -> anyhow::Result<()> {
855        if Some(greeks.instrument_id) == self.call_instrument_id {
856            self.call_greeks = Some(*greeks);
857            self.call_delta = greeks.greeks.delta;
858            self.call_delta_ready = true;
859
860            if let Some(iv) = greeks.mark_iv {
861                self.call_mark_iv = Some(iv);
862            }
863        } else if Some(greeks.instrument_id) == self.put_instrument_id {
864            self.put_greeks = Some(*greeks);
865            self.put_delta = greeks.greeks.delta;
866            self.put_delta_ready = true;
867
868            if let Some(iv) = greeks.mark_iv {
869                self.put_mark_iv = Some(iv);
870            }
871        }
872
873        let portfolio_delta = self.portfolio_delta();
874
875        log::info!(
876            "Greeks update: {} delta={:.4} | portfolio_delta={portfolio_delta:.4} \
877             (call={:.4}*{}, put={:.4}*{}, hedge={})",
878            greeks.instrument_id,
879            greeks.greeks.delta,
880            self.call_delta,
881            self.call_position,
882            self.put_delta,
883            self.put_position,
884            self.hedge_position,
885        );
886
887        self.enter_strangle()?;
888        self.check_rehedge()?;
889
890        Ok(())
891    }
892
893    fn on_quote(&mut self, quote: &QuoteTick) -> anyhow::Result<()> {
894        if Some(quote.instrument_id) == self.call_instrument_id {
895            self.call_quote = Some(*quote);
896            log::debug!(
897                "Call quote: bid={} ask={} on {}",
898                quote.bid_price,
899                quote.ask_price,
900                quote.instrument_id,
901            );
902            self.enter_strangle()?;
903        } else if Some(quote.instrument_id) == self.put_instrument_id {
904            self.put_quote = Some(*quote);
905            log::debug!(
906                "Put quote: bid={} ask={} on {}",
907                quote.bid_price,
908                quote.ask_price,
909                quote.instrument_id,
910            );
911            self.enter_strangle()?;
912        } else if quote.instrument_id == self.config.hedge_instrument_id {
913            log::debug!(
914                "Hedge quote: bid={} ask={} on {}",
915                quote.bid_price,
916                quote.ask_price,
917                quote.instrument_id,
918            );
919        }
920
921        Ok(())
922    }
923
924    fn on_time_event(&mut self, event: &TimeEvent) -> anyhow::Result<()> {
925        if event.name == REHEDGE_TIMER {
926            let order_ids_purged: Vec<_> = {
927                let cache = self.cache();
928                self.order_filled_qty
929                    .keys()
930                    .filter(|id| !cache.order_exists(id))
931                    .copied()
932                    .collect()
933            };
934
935            for id in order_ids_purged {
936                self.order_filled_qty.remove(&id);
937            }
938
939            self.check_rehedge()?;
940        }
941
942        Ok(())
943    }
944
945    fn on_reset(&mut self) -> anyhow::Result<()> {
946        self.call_instrument_id = None;
947        self.put_instrument_id = None;
948        self.subscribed_greeks.clear();
949        self.call_delta = 0.0;
950        self.put_delta = 0.0;
951        self.call_mark_iv = None;
952        self.put_mark_iv = None;
953        self.call_quote = None;
954        self.put_quote = None;
955        self.call_greeks = None;
956        self.put_greeks = None;
957        self.call_delta_ready = false;
958        self.put_delta_ready = false;
959        self.call_position = 0.0;
960        self.put_position = 0.0;
961        self.hedge_position = 0.0;
962        self.order_filled_qty.clear();
963        self.hedge_pending = false;
964        self.entry_attempted = false;
965        Ok(())
966    }
967}