> ## 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.

# Fees

> Transaction costs are modelled as a pluggable, per-pulse calculator. They are strictly opt-in: the default NoFeeCalculator charges zero, so a backtest only sees fees once you inject a real calculator.

Transaction costs are modelled as a pluggable, per-pulse calculator. They are strictly opt-in: the
default `NoFeeCalculator` charges zero, so a backtest only sees fees once you inject a real
calculator.

## How fees are charged

Within a single pulse the portfolio collects every fee-bearing transaction into one batch, then
charges the whole batch at once. There are three kinds of event, captured by `FeeEventType`:

| `FeeEventType` | When it is collected |
| - | - |
| `ENTRY` | A new trade is booked (`Portfolio.add_trade`). |
| `REBALANCE` | The portfolio's rebalance detector sees a position change on the pulse. |
| `EXIT` | A trade is closed. |

Each event is a frozen `FeeEvent` dataclass carrying the `trade`, the signed `quantity_units` (lots
already expanded to units, positive for buys and negative for sells), the fill `price`, and the
`event_type`.

At the end of the pulse the portfolio drains the batch in a single call:

```
fees = calculator.calculate(events, datafeed)   # one fee per event, same order
```

The returned per-event fees are summed and netted against equity for that pulse:

```
current_equity += pulse_total_pnl - pulse_fees
```

> [!NOTE]
>
> **Why a batch, not one call per trade**
>
> Passing the whole pulse's events together lets a calculator price events relative to each
> other - for example block-trade pricing where the larger-notional side is charged and the
> other side is rebated to zero. A per-event call could not see those relationships.

## Built-in calculators

All live in [`pulse.fees`](https://github.com/AllassoSA/pulse-core). `FeeCalculator` is the ABC; the
contract is `calculate(events, datafeed) -> list[float]`, returning one non-negative fee per event in
the same order and length as the input.

| Calculator | Charge per event |
| - | - |
| `NoFeeCalculator()` | `0.0` (default). |
| `FixedFeeCalculator(per_unit)` | `per_unit * abs(quantity_units)` - a flat fee per contract. |
| `PercentageFeeCalculator(rate)` | `rate * abs(quantity_units) * abs(price)` - a fraction of traded notional. |

`FixedFeeCalculator` and `PercentageFeeCalculator` reject a negative argument with `ValueError`.

## Injecting a calculator

Three entry points, all interchangeable:

```python theme={null}
from pulse import run_sequentially
from pulse.core.fees import FixedFeeCalculator

# 1. directly on the runner
result = run_sequentially([MyStrategy()], fee_calculator=FixedFeeCalculator(per_unit=1.5))[0]

# 2. on the EnvironmentBuilder
env = EnvironmentBuilder(underlying_ids="IND.ES").with_fee_calculator(FixedFeeCalculator(1.5)).build()

# 3. on the Portfolio
portfolio = Portfolio(initial_equity=1_000_000, fee_calculator=FixedFeeCalculator(1.5))
```

## A custom calculator

Subclass `FeeCalculator` and implement `calculate`. Use the `datafeed` for contract metadata or
market lookups when a scheme needs it.

```python theme={null}
from pulse.core.fees import FeeCalculator, FeeEvent, FeeEventType

class TieredFeeCalculator(FeeCalculator):
    """Cheaper per unit once a single event crosses a size threshold."""

    def calculate(self, events: list[FeeEvent], datafeed) -> list[float]:
        fees = []
        for e in events:
            units = abs(e.quantity_units)
            rate = 0.5 if units >= 100 else 1.0
            # waive the exit leg, charge entries and rebalances
            if e.event_type is FeeEventType.EXIT:
                rate = 0.0
            fees.append(rate * units)
        return fees
```

Return exactly one fee per event, in order; the portfolio relies on the alignment.

## Reading fees back

After a run the totals live on the portfolio and in `Stats`:

* `portfolio.total_fees` - cumulative fees over the whole run.
* `portfolio.pulse_fees_history` - fees per pulse, aligned with the equity history.
* `Stats.fee_stats` - a `FeeStats` with `total_fees`, `fee_drag_pct` (fees over initial equity),
  `avg_fee_per_trade`, `fees_pct_of_gross_pnl`, `max_pulse_fees`, and `max_pulse_fees_datetime`.
  When fees are all zero (the default), `fee_stats` is a zero-valued instance.

Three charts visualise the impact: `plot_pulse_fees_history`, `plot_cumulative_fees`, and
`plot_fee_impact_on_equity`. The last one synthesises the no-fee counterfactual from
`pulse_total_pnl_history`, so you do not need to run the backtest twice to see the drag.

> [!TIP]
>
> **Gross vs net**
>
> `pulse_total_pnl_history` is **gross** of fees (per-pulse market PnL before fees);
> `equity_history` is **net** (the money in the account after fees). With `NoFeeCalculator`
> the two agree. See [Portfolio, equity and PnL](https://docs.allasso.ch/dev/pulse/concepts/portfolio-pnl.md) for the full distinction.

**Related:** [Portfolio, equity and PnL](https://docs.allasso.ch/dev/pulse/concepts/portfolio-pnl.md) · [Metrics and Stats](https://docs.allasso.ch/dev/pulse/concepts/metrics.md) ·
[Architecture and the pulse loop](https://docs.allasso.ch/dev/pulse/concepts/architecture.md) · [Fees notebook](https://docs.allasso.ch/dev/pulse/notebooks/fees.md)


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