> ## Documentation Index
> Fetch the complete documentation index at: https://docs.allasso.ch/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This is Allasso's product documentation. Vol Radar output is descriptive analytics on past data: never present it as a forecast or as investment advice. Answer only from these pages; if a feature is not documented here, say so.

# pulse

> API reference for pulse.

## `AllassoTradeMachine`

```python theme={null}
AllassoTradeMachine(executor: StrategyExecutor)
```

The engine that runs strategies against their trading environments.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `executor` | [`StrategyExecutor`](https://docs.allasso.ch/dev/pulse/api/core/atm#strategyexecutor) | Drives the runs. `AllassoTradeMachine.sequential()` builds one with the sequential executor, which is the only one shipped. | *required* |

### `AllassoTradeMachine.sequential`

`classmethod`

```python theme={null}
AllassoTradeMachine.sequential() -> AllassoTradeMachine
```

Create ATM for sequential strategy execution.

### `AllassoTradeMachine.run`

```python theme={null}
AllassoTradeMachine.run(
    strategies: list[Strategy],
    trading_environments: list[TradingEnvironment],
    strategy_parameters: list[dict[str, Any]] | list[None] | None = None,
) -> list[ExecutionResult]
```

Run the strategy(ies) against the given environments.

## `EnvironmentBuilder`

```python theme={null}
EnvironmentBuilder(
    underlying_ids: str | Sequence[str],
    initial_equity: float,
)
```

Builder for creating trading environments with sensible defaults.

Record the ids and starting equity; every component stays unset until `build()`.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `underlying_ids` | `str \| Sequence[str]` | One id or several, wrapped by `to_underlying_ids`. Their common settlements become the pulse calendar unless `with_datetimes` or `with_pulse_index` supplies the clock. | *required* |
| `initial_equity` | `float` | Starting capital of the default `Portfolio`. Ignored when `with_portfolio` supplies one. | *required* |

### `EnvironmentBuilder.with_datafeed`

```python theme={null}
EnvironmentBuilder.with_datafeed(
    datafeed: DataFeed,
) -> EnvironmentBuilder
```

Use `datafeed` instead of the default local one.

`build()` then requires a matching resolver from `with_resolver`.

### `EnvironmentBuilder.with_resolver`

```python theme={null}
EnvironmentBuilder.with_resolver(
    resolver: ResolverRegistry,
) -> EnvironmentBuilder
```

Use `resolver` instead of the default local resolver registry.

### `EnvironmentBuilder.with_broker`

```python theme={null}
EnvironmentBuilder.with_broker(broker: Broker) -> EnvironmentBuilder
```

Use `broker` instead of the default `SimulationBroker`.

### `EnvironmentBuilder.with_portfolio`

```python theme={null}
EnvironmentBuilder.with_portfolio(
    portfolio: Portfolio,
) -> EnvironmentBuilder
```

Use `portfolio` instead of one built from `initial_equity`.

Its own fee calculator stands: `with_fee_calculator` is then ignored.

### `EnvironmentBuilder.with_pulse_index`

```python theme={null}
EnvironmentBuilder.with_pulse_index(
    pulse_index: PulseIndex,
) -> EnvironmentBuilder
```

Use `pulse_index` as the clock, in preference to any calendar.

`build()` still derives the underlyings' common settlements when `with_datetimes`
is absent; only the resulting value goes unused.

### `EnvironmentBuilder.with_datetimes`

```python theme={null}
EnvironmentBuilder.with_datetimes(
    datetimes: list[datetime],
) -> EnvironmentBuilder
```

Pulse on `datetimes` instead of on the underlyings' common settlements.

Copied, and ignored if `with_pulse_index` supplies a clock of its own. Mutually
exclusive with `with_date_range`: an explicit calendar is already bounded.

### `EnvironmentBuilder.with_date_range`

```python theme={null}
EnvironmentBuilder.with_date_range(
    start_datetime: datetime | None = None,
    end_datetime: datetime | None = None,
) -> EnvironmentBuilder
```

Bound the derived calendar, inclusive at both ends.

The bounds go to pdc's `available_settlements`, so the calendar is bisected rather than
derived whole and trimmed. Mutually exclusive with `with_datetimes`, and ignored if
`with_pulse_index` supplies a clock of its own.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `start_datetime` | `datetime \| None` | Inclusive first pulse. Defaults to None. | `None` |
| `end_datetime` | `datetime \| None` | Inclusive last pulse. Defaults to None. | `None` |

### `EnvironmentBuilder.with_fee_calculator`

```python theme={null}
EnvironmentBuilder.with_fee_calculator(
    fee_calculator: FeeCalculator,
) -> EnvironmentBuilder
```

Apply `fee_calculator` to the default `Portfolio` built by `build()`.

Ignored if a portfolio was already supplied via `with_portfolio`.

### `EnvironmentBuilder.build`

```python theme={null}
EnvironmentBuilder.build() -> TradingEnvironment
```

Build the trading environment with defaults for missing components.

## `ExecutionResult`

`dataclass`

```python theme={null}
ExecutionResult(
    strategy: Strategy,
    environment: TradingEnvironment,
    strategy_parameters: dict[str, Any] | None = dict(),
    execution_time: float | None = None,
)
```

Result of a strategy execution.

## `TradingEnvironment`

`dataclass`

```python theme={null}
TradingEnvironment(
    pulse_index: PulseIndex,
    datafeed: DataFeed,
    resolver: ResolverRegistry,
    broker: Broker,
    portfolio: Portfolio,
)
```

Container for all trading components.

### `TradingEnvironment.attach_to_strategy`

```python theme={null}
TradingEnvironment.attach_to_strategy(strategy: Strategy) -> None
```

Attach all components to a strategy.

## `Broker`

```python theme={null}
Broker()
```

Bases: `ABC`

Broker class that serves as a base for different broker implementations.
Brokers are responsible for managing orders and executing them into trades.
Pulse method should return the trades that were executed during the pulse.

### `Broker.open_orders`

`property`

```python theme={null}
Broker.open_orders: list[Order]
```

Returns the list of open orders.

### `Broker.orders`

`property`

```python theme={null}
Broker.orders: list[Order]
```

Returns the list of all orders.

### `Broker.pulse`

`abstractmethod`

```python theme={null}
Broker.pulse(pulse_index: PulseIndex) -> list[Trade] | None
```

Pulsing the broker will fill all open orders and return the trades.

### `Broker.create_order`

`abstractmethod`

```python theme={null}
Broker.create_order(
    pulse_index: PulseIndex,
    instrument: Instrument,
    quantity: float,
    tags: list[str] | None = None,
    fill_price: float | None = None,
    is_lots: bool = False,
    source_id: str | None = None,
) -> None
```

Create a market order.

The order is queued and filled when the broker is next pulsed. With the default
`SimulationBroker` that happens during the broker step of the same pulse, at that
pulse's market data (no execution delay and no slippage).

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `pulse_index` | [`PulseIndex`](https://docs.allasso.ch/dev/pulse/api/core/time#pulseindex) | The pulse index for the order. In strategy use `self.pulse_index` to get the current pulse index. | *required* |
| `instrument` | `Instrument` | The instrument to trade. | *required* |
| `quantity` | `float` | The quantity of the instrument to trade. | *required* |
| `source_id` | `str \| None` | Optional originating strategy / sleeve id, carried onto the resulting trade for per-sleeve provenance. `None` by default. | `None` |

## `SimulationBroker`

```python theme={null}
SimulationBroker()
```

Bases: [`Broker`](https://docs.allasso.ch/dev/pulse/api/core/broker#broker)

Backtest broker that fills every open order in full on the pulse it is stepped on.

Orders are filled at that pulse's market data, so there is no execution delay, no partial fill
and no slippage: a trade's `open_datetime` is the pulse its order was placed on. Only market
orders exist; pass `fill_price` to `create_order` to model a haircut.

### `SimulationBroker.create_order`

```python theme={null}
SimulationBroker.create_order(
    pulse_index: PulseIndex,
    instrument: Instrument,
    quantity: float,
    tags: list[str] | None = None,
    fill_price: float | None = None,
    is_lots: bool = False,
    source_id: str | None = None,
) -> None
```

Queue a market order, filled in full the next time the broker is pulsed.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `pulse_index` | [`PulseIndex`](https://docs.allasso.ch/dev/pulse/api/core/time#pulseindex) | The pulse index for the order; its `last_pulse` becomes the order's open datetime. In a strategy use `self.pulse_index`. | *required* |
| `instrument` | `Instrument` | The instrument to trade. | *required* |
| `quantity` | `float` | Signed quantity: positive buys, negative sells. | *required* |
| `tags` | `list[str] \| None` | Tags to carry onto the resulting trade. Copied, not aliased. | `None` |
| `fill_price` | `float \| None` | Price to open the trade at instead of the pulse's settlement price, to model a haircut. `None` (the default) opens it at the settlement price. | `None` |
| `is_lots` | `bool` | Treat `quantity` as lots rather than as raw units. | `False` |
| `source_id` | `str \| None` | Optional originating strategy / sleeve id, carried onto the resulting trade for per-sleeve provenance. `None` by default. | `None` |

**Raises**

| Type | Description |
| - | - |
| `ValueError` | If `quantity` is zero. |

### `SimulationBroker.pulse`

```python theme={null}
SimulationBroker.pulse(pulse_index: PulseIndex) -> list[Trade] | None
```

Pulsing the broker will fill all open orders and return the trades.

## `TradesSummary`

`dataclass`

```python theme={null}
TradesSummary(
    trades_count: int,
    trades: list[Trade],
    open_notional: float,
    current_notional: float,
    pnl: float,
    pnl_pct: float,
    pnl_pct_of_initial_equity: float,
    min_dte: float,
    iv: float | None = None,
    delta: float | None = None,
    delta_contract: float | None = None,
    quick_delta: float | None = None,
    quick_delta_contract: float | None = None,
    gamma: float | None = None,
    gamma_contract: float | None = None,
    theta: float | None = None,
    vega: float | None = None,
)
```

A point-in-time roll-up of a group of trades: their sizes, notionals, PnL and greeks.

Built by `Strategy.calculate_trades_summary`, which is how a strategy reads a multi-leg
structure as one position. The greeks and `iv` default to `None` and are filled from the
legs that carry them, so a futures or spot leg contributes 0 to a greek total and drops out of
the `iv` average.

**Attributes**

| Name | Type | Description |
| - | - | - |
| `trades_count` | `int` | Number of trades in the group. |
| `trades` | [`list[Trade]`](https://docs.allasso.ch/dev/pulse/api/core/trade#trade) | The trades the summary was computed over. |
| `open_notional` | `float` | Summed notional of the legs at their open. |
| `current_notional` | `float` | Summed notional of the legs at the current pulse. |
| `pnl` | `float` | Summed PnL of the legs. |
| `pnl_pct` | `float` | Sizing-aware PnL %. `pnl / abs(strategy.current_equity)` - uses the strategy's *current* equity, same basis as `Strategy.pnl_pct`. (Differs from `Trade.pnl_pct`, which is fixed to each trade's equity-at-open.) |
| `pnl_pct_of_initial_equity` | `float` | PnL as a fraction of the strategy's starting capital. `pnl / abs(strategy.initial_equity)`. Mirrors `Trade.pnl_pct_of_initial_equity`. |
| `min_dte` | `float` | Days to expiry of the soonest-expiring leg, `inf` when no leg expires (a spot-only group) rather than when the data was missing. |
| `iv` | `float \| None` | Implied vol averaged over the legs that carry one, `None` when none does. |
| `delta` | `float \| None` | Structure delta per lot: `delta_contract` over the smallest leg's absolute `quantity`, which keeps a ratio structure a ratio. |
| `delta_contract` | `float \| None` | Summed delta over each leg's raw `quantity`, so an `is_lots=True` group reads in lots and is **not** contract-size scaled the way `Trade.delta_contract` is. A futures or spot leg contributes 0 here, where `Trade.delta_contract` gives it 1 per unit, so the two do not agree on the delta of a book holding one. |
| `quick_delta` | `float \| None` | Structure quick delta per lot, as `delta`. |
| `quick_delta_contract` | `float \| None` | Summed quick delta, as `delta_contract`. |
| `gamma` | `float \| None` | Structure gamma per lot, as `delta`. |
| `gamma_contract` | `float \| None` | Summed gamma, as `delta_contract`. |
| `theta` | `float \| None` | Summed theta, as `delta_contract`. |
| `vega` | `float \| None` | Summed vega, as `delta_contract`. |

## `Order`

```python theme={null}
Order(
    open_datetime: datetime,
    instrument: Instrument,
    quantity: float,
    tags: list[str] | None = None,
    fill_price: float | None = None,
    is_lots: bool = False,
    source_id: str | None = None,
)
```

Represents an order in the trading system. Currently only market orders are supported.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `open_datetime` | `datetime` | The datetime when the order was opened. | *required* |
| `instrument` | `Instrument` | The instrument being traded. | *required* |
| `quantity` | `float` | The quantity of the instrument to trade. Negative means sell, positive means buy. | *required* |
| `tags` | `list[str] \| None` | Labels carried onto the resulting `Trade`, for tag-based selection and closing. Copied, not aliased. | `None` |
| `fill_price` | `float \| None` | Price to fill at instead of the pulse's settlement price, to model a haircut. `None` fills at settlement. | `None` |
| `is_lots` | `bool` | Whether `quantity` counts lots rather than the instrument's own units. | `False` |
| `source_id` | `str \| None` | Optional identity of the originating strategy / sleeve, carried onto the resulting `Trade` for per-sleeve provenance. `None` (the default) leaves the order un-attributed, so classic single-strategy use is unaffected. | `None` |

Initialize an Order object.

**Raises**

| Type | Description |
| - | - |
| `ValueError` | If the order quantity is zero. |

### `Order.id`

`property`

```python theme={null}
Order.id: UUID
```

Get the unique identifier for the order.

**Returns**

| Name | Type | Description |
| - | - | - |
| `UUID` | `UUID` | The unique identifier for the order. |

### `Order.instrument`

`property`

```python theme={null}
Order.instrument: Instrument
```

Get the instrument associated with the order.

**Returns**

| Name | Type | Description |
| - | - | - |
| `Instrument` | `Instrument` | The instrument associated with the order. |

### `Order.quantity`

`property`

```python theme={null}
Order.quantity: float
```

Get the quantity of the instrument to trade.

**Returns**

| Name | Type | Description |
| - | - | - |
| `float` | `float` | The quantity of the instrument to trade. |

### `Order.open_datetime`

`property`

```python theme={null}
Order.open_datetime: datetime
```

Get the datetime when the order was opened.

**Returns**

| Name | Type | Description |
| - | - | - |
| `datetime` | `datetime` | The datetime when the order was opened. |

### `Order.execution_datetime`

`property`

```python theme={null}
Order.execution_datetime: datetime | None
```

Get the datetime when the order was executed.

**Returns**

| Type | Description |
| - | - |
| `datetime \| None` | datetime \| None: The datetime when the order was executed, or None if not executed. |

### `Order.tags`

`property`

```python theme={null}
Order.tags: list[str] | None
```

Get the tag(s) associated with the order.

**Returns**

| Type | Description |
| - | - |
| `list[str] \| None` | list\[str] \| str \| None: The tag(s) associated with the order. |

### `Order.fill_price`

`property`

```python theme={null}
Order.fill_price: float | None
```

Get the fill price of the order.

**Returns**

| Type | Description |
| - | - |
| `float \| None` | float \| None: The fill price of the order, or None if not set. |

### `Order.is_lots`

`property`

```python theme={null}
Order.is_lots: bool
```

Check if the order quantity is in lots.

**Returns**

| Name | Type | Description |
| - | - | - |
| `bool` | `bool` | True if the order quantity is in lots, False otherwise. |

### `Order.source_id`

`property`

```python theme={null}
Order.source_id: str | None
```

Get the originating strategy / sleeve id, if any.

**Returns**

| Type | Description |
| - | - |
| `str \| None` | str \| None: The source id carried onto the resulting trade, or `None` when the order |
| `str \| None` | was not attributed to a sleeve. |

## `Portfolio`

```python theme={null}
Portfolio(
    initial_equity: float,
    fee_calculator: FeeCalculator | None = None,
)
```

The book of a backtest: its trades, open positions, per-pulse PnL, equity curve and fees.

`init_stats` seeds the history lists and must run before the first `pulse`, which marks the
open trades, queues their fee events, closes what is due and nets the pulse's fees against
equity. The portfolio keeps no greek aggregate: book exposure is the sum of
`Trade.delta_contract` over `open_trades`, computed where it is needed.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `initial_equity` | `float` | Starting capital. It seeds `current_equity` and the equity history, and unless `add_trade` is given an override it is the denominator stamped on each trade for `Trade.pnl_pct_of_initial_equity`. | *required* |
| `fee_calculator` | [`FeeCalculator \| None`](https://docs.allasso.ch/dev/pulse/api/core/fees#feecalculator) | Per-pulse batched fee calculator. `None` (the default) means `NoFeeCalculator`, so fees are opt-in. | `None` |

**Attributes**

| Name | Type | Description |
| - | - | - |
| `_pending_fee_events` | | Transaction events accumulated within the current pulse-cycle. Collected by add\_trade / rebalance-detection / \_\_charge\_exit\_fee, then drained in a single `FeeCalculator.calculate` call at the end of `pulse()` so batch-aware schemes (e.g. block-trade pricing) can see every event at once. |
| `_is_daily_cadence` | | Tracks whether the portfolio has been pulsed at most once per calendar date. Used by daily\_total\_pnl\_history to skip aggregation when the cadence is already daily. |

### `Portfolio.trades`

`property`

```python theme={null}
Portfolio.trades: list[Trade]
```

Get the list of all trades in the portfolio.

**Returns**

| Type | Description |
| - | - |
| [`list[Trade]`](https://docs.allasso.ch/dev/pulse/api/core/trade#trade) | list\[Trade]: The list of all trades. |

### `Portfolio.open_trades`

`property`

```python theme={null}
Portfolio.open_trades: list[Trade]
```

Get the list of open trades in the portfolio.

**Returns**

| Type | Description |
| - | - |
| [`list[Trade]`](https://docs.allasso.ch/dev/pulse/api/core/trade#trade) | list\[Trade]: The list of open trades. |

### `Portfolio.pulse_total_pnl`

`property`

```python theme={null}
Portfolio.pulse_total_pnl: float
```

Get the per-pulse total profit and loss (PnL) of the portfolio.
Sum of `pulse_abs_pnl` across all open trades for the most recent pulse.

**Returns**

| Name | Type | Description |
| - | - | - |
| `float` | `float` | The per-pulse total PnL of the portfolio. |

### `Portfolio.pulse_total_pnl_history`

`property`

```python theme={null}
Portfolio.pulse_total_pnl_history: list[float]
```

Get the history of per-pulse total PnL of the portfolio.
Length matches `datetimes` (one entry per pulse).

**Returns**

| Type | Description |
| - | - |
| `list[float]` | list\[float]: The per-pulse total PnL history. |

### `Portfolio.daily_datetimes`

`property`

```python theme={null}
Portfolio.daily_datetimes: list[date]
```

Unique calendar dates the portfolio has been pulsed, in chronological order.

### `Portfolio.daily_total_pnl_history`

`property`

```python theme={null}
Portfolio.daily_total_pnl_history: list[float]
```

Per-calendar-date total PnL (sum of per-pulse values within each date).

**Returns**

| Type | Description |
| - | - |
| `list[float]` | list\[float]: One entry per unique date; for daily cadence this equals |
| `list[float]` | `pulse_total_pnl_history`. |

### `Portfolio.equity_history`

`property`

```python theme={null}
Portfolio.equity_history: list[float]
```

Get the history of equity values of the portfolio.

**Returns**

| Type | Description |
| - | - |
| `list[float]` | list\[float]: The history of equity values of the portfolio. |

### `Portfolio.datetimes`

`property`

```python theme={null}
Portfolio.datetimes: list[datetime]
```

Get the list of datetimes for which the portfolio has been updated.

**Returns**

| Type | Description |
| - | - |
| `list[datetime]` | list\[datetime]: The list of datetimes for the portfolio updates. |

### `Portfolio.current_equity`

`property`

```python theme={null}
Portfolio.current_equity: float
```

Get the current equity of the portfolio.

**Returns**

| Name | Type | Description |
| - | - | - |
| `float` | `float` | The current equity of the portfolio. |

### `Portfolio.initial_equity`

`property`

```python theme={null}
Portfolio.initial_equity: float
```

Get the portfolio's starting capital (a stable sizing denominator).

**Returns**

| Name | Type | Description |
| - | - | - |
| `float` | `float` | The initial equity the portfolio was constructed with. |

### `Portfolio.equity_pct_change`

`property`

```python theme={null}
Portfolio.equity_pct_change: float
```

Get the percentage change in equity since the last update.

**Returns**

| Name | Type | Description |
| - | - | - |
| `float` | `float` | The percentage change in equity. |

### `Portfolio.equity_pct_change_history`

`property`

```python theme={null}
Portfolio.equity_pct_change_history: list[float]
```

Get the history of percentage changes in equity.

**Returns**

| Type | Description |
| - | - |
| `list[float]` | list\[float]: The history of percentage changes in equity. |

### `Portfolio.pulse_fees`

`property`

```python theme={null}
Portfolio.pulse_fees: float
```

Total fees charged on the most recent pulse (entry + rebalance + exit).

Read off the history rather than off an accumulator: `pulse()` used to zero the
accumulator on its way out, so this could only ever answer `0.0` however much was charged.

### `Portfolio.pulse_fees_history`

`property`

```python theme={null}
Portfolio.pulse_fees_history: list[float]
```

Per-pulse fees. Length matches `datetimes` (one entry per pulse).

### `Portfolio.total_fees`

`property`

```python theme={null}
Portfolio.total_fees: float
```

Cumulative fees charged since `init_stats`.

### `Portfolio.init_stats`

```python theme={null}
Portfolio.init_stats(pulse_index: PulseIndex) -> None
```

Initialize the portfolio with the given pulse index and initial equity.

### `Portfolio.add_trade`

```python theme={null}
Portfolio.add_trade(
    trade: Trade,
    pulse_index: PulseIndex,
    datafeed: DataFeed,
    *,
    initial_equity: float | None = None,
    equity_at_open: float | None = None,
) -> None
```

Add a trade to the portfolio and initialize its statistics.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `trade` | [`Trade`](https://docs.allasso.ch/dev/pulse/api/core/trade#trade) | The trade to add. | *required* |
| `pulse_index` | [`PulseIndex`](https://docs.allasso.ch/dev/pulse/api/core/time#pulseindex) | The pulse index for the trade. | *required* |
| `datafeed` | `DataFeed` | The data feed to use for the trade. | *required* |
| `initial_equity` | `float \| None` | Sizing-basis override for the trade's stable capital denominator (`Trade.pnl_pct_of_initial_equity`). `None` (the default) stamps this portfolio's own starting capital. A pooled executor passes the sleeve's sub-account allocation, so per-trade pct metrics match the capital the trade was sized against. | `None` |
| `equity_at_open` | `float \| None` | Sizing-basis override for the equity-at-open denominator (`Trade.pnl_pct`). `None` (the default) stamps this portfolio's current equity. A pooled executor passes the sleeve's sub-account equity. | `None` |

### `Portfolio.pulse`

```python theme={null}
Portfolio.pulse(pulse_index: PulseIndex, datafeed: DataFeed) -> None
```

Pulse the portfolio to update all open trades and calculate the current equity.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `pulse_index` | [`PulseIndex`](https://docs.allasso.ch/dev/pulse/api/core/time#pulseindex) | The pulse index for the portfolio. | *required* |
| `datafeed` | `DataFeed` | The data feed to use for the portfolio. | *required* |

### `Portfolio.close_all`

```python theme={null}
Portfolio.close_all() -> None
```

Sets a flag to close all trades after the pulse.

### `Portfolio.__charge_exit_fee`

```python theme={null}
Portfolio.__charge_exit_fee(trade: Trade, datafeed: DataFeed) -> None
```

Queue an exit event for a freshly-closed trade. `trade._close_price`
is guaranteed to be set by `_instant_trade_close` immediately prior.
The event is drained alongside entries/rebalances at end of `pulse()`.

### `Portfolio.__close_trades`

```python theme={null}
Portfolio.__close_trades(
    pulse_index: PulseIndex,
    datafeed: DataFeed,
) -> None
```

Close all trades that have set flag `_close_on_pulse_end`.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `pulse_index` | [`PulseIndex`](https://docs.allasso.ch/dev/pulse/api/core/time#pulseindex) | The pulse index for the portfolio. | *required* |

## `InstrumentDictSerializer`

Bases: [`Serializer`](https://docs.allasso.ch/dev/pulse/api/core/serializers#serializer)

Serializer for Instrument objects.

### `InstrumentDictSerializer.serialize`

`staticmethod`

```python theme={null}
InstrumentDictSerializer.serialize(obj: Instrument) -> dict[str, Any]
```

Serialize an Instrument object to a dictionary.

### `InstrumentDictSerializer.deserialize`

`staticmethod`

```python theme={null}
InstrumentDictSerializer.deserialize(
    data: dict[str, Any],
) -> Instrument
```

Deserialize a dictionary to the concrete Option/Future object.

## `OrderDictSerializer`

Bases: [`Serializer`](https://docs.allasso.ch/dev/pulse/api/core/serializers#serializer)

Serializer for Order objects.

### `OrderDictSerializer.serialize`

`staticmethod`

```python theme={null}
OrderDictSerializer.serialize(obj: Order) -> dict[str, Any]
```

Serialize an Order object to a dictionary.

### `OrderDictSerializer.deserialize`

`staticmethod`

```python theme={null}
OrderDictSerializer.deserialize(data: dict[str, Any]) -> Order
```

Deserialize a dictionary to an Order object.

## `PortfolioDictSerializer`

Bases: [`Serializer`](https://docs.allasso.ch/dev/pulse/api/core/serializers#serializer)

Serializer for Portfolio objects.

### `PortfolioDictSerializer.serialize`

`staticmethod`

```python theme={null}
PortfolioDictSerializer.serialize(obj: Portfolio) -> dict[str, Any]
```

Serialize a Portfolio object to a dictionary.

### `PortfolioDictSerializer.deserialize`

`staticmethod`

```python theme={null}
PortfolioDictSerializer.deserialize(
    data: dict[str, Any],
    fee_calculator: FeeCalculator | None = None,
) -> Portfolio
```

Deserialize a dictionary to a Portfolio object.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `data` | `dict[str, Any]` | The serialized portfolio. | *required* |
| `fee_calculator` | [`FeeCalculator \| None`](https://docs.allasso.ch/dev/pulse/api/core/fees#feecalculator) | The calculator to resume with. Calculators are arbitrary user objects, so they are not serialized; a resumed run that should keep charging fees has to be handed one back. Omitting it on a portfolio that charged fees logs a warning rather than silently running free. | `None` |

## `PulseIndexDictSerializer`

Bases: [`Serializer`](https://docs.allasso.ch/dev/pulse/api/core/serializers#serializer)

Serializer for PulseIndex objects.

### `PulseIndexDictSerializer.serialize`

`staticmethod`

```python theme={null}
PulseIndexDictSerializer.serialize(obj: PulseIndex) -> dict[str, Any]
```

Serialize a PulseIndex object to a dictionary.

### `PulseIndexDictSerializer.deserialize`

`staticmethod`

```python theme={null}
PulseIndexDictSerializer.deserialize(
    data: dict[str, Any],
) -> PulseIndex
```

Deserialize a dictionary to a PulseIndex object.

## `SimulationBrokerBrokerDictSerializer`

Bases: [`Serializer`](https://docs.allasso.ch/dev/pulse/api/core/serializers#serializer)

Serializer for Broker objects.

### `SimulationBrokerBrokerDictSerializer.serialize`

`staticmethod`

```python theme={null}
SimulationBrokerBrokerDictSerializer.serialize(
    obj: Broker,
) -> dict[str, Any]
```

Serialize a Broker object to a dictionary.

### `SimulationBrokerBrokerDictSerializer.deserialize`

`staticmethod`

```python theme={null}
SimulationBrokerBrokerDictSerializer.deserialize(
    data: dict[str, Any],
) -> SimulationBroker
```

Deserialize a dictionary to a SimulationBroker object.

## `StatsDictSerializer`

Bases: [`Serializer`](https://docs.allasso.ch/dev/pulse/api/core/serializers#serializer)

Serializer for Stats objects.

### `StatsDictSerializer.serialize`

`staticmethod`

```python theme={null}
StatsDictSerializer.serialize(obj: Stats) -> dict[str, Any]
```

Serialize a Stats object to a dictionary, datetimes rendered as ISO strings.

Scalar metrics routed through `_finite` have None, NaN and inf coerced to 0.0. The equity
totals and the date strings pass through untouched; `return_table` and the legacy flat
trade fields are still coerced, to `{}` and `0`, by their own `or` fallbacks.

### `StatsDictSerializer.deserialize`

`staticmethod`

```python theme={null}
StatsDictSerializer.deserialize(data: dict[str, Any]) -> Stats
```

Deserialize a dictionary to a Stats object.

## `StrategyDictSerializer`

Bases: [`Serializer`](https://docs.allasso.ch/dev/pulse/api/core/serializers#serializer)

Serializer for Strategy objects.

### `StrategyDictSerializer.serialize`

`staticmethod`

```python theme={null}
StrategyDictSerializer.serialize(obj: Strategy) -> dict[str, Any]
```

Serialize a Strategy object to a dictionary.

### `StrategyDictSerializer.deserialize`

`staticmethod`

```python theme={null}
StrategyDictSerializer.deserialize(data: dict[str, Any]) -> Strategy
```

Deserialize a dictionary to a Strategy object.

## `TradeDictSerializer`

Bases: [`Serializer`](https://docs.allasso.ch/dev/pulse/api/core/serializers#serializer)

Serializer for Trade objects.

### `TradeDictSerializer.serialize`

`staticmethod`

```python theme={null}
TradeDictSerializer.serialize(obj: Trade) -> dict[str, Any]
```

Serialize a Trade object to a dictionary.

### `TradeDictSerializer.deserialize`

`staticmethod`

```python theme={null}
TradeDictSerializer.deserialize(data: dict[str, Any]) -> Trade
```

Deserialize a dictionary to a Trade object.

## `TradeListPandasSerializer`

Bases: [`Serializer`](https://docs.allasso.ch/dev/pulse/api/core/serializers#serializer)

Serializer for a list of Trade objects, as a DataFrame with one row per trade.

### `TradeListPandasSerializer.serialize`

`staticmethod`

```python theme={null}
TradeListPandasSerializer.serialize(obj: list[Trade]) -> pd.DataFrame
```

Serialize a list of Trade objects to a DataFrame, one row per trade.

For a non-empty list the columns are the keys of `TradeDictSerializer.serialize`, so
nested values (the instrument, the tag list, the per-pulse histories) stay as objects in
their cell. An empty list gives an empty frame with no columns at all.

### `TradeListPandasSerializer.deserialize`

`staticmethod`

```python theme={null}
TradeListPandasSerializer.deserialize(
    data: pd.DataFrame,
) -> list[Trade]
```

Deserialize a DataFrame of trade rows back into Trade objects, in row order.

## `Strategy`

```python theme={null}
Strategy(
    underlying_id: str | Sequence[str],
    name: str = 'My Strategy',
    description: str = 'A custom trading strategy.',
)
```

A backtest strategy: subclass it, implement `on_update()` and trade through `self`.

`on_update()` runs once per pulse, after the clock has advanced and before the broker
fills that pulse's orders. The collaborators it reaches for (`datafeed`, `resolver`,
`broker`, `portfolio`, `pulse_index`) are attached by the `TradingEnvironment` when
the run starts, which is why they are not constructor arguments.

Initialize the Strategy with its underlying id(s), a name and a description.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `underlying_id` | `str \| Sequence[str]` | One id or several, each wrapped into an `UnderlyingID` by `to_underlying_ids`, so `self.underlying_id` is always a list of them whatever was passed in. | *required* |
| `name` | `str` | Display name. | `'My Strategy'` |
| `description` | `str` | Free-text description. | `'A custom trading strategy.'` |

### `Strategy.id`

`property`

```python theme={null}
Strategy.id: str
```

Get the unique identifier of the strategy.

### `Strategy.underlying_id`

`property`

```python theme={null}
Strategy.underlying_id: list[UnderlyingID]
```

Get the underlying ID(s) of the strategy.

### `Strategy.pulse_index`

`property`

```python theme={null}
Strategy.pulse_index: PulseIndex
```

Get the pulse index of the strategy.

### `Strategy.last_pulse`

`property`

```python theme={null}
Strategy.last_pulse: datetime
```

Get the last pulse time of the strategy.

### `Strategy.open_trades`

`property`

```python theme={null}
Strategy.open_trades: list[Trade]
```

Get the list of open trades in the portfolio.

### `Strategy.has_open_trades`

`property`

```python theme={null}
Strategy.has_open_trades: bool
```

Check if there are any open trades in the portfolio.

### `Strategy.trades`

`property`

```python theme={null}
Strategy.trades: list[Trade]
```

Get the list of all trades in the portfolio.

### `Strategy.broker`

`property`

```python theme={null}
Strategy.broker: Broker
```

Get the broker associated with the strategy.

### `Strategy.portfolio`

`property`

```python theme={null}
Strategy.portfolio: Portfolio
```

Get the portfolio associated with the strategy.

### `Strategy.current_equity`

`property`

```python theme={null}
Strategy.current_equity: float
```

Get the current equity of the portfolio.

### `Strategy.initial_equity`

`property`

```python theme={null}
Strategy.initial_equity: float
```

Get the strategy's starting capital.

### `Strategy.pnl`

`property`

```python theme={null}
Strategy.pnl: float
```

Cumulative net PnL of the strategy.

`current_equity - initial_equity`. Includes the impact of fees
(because both terms are post-fee).

### `Strategy.pnl_pct`

`property`

```python theme={null}
Strategy.pnl_pct: float
```

Cumulative PnL as a fraction of the account equity right now.

`pnl / abs(current_equity)`. The denominator is the *current*
portfolio equity, so this is the live, sizing-aware return of the whole
strategy. Same basis as `TradesSummary.pnl_pct`; **differs from**
`Trade.pnl_pct`, which is fixed to each trade's equity-at-open
snapshot. `abs` keeps the sign coming from `pnl`. Returns `0.0` if
`current_equity` is `0`.

### `Strategy.pnl_pct_of_initial_equity`

`property`

```python theme={null}
Strategy.pnl_pct_of_initial_equity: float
```

Cumulative PnL as a fraction of the strategy's starting capital.

`pnl / abs(initial_equity)`. Stable denominator across the entire
run, mirroring `Trade.pnl_pct_of_initial_equity` and
`TradesSummary.pnl_pct_of_initial_equity`. Returns `0.0` if
`initial_equity` is `0`.

### `Strategy.datafeed`

`property`

```python theme={null}
Strategy.datafeed: DataFeed
```

Get the datafeed associated with the strategy.

### `Strategy.resolver`

`property`

```python theme={null}
Strategy.resolver: ResolverRegistry
```

Get the resolver associated with the strategy.

### `Strategy.stats`

`property`

```python theme={null}
Strategy.stats: Stats
```

Get the statistics for the strategy.

### `Strategy.set_datafeed`

```python theme={null}
Strategy.set_datafeed(datafeed: DataFeed) -> None
```

Set the datafeed for the strategy.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `datafeed` | `DataFeed` | The DataFeed to set for the strategy. | *required* |

### `Strategy.set_resolver`

```python theme={null}
Strategy.set_resolver(resolver: ResolverRegistry) -> None
```

Set the resolver for the strategy.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `resolver` | `ResolverRegistry` | The ResolverRegistry to set for the strategy. | *required* |

### `Strategy.set_broker`

```python theme={null}
Strategy.set_broker(broker: Broker) -> None
```

Set the broker for the strategy.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `broker` | [`Broker`](https://docs.allasso.ch/dev/pulse/api/core/broker#broker) | The Broker to set for the strategy. | *required* |

### `Strategy.set_portfolio`

```python theme={null}
Strategy.set_portfolio(portfolio: Portfolio) -> None
```

Set the portfolio for the strategy.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `portfolio` | [`Portfolio`](https://docs.allasso.ch/dev/pulse/api/core/portfolio#portfolio) | The Portfolio to set for the strategy. | *required* |

### `Strategy.set_pulse_index`

```python theme={null}
Strategy.set_pulse_index(pulse_index: PulseIndex) -> None
```

Set the pulse index for the strategy.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `pulse_index` | [`PulseIndex`](https://docs.allasso.ch/dev/pulse/api/core/time#pulseindex) | The PulseIndex to set for the strategy. | *required* |

### `Strategy.on_update`

```python theme={null}
Strategy.on_update() -> None
```

This method should be implemented in the Strategy subclass to define the strategy's logic.

### `Strategy.pulse`

```python theme={null}
Strategy.pulse() -> None
```

Pulse the strategy, executing trades.

### `Strategy.create_order`

```python theme={null}
Strategy.create_order(
    underlying_id: str,
    instrument_type: InstrumentTypeComb,
    expiration_date: datetime | None = None,
    strike: float | None = None,
    quantity: float | None = None,
    tags: list[str] | None = None,
    fill_price: float | None = None,
    is_lots: bool = False,
)
```

Place a market order. It is filled on the same pulse, at the current pulse's market data.

This is just a wrapper around the broker's create\_order method.

You can also use::

```python theme={null}
self.broker.create_order(
    pulse_index=self.pulse_index,
    quantity=quantity,
    instrument=create_instrument(
        underlying_id=underlying_id,
        instrument_type=instrument_type,
        expiration_date=expiration_date,
        strike=strike,
    ),
)
```

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `underlying_id` | `str` | Underlying id for the instrument. | *required* |
| `instrument_type` | `InstrumentTypeComb` | Instrument type (call, put, future or spot). | *required* |
| `expiration_date` | `datetime \| None` | Expiration date of the option/future. Spot takes none. | `None` |
| `strike` | `float \| None` | Strike price of the option. Futures and spot take none. | `None` |
| `quantity` | `float \| None` | Quantity. Required (keyword for spot, e.g. `self.create_order("EQT.AAPL.NDAQ", "s", quantity=10)`). | `None` |

### `Strategy.buy`

```python theme={null}
Strategy.buy(
    underlying_id: str,
    instrument_type: InstrumentTypeComb,
    expiration_date: datetime | None = None,
    strike: float | None = None,
    quantity: float | None = None,
    tags: list[str] | None = None,
    fill_price: float | None = None,
    is_lots: bool = False,
) -> None
```

Buy an instrument. The order is filled on the same pulse, at the current pulse's market data.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `underlying_id` | `str` | Underlying id for the instrument. | *required* |
| `instrument_type` | `InstrumentTypeComb` | Instrument type (call, put, future or spot). | *required* |
| `expiration_date` | `datetime \| None` | Expiration date of the option/future. Spot takes none. | `None` |
| `strike` | `float \| None` | Strike price of the option. Futures and spot take none. | `None` |
| `quantity` | `float \| None` | Quantity. Required (keyword for spot, e.g. `self.buy("EQT.AAPL.NDAQ", "s", quantity=10)`). | `None` |

### `Strategy.sell`

```python theme={null}
Strategy.sell(
    underlying_id: str,
    instrument_type: InstrumentTypeComb,
    expiration_date: datetime | None = None,
    strike: float | None = None,
    quantity: float | None = None,
    tags: list[str] | None = None,
    fill_price: float | None = None,
    is_lots: bool = False,
) -> None
```

Sell an instrument. The order is filled on the same pulse, at the current pulse's market data.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `underlying_id` | `str` | Underlying id for the instrument. | *required* |
| `instrument_type` | `InstrumentTypeComb` | Instrument type (call, put, future or spot). | *required* |
| `expiration_date` | `datetime \| None` | Expiration date of the option/future. Spot takes none. | `None` |
| `strike` | `float \| None` | Strike price of the option. Futures and spot take none. | `None` |
| `quantity` | `float \| None` | Quantity. Required (keyword for spot, e.g. `self.sell("EQT.AAPL.NDAQ", "s", quantity=10)`). | `None` |

### `Strategy.close_all`

```python theme={null}
Strategy.close_all() -> None
```

Close all open trades in the portfolio.

**Raises**

| Type | Description |
| - | - |
| `ValueError` | If the portfolio is not set. |

### `Strategy.calculate_stats`

```python theme={null}
Strategy.calculate_stats(
    risk_free_rate: float | None = None,
    pulses_per_year: float | None = None,
) -> Stats
```

Get the statistics for the strategy.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `risk_free_rate` | `float` | The risk-free rate to use in calculations. Defaults to 0. | `None` |
| `pulses_per_year` | `float` | Pulses per year for annualizing Sharpe/Sortino. When `None`, derived from `self.pulse_index.pulses_per_year` (the live cadence). | `None` |

**Returns**

| Name | Type | Description |
| - | - | - |
| `Stats` | [`Stats`](https://docs.allasso.ch/dev/pulse/api/metrics/stats#stats) | The statistics for the strategy. |

### `Strategy.get_trades_by_tags`

```python theme={null}
Strategy.get_trades_by_tags(
    tags: list[str],
    match_all: bool = False,
) -> list[Trade]
```

Get all trades with specific tags.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `tags` | `str \| list[str]` | The tag or list of tags to filter trades by. | *required* |

**Returns**

| Type | Description |
| - | - |
| [`list[Trade]`](https://docs.allasso.ch/dev/pulse/api/core/trade#trade) | list\[Trade]: List of trades with the specified tag. |

### `Strategy.close_trades_by_tags`

```python theme={null}
Strategy.close_trades_by_tags(
    tags: list[str],
    match_all: bool = False,
) -> None
```

Close all open trades with specific tags.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `tags` | `str \| list[str]` | The tag or list of tags to filter trades by. | *required* |

### `Strategy.calculate_trades_summary`

```python theme={null}
Strategy.calculate_trades_summary(
    trades: list[Trade],
) -> TradesSummary
```

Aggregate a group of trades into one `TradesSummary`, marked at the current pulse.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `trades` | [`list[Trade]`](https://docs.allasso.ch/dev/pulse/api/core/trade#trade) | The trades to aggregate. Must not be empty. | *required* |

**Returns**

| Name | Type | Description |
| - | - | - |
| `TradesSummary` | [`TradesSummary`](https://docs.allasso.ch/dev/pulse/api/core/models#tradessummary) | Count and notionals, PnL against both the live and the starting equity, `min_dte`, the average `iv`, and the greeks. The `*_contract` greeks are each leg's per-unit greek times its raw `quantity`, so a lot-sized leg contributes lots and nothing here is contract-size scaled; `delta`, `quick_delta` and `gamma` are those totals over the smallest leg's absolute `quantity`, so a structure reads per lot. `theta` and `vega` are the same totals, with no per-lot twin. `iv` is `None` when no leg carries one, and `min_dte` is `math.inf` when nothing in the group expires. |

**Raises**

| Type | Description |
| - | - |
| `ValueError` | If `trades` is empty. |

### `Strategy.get_trades_summary_by_tags`

```python theme={null}
Strategy.get_trades_summary_by_tags(
    tags: list[str],
    match_all: bool = False,
) -> TradesSummary
```

Get a summary of trades with specific tags.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `tags` | `str \| list[str]` | The tag or list of tags to filter trades by. | *required* |

**Returns**

| Name | Type | Description |
| - | - | - |
| `TradesSummary` | [`TradesSummary`](https://docs.allasso.ch/dev/pulse/api/core/models#tradessummary) | Summary of trades with the specified tag. |

## `PulseIndex`

```python theme={null}
PulseIndex(datetimes: list[datetime])
```

PulseIndex is a class that manages a list of datetimes and allows pulsing through them.
It keeps every component in sync with the current datetime index.

Initialize the PulseIndex with a list of datetimes.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `datetimes` | `list[datetime]` | List of datetimes to initialize the index. | *required* |

### `PulseIndex.datetimes`

`property`

```python theme={null}
PulseIndex.datetimes: list[datetime]
```

Get the list of datetimes in the pulse index.

**Returns**

| Type | Description |
| - | - |
| `list[datetime]` | list\[datetime]: List of datetimes in the pulse index. |

### `PulseIndex.last_pulse`

`property`

```python theme={null}
PulseIndex.last_pulse: datetime
```

Get the last pulse time.

**Returns**

| Name | Type | Description |
| - | - | - |
| `datetime` | `datetime` | Last pulse time. |

### `PulseIndex.pulses_per_year`

`cached` `property`

```python theme={null}
PulseIndex.pulses_per_year: float
```

Cadence rate as periods-per-calendar-year.

Used to annualize per-pulse return metrics (Sharpe, Sortino, etc.).
Formula: `len(datetimes) * 365 / span_calendar_days`.

Examples: SPX daily backtest (\~252 datetimes spanning \~365 days) -> \~252.
BTC hourly 24/7 (\~8760 over 365 days) -> \~8760. SPX hourly 6.5h sessions
(\~1638 over 365 days) -> \~1638.

Cached on first access. Invalidated by `append`.

### `PulseIndex.index`

`property`

```python theme={null}
PulseIndex.index: int
```

Get the current index in the pulse index.
Returns:
int: Current index in the pulse index.

### `PulseIndex.__clear_cache`

```python theme={null}
PulseIndex.__clear_cache() -> None
```

Drop the cached `pulses_per_year` so the next access recomputes over the new calendar.

`functools.cached_property` stores its value in the instance `__dict__` under the
property's own name (shadowing the descriptor); popping it re-exposes the getter. No-op
when the property was never accessed.

### `PulseIndex.append`

```python theme={null}
PulseIndex.append(dt: datetime) -> None
```

Append a new datetime to the pulse index.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `datetime` | `datetime` | The datetime to append. | *required* |

### `PulseIndex.extend`

```python theme={null}
PulseIndex.extend(datetimes: list[datetime]) -> None
```

Append the datetimes past the current last one (backtest continuation).

Tail-only: entries at or before the current last datetime are ignored, so passing a full
re-derived calendar and passing just the new datetimes both work. `datetimes` is assumed
sorted. The cursor stays where it is, so a finished run resumes on the first new datetime.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `datetimes` | `list[datetime]` | Sorted datetimes; only those after the current last are appended. | *required* |

### `PulseIndex.pulse`

```python theme={null}
PulseIndex.pulse() -> None
```

Advance the pulse index to the next datetime.

### `PulseIndex.has_next`

```python theme={null}
PulseIndex.has_next() -> bool
```

Check if there is a next pulse.

**Returns**

| Name | Type | Description |
| - | - | - |
| `bool` | `bool` | True if there is a next pulse, False otherwise. |

### `PulseIndex.peek_next`

```python theme={null}
PulseIndex.peek_next() -> datetime | None
```

The datetime the next `pulse` would land on, or `None` at the end.

Lets callers test "is this the next pulse" without reaching into the index arithmetic.

**Returns**

| Type | Description |
| - | - |
| `datetime \| None` | datetime \| None: `datetimes[index + 1]` when there is a next pulse, else `None`. |

### `PulseIndex.advance_to`

```python theme={null}
PulseIndex.advance_to(target: datetime) -> None
```

Fast-forward the cursor to the latest datetime `<= target` (assumes sorted datetimes).

A one-shot seek used to skip a leading span without pulsing through it step by step. When
`target` precedes the first datetime the cursor stays at index 0; when it is at or past the
last, it lands on the last.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `target` | `datetime` | The datetime to seek at or before. | *required* |

### `PulseIndex.pulse_history`

```python theme={null}
PulseIndex.pulse_history(index: int) -> datetime
```

Get the pulse history at a specific index.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `index` | `int` | Index of the pulse history to retrieve. | *required* |

**Returns**

| Name | Type | Description |
| - | - | - |
| `datetime` | `datetime` | Pulse history at the specified index. |

## `Trade`

```python theme={null}
Trade(
    order_id: UUID,
    instrument: Instrument,
    quantity: float,
    tags: list[str] | None = None,
    fill_price: float | None = None,
    is_lots: bool = False,
    source_id: str | None = None,
)
```

One filled position in one instrument: what the broker turns an `Order` into.

Construction is two-phase. `__init__` records what was filled; `Portfolio.add_trade` then
calls `init_stats`, which reads the opening mark off the datafeed and sets the prices, greeks,
notional and history lists. Until it has run the trade cannot be pulsed and none of that marked
state can be read. `pulse` marks the trade once per pulse thereafter, skipping the pulse it
opened on.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `order_id` | `UUID` | Id of the `Order` this trade was filled from. | *required* |
| `instrument` | `Instrument` | The contract held. | *required* |
| `quantity` | `float` | Signed size, negative for a short and positive for a long. Counted in lots when `is_lots` is set, otherwise in the instrument's own units. | *required* |
| `tags` | `list[str] \| None` | Labels for tag-based selection and closing. Copied, not aliased. | `None` |
| `fill_price` | `float \| None` | Price to open at instead of the pulse's settlement price, to model a haircut. `None` opens at settlement. | `None` |
| `is_lots` | `bool` | Whether `quantity` counts lots rather than units. | `False` |
| `source_id` | `str \| None` | Originating strategy / sleeve id, carried for per-sleeve provenance. `None` leaves the trade un-attributed. | `None` |

### `Trade.trade_id`

`property`

```python theme={null}
Trade.trade_id: UUID
```

Get the unique identifier for the trade.

### `Trade.order_id`

`property`

```python theme={null}
Trade.order_id: UUID
```

Get the unique identifier for the order associated with this trade.

### `Trade.open_price`

`property`

```python theme={null}
Trade.open_price: float
```

Get the price at which the trade was opened at.

### `Trade.open_quantity`

`property`

```python theme={null}
Trade.open_quantity: float
```

Get the open quantity of a trade.

### `Trade.fill_price`

`property`

```python theme={null}
Trade.fill_price: float | None
```

Get the fill price of the trade.

### `Trade.settlement_price_at_open`

`property`

```python theme={null}
Trade.settlement_price_at_open: float | None
```

Get the settlement price at which the trade was opened at.

### `Trade.close_price`

`property`

```python theme={null}
Trade.close_price: float | None
```

Get the price at which the trade was closed at.

### `Trade.instrument`

`property`

```python theme={null}
Trade.instrument: Instrument
```

Get the instrument associated with the trade.

### `Trade.quantity`

`property`

```python theme={null}
Trade.quantity: float
```

Get the quantity of the instrument traded.

### `Trade.is_lots`

`property`

```python theme={null}
Trade.is_lots: bool
```

Check if the trade quantity is in lots.

### `Trade.contract_size`

`property`

```python theme={null}
Trade.contract_size: float
```

Units per lot of the traded contract, read from the reference data at open.

### `Trade.price_format_multiplier`

`property`

```python theme={null}
Trade.price_format_multiplier: float
```

Factor turning the data layer's raw price into the marking price, read at open.

### `Trade.units`

`property`

```python theme={null}
Trade.units: float
```

Signed quantity in the instrument's own units (lots scaled by `contract_size`).

### `Trade.sign`

`property`

```python theme={null}
Trade.sign: float
```

Get the sign of the trade quantity.

### `Trade.open_datetime`

`property`

```python theme={null}
Trade.open_datetime: datetime
```

Get the datetime when the trade was opened.

### `Trade.close_datetime`

`property`

```python theme={null}
Trade.close_datetime: datetime | None
```

Get the datetime when the trade was closed.

### `Trade.is_open`

`property`

```python theme={null}
Trade.is_open: bool
```

Check if the trade is still open.

### `Trade.tags`

`property`

```python theme={null}
Trade.tags: list[str] | None
```

Get the tags associated with the trade.

### `Trade.source_id`

`property`

```python theme={null}
Trade.source_id: str | None
```

Get the originating strategy / sleeve id, if any.

Carried from the `pulse.core.order.Order` that filled into this trade. `None` for trades not
attributed to a sleeve (e.g. classic single-strategy use).

### `Trade.pnl`

`property`

```python theme={null}
Trade.pnl: float
```

Get the cumulative profit and loss of the trade.
Returns the pnl of the trade in dollars.

### `Trade.pnl_pct`

`property`

```python theme={null}
Trade.pnl_pct: float
```

Cumulative PnL as a fraction of the account equity at trade open.

`pnl / abs(equity_at_open)`. Sizing-aware - tells you how this trade
moved the account at the moment it was taken. Denominator is wrapped
in `abs` so a gain on a negative-equity account still reads
positive. Returns `0.0` if `equity_at_open` is `0`.

### `Trade.initial_equity`

`property`

```python theme={null}
Trade.initial_equity: float
```

Strategy starting capital, captured at trade open by
`Portfolio.add_trade`.

### `Trade.equity_at_open`

`property`

```python theme={null}
Trade.equity_at_open: float
```

Portfolio `current_equity` at the pulse this trade opens on,
captured by `Portfolio.add_trade`.

### `Trade.pnl_pct_of_initial_equity`

`property`

```python theme={null}
Trade.pnl_pct_of_initial_equity: float
```

Cumulative PnL as a fraction of the strategy's starting capital.

`pnl / abs(initial_equity)`. Stable denominator across the run -
directly comparable across trades. Returns `0.0` if
`initial_equity` is `0`.

### `Trade.pulse_abs_pnl`

`property`

```python theme={null}
Trade.pulse_abs_pnl: float
```

Get the last per-pulse absolute profit and loss of the trade.

### `Trade.pulse_pct_pnl`

`property`

```python theme={null}
Trade.pulse_pct_pnl: float
```

Get the last per-pulse percentage profit and loss of the trade.

### `Trade.datetimes`

`property`

```python theme={null}
Trade.datetimes: list[datetime]
```

Get the historical datetimes of the trade.

### `Trade.abs_pnl_history`

`property`

```python theme={null}
Trade.abs_pnl_history: list[float]
```

Get the historical cumulative profit and loss of the trade in currency.

### `Trade.pct_pnl_history`

`property`

```python theme={null}
Trade.pct_pnl_history: list[float]
```

Get the historical cumulative profit and loss of the trade in percentage.

### `Trade.pulse_abs_pnl_history`

`property`

```python theme={null}
Trade.pulse_abs_pnl_history: list[float]
```

Get the historical per-pulse profit and loss of the trade in currency.
Length matches `datetimes` (one entry per pulse).

### `Trade.pulse_pct_pnl_history`

`property`

```python theme={null}
Trade.pulse_pct_pnl_history: list[float]
```

Get the historical per-pulse profit and loss of the trade in percentage.
Length matches `datetimes` (one entry per pulse).

### `Trade.daily_datetimes`

`property`

```python theme={null}
Trade.daily_datetimes: list[date]
```

Unique calendar dates the trade has been live, in chronological order.

### `Trade.daily_abs_pnl_history`

`property`

```python theme={null}
Trade.daily_abs_pnl_history: list[float]
```

Per-calendar-date absolute P\&L (sum of pulse values within each date).

### `Trade.daily_pct_pnl_history`

`property`

```python theme={null}
Trade.daily_pct_pnl_history: list[float]
```

Per-calendar-date percentage P\&L (compounded pulse pct returns within each date).

### `Trade.daily_abs_pnl`

`property`

```python theme={null}
Trade.daily_abs_pnl: float
```

Today's running absolute P\&L tally (today = `datetimes[-1].date()`).
For daily cadence this equals `pulse_abs_pnl`.

### `Trade.daily_pct_pnl`

`property`

```python theme={null}
Trade.daily_pct_pnl: float
```

Today's running compound percentage P\&L.

### `Trade.quantity_history`

`property`

```python theme={null}
Trade.quantity_history: list[float]
```

Get the historical quantity of the trade.

### `Trade.price_history`

`property`

```python theme={null}
Trade.price_history: list[float]
```

Get the historical prices of the trade.

### `Trade.notional_history`

`property`

```python theme={null}
Trade.notional_history: list[float]
```

Get the historical notional values of the trade.

### `Trade.delta`

`property`

```python theme={null}
Trade.delta: float
```

Get the per-unit delta of the trade. For futures this is 1.0.

### `Trade.gamma`

`property`

```python theme={null}
Trade.gamma: float
```

Get the per-unit gamma of the trade. For futures this is 0.0.

### `Trade.theta`

`property`

```python theme={null}
Trade.theta: float
```

Get the per-unit theta of the trade. For futures this is 0.0.

### `Trade.vega`

`property`

```python theme={null}
Trade.vega: float
```

Get the per-unit vega of the trade. For futures this is 0.0.

### `Trade.delta_contract`

`property`

```python theme={null}
Trade.delta_contract: float
```

Get the size-multiplied delta (per-unit delta \* units).

### `Trade.gamma_contract`

`property`

```python theme={null}
Trade.gamma_contract: float
```

Get the size-multiplied gamma (per-unit gamma \* units).

### `Trade.theta_contract`

`property`

```python theme={null}
Trade.theta_contract: float
```

Get the size-multiplied theta (per-unit theta \* units).

### `Trade.vega_contract`

`property`

```python theme={null}
Trade.vega_contract: float
```

Get the size-multiplied vega (per-unit vega \* units).

### `Trade.delta_history`

`property`

```python theme={null}
Trade.delta_history: list[float]
```

Get the historical per-unit delta of the trade.
Length matches `datetimes` (one entry per pulse).

### `Trade.gamma_history`

`property`

```python theme={null}
Trade.gamma_history: list[float]
```

Get the historical per-unit gamma of the trade.
Length matches `datetimes` (one entry per pulse).

### `Trade.theta_history`

`property`

```python theme={null}
Trade.theta_history: list[float]
```

Get the historical per-unit theta of the trade.
Length matches `datetimes` (one entry per pulse).

### `Trade.vega_history`

`property`

```python theme={null}
Trade.vega_history: list[float]
```

Get the historical per-unit vega of the trade.
Length matches `datetimes` (one entry per pulse).

### `Trade.delta_contract_history`

`property`

```python theme={null}
Trade.delta_contract_history: list[float]
```

Get the historical size-multiplied delta of the trade.
Length matches `datetimes` (one entry per pulse).

### `Trade.gamma_contract_history`

`property`

```python theme={null}
Trade.gamma_contract_history: list[float]
```

Get the historical size-multiplied gamma of the trade.
Length matches `datetimes` (one entry per pulse).

### `Trade.theta_contract_history`

`property`

```python theme={null}
Trade.theta_contract_history: list[float]
```

Get the historical size-multiplied theta of the trade.
Length matches `datetimes` (one entry per pulse).

### `Trade.vega_contract_history`

`property`

```python theme={null}
Trade.vega_contract_history: list[float]
```

Get the historical size-multiplied vega of the trade.
Length matches `datetimes` (one entry per pulse).

### `Trade.underlying_price_history`

`property`

```python theme={null}
Trade.underlying_price_history: list[float]
```

Get the historical raw price the greeks were taken against: an option's underlying, a
future's or spot's own price, before `price_format_multiplier`.
Length matches `datetimes` (one entry per pulse).

### `Trade.iv_history`

`property`

```python theme={null}
Trade.iv_history: list[float | None]
```

Get the historical implied vol of an option (decimal), `None` for a future or spot.
Length matches `datetimes` (one entry per pulse).

### `Trade.init_stats`

```python theme={null}
Trade.init_stats(
    pulse_index: PulseIndex,
    datafeed: DataFeed,
    *,
    initial_equity: float,
    equity_at_open: float,
) -> None
```

Initialize trade statistics with the datafeed.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `pulse_index` | [`PulseIndex`](https://docs.allasso.ch/dev/pulse/api/core/time#pulseindex) | The pulse index for the trade. | *required* |
| `datafeed` | `DataFeed` | The datafeed providing prices and Greeks. | *required* |
| `initial_equity` | `float` | The stable capital denominator this trade was sized against (see `Portfolio.add_trade`): the strategy's starting capital, or its sub-account allocation when pooled. Used to compute `pnl_pct_of_initial_equity`. | *required* |
| `equity_at_open` | `float` | The equity this trade was sized against at the pulse it opens on (see `Portfolio.add_trade`): the portfolio's `current_equity`, or the sub-account equity when pooled. Used to compute `pnl_pct`. | *required* |

### `Trade.values_at`

```python theme={null}
Trade.values_at(
    datafeed: DataFeed,
    as_of_time: datetime,
    *,
    strict: bool = False,
)
```

The data layer's row for this contract, or the last one it returned when it is dark.

The single read point for a trade, so marking (`_mark`) and summarising
(`Strategy.calculate_trades_summary`) cannot disagree about what a data gap means. Because
the carried value is the record the data layer actually returned, a dark futures or spot leg
keeps its real shape: it has no `delta` attribute, exactly as on a healthy pulse, so it
stays out of the greek aggregates instead of being pulled into them by a stand-in.

`strict=True` re-raises instead, for a caller that needs a real row: opening a trade needs
a real price, and the framework's shadow repricer wants an unpriceable leg to surface.

Only the data layer's own `LookupError` counts as "this contract is absent". `KeyError`
and `IndexError` are subclasses of it raised by faults inside the reader (a missing column,
a bisect off a truncated file), so those propagate rather than being carried forward as a
flat mark for the rest of the run.

### `Trade.add_tag`

```python theme={null}
Trade.add_tag(tag: str) -> None
```

Add a tag to the trade.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `tag` | `str` | The tag to add to the trade. | *required* |

### `Trade.has_tag`

```python theme={null}
Trade.has_tag(tags: list[str], match_all: bool = True) -> bool
```

Checks if `Trade` has tag or list of tags.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `tag` | `str \| list[str]` | Tags or list of tags | *required* |
| `match_all` | `bool` | If set to true and tag is a list of tags, Trades that have all | `True` |

**Returns**

| Name | Type | Description |
| - | - | - |
| `bool` | `bool` | True if the trade has the specified tag(s), False otherwise. |

### `Trade.rebalance`

```python theme={null}
Trade.rebalance(quantity: float) -> None
```

Rebalance the trade by adjusting the quantity.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `quantity` | `float` | The new quantity to set for the trade. | *required* |

**Raises**

| Type | Description |
| - | - |
| `ValueError` | If the trade is closed and an attempt is made to rebalance it. |

### `Trade.pulse`

```python theme={null}
Trade.pulse(pulse_index: PulseIndex, datafeed: DataFeed) -> None
```

Update the trade with the latest price and calculate PnL.

**Raises**

| Type | Description |
| - | - |
| `ValueError` | If the trade is closed and an attempt is made to pulse it. |

### `Trade.close`

```python theme={null}
Trade.close(pulse_index: PulseIndex) -> None
```

Close the trade

## `Stats`

`dataclass`

```python theme={null}
Stats(
    risk_free_rate: float = RISK_FREE_RATE,
    pulses_per_year: float = float(NUMBER_OF_TRADING_DAYS_PER_YEAR),
    start_datetime: datetime.datetime | None = None,
    end_datetime: datetime.datetime | None = None,
    duration: datetime.timedelta | None = None,
    start_equity: float | None = None,
    end_equity: float | None = None,
    diff_equity: float | None = None,
    total_return: float | None = None,
    cagr: float | None = None,
    annualized_sharpe_ratio: float | None = None,
    annualized_calmar_ratio: float | None = None,
    annualized_sortino_ratio: float | None = None,
    best_day: float | None = None,
    best_day_date: datetime.datetime | None = None,
    worst_day: float | None = None,
    worst_day_date: datetime.datetime | None = None,
    max_drawdown: float | None = None,
    avg_drawdown: float | None = None,
    avg_drawdown_days: float | None = None,
    time_to_recovery: int | None = None,
    longest_time_underwater: int | None = None,
    trade_count: int | None = None,
    trade_win_rate_pct: float | None = None,
    best_trade: float | None = None,
    worst_trade: float | None = None,
    average_trade_pnl: float | None = None,
    average_trade_duration: float | None = None,
    max_trade_duration: float | None = None,
    profit_factor: float | None = None,
    trade_stats: TradeStats | None = None,
    fee_stats: FeeStats | None = None,
    daily_mean: float | None = None,
    daily_vol: float | None = None,
    daily_sharpe: float | None = None,
    daily_sortino: float | None = None,
    daily_skew: float | None = None,
    daily_kurt: float | None = None,
    monthly_returns: tuple | None = None,
    monthly_mean: float | None = None,
    monthly_vol: float | None = None,
    best_month: float | None = None,
    best_month_date: str | None = None,
    worst_month: float | None = None,
    worst_month_date: str | None = None,
    mtd: float | None = None,
    three_month: float | None = None,
    six_month: float | None = None,
    pos_month_perc: float | None = None,
    avg_up_month: float | None = None,
    avg_down_month: float | None = None,
    monthly_skew: float | None = None,
    monthly_kurt: float | None = None,
    yearly_returns: tuple | None = None,
    ytd: float | None = None,
    one_year: float | None = None,
    yearly_mean: float | None = None,
    yearly_vol: float | None = None,
    best_year: float | None = None,
    best_year_date: str | None = None,
    worst_year: float | None = None,
    worst_year_date: str | None = None,
    three_year: float | None = None,
    five_year: float | None = None,
    ten_year: float | None = None,
    win_year_perc: float | None = None,
    twelve_month_win_perc: float | None = None,
    yearly_skew: float | None = None,
    yearly_kurt: float | None = None,
    return_table: dict = dict(),
)
```

Encapsulates the computed statistics for a trading strategy.

### `Stats.from_data`

`classmethod`

```python theme={null}
Stats.from_data(
    equity_history: list[float],
    datetimes: list[datetime.datetime],
    trades: list[Trade] | None = None,
    risk_free_rate: float = RISK_FREE_RATE,
    pulses_per_year: float = float(NUMBER_OF_TRADING_DAYS_PER_YEAR),
    pulse_fees_history: list[float] | None = None,
    pulse_total_pnl_history: list[float] | None = None,
    initial_equity: float | None = None,
) -> Stats
```

Create a Stats instance from raw equity and datetime data.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `equity_history` | `list[float]` | List of equity values over time (one per pulse). | *required* |
| `datetimes` | `list[datetime]` | Corresponding datetime points. | *required* |
| `trades` | [`list[Trade] \| None`](https://docs.allasso.ch/dev/pulse/api/core/trade#trade) | Optional list of Trade objects for trade-level metrics. | `None` |
| `risk_free_rate` | `float` | Risk-free rate for ratio calculations. | `RISK_FREE_RATE` |
| `pulses_per_year` | `float` | Pulses per year for annualization. Defaults to 252 (daily cadence). For other cadences pass the actual rate, e.g. `strategy.pulse_index.pulses_per_year` from a live PulseIndex. | `float(NUMBER_OF_TRADING_DAYS_PER_YEAR)` |
| `pulse_fees_history` | `list[float] \| None` | Optional per-pulse fee charges aligned with `datetimes`. When provided alongside `pulse_total_pnl_history` and `initial_equity`, populates `Stats.fee_stats`. | `None` |
| `pulse_total_pnl_history` | `list[float] \| None` | Optional per-pulse gross PnL aligned with `datetimes`. Required to compute `fees_pct_of_gross_pnl`. | `None` |
| `initial_equity` | `float \| None` | Starting equity. Defaults to `equity_history[0]` when not provided. | `None` |

**Returns**

| Type | Description |
| - | - |
| [`Stats`](https://docs.allasso.ch/dev/pulse/api/metrics/stats#stats) | Populated Stats instance. |

### `Stats.from_strategy`

`classmethod`

```python theme={null}
Stats.from_strategy(
    strategy: Strategy,
    risk_free_rate: float = RISK_FREE_RATE,
    pulses_per_year: float | None = None,
) -> Stats
```

Create a Stats instance from a Strategy object.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `strategy` | [`Strategy`](https://docs.allasso.ch/dev/pulse/api/core/strategy#strategy) | A completed Strategy instance with portfolio and trades. | *required* |
| `risk_free_rate` | `float` | Risk-free rate for ratio calculations. | `RISK_FREE_RATE` |
| `pulses_per_year` | `float \| None` | Pulses per year for annualization. When `None` (default), reads from `strategy.pulse_index.pulses_per_year` so the metric reflects the actual cadence of the simulation. | `None` |

**Returns**

| Type | Description |
| - | - |
| [`Stats`](https://docs.allasso.ch/dev/pulse/api/metrics/stats#stats) | Populated Stats instance. |

### `Stats.calculate`

```python theme={null}
Stats.calculate(strategy: Strategy) -> None
```

Populate stats from a Strategy object (backward-compatible method).

Prefer using Stats.from\_strategy() for new code.

## `run_sequentially`

```python theme={null}
run_sequentially(
    strategies: list[Strategy],
    initial_equity: float,
    strategy_parameters: list[dict[str, Any]] | list[None] | None = None,
    datetimes: list[datetime] | None = None,
    start_datetime: datetime | None = None,
    end_datetime: datetime | None = None,
    datafeed: DataFeed | None = None,
    resolver: ResolverRegistry | None = None,
    fee_calculator: FeeCalculator | None = None,
) -> list[ExecutionResult]
```

Run strategies one after another, each in its own trading environment.

One `EnvironmentBuilder` per strategy, built from that strategy's own `underlying_id`,
so a sweep is just a list of strategies here. Every strategy gets its own portfolio, broker
and pulse index; the datafeed and resolver are shared, which is what makes the warmed readers
worth paying for once.

The pulse calendar is the underlyings' common settlements, optionally bounded by
`start_datetime` / `end_datetime`, which are handed to pdc's `available_settlements`
and are inclusive at both ends. `datetimes` replaces that calendar outright instead, so it
cannot be combined with the bounds.

**Parameters**

| Name | Type | Description | Default |
| - | - | - | - |
| `strategies` | [`list[Strategy]`](https://docs.allasso.ch/dev/pulse/api/core/strategy#strategy) | The strategies to run, in order. | *required* |
| `initial_equity` | `float` | Starting capital, per strategy. | *required* |
| `strategy_parameters` | `list[dict[str, Any]] \| list[None] \| None` | Parameters recorded on each `ExecutionResult`, positionally matched to `strategies`. They are carried, not applied: the strategy is already constructed. Defaults to None. | `None` |
| `datetimes` | `list[datetime] \| None` | An explicit calendar for every strategy. Defaults to None, deriving it from the underlyings. | `None` |
| `start_datetime` | `datetime \| None` | Inclusive first pulse of the derived calendar. Defaults to None (from the first common settlement). | `None` |
| `end_datetime` | `datetime \| None` | Inclusive last pulse of the derived calendar. Defaults to None (to the last common settlement). | `None` |
| `datafeed` | `DataFeed \| None` | Defaults to None, building a local one. Passing one requires passing `resolver` too. | `None` |
| `resolver` | `ResolverRegistry \| None` | Defaults to None, building a local one. | `None` |
| `fee_calculator` | [`FeeCalculator \| None`](https://docs.allasso.ch/dev/pulse/api/core/fees#feecalculator) | Applied to every strategy's portfolio. Defaults to None, meaning no fees. | `None` |

**Raises**

| Type | Description |
| - | - |
| `ValueError` | if `datetimes` is combined with either bound, if a datafeed is passed without a resolver, or if the underlyings share no settlement in the range. |
| `Exception` | whatever a strategy raised. A failing strategy aborts the batch, so the results of the strategies that already finished are lost with it. |

**Returns**

| Type | Description |
| - | - |
| [`list[ExecutionResult]`](https://docs.allasso.ch/dev/pulse/api/core/atm#executionresult) | list\[ExecutionResult]: One result per strategy, in the order given. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.