---
title: "Handling Data"
description: "LEAN passes the data you request to the OnData method so you can make trading decisions. The Slice object groups the data together with a timestamp."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/equity-options/handling-data
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/equity-options/handling-data.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/03%20Securities/99%20Asset%20Classes/02%20Equity%20Options/02%20Handling%20Data
modified: 2026-10-29
index: https://www.quantconnect.com/llms.txt
---

# Handling Data

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Securities > [Asset Classes](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes.md) > [Equity Options](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/equity-options.md) > Handling Data

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## Introduction

LEAN passes the data you request to the `on_data` method so you can make trading decisions. The `Slice` object that the `on_data` method receives groups all the data together at a single moment in time. To access the `Slice` outside of the `on_data` method, use the `current_slice` property of your algorithm.

All the data formats use `DataDictionary` objects to group data by `Symbol` and provide easy access to information. The plural of the type denotes the collection of objects. For instance, the `TradeBars` `DataDictionary` is made up of `TradeBar` objects. To access individual data points in the dictionary, you can index the dictionary with the contract ticker or `symbol`, but we recommend you use the `symbol`.

To view the resolutions that are available for Equity Options data, see [Resolutions](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/equity-options/requesting-data/individual-contracts.md#03-Resolutions).

## Trades

`TradeBar` objects are price bars that consolidate individual trades from the exchanges. They contain the open, high, low, close, and volume of trading activity over a period of time.

![Tradebar decomposition](https://cdn.quantconnect.com/docs/i/dataformat-tradebar.png)

To get the `TradeBar` objects in the `Slice`, index the `Slice` or index the `bars` property of the `Slice` with the contract `symbol`. If the contract doesn't actively trade or you are in the same time step as when you added the contract subscription, the `Slice` may not contain data for your `symbol`. To avoid issues, check if the `Slice` contains data for your contract before you index the `Slice` with the contract `symbol`.

```python
def on_data(self, slice: Slice) -> None:
    # Obtain the mapped TradeBar of the symbol if any
    trade_bar = slice.bars.get(self._contract_symbol)   # None if not found
```

You can also iterate through the `TradeBars` dictionary. The keys of the dictionary are the `Symbol` objects and the values are the `TradeBar` objects.

```python
def on_data(self, slice: Slice) -> None:
    # Iterate all received Symbol-TradeBar key-value pairs
    for symbol, trade_bar in slice.bars.items():
        close_price = trade_bar.close
```

`TradeBar` objects have the following properties:

*Members of `QuantConnect.Data.Market.TradeBar` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.Data.Market.TradeBar&language=python*

## Quotes

`QuoteBar` objects are bars that consolidate NBBO quotes from the exchanges. They contain the open, high, low, and close prices of the bid and ask. The `open`, `high`, `low`, and `close` properties of the `QuoteBar` object are the mean of the respective bid and ask prices. If the bid or ask portion of the `QuoteBar` has no data, the `open`, `high`, `low`, and `close` properties of the `QuoteBar` copy the values of either the `bid` or `ask` instead of taking their mean.

![Quotebar decomposition](https://cdn.quantconnect.com/docs/i/dataformat-quotebar.png)

To get the `QuoteBar` objects in the `Slice`, index the `QuoteBars` property of the `Slice` with the contract `symbol`. If the contract doesn't actively get quotes or you are in the same time step as when you added the contract subscription, the `Slice` may not contain data for your `symbol`. To avoid issues, check if the `Slice` contains data for your contract before you index the `Slice` with the contract `symbol`.

```python
def on_data(self, slice: Slice) -> None:
    # Obtain the mapped QuoteBar of the symbol if any
    quote_bar = slice.quote_bars.get(self._contract_symbol)   # None if not found
```

You can also iterate through the `QuoteBars` dictionary. The keys of the dictionary are the `Symbol` objects and the values are the `QuoteBar` objects.

```python
def on_data(self, slice: Slice) -> None:
    # Iterate all received Symbol-QuoteBar key-value pairs
    for symbol, quote_bar in slice.quote_bars.items():
        ask_price = quote_bar.ask.close
```

`QuoteBar` objects let LEAN incorporate spread costs into your [simulated trade fills](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/trade-fills/key-concepts.md) to make backtest results more realistic.

`QuoteBar` objects have the following properties:

*Members of `QuantConnect.Data.Market.QuoteBar` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.Data.Market.QuoteBar&language=python*

## Option Chains

`OptionChain` objects represent an entire chain of Option contracts for a single underlying security.

To get the `OptionChain`, index the `option_chains` property of the `Slice` with the canonical `Symbol`.

```python
def on_data(self, slice: Slice) -> None:
    # Try to get the OptionChain using the canonical symbol (None if no OptionChain return)
    chain = slice.option_chains.get(self._contract_symbol.Canonical)
    if chain:
        # Get all contracts if the OptionChain contains any member
        contracts = chain.contracts
```

You can also loop through the `option_chains` property to get each `OptionChain`.

```python
def on_data(self, slice: Slice) -> None:
    # Iterate all received Canonical Symbol-OptionChain key-value pairs
    for canonical_symbol, chain in slice.option_chains.items():
        contracts = chain.contracts
```

### Filter Chains

`OptionChain` objects provide the same filter methods as [Option universe selection](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/equity-options.md), with the same names and the same behavior. Each method returns a new `OptionChain` and leaves the source chain unchanged, so you can chain the calls together.

```python
# Select the call contracts that expire in 20-40 days and are within 3 strikes of the underlying price.
contracts = chain.calls_only().expiration(20, 40).strikes(-3, 3)
```

The contract property filters, the Greeks and implied volatility filters, and the [Option strategy](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/option-strategies.md) filters are all available. The strategy filters select the legs of the strategy, or return an empty chain when no set of contracts matches the criteria.

```python
# Select the four legs of an Iron Condor that expires in at least 30 days.
legs = chain.iron_condor(30, 5, 10)
```

To filter the chain with your own predicate, call the `where` method.

```python
liquid_contracts = chain.where(lambda contract: contract.open_interest > 100)
```

The `standards_only` and `weeklys_only` methods of a chain apply to the contracts the chain already holds, so you can combine them with the expiration filters in any order. In universe selection, these two filters always run last.

### Select Contracts

To get a single contract from the chain, call the `select` method. It returns the contract that best matches the criteria you provide, or `None` when the chain holds no match.

```python
# Get the put contract at 85% of the underlying price, from the expiration closest to 30 days out.
contract = chain.select(OptionRight.PUT, target_dte=30, moneyness=-0.15)
```

These methods take a *target* number of days to expiration and return the closest expiration within the optional `min_dte` and `max_dte` window. The Option strategy filters instead take a *minimum* number of days to expiration and return the first expiration at or after it.

The following table describes the contract selection methods of the `OptionChain` class:

`select(right: OptionRight = None, target_dte: int = None, min_dte: int = None, max_dte: int = None, moneyness: float = 0)`

Selects the contract with the strike closest to `moneyness` as a signed fraction of the underlying price. For example, -0.15 targets 85% of the underlying price and 0 targets the at-the-money strike.

`pick(right: OptionRight = None, target_dte: int = None, min_dte: int = None, max_dte: int = None, moneyness: float = 0)`

A synonym of the `select` method.

`select_by_strike_distance(strike_from_atm: float, right: OptionRight = None, target_dte: int = None, min_dte: int = None, max_dte: int = None)`

Selects the contract with the strike closest to a signed distance from the underlying price, in price units. This is how the Option strategy filters express their strikes.

`select_by_delta(target_delta: float, right: OptionRight = None, target_dte: int = None, min_dte: int = None, max_dte: int = None)`

Selects the contract with the absolute delta closest to the absolute target, so a 30 delta put is 0.3 or -0.3. Contracts without Greeks are ignored.

`at_the_money(right: OptionRight = None)`

Selects the contract with the strike closest to the underlying price. Ties go to the lower strike, then to the nearest expiration.

`closest_expiry(target_dte: int = None, min_dte: int = None, max_dte: int = None)`

Returns the expiration date closest to the target number of days out, or `None` when no expiration falls in the window.

`at(expiry: datetime)`

Returns a new chain with the contracts of the given expiration date. The time of day is ignored.

The expiration methods compose with the chain filters, so you can narrow a single expiration down further.

```python
expiry = chain.closest_expiry(target_dte=45, min_dte=30, max_dte=60)
contracts = chain.at(expiry).puts_only().strikes(-2, 0)
```

`OptionChain` objects also expose read-only views of their contracts: `calls` and `puts`, sorted by expiration and then strike; `expiries`, the distinct expiration dates in ascending order; and `strike_prices`, the distinct strikes in ascending order.

`strike_prices` is a `StrikeList` object, which adds the `closest_to`, `first_above`, and `first_below` methods. Each one takes a reference price and returns `None` when no strike matches.

```python
strike = chain.strike_prices.first_above(chain.underlying.price)
```

### Properties

`OptionChain` objects have the following properties:

*Members of `QuantConnect.Data.Market.OptionChain` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.Data.Market.OptionChain&language=python*

## Option Contracts

`OptionContract` objects represent the data of a single Option contract in the market. To get the Option contracts in the `Slice`, use the `contracts` property of the `OptionChain`.

```python
def on_data(self, slice: Slice) -> None:
    # Try to get the OptionChain using the canonical symbol
    chain = slice.option_chains.get(self._contract_symbol.canonical)
    if chain:
        # Get individual contract data
        contract = chain.contracts.get(self._contract_symbol)
        if contract:
            price = contract.price
```

### Greeks and Implied Volatility

To get the Greeks and implied volatility of an Option contract, use the `greeks` and `implied_volatility` members.

```python
def on_data(self, slice: Slice) -> None:
    # Try to get the OptionChain using the canonical symbol
    chain = slice.option_chains.get(self._contract_symbol.canonical)
    if chain:
        # Get individual contract data
        contract = chain.contracts.get(self._contract_symbol)
        if contract:
            # Get greeks data of the selected contract
            delta = contract.greeks.delta
            iv = contract.implied_volatility
```

LEAN only calculates Greeks and implied volatility when you request them because they are expensive operations. If you invoke the `greeks` property, the Greeks aren't calculated. However, if you invoke the `greeks.delta`, LEAN calculates the delta. To avoid unecessary computation in your algorithm, only request the Greeks and implied volatility when you need them. For more information about the Greeks and implied volatility, see [Options Pricing](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/options-models/pricing.md).

### Open Interest

Open interest is the number of outstanding contracts that haven't been settled. It provides a measure of investor interest and the market liquidity, so it's a popular metric to use for contract selection. Open interest is calculated once per day. To get the latest open interest value, use the `open_interest` property of the `Option` or `option_contract`.

```python
def on_data(self, slice: Slice) -> None:
    # Try to get the option_chains using the canonical symbol
    chain = slice.option_chains.get(self._contract_symbol.canonical)
    if chain:
        # Get individual contract data
        contract = chain.contracts.get(self._contract_symbol)
        if contract:
            # Get the open interest of the selected contracts
            open_interest = contract.open_interest
```

### Properties

`OptionContract` objects have the following properties:

*Members of `QuantConnect.Data.Market.OptionContract` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.Data.Market.OptionContract&language=python*

## Examples

### Example 1: Get Mid Price For Individual Contracts

This example shows how to handle `QuoteBar` data for shortlisted Equity Option contracts to calculate mid price using bid close and ask close data, while [filter individual option contracts and request data](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/equity-options/requesting-data/individual-contracts.md) using `self.option_chain` method for the contracts that expires within the current week. Using mid price, we can examine the market fair value of the Option and compare with model theoretical price.

```python
class EquityOptionHandlingDataAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 9, 30)

        self.contracts = []

        # Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering.
        self.settings.seed_initial_prices = True
        # Subscribe to underlying data for ATM calculation using the update underlying price.
        # Set data normalization mode to raw is required to ensure strike price and underlying price is comparable.
        self.spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol

        # Update the tradable contracts daily before market open since the option contract list provider populate them daily.
        self.schedule.on(
            self.date_rules.every_day(self.spy),
            self.time_rules.at(9, 0),
            self.update_contracts
        )

    def update_contracts(self) -> None:
        # Get all contracts that expiring this week to trade with, subscribe to data for trading need.
        contracts = self.option_chain(self.spy)
        self.contracts = [self.add_option_contract(x).symbol for x in contracts
            if x.id.date < Expiry.end_of_week(self.time)]

    def on_data(self, slice: Slice) -> None:
        # Only focus on filtered list of option contracts to trade.
        for contract in self.contracts:
            # Mid price can only be calculated when quote bar data is available.
            quote = slice.quote_bars.get(contract)
            if quote and quote.bid is not None and quote.ask is not None:
                # Mid price = average of bid close price and ask close price.
                mid_price = (quote.bid.close + quote.ask.close) * 0.5
```

### Example 2: Get Mid Price For Universe

This example shows how to handle `QuoteBar` data for shortlisted Equity Option contracts to calculate mid price using bid close and ask close data, while [request data through universe selection function](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/equity-options/requesting-data/universes.md) using `set_filter` method for the contracts that expires within the current week. Using mid price, we can examine the market fair value of the Option and compare with model theoretical price.

```python
class EquityOptionHandlingDataAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 9, 30)

        # Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering.
        self.settings.seed_initial_prices = True
        # Subscribe to underlying data for ATM calculation using the update underlying price.
        # Set data normalization mode to raw is required to ensure strike price and underlying price is comparable.
        spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol
        # Subscribe to SPY option data.
        option = self.add_option(spy)
        self._symbol = option.symbol
        # We wish to only trade the contracts expiring within the same week since they have the highest volume.
        option.set_filter(lambda u: u.contracts(lambda x: [s for s in x if s.id.date <= Expiry.end_of_week(self.time)]))

    def on_data(self, slice: Slice) -> None:
        # Only want to obtain the option chain of the selected symbol.
        chain = slice.option_chains.get(self._symbol)
        if not chain:
            return

        for contract in chain:
            # Mid price = average of bid close price and ask close price
            mid_price = (contract.bid_price + contract.ask_price) * 0.5
```

### Example 3: Get Instant Delta

The option greeks change rapidly, so we need to obtain the instant greeks to accurately calculate the hedge size for arbitration or replication portfolio. You can call the `Greeks` property from the `OptionChain` data to access various greeks. In this example, we will demonstrate how to obtain the contract with delta closest to 0.4 among all call contracts expiring the same week.

```python
class EquityOptionHandlingDataAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2024, 9, 5)
        self.set_end_date(2024, 9, 5)

        # Seed the price with last known price to ensure the underlying price data is available on initial option contract filtering.
        self.settings.seed_initial_prices = True
        # Subscribe to underlying data for ATM calculation using the update underlying price.
        # Set data normalization mode to raw is required to ensure strike price and underlying price is comparable.
        spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW).symbol
        # Subscribe to SPY option data.
        option = self.add_option(spy)
        self._symbol = option.symbol
        # We wish to only trade the contracts expiring within the same week since they have the highest volume.
        # 0.4 Delta will only appear in call contracts.
        option.set_filter(lambda u: u.delta(0.2, 0.6).contracts(lambda x: [s for s in x if s.id.date <= Expiry.end_of_week(self.time)]))

    def on_data(self, slice: Slice) -> None:
        # Only want to obtain the option chain of the selected symbol.
        chain = slice.option_chains.get(self._symbol)
        if not chain:
            return

        # Get the contract with Delta closest to 0.4 to trade.
        # The arbitary delta criterion might be set due to hedging need or risk adjustment.
        selected = sorted(chain, key=lambda x: abs(x.greeks.delta - 0.4))[0]
```

### Example 4: Delta-Hedged Short Straddle

This example demonstrates a delta-hedged [short straddle](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/option-strategies/short-straddle.md) strategy that sells an at-the-money (ATM) straddle with 7-30 days to expiration and continuously neutralizes the portfolio delta using the underlying shares. The `StraddleSelector` helper class picks the farthest expiry within the DTE range and the strike closest to the spot price. On each [slice](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/time-modeling/timeslices.md), the combined Option delta is accumulated from the `OptionChain` and the net portfolio delta is computed by adding the underlying position. The `DeltaHedger` helper enforces a minimum share threshold and a rehedge band to avoid over-trading, and applies a time delay between successive hedges. A [Scheduled Event](https://www.quantconnect.com/docs/v2/writing-algorithms/scheduled-events.md) closes the straddle on expiration day and assignment events are handled to keep the underlying position clean.

```python
class DeltaHedgedStraddleAlgo(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(1_000_000)
        self.settings.seed_initial_prices = True
        self._spy = self.add_equity("SPY", data_normalization_mode=DataNormalizationMode.RAW)
        # Initialize the straddle selector with 7-30 day DTE range.
        self._straddle_selector = StraddleSelector(min_dte=7, max_dte=30)
        # Initialize the delta hedger with 30 share minimum, 20 share rehedge band, and 4 hour delay.
        self._hedger = DeltaHedger(30, 20, timedelta(hours=4))
        self._canonical_option = Symbol.create_canonical_option(self._spy)
        # Set the straddle position size to 50% of portfolio value.
        self._straddle_weight = 0.5
        self._short_straddle = None
        self._exit_day = None
        # Schedule the rebalance method to run 30 minutes after market open.
        self.schedule.on(
            self.date_rules.every_day(self._spy),
            self.time_rules.after_market_open(self._spy, 30),
            self._rebalance
        )
        # Schedule the close expiring method to run 60 minutes before market close.
        self.schedule.on(
            self.date_rules.every_day(self._spy),
            self.time_rules.before_market_close(self._spy, 60),
            self._close_expiring
        )
        self.set_warm_up(timedelta(45))

    def on_data(self, data):
        if self.is_warming_up or not data.bars:
            return
        chain = data.option_chains.get(self._canonical_option)
        if not chain or not self._short_straddle:
            return
        # Accumulate the delta from all option legs in the straddle.
        for leg in self._short_straddle.option_legs:
            contract = chain.contracts.get(leg.symbol)
            if contract:
                self._delta += contract.greeks.delta
        # Calculate the net portfolio delta including underlying and options.
        net_delta = self._hedger.compute_net_delta(self, self._short_straddle.option_legs, self._spy.holdings.quantity, self._delta)
        # Reset the delta accumulator for the next iteration.
        self._delta = 0
        # Exit if it's not time to hedge or net delta is zero.
        if not (self._hedger.should_hedge(self.time) and net_delta):
            return
        # Calculate the hedge quantity needed to neutralize delta.
        hedge_qty = self._hedger.get_quantity(net_delta)
        if hedge_qty:
            self.market_order(self._spy, hedge_qty, tag=f"Daily delta hedge ({net_delta:.2f} share delta)")
            # Record the hedge operation with timestamp and delta.
            self._hedger.record_hedge(self.time, net_delta)
            # Update the net delta after the hedge.
            net_delta += hedge_qty
        self.plot("Portfolio Delta", "Delta", net_delta)

    def _rebalance(self):
        if self.is_warming_up or self.portfolio.invested:
            return
        chain = self.option_chain(self._spy)
        if not chain:
            return
        # Use the straddle selector to find the best ATM straddle.
        result = self._straddle_selector.select(chain, self._spy.price, self.time.date())
        if not result:
            return
        self._delta, expiry, strike = result
        self._short_straddle = OptionStrategies.short_straddle(self._canonical_option, strike, expiry)
        # Calculate the number of contracts based on portfolio value and weight.
        qty = int(self.portfolio.total_portfolio_value * self._straddle_weight / (self._spy.price * 100.0))
        if qty:
            self.buy(self._short_straddle, qty, tag=f"Sell ATM straddle exp {expiry.date()}")
        self._hedger.reset()
        self._exit_day = expiry.date()

    def _close_expiring(self):
        if not self._short_straddle or not self._exit_day or self.time.date() < self._exit_day:
            return
        # Liquidate all positions before expiration.
        self.liquidate(tag="Expiry hedge liquidation")

    def on_order_event(self, order_event):
        # Handle option assignment events.
        if order_event.status == OrderStatus.FILLED and order_event.is_assignment:
            # Liquidate all option legs of the straddle.
            for leg in self._short_straddle.option_legs:
                self.liquidate(leg.symbol, tag="Assignment liquidation")
            # Determine the direction based on whether it's a call or put assignment.
            direction = 1 if self.securities[order_event.symbol].right == OptionRight.CALL else -1
            self.market_order(self._spy, -self._spy.holdings.quantity + order_event.quantity * direction * 100)
            self._short_straddle = None

class StraddleSelector:

    def __init__(self, min_dte, max_dte):
        # Store the minimum days to expiration for contract selection.
        self._min_dte = min_dte
        # Store the maximum days to expiration for contract selection.
        self._max_dte = max_dte

    def select(self, chain, spot_price, current_date):
        # Filter contracts to those within the specified DTE range.
        contracts = [
            contract for contract in chain
            if self._min_dte <= (contract.expiry.date() - current_date).days <= self._max_dte
        ]
        if not contracts:
            return
        # Select the farthest expiration date from the filtered contracts.
        expiry = max(contract.expiry for contract in contracts)
        # Filter to only contracts with the selected expiration.
        contracts = [contract for contract in contracts if contract.expiry == expiry]
        # Find the strike price closest to the current spot price.
        strike = min(contracts, key=lambda c: abs(c.strike - spot_price)).strike
        # Filter to only contracts with the selected strike.
        contracts = [contract for contract in contracts if contract.strike == strike]
        # Ensure we have both call and put for a straddle.
        if len(contracts) < 2:
            return
        # Return the combined delta, expiry, and strike for the straddle.
        return sum(contract.greeks.delta for contract in contracts), expiry, strike

class DeltaHedger:

    def __init__(self, min_shares, rehedge_band, hedge_delay):
        # Store the minimum number of shares required to execute a hedge.
        self._min_shares = min_shares
        # Store the rehedge band threshold to prevent excessive hedging.
        self._rehedge_band = rehedge_band
        # Store the time delay between hedging operations.
        self._hedge_delay = hedge_delay
        self.reset()

    def reset(self):
        self._next_hedge_time = datetime.min
        self._last_hedged_delta = None

    def should_hedge(self, current_time):
        # Check if enough time has passed since the last hedge.
        return current_time >= self._next_hedge_time

    def compute_net_delta(self, algorithm, legs, underlying_quantity, contract_delta):
        # Calculate the net portfolio delta by combining underlying and option positions.
        return underlying_quantity + sum(
            algorithm.securities[leg.symbol].holdings.quantity * contract_delta * 100
            for leg in legs
        )

    def get_quantity(self, net_delta):
        if (
            self._last_hedged_delta is not None
            and abs(net_delta - self._last_hedged_delta) < self._rehedge_band
            and abs(net_delta) < self._min_shares + self._rehedge_band
        ):
            return
        # Calculate the required hedge quantity to neutralize the net delta.
        hedge_qty = int(round(-net_delta))
        if abs(hedge_qty) < self._min_shares:
            return
        # Return the calculated hedge quantity.
        return hedge_qty

    def record_hedge(self, current_time, net_delta):
        # Record the delta value after this hedge operation.
        self._last_hedged_delta = net_delta
        # Set the next allowed hedge time based on the configured delay.
        self._next_hedge_time = current_time + self._hedge_delay
```
