Strategy¶
- class qtrade.backtest.Strategy(broker, data, params)[源代码]¶
Base class for trading strategies.
Single-asset strategies use the legacy attribute-style API (
self.data,self.position,self.buy(size=10)); multi-asset strategies useself.data_by_asset[asset],self.positions[asset], and pass an asset symbol toself.buy("AAPL", size=10).- 参数:
broker -- The Broker instance.
data -- Either a single DataFrame (single-asset, kept under the key
"default") or a dict[str, DataFrame] (multi-asset).params -- Strategy parameters dict; entries are also bound as attributes.
Lifecycle methods¶
Order placement¶
- Strategy.buy(asset: str | None = None, *, size: int | None = None, limit: float | None = None, stop: float | None = None, sl: float | None = None, tp: float | None = None, trail_percent: float | None = None, trail_amount: float | None = None, tag: object | None = None)[源代码]¶
Place a buy order.
- 参数:
asset -- Asset symbol (positional). Required when the strategy is running on more than one asset; optional otherwise.
size -- Order size. If omitted, defaults to the maximum size that fits in current available margin at the most recent close.
tag (limit / stop / sl / tp /) -- standard order fields.
trail_percent -- Trailing-stop distance as a fraction (e.g.
0.05for 5%). The Broker auto-bumps the SL each bar so it ratchets up only — never moves against the trade. Mutually exclusive withtrail_amount.trail_amount -- Trailing-stop distance as an absolute price gap. Mutually exclusive with
trail_percent.
- Strategy.sell(asset: str | None = None, *, size: int | None = None, limit: float | None = None, stop: float | None = None, sl: float | None = None, tp: float | None = None, trail_percent: float | None = None, trail_amount: float | None = None, tag: object | None = None)[源代码]¶
Place a sell order.
- 参数:
asset -- Asset symbol (positional). Required when the strategy is running on more than one asset; optional otherwise.
size -- Order size. If omitted, defaults to the current position size on that asset (used for closing longs).
tag (limit / stop / sl / tp /) -- standard order fields.
trail_amount (trail_percent /) -- see
buy(). For shorts, the trailing stop ratchets down as price falls.
Read accessors¶
Single-asset shorthand: data, position, equity, unrealized_pnl,
active_trades, closed_trades, pending_orders.
Multi-asset accessors: assets (list of symbols), positions (dict),
data_by_asset (dict of truncated DataFrames). The single-asset shorthand
properties (data, position) raise AttributeError with a clear message
when the strategy is running on more than one asset.