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

# Write a custom fee model

> When the built-in calculators do not match a venue, subclass FeeCalculator and implement one method.

When the built-in calculators do not match a venue, subclass `FeeCalculator` and implement one method.
The mechanics (per-pulse batch, three event types, how fees net against equity) are covered in
[Fees](https://docs.allasso.ch/dev/pulse/concepts/fees.md); this page is the applied recipe.

## The contract

A calculator implements a single method:

```python theme={null}
def calculate(self, events: list[FeeEvent], datafeed) -> list[float]: ...
```

It receives every fee-bearing event collected during the pulse and must return one non-negative fee
per event, in the same order and length. Each `FeeEvent` is a frozen dataclass with four fields:

| Field | Meaning |
| - | - |
| `trade` | The `Trade` being transacted. |
| `quantity_units` | Signed quantity in units (lots already expanded; positive buys, negative sells). |
| `price` | The fill price of the transaction. |
| `event_type` | A `FeeEventType`: `ENTRY`, `REBALANCE`, or `EXIT`. |

## A minimum-floor calculator

A common venue rule is "a percentage of notional, but never less than a fixed floor per transaction".

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


class FloorFeeCalculator(FeeCalculator):
    """Percentage-of-notional fee with a per-event minimum floor."""

    def __init__(self, rate: float, floor: float):
        if rate < 0 or floor < 0:
            raise ValueError("rate and floor must be non-negative")
        self._rate = rate
        self._floor = floor

    def calculate(self, events: list[FeeEvent], datafeed) -> list[float]:
        fees = []
        for e in events:
            notional = abs(e.quantity_units) * abs(e.price)
            fees.append(max(self._rate * notional, self._floor))
        return fees
```

## Per-event-type fees

The `event_type` lets you charge entries, rebalances, and exits differently; for example a flat fee on
entry and exit while waiving rebalances:

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


class EntryExitFeeCalculator(FeeCalculator):
    """Flat per-unit fee on entries and exits; rebalances are free."""

    def __init__(self, per_unit: float):
        self._per_unit = per_unit

    def calculate(self, events: list[FeeEvent], datafeed) -> list[float]:
        fees = []
        for e in events:
            if e.event_type is FeeEventType.REBALANCE:
                fees.append(0.0)
            else:
                fees.append(self._per_unit * abs(e.quantity_units))
        return fees
```

> [!NOTE]
>
> **Return one fee per event, in order**
>
> The portfolio sums the returned list positionally and nets it against equity. Returning a list of a
> different length, or reordering it, breaks the alignment. Use the `datafeed` argument when a scheme
> needs contract metadata or a market lookup.

## Inject it

The calculator plugs in at any of three points, exactly like the built-ins:

```python theme={null}
from pulse import run_sequentially

# 1. directly on the runner
result = run_sequentially([MyStrategy()], fee_calculator=FloorFeeCalculator(rate=0.0005, floor=2.0))[0]

# 2. on the EnvironmentBuilder
env = EnvironmentBuilder(underlying_ids="IND.ES").with_fee_calculator(FloorFeeCalculator(0.0005, 2.0)).build()

# 3. on the Portfolio
portfolio = Portfolio(initial_equity=1_000_000, fee_calculator=FloorFeeCalculator(0.0005, 2.0))
```

## Read the results back

After the run the fee totals are on the portfolio and in `Stats`:

```python theme={null}
strategy = result.strategy
strategy.portfolio.total_fees        # cumulative fees over the whole run
strategy.stats.fee_stats.fee_drag_pct   # fees as a fraction of initial equity
```

`strategy.stats.fee_stats` is a `FeeStats` with `total_fees`, `fee_drag_pct`, `avg_fee_per_trade`,
`fees_pct_of_gross_pnl`, `max_pulse_fees`, and `max_pulse_fees_datetime`. See
[Fees](https://docs.allasso.ch/dev/pulse/concepts/fees.md) for the per-pulse history and the impact charts.

**Related:** [Fees](https://docs.allasso.ch/dev/pulse/concepts/fees.md) · [Fees notebook](https://docs.allasso.ch/dev/pulse/notebooks/fees.md) ·
[Metrics and Stats](https://docs.allasso.ch/dev/pulse/concepts/metrics.md)


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