BaseStrategy¶
The class-based strategy interface used by the oneshot backtester and the built-in strategies.
cjtrade.pkgs.strategy.base_strategy
¶
pkgs/strategy/base_strategy.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Abstract base class for all CJTrade strategies.
Both the bar-by-bar runner (the CJTrade app's bots) and the one-shot backtest engine (apps/oneshot_backtest.py) drive strategies through the same interface, so a strategy written once works in both modes.
Lifecycle
on_start(context) ← called once before the first bar
for each bar:
on_bar(bar, context) → List[Signal]
monitors() → dict ← optional; what to watch, and why the
bar did or did not produce a signal
on_fill(fill, context) ← called after each simulated fill
on_end(context) ← called once after the last bar
Signal types
Signal(action='BUY'|'SELL'|'HOLD', symbol, quantity, price, reason)
Example
class MyStrategy(BaseStrategy):
def on_bar(self, bar, ctx):
if bar.close < ctx.lower_bb(bar.symbol):
return [Signal('BUY', bar.symbol, ctx.calc_qty(bar.close), bar.close)]
return []
Signal(action, symbol, quantity, price, reason='', meta=dict())
dataclass
¶
A trade signal produced by a strategy on a given bar.
Attributes:
| Name | Type | Description |
|---|---|---|
action |
str
|
'BUY', 'SELL', or 'HOLD' (HOLD is a no-op, mostly for logging). |
symbol |
str
|
Stock ticker, e.g. '2330'. |
quantity |
int
|
Number of lots (張). Must be > 0 for BUY/SELL. |
price |
float
|
Limit price to submit. |
reason |
(str, optional)
|
Human-readable explanation (appears in logs / fill_history). |
meta |
(dict, optional)
|
Arbitrary extra data (e.g. indicator values at signal time). |
StrategyContext(timestamp, balance, equity, positions, price_history, bar_index=0, params=dict())
dataclass
¶
Snapshot of account state visible to the strategy at each bar.
The engine populates this before calling on_bar() so the strategy never has to call the broker API directly.
Attributes:
| Name | Type | Description |
|---|---|---|
timestamp |
datetime
|
Mock/real time of the current bar. |
balance |
float
|
Available cash. |
equity |
float
|
balance + total market value of all open positions. |
positions |
list[dict]
|
Each dict: {'symbol', 'quantity', 'avg_cost', 'current_price', 'market_value', 'unrealized_pnl'} |
price_history |
dict[symbol, list[float]]
|
Close prices seen so far (most-recent last). |
bar_index |
int
|
0-based index of the current bar within the full kbar list. |
params |
dict
|
Strategy-specific parameters forwarded from the runner config. |
has_position(symbol)
¶
True if positions holds a positive quantity of symbol.
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
116 117 118 119 | |
position_qty(symbol)
¶
Quantity held of symbol, or 0 if there is no position.
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
121 122 123 124 125 126 | |
calc_qty(price, max_pct=0.05)
¶
Return lot count that keeps position ≤ max_pct of current equity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
price
|
float
|
Price per unit. |
required |
max_pct
|
float
|
Fraction of equity to allocate. |
0.05
|
Returns:
| Type | Description |
|---|---|
int
|
At least 1 if cash covers one unit at |
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
prices(symbol)
¶
Shorthand for price_history[symbol] (returns [] if not found).
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
149 150 151 | |
Fill(symbol, action, quantity, price, timestamp, commission=0.0, tax=0.0, slippage_cost=0.0, reason='')
dataclass
¶
Represents an executed trade returned to on_fill().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Stock ticker. |
required |
action
|
str
|
'BUY' or 'SELL'. |
required |
quantity
|
int
|
Quantity filled. |
required |
price
|
float
|
Fill price. |
required |
timestamp
|
datetime
|
Fill time. |
required |
commission
|
float
|
Costs charged on the fill. |
0.0
|
tax
|
float
|
Costs charged on the fill. |
0.0
|
slippage_cost
|
float
|
Costs charged on the fill. |
0.0
|
reason
|
str
|
Reason carried from the signal. |
''
|
BaseStrategy
¶
Bases: ABC
All strategies must subclass this and implement on_bar().
The engine calls the lifecycle hooks in order: on_start → [on_bar → on_fill*] × N → on_end
on_start(ctx)
¶
Called once before the first bar. Override for initialisation.
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
208 209 210 | |
on_bar(bar, ctx)
abstractmethod
¶
Process one Kbar and return a list of Signals (may be empty).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bar
|
Kbar
|
The current bar (open, high, low, close, volume, timestamp). |
required |
ctx
|
StrategyContext
|
Current account state and price history. |
required |
Returns:
| Type | Description |
|---|---|
list[Signal]
|
Zero or more signals. HOLD signals are logged but not traded. |
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | |
on_fill(fill, ctx)
¶
Called after every simulated fill. Override to track state.
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
230 231 232 | |
on_end(ctx)
¶
Called once after the last bar. Override for cleanup/logging.
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
234 235 236 | |
plots()
¶
Series this strategy wants drawn against the price, this bar.
Separate from monitors() because the two are consumed differently: a monitor is a number to read now, a plot is a point in a series accumulated over the run. A runner samples this once per bar and keeps the history; the strategy only reports the current value.
Numbers only, and in the same units as the price where that makes sense -- bands, moving averages, breakout levels. A value on a different scale (an oscillator, a count) is still fine; it is the chart's job to put it on its own axis.
Default is empty, so a strategy that does not care has nothing to say and nothing breaks. The price itself is never returned here: every runner already knows the bar it just handed over, and a strategy re-reporting it would be a second answer that could disagree.
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
monitors()
¶
Named values this strategy wants watched. Read-only and cheap.
Called by a runner after on_bar, as often as once per bar. Return whatever makes this strategy's behaviour legible: indicator levels, counters, a regime label, and above all WHY the last bar did or did not produce a signal -- on_bar returns an empty list for several different reasons and the caller cannot tell them apart.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Scalars and strings only. A runner may put this on a wire or in a table, so nothing here should be a numpy type, a model object, or anything that needs the strategy alive to interpret. |
Default is empty, so an existing strategy keeps working and simply has
|
|
nothing to show. Deliberately not abstract for the same reason.
|
|
Accumulated values (counters, running means) live on the strategy and
|
|
are updated in on_bar; this method only reads them. A caller that wants
|
|
rates or deltas keeps its own history of these snapshots -- that is why
|
|
there is no need to declare which values are counters and which are
|
|
gauges.
|
|
Source code in src/cjtrade/pkgs/strategy/base_strategy.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | |