pybroker.slippage module

Implements slippage models.

class FixedSlippageModel(bps: float = 5)[source]

Bases: SlippageModel

Deterministic fixed-basis-point slippage on fill price.

Buy fills are worsened upward; sell fills are worsened downward. Applies to long entries, short entries, long exits, and covers.

Parameters:

bps – Adverse slippage in basis points. 0 is a no-op. Must be less than 10000 (100%), which would make sell fills non-positive.

adjust_fill_price(side: Literal['buy', 'sell'], fill_price: Decimal) → Decimal[source]

Returns fill_price adjusted for side without extra context.

apply_slippage(ctx: SlippageContext) → tuple[Decimal, Decimal][source]

Applies slippage using data from the fill bar.

The returned share quantity may be reduced to simulate a partial fill, but never increased: returning more than ctx.shares (or a negative quantity) raises a ValueError at the fill.

Returns:

Tuple of (shares, fill_price) after slippage.

property is_fill_noop: bool

Whether apply_slippage() is a no-op for this model.

class SlippageContext(side: Literal['buy', 'sell'], symbol: str, shares: Decimal, fill_price: Decimal, col_scope: ColumnScope | None, ind_scope: IndicatorScope | None, sym_end_index: Mapping[str, int] | None, enable_fractional_shares: bool = True)[source]

Bases: object

Context passed to slippage adjustments.

side

Order side, either buy or sell.

Type:

Literal[‘buy’, ‘sell’]

symbol

Ticker symbol of the order.

Type:

str

shares

Number of shares to fill before slippage.

Type:

decimal.Decimal

fill_price

Base fill price resolved on the fill bar.

Type:

decimal.Decimal

col_scope

Column scope over the whole test window — not pre-sliced to the fill bar. Causal reads must bound every fetch with the fill bar’s index, e.g. ctx.col_scope.fetch(ctx.symbol, "close", end_index=ctx.sym_end_index[ctx.symbol]); fetching without end_index returns the full window, including bars after the fill. None when bar data is unavailable, in which case volume- and volatility-based models leave the fill unadjusted.

Type:

pybroker.scope.ColumnScope | None

ind_scope

Indicator scope over the whole test window — the same end_index bound applies as for col_scope. None when indicator data is unavailable, in which case indicator-based models leave the fill unadjusted.

Type:

pybroker.scope.IndicatorScope | None

sym_end_index

Current bar index per symbol, or None when unavailable.

Type:

Mapping[str, int] | None

enable_fractional_shares

Whether fractional shares are enabled. When False, a returned share quantity is truncated to a whole number by the caller; the flag lets a model compute price-dependent values (such as volume participation) from the quantity that will actually fill.

Type:

bool

class SlippageModel[source]

Bases: ABC

Base class for implementing a slippage model.

A slippage model may adjust fill price, share quantity, or both, using data from the fill bar in apply_slippage().

apply_slippage() is called for scheduled buy and sell orders, for stop exits (stop loss, take profit, trailing, and bar stops), and for pybroker.portfolio.Portfolio.exit_position() fills. Stop and exit fills apply the returned fill price only; a returned share quantity is ignored, since those paths exit an entry in full.

adjust_fill(side: Literal['buy', 'sell'], symbol: str, shares: Decimal, fill_price: Decimal, col_scope: ColumnScope | None = None, ind_scope: IndicatorScope | None = None, sym_end_index: Mapping[str, int] | None = None, enable_fractional_shares: bool = True) → tuple[Decimal, Decimal][source]

Builds a SlippageContext and applies apply_slippage() to it.

Provided so that callers which cannot import pybroker.slippage (such as pybroker.portfolio) can still apply slippage to a fill.

Returns:

Tuple of (shares, fill_price) after slippage.

apply_slippage(ctx: SlippageContext) → tuple[Decimal, Decimal][source]

Applies slippage using data from the fill bar.

The returned share quantity may be reduced to simulate a partial fill, but never increased: returning more than ctx.shares (or a negative quantity) raises a ValueError at the fill.

Returns:

Tuple of (shares, fill_price) after slippage.

property is_fill_noop: bool

Whether apply_slippage() is a no-op for this model.

validate(strategy: Strategy) → None[source]

Validates model configuration before a backtest starts.

class VolatilitySlippageModel(atr_period: int = 14, scale: float = 0.1)[source]

Bases: SlippageModel

ATR-scaled slippage on fill price.

Adverse price adjustment equals scale * ATR at the fill bar, where the Average True Range is computed over the atr_period bars ending at the fill bar (see pybroker.vect.atr()). Fills during the warmup period – the first atr_period bars, which have no full ATR window – or on bars where the ATR is NaN are left unadjusted.

Parameters:
  • atr_period – Number of lookback bars for the ATR. Defaults to 14.

  • scale – Multiplier applied to the ATR value.

apply_slippage(ctx: SlippageContext) → tuple[Decimal, Decimal][source]

Applies slippage using data from the fill bar.

The returned share quantity may be reduced to simulate a partial fill, but never increased: returning more than ctx.shares (or a negative quantity) raises a ValueError at the fill.

Returns:

Tuple of (shares, fill_price) after slippage.

property is_fill_noop: bool

Whether apply_slippage() is a no-op for this model.

class VolumeSlippageModel(price_impact: float = 0.1, volume_limit: float | None = 0.025)[source]

Bases: SlippageModel

Volume-based participation cap and square-law price impact.

Share quantity may be capped at volume_limit * bar_volume. Price impact is price_impact * (filled_shares / bar_volume) ** 2. Either effect can be disabled by passing 0 or None.

Requires a volume data column, which is optional in PyBroker. Bars where the volume is missing or NaN are left unadjusted.

Parameters:
  • price_impact – Square-law impact coefficient. 0 disables impact.

  • volume_limit – Max participation as a fraction of bar volume. None or 0 disables the cap.

apply_slippage(ctx: SlippageContext) → tuple[Decimal, Decimal][source]

Applies slippage using data from the fill bar.

The returned share quantity may be reduced to simulate a partial fill, but never increased: returning more than ctx.shares (or a negative quantity) raises a ValueError at the fill.

Returns:

Tuple of (shares, fill_price) after slippage.

property is_fill_noop: bool

Whether apply_slippage() is a no-op for this model.

validate(strategy: Strategy) → None[source]

Validates model configuration before a backtest starts.