跳轉到

內建策略

給 oneshot 回測和 engine 的 bot 使用的 class 型策略。參數用 params={"<前綴>__<名稱>": 值} 傳入。

Warning

窗口類參數以 K 棒數計算,所以同一個值在 1m 和 1d 上是不同的策略。各 interval 的預設值見策略參數。

cjtrade.pkgs.strategy.bb

pkgs/strategy/bb_1m.py ~~~~~~~~~~~~~~~~~~~~~~~ Bollinger Band mean-reversion strategy using TA-Lib (matches arenax.py).

Copy this file, rename the class, and implement your own logic in on_bar().

Run it: from cjtrade.apps.oneshot_backtest import run_oneshot from cjtrade.pkgs.strategy.bb_1m import BollingerStrategy

run_oneshot(symbol="2330", start="2023-01-01", strategy=BollingerStrategy())

TALibWrapper

Pine Script style API

sma(real, timeperiod=20)

Simple Moving Average

Source code in src/cjtrade/pkgs/analytics/technical/talib_wrapper.py
 8
 9
10
def sma(self, real, timeperiod=20):
    """Simple Moving Average"""
    return talib.SMA(real, timeperiod=timeperiod)

ema(real, timeperiod=20)

Exponential Moving Average

Source code in src/cjtrade/pkgs/analytics/technical/talib_wrapper.py
12
13
14
def ema(self, real, timeperiod=20):
    """Exponential Moving Average"""
    return talib.EMA(real, timeperiod=timeperiod)

wma(real, timeperiod=20)

Weighted Moving Average

Source code in src/cjtrade/pkgs/analytics/technical/talib_wrapper.py
16
17
18
def wma(self, real, timeperiod=20):
    """Weighted Moving Average"""
    return talib.WMA(real, timeperiod=timeperiod)

bb(real, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)

Bollinger Bands

Source code in src/cjtrade/pkgs/analytics/technical/talib_wrapper.py
21
22
23
24
def bb(self, real, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0):
    """Bollinger Bands"""
    return talib.BBANDS(real, timeperiod=timeperiod,
                       nbdevup=nbdevup, nbdevdn=nbdevdn, matype=matype)

rsi(real, timeperiod=14)

Relative Strength Index

Source code in src/cjtrade/pkgs/analytics/technical/talib_wrapper.py
27
28
29
def rsi(self, real, timeperiod=14):
    """Relative Strength Index"""
    return talib.RSI(real, timeperiod=timeperiod)

macd(real, fastperiod=12, slowperiod=26, signalperiod=9)

MACD - Moving Average Convergence Divergence

Source code in src/cjtrade/pkgs/analytics/technical/talib_wrapper.py
31
32
33
34
35
36
def macd(self, real, fastperiod=12, slowperiod=26, signalperiod=9):
    """MACD - Moving Average Convergence Divergence"""
    macd, signal, hist = talib.MACD(real, fastperiod=fastperiod,
                                    slowperiod=slowperiod,
                                    signalperiod=signalperiod)
    return macd, signal, hist

stoch(high, low, close, fastk_period=5, slowk_period=3, slowd_period=3, slowk_matype=0, slowd_matype=0)

Stochastic

Source code in src/cjtrade/pkgs/analytics/technical/talib_wrapper.py
38
39
40
41
42
43
44
45
46
47
def stoch(self, high, low, close, fastk_period=5, slowk_period=3,
          slowd_period=3, slowk_matype=0, slowd_matype=0):
    """Stochastic"""
    slowk, slowd = talib.STOCH(high, low, close,
                               fastk_period=fastk_period,
                               slowk_period=slowk_period,
                               slowd_period=slowd_period,
                               slowk_matype=slowk_matype,
                               slowd_matype=slowd_matype)
    return slowk, slowd

atr(high, low, close, timeperiod=14)

Average True Range

Source code in src/cjtrade/pkgs/analytics/technical/talib_wrapper.py
50
51
52
def atr(self, high, low, close, timeperiod=14):
    """Average True Range"""
    return talib.ATR(high, low, close, timeperiod=timeperiod)

adx(high, low, close, timeperiod=14)

Average Directional Index

Source code in src/cjtrade/pkgs/analytics/technical/talib_wrapper.py
54
55
56
def adx(self, high, low, close, timeperiod=14):
    """Average Directional Index"""
    return talib.ADX(high, low, close, timeperiod=timeperiod)

BollingerStrategy

Bases: BaseStrategy

Bollinger Band mean-reversion strategy using TA-Lib.

Matches the behavior of arenax.py's calculate_bollinger_bands_mock(). Buys when price touches lower band, sells when it touches upper band. Keeps at most one position (no pyramiding).

Warnings

bb__window_size is counted in bars, so the same value means a different time span on each bar interval.

on_start(ctx)

Read parameters from ctx.params and reset monitor state.

Reads bb__window_size (default 20), bb__min_width_pct (0.01), bb__std_dev (2.0) and risk__max_position_pct (0.05); the older single-underscore names are accepted as fallbacks.

Source code in src/cjtrade/pkgs/strategy/bb.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def on_start(self, ctx):
    """Read parameters from `ctx.params` and reset monitor state.

    Reads `bb__window_size` (default 20), `bb__min_width_pct` (0.01),
    `bb__std_dev` (2.0) and `risk__max_position_pct` (0.05); the older
    single-underscore names are accepted as fallbacks.
    """
    p = ctx.params
    # Read from params (support both old and new param names for backward compatibility)
    self._window = int(p.get("bb__window_size", p.get("bb_window_size", 20)))
    self._min_bw = float(p.get("bb__min_width_pct", p.get("bb_min_width_pct", 0.01)))
    # How many standard deviations out the bands sit. This was advertised
    # by the interval presets and ignored here while ta.bb() was called
    # with a hardcoded 2, so the single most important knob for signal
    # frequency did nothing: 2.0 and 5.0 produced identical runs.
    self._std = float(p.get("bb__std_dev", p.get("bb_std_dev", 2.0)))
    self._max_pct = float(p.get("risk__max_position_pct", p.get("risk_max_position_pct", 0.05)))
    self._n_bars = self._n_upper = self._n_lower = 0
    self._n_cross = self._n_signals = 0
    self._upper = self._middle = self._lower = self._bw = 0.0
    self._bw_sum, self._bw_n = 0.0, 0
    self._prev_above_mid = None
    self._last_reason = "no bars yet"
    log.info(f"window={self._window} std_dev={self._std} "
             f"min_bw={self._min_bw*100:.2f}%")

plots()

The three bands, to be drawn against the price.

The same numbers monitors() reports, named for the chart rather than for the table. Separate because a runner samples these once per bar and keeps the series, while monitors are read as they are.

Empty until the bands exist, so the chart has no leading run of zeros that squashes the price into the top of the frame.

Source code in src/cjtrade/pkgs/strategy/bb.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def plots(self) -> dict:
    """The three bands, to be drawn against the price.

    The same numbers monitors() reports, named for the chart rather than
    for the table. Separate because a runner samples these once per bar and
    keeps the series, while monitors are read as they are.

    Empty until the bands exist, so the chart has no leading run of zeros
    that squashes the price into the top of the frame.
    """
    if not self._bw_n:
        return {}
    return {"upper": self._upper, "middle": self._middle,
            "lower": self._lower}

monitors()

See BaseStrategy.monitors. Plain floats, ints and strings only.

Source code in src/cjtrade/pkgs/strategy/bb.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def monitors(self) -> dict:
    """See BaseStrategy.monitors. Plain floats, ints and strings only."""
    bw_avg = self._bw_sum / self._bw_n if self._bw_n else 0.0
    # Volatility is relative to this symbol's own history rather than an
    # absolute threshold: a 0.5% band is wide for an ETF and narrow for a
    # small cap, so a fixed cutoff would mean different things per symbol.
    if self._bw_n == 0:
        volatility = "unknown"
    elif self._bw > bw_avg * 1.2:
        volatility = "high"
    elif self._bw < bw_avg * 0.8:
        volatility = "low"
    else:
        volatility = "normal"

    return {
        "bars_seen":         self._n_bars,
        "window":            self._window,
        "upper":             round(self._upper, 2),
        "middle":            round(self._middle, 2),
        "lower":             round(self._lower, 2),
        "bandwidth_pct":     round(self._bw * 100, 3),
        "bandwidth_avg_pct": round(bw_avg * 100, 3),
        "volatility":        volatility,
        # Whether the squeeze gate would let a touch through right now.
        "regime":            "tradeable" if self._bw >= self._min_bw else "squeeze",
        "upper_touches":     self._n_upper,
        "lower_touches":     self._n_lower,
        "mid_crossings":     self._n_cross,
        "signals_emitted":   self._n_signals,
        "last_decision":     self._last_reason,
    }

on_bar(bar, ctx)

Buy on a lower-band touch, sell on an upper-band touch.

Parameters:

Name Type Description Default
bar Kbar

The bar that just closed.

required
ctx StrategyContext

Account and price history as of this bar.

required

Returns:

Type Description
list

At most one signal; empty while warming up, in a squeeze, or when no touch is actionable.

Source code in src/cjtrade/pkgs/strategy/bb.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def on_bar(self, bar, ctx):
    """Buy on a lower-band touch, sell on an upper-band touch.

    Parameters
    ----------
    bar : Kbar
        The bar that just closed.
    ctx : StrategyContext
        Account and price history as of this bar.

    Returns
    -------
    list
        At most one signal; empty while warming up, in a squeeze, or when
        no touch is actionable.
    """
    self._n_bars += 1
    prices = ctx.prices(bar.symbol)
    # Need enough data for TA-Lib BB calculation
    if len(prices) < self._window:
        self._last_reason = (f"warming up: {len(prices)} of "
                             f"{self._window} bars")
        return []

    # Only slice the last _window prices — TA-Lib only needs exactly this
    # many points to compute the latest BB values. Avoids O(n) numpy
    # allocation that grows with the entire price history.
    prices_array = np.array(prices[-self._window:], dtype=float)
    upper_bands, middle_bands, lower_bands = ta.bb(
        prices_array,
        timeperiod=self._window,
        nbdevup=self._std,
        nbdevdn=self._std
    )

    # Get the latest BB values
    upper = float(upper_bands[-1])
    middle = float(middle_bands[-1])
    lower = float(lower_bands[-1])
    bw = (upper - lower) / middle if middle > 0 else 0.0
    price = bar.close

    self._observe(price, upper, middle, lower, bw)

    # Skip if band is too narrow
    if bw < self._min_bw:
        self._last_reason = (f"squeeze: bandwidth {bw*100:.3f}% under the "
                             f"{self._min_bw*100:.3f}% floor")
        return []

    ts_str = bar.timestamp.strftime("%Y-%m-%d %H:%M:%S")
    holding = ctx.has_position(bar.symbol)

    # BUY: price touches or breaks below lower band and we don't have a position
    if price <= lower and not holding:
        qty = ctx.calc_qty(price, self._max_pct)
        if qty > 0:
            self._n_signals += 1
            self._last_reason = (f"BUY {qty} @ {price:.2f} on lower-band "
                                 f"touch (lower={lower:.2f})")
            log.info(f"@{ts_str} BUY {bar.symbol} qty={qty} px={price:.2f} (BB lower={lower:.2f})")
            return [type("Signal", (), {
                "action": "BUY", "symbol": bar.symbol,
                "quantity": qty, "price": price,
                "reason": f"BB lower touch (bw={bw*100:.2f}%)",
                "meta": {"upper": upper, "middle": middle, "lower": lower},
            })]
        self._last_reason = (f"lower-band touch at {price:.2f} but size is "
                             f"0: {self._max_pct:.0%} of equity "
                             f"{ctx.equity:,.0f} buys nothing at this price")
        return []

    # SELL: price touches or rises above upper band and we hold a position
    elif price >= upper and holding:
        qty = ctx.position_qty(bar.symbol)
        self._n_signals += 1
        self._last_reason = (f"SELL {qty} @ {price:.2f} on upper-band "
                             f"touch (upper={upper:.2f})")
        log.info(f"@{ts_str} SELL {bar.symbol} qty={qty} px={price:.2f} (BB upper={upper:.2f})")
        return [type("Signal", (), {
            "action": "SELL", "symbol": bar.symbol,
            "quantity": qty, "price": price,
            "reason": f"BB upper touch (bw={bw*100:.2f}%)",
            "meta": {"upper": upper, "middle": middle, "lower": lower},
        })]

    # No actionable signal this bar. Which of the three it was matters:
    # "between the bands" is the market doing nothing, while the other two
    # are the strategy declining a touch it saw, and only one of those is
    # ever the thing you are looking for when a run trades less than
    # expected.
    if price <= lower:
        self._last_reason = (f"lower-band touch at {price:.2f} ignored: "
                             f"already holding {ctx.position_qty(bar.symbol)}")
    elif price >= upper:
        self._last_reason = (f"upper-band touch at {price:.2f} ignored: "
                             f"no position to sell")
    else:
        self._last_reason = (f"price {price:.2f} inside the bands "
                             f"[{lower:.2f}, {upper:.2f}]")
    return []

cjtrade.pkgs.strategy.adx

pkgs/strategy/adx.py ~~~~~~~~~~~~~~~~~~~~~ Regime-switching strategy: Donchian breakout in trends + SNR in consolidation.

What measures the trend

An efficiency ratio on a 0-100 scale (net displacement / total path travelled over adx__period closes), NOT the Wilder ADX, which needs a history of each bar's high and low that this strategy does not keep. See _calculate_adx, which also records what it replaced and why the 40/20 thresholds still mean something.

Behavior
  • Measures trend strength to pick a regime
  • Splits into 3 regimes:
  • Strong Trend (strength > adx__strong_threshold, e.g. 40): Donchian breakout
  • Consolidation (strength < adx__weak_threshold, e.g. 20): Support & Resistance
  • Neutral (mid-range): Conservative mixed mode

  • Donchian Breakout: BUY on breakout above N-day high, SELL below N-day low

  • SNR Mode: BUY near support, SELL near resistance (like SupportResistanceStrategy)

Parameters (via ctx.params or constructor defaults) - adx__period: ADX calculation period (default: 14) - adx__strong_threshold: ADX value to enter strong trend mode (default: 40) - adx__weak_threshold: ADX value to enter consolidation mode (default: 20) - adx__donchian_period: Donchian lookback in trend mode (default: 20) - adx__snr_lookback_days: Support/Resistance lookback in consolidation mode (default: 20) - adx__snr_threshold_pct: How close to S/R before trading (default: 0.01) - risk__max_position_pct: Max position size (default: 0.05)

Usage

from cjtrade.pkgs.strategy.custom import ADXAdaptiveStrategy strategy = ADXAdaptiveStrategy( adx_period=14, adx_strong_threshold=40, adx_weak_threshold=20, ) run_oneshot(symbol="2330", start="2023-01-01", strategy=strategy)

ADXAdaptiveStrategy(adx_period=14, adx_strong_threshold=40.0, adx_weak_threshold=20.0, adx_donchian_period=20, adx_snr_lookback_days=20, adx_snr_threshold_pct=0.01, max_position_pct=0.05)

Bases: BaseStrategy

Adaptive strategy using ADX to switch between Donchian breakout and SNR.

Parameters:

Name Type Description Default
adx_period int

Trend-strength window, in bars.

14
adx_strong_threshold float

Strength above which the TREND regime is used.

40.0
adx_weak_threshold float

Strength below which the CONSOLIDATION regime is used.

20.0
adx_donchian_period int

Donchian channel lookback, in bars.

20
adx_snr_lookback_days int

Support/resistance lookback, in days (converted to bars via the interval hint).

20
adx_snr_threshold_pct float

How close to support/resistance before trading.

0.01
max_position_pct float

Max position size as a fraction of equity.

0.05
Notes

All of these can be overridden by ctx.params in on_start.

Warnings

adx__period and adx__donchian_period are counted in bars and change meaning with the bar interval. adx__snr_lookback_days is converted with a fixed bars-per-day table keyed on adx__interval (default 1m).

Source code in src/cjtrade/pkgs/strategy/adx.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def __init__(
    self,
    adx_period: int = 14,
    adx_strong_threshold: float = 40.0,
    adx_weak_threshold: float = 20.0,
    adx_donchian_period: int = 20,
    adx_snr_lookback_days: int = 20,
    adx_snr_threshold_pct: float = 0.01,
    max_position_pct: float = 0.05,
) -> None:
    self._adx_period = adx_period
    self._adx_strong_threshold = adx_strong_threshold
    self._adx_weak_threshold = adx_weak_threshold
    self._donchian_period = adx_donchian_period
    self._snr_lookback_days = adx_snr_lookback_days
    self._snr_threshold_pct = adx_snr_threshold_pct
    self._max_position_pct = max_position_pct

    # Per-symbol state
    self._prev_close: Dict[str, float] = {}
    self._prev_high: Dict[str, float] = {}
    self._prev_low: Dict[str, float] = {}
    self._donchian_broken: Dict[str, bool] = {}  # Track breakout state

    # Bars per day calculation (auto-detect from interval)
    self._bars_per_day: int = 270  # default for 1m

    # ── monitor state ────────────────────────────────────────────────────
    # Read by monitors(), written in on_bar and the three regime handlers.
    # Declared here so monitors() is safe to call before the first bar,
    # which a runner polling on a timer will do.
    self._n_bars = 0
    self._n_signals = 0
    self._adx = 0.0
    self._regime = "unknown"
    self._bars_in_regime: Dict[str, int] = {"TREND": 0,
                                            "CONSOLIDATION": 0,
                                            "NEUTRAL": 0}
    # Whatever levels the active regime's handler last computed, so the
    # monitor can show the numbers the decision was actually made against
    # rather than re-deriving them.
    self._levels: Dict[str, float] = {}
    self._last_reason = "not started"

on_start(ctx)

Initialize parameters from ctx.params.

Also sets bars-per-day from adx__interval (falling back to sr__interval / sr_interval, default "1m").

Source code in src/cjtrade/pkgs/strategy/adx.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def on_start(self, ctx: StrategyContext) -> None:
    """Initialize parameters from ctx.params.

    Also sets bars-per-day from `adx__interval` (falling back to
    `sr__interval` / `sr_interval`, default "1m").
    """
    p = ctx.params

    # Read ADX parameters (support both old and new naming)
    self._adx_period = int(p.get("adx__period", p.get("adx_period", self._adx_period)))
    self._adx_strong_threshold = float(p.get("adx__strong_threshold", p.get("adx_strong_threshold", self._adx_strong_threshold)))
    self._adx_weak_threshold = float(p.get("adx__weak_threshold", p.get("adx_weak_threshold", self._adx_weak_threshold)))
    self._donchian_period = int(p.get("adx__donchian_period", p.get("adx_donchian_period", self._donchian_period)))
    self._snr_lookback_days = int(p.get("adx__snr_lookback_days", p.get("adx_snr_lookback_days", self._snr_lookback_days)))
    self._snr_threshold_pct = float(p.get("adx__snr_threshold_pct", p.get("adx_snr_threshold_pct", self._snr_threshold_pct)))
    self._max_position_pct = float(p.get("risk__max_position_pct", p.get("risk_max_position_pct", self._max_position_pct)))

    # Auto-detect bars per day from interval hint. adx__interval is the
    # name that matches every other parameter this strategy reads; the sr_*
    # spellings are what it used to be called, kept so an existing config
    # does not silently fall back to 1m.
    interval_hint = p.get("adx__interval",
                          p.get("sr__interval", p.get("sr_interval", "1m")))
    if interval_hint.lower() == "1d":
        self._bars_per_day = 1
    elif interval_hint.lower() == "1h":
        self._bars_per_day = 7
    elif interval_hint.lower() == "5m":
        self._bars_per_day = 54
    else:  # default 1m
        self._bars_per_day = 270

    self._n_bars = self._n_signals = 0
    self._adx = 0.0
    self._regime = "unknown"
    self._bars_in_regime = {"TREND": 0, "CONSOLIDATION": 0, "NEUTRAL": 0}
    self._levels = {}
    self._last_reason = "no bars yet"

    log.info(
        f"ADX_period={self._adx_period} "
        f"strong_threshold={self._adx_strong_threshold} "
        f"weak_threshold={self._adx_weak_threshold} "
        f"donchian_period={self._donchian_period} "
        f"snr_lookback_days={self._snr_lookback_days}"
    )

plots()

Whatever levels the active regime is trading against.

Which keys appear changes with the regime, because the levels do: a Donchian channel in a trend, support and resistance in a range. The chart draws what it is given rather than expecting fixed names.

Source code in src/cjtrade/pkgs/strategy/adx.py
188
189
190
191
192
193
194
195
def plots(self) -> Dict[str, float]:
    """Whatever levels the active regime is trading against.

    Which keys appear changes with the regime, because the levels do: a
    Donchian channel in a trend, support and resistance in a range. The
    chart draws what it is given rather than expecting fixed names.
    """
    return {k: float(v) for k, v in self._levels.items()}

monitors()

See BaseStrategy.monitors. Plain floats, ints and strings only.

trend_strength is the efficiency ratio this strategy computes, not the Wilder ADX -- see _calculate_adx. Reported anyway because the regime switch is made against this number, so it is the one that explains the behaviour.

Source code in src/cjtrade/pkgs/strategy/adx.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def monitors(self) -> Dict[str, Any]:
    """See BaseStrategy.monitors. Plain floats, ints and strings only.

    `trend_strength` is the efficiency ratio this strategy computes, not
    the Wilder ADX -- see _calculate_adx. Reported anyway because the
    regime switch is made against this number, so it is the one that
    explains the behaviour.
    """
    out: Dict[str, Any] = {
        "bars_seen":         self._n_bars,
        "trend_strength":    round(self._adx, 2),
        "measure":           "efficiency ratio (net move / path, 0-100)",
        "regime":            self._regime,
        "strong_threshold":  self._adx_strong_threshold,
        "weak_threshold":    self._adx_weak_threshold,
        "bars_trend":        self._bars_in_regime["TREND"],
        "bars_consolidation": self._bars_in_regime["CONSOLIDATION"],
        "bars_neutral":      self._bars_in_regime["NEUTRAL"],
        "signals_emitted":   self._n_signals,
        "last_decision":     self._last_reason,
    }
    # The active regime's levels, whatever they are called. Flattened into
    # the same dict because a runner puts this straight on a wire.
    for key, value in self._levels.items():
        out[key] = round(value, 2)
    return out

on_bar(bar, ctx)

Process incoming bar and generate signals.

Parameters:

Name Type Description Default
bar Kbar

The bar that just closed.

required
ctx StrategyContext

Account and price history as of this bar.

required

Returns:

Type Description
list of Signal

At most one signal; empty while warming up or when no level is hit.

Source code in src/cjtrade/pkgs/strategy/adx.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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
288
289
290
291
292
293
294
295
296
297
298
299
def on_bar(self, bar, ctx: StrategyContext) -> List[Signal]:
    """Process incoming bar and generate signals.

    Parameters
    ----------
    bar : Kbar
        The bar that just closed.
    ctx : StrategyContext
        Account and price history as of this bar.

    Returns
    -------
    list of Signal
        At most one signal; empty while warming up or when no level is hit.
    """
    self._n_bars += 1
    symbol = bar.symbol
    close = bar.close
    high = bar.high
    low = bar.low

    # Ensure we have history
    prices = ctx.prices(symbol)
    if len(prices) < self._adx_period + 5:
        # Not enough data yet
        self._prev_close[symbol] = close
        self._prev_high[symbol] = high
        self._prev_low[symbol] = low
        self._last_reason = (f"warming up: {len(prices)} of "
                             f"{self._adx_period + 5} bars")
        return []

    # Calculate ADX
    adx_value = self._calculate_adx(bar, ctx)
    self._adx = adx_value

    # Determine market regime
    if adx_value > self._adx_strong_threshold:
        # Strong trend → Donchian breakout
        regime = "TREND"
        signal = self._donchian_logic(bar, ctx, symbol, close)
    elif adx_value < self._adx_weak_threshold:
        # Consolidation → Support & Resistance
        regime = "CONSOLIDATION"
        signal = self._snr_logic(bar, ctx, symbol, close, high, low)
    else:
        # Neutral/mixed
        regime = "NEUTRAL"
        signal = self._neutral_logic(bar, ctx, symbol, close, high, low)

    self._regime = regime
    self._bars_in_regime[regime] += 1

    # Store state
    self._prev_close[symbol] = close
    self._prev_high[symbol] = high
    self._prev_low[symbol] = low

    if signal:
        signal.meta["regime"] = regime
        signal.meta["trend_strength"] = adx_value
        self._n_signals += 1
        self._last_reason = (f"{signal.action} {signal.quantity} "
                             f"{signal.symbol} @ {signal.price:.2f} — "
                             f"{signal.reason}")
        return [signal]

    # Nothing fired. Which regime declined, and against which levels, is
    # the whole of what makes a quiet run legible -- "no signal" on its own
    # does not distinguish a ranging market from a strategy that never had
    # enough history to compute its support band.
    levels = "  ".join(f"{k}={v:.2f}" for k, v in self._levels.items())
    self._last_reason = (f"{regime} (strength={adx_value:.1f}): price "
                         f"{close:.2f} reached no level"
                         + (f" [{levels}]" if levels else ""))
    return []

on_fill(fill, ctx)

Called after a fill is executed.

Source code in src/cjtrade/pkgs/strategy/adx.py
474
475
476
def on_fill(self, fill: Fill, ctx: StrategyContext) -> None:
    """Called after a fill is executed."""
    log.info(f"@{fill.timestamp:%Y-%m-%d %H:%M} {fill.action} filled {fill.symbol} qty={fill.quantity} px={fill.price}")

on_end(ctx)

Called at end of backtest.

Source code in src/cjtrade/pkgs/strategy/adx.py
478
479
480
def on_end(self, ctx: StrategyContext) -> None:
    """Called at end of backtest."""
    log.info("backtest done")

cjtrade.pkgs.strategy.dca

pkgs/strategy/dca.py ~~~~~~~~~~~~~~~~~~~~~ Monthly dollar-cost averaging.

Behavior
  • Buys a fixed NT$ amount of each symbol it sees, once per calendar month, on the first bar of that month this strategy is given.
  • Never sells. This is the accumulate-and-hold baseline, so there is no exit.
Why calendar months and not "30 days since the last buy"

This used to wait timedelta(days=30), which drifts: buy on 5 January and the next purchase is 4 February, then 6 March, and by December the instalment has slid a week and a half earlier. Over a multi-year backtest that silently changes how many instalments fit in the run -- 12.2 a year rather than 12 -- and the comparison against a real monthly savings plan stops holding.

"The first bar of the month" also needs no trading calendar. The month rolls over on whatever bar arrives first, so a 1st that is a Sunday, a holiday or a typhoon day resolves itself: the bot buys on the first bar it is actually given in the new month. The alternative -- "buy on the 1st, or the next trading day if the 1st is closed" -- would need holiday data this codebase does not have (TradingCalendar.is_trading_day is weekday-only; see trading_calendar.py).

Usage
from cjtrade.pkgs.strategy.dca import DCA_Monthly
strategy = DCA_Monthly(amount=10_000)

DCA_Monthly(amount=DCA_MONTHLY_AMOUNT, max_position_pct=0.0, buy_frequency_months=1)

Bases: BaseStrategy

Buy a fixed amount of each symbol, once per calendar month.

Parameters:

Name Type Description Default
amount float

NT$ to spend per instalment, per symbol (dca__amount).

DCA_MONTHLY_AMOUNT
max_position_pct float

Size the instalment as this fraction of current equity instead of a fixed sum (dca__max_position_pct). Takes precedence over amount when non-zero, because it is the one the interval presets actually ship.

0.0
buy_frequency_months int

Months between instalments (dca__buy_frequency_months, default 1).

1
Notes

The same values can be given via ctx.params in on_start, plus dca__last_buy_time: optional {symbol: ISO timestamp} of the last purchase made before this run, so a resumed run does not buy twice in one month.

Source code in src/cjtrade/pkgs/strategy/dca.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def __init__(self, amount: float = DCA_MONTHLY_AMOUNT,
             max_position_pct: float = 0.0,
             buy_frequency_months: int = 1) -> None:
    self._amount = float(amount)
    # 0.0 means "size by a fixed amount". Anything else overrides it and
    # sizes each instalment against equity, which is what the interval
    # presets have always advertised and what this strategy never read.
    self._pct = float(max_position_pct)
    self._months = max(1, int(buy_frequency_months))
    # The (year, month) each symbol was last bought in. A month rather than
    # a timestamp because that is the whole of the decision: comparing
    # months cannot drift, and two bars in the same month are the same
    # answer however far apart they are.
    self._last_buy_month: Dict[str, Tuple[int, int]] = {}
    self._last_buy_at: Dict[str, datetime] = {}

    # ── monitor state ────────────────────────────────────────────────────
    self._n_bars = 0
    self._n_signals = 0
    self._shares = 0
    self._deployed = 0.0
    # (symbol, year, month) already reported as unaffordable, so the
    # warning is one line per month rather than one per bar.
    self._unaffordable: set[Tuple[str, int, int]] = set()
    self._last_reason = "not started"

on_start(ctx)

Read parameters from ctx.params and seed last-buy months.

Warnings

dca__buy_frequency_days is not used; only a warning is logged.

Source code in src/cjtrade/pkgs/strategy/dca.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def on_start(self, ctx: StrategyContext) -> None:
    """Read parameters from `ctx.params` and seed last-buy months.

    Warnings
    --------
    `dca__buy_frequency_days` is not used; only a warning is logged.
    """
    p = ctx.params
    # Support the older spellings so an existing config keeps working.
    self._amount = float(p.get("dca__amount",
                               p.get("dca_amount", self._amount)))
    # Equity-fraction sizing. Read from the dca__ key first and fall back
    # to the shared risk__ one, so a run that only sets the global
    # position limit still sizes its instalments by it.
    self._pct = float(p.get("dca__max_position_pct",
                            p.get("dca_max_position_pct",
                                  p.get("risk__max_position_pct",
                                        self._pct))))
    self._months = max(1, int(p.get("dca__buy_frequency_months",
                                    p.get("dca_buy_frequency_months",
                                          self._months))))
    # dca__buy_frequency_days was shipped by every interval preset and read
    # by nothing. It is not wired up now either, because a day count is the
    # drifting behaviour this strategy deliberately replaced with calendar
    # months -- see the module docstring. Said out loud rather than ignored
    # a second time, so a parameter sweep does not explore a dead axis.
    if any(k in p for k in ("dca__buy_frequency_days",
                            "dca_buy_frequency_days")):
        log.warning(
            "dca__buy_frequency_days is unused: instalments are keyed "
            "to calendar months, which cannot drift; use "
            "dca__buy_frequency_months (now %d)", self._months)

    seed = p.get("dca__last_buy_time", p.get("dca_last_buy_time"))
    if isinstance(seed, dict):
        for sym, iso in seed.items():
            try:
                when = datetime.fromisoformat(iso)
            except (TypeError, ValueError):
                log.warning("ignoring unparseable last_buy_time for %s: %r",
                            sym, iso)
                continue
            self._last_buy_at[sym] = when
            self._last_buy_month[sym] = (when.year, when.month)

    self._last_reason = "no bars yet"
    sizing = (f"{self._pct * 100:.2f}% of equity" if self._pct > 0
              else f"{self._amount:,.0f}")
    log.info(f"instalment={sizing} every "
             f"{self._months} month(s) per symbol")

plots()

The running average cost, which is the only line this strategy has.

A DCA chart's whole question is where the average sits against the price, so that is what gets drawn. Nothing until the first purchase, because an average of no purchases is not zero -- it does not exist.

Source code in src/cjtrade/pkgs/strategy/dca.py
158
159
160
161
162
163
164
165
166
167
def plots(self) -> Dict[str, float]:
    """The running average cost, which is the only line this strategy has.

    A DCA chart's whole question is where the average sits against the
    price, so that is what gets drawn. Nothing until the first purchase,
    because an average of no purchases is not zero -- it does not exist.
    """
    if not self._shares:
        return {}
    return {"avg_cost": self._deployed / self._shares}

monitors()

See BaseStrategy.monitors. Plain floats, ints and strings only.

Source code in src/cjtrade/pkgs/strategy/dca.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def monitors(self) -> Dict[str, Any]:
    """See BaseStrategy.monitors. Plain floats, ints and strings only."""
    last = max(self._last_buy_at.values()) if self._last_buy_at else None
    return {
        "bars_seen":        self._n_bars,
        "amount":           round(self._amount, 2),
        "instalment_pct":   round(self._pct, 4),
        "frequency_months": self._months,
        "instalments":      self._n_signals,
        "shares_bought":    self._shares,
        "cash_deployed":    round(self._deployed, 2),
        "avg_cost":         round(self._deployed / self._shares, 2) if self._shares else 0.0,
        "last_buy":         last.isoformat(sep=" ", timespec="minutes") if last else "never",
        # Months skipped because one share cost more than the instalment.
        # Separated from the normal "already bought" case because it is the
        # only way this strategy silently does nothing for a whole month.
        "months_unaffordable": len(self._unaffordable),
        "signals_emitted":  self._n_signals,
        "last_decision":    self._last_reason,
    }

on_bar(bar, ctx)

Buy one instalment on the first bar of a due month.

Parameters:

Name Type Description Default
bar Kbar

The bar that just closed.

required
ctx StrategyContext

Account and price history as of this bar; ctx.timestamp decides the month.

required

Returns:

Type Description
list of Signal

One BUY, or empty if already bought this period or unaffordable.

Source code in src/cjtrade/pkgs/strategy/dca.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def on_bar(self, bar, ctx: StrategyContext) -> List[Signal]:
    """Buy one instalment on the first bar of a due month.

    Parameters
    ----------
    bar : Kbar
        The bar that just closed.
    ctx : StrategyContext
        Account and price history as of this bar; `ctx.timestamp` decides
        the month.

    Returns
    -------
    list of Signal
        One BUY, or empty if already bought this period or unaffordable.
    """
    self._n_bars += 1

    now: datetime = ctx.timestamp
    sym = bar.symbol
    price = bar.close
    this_month = (now.year, now.month)

    # Months elapsed rather than "is it the same month", so a frequency of
    # more than one month is expressible. Counted in whole months so it
    # cannot drift, for the reason in the module docstring.
    last = self._last_buy_month.get(sym)
    if last is not None:
        elapsed = (now.year * 12 + now.month) - (last[0] * 12 + last[1])
        if elapsed < self._months:
            # The elapsed count only tells a reader something when the
            # cadence is longer than a month; at the default it is noise.
            self._last_reason = (
                f"already bought {sym} in {now.year}-{now.month:02d}"
                if self._months == 1 else
                f"bought {sym} in {last[0]}-{last[1]:02d}, "
                f"{elapsed} of {self._months} month(s) elapsed")
            return []

    if price <= 0:
        self._last_reason = f"no usable price for {sym} ({price})"
        return []

    # Whole shares of one instalment, so the purchase is at most the
    # instalment and the remainder is simply not spent. Odd lots, which is
    # what the engine submits anyway (bot_runner's OrderLot.IntraDayOdd).
    instalment = ctx.equity * self._pct if self._pct > 0 else self._amount
    qty = int(instalment // price)
    if qty <= 0:
        # One share costs more than a whole instalment. Reported rather
        # than retried silently: nothing will change within the month, and
        # the month is deliberately NOT consumed, so a later bar at a lower
        # price can still buy.
        marker = (sym, now.year, now.month)
        if marker not in self._unaffordable:
            self._unaffordable.add(marker)
            log.warning(f"@{now:%Y-%m-%d %H:%M} {sym} px={price:.2f} costs more "
                        f"than one instalment of {instalment:,.0f} — "
                        f"skipping {now.year}-{now.month:02d} unless it "
                        f"falls before month end")
        self._last_reason = (f"unaffordable: one share of {sym} at "
                             f"{price:.2f} exceeds {instalment:,.0f}")
        return []

    # Consume the month when the signal is ISSUED, not when it fills.
    #
    # The trade-off is deliberate and it cuts both ways: a rejected or
    # never-filled order means this month's instalment is lost, but marking
    # it on the fill instead would re-signal on every bar until one fills,
    # and a limit order that is merely resting would collect a dozen
    # duplicates before the first one settles.
    self._last_buy_month[sym] = this_month
    self._last_buy_at[sym] = now
    self._n_signals += 1
    self._shares += qty
    self._deployed += qty * price

    self._last_reason = (f"BUY {qty} {sym} @ {price:.2f} — instalment for "
                         f"{now.year}-{now.month:02d}")
    ts_str = bar.timestamp.strftime("%Y-%m-%d %H:%M:%S")
    log.info(f"@{ts_str} BUY {sym} qty={qty} px={price:.2f} "
             f"(DCA {now.year}-{now.month:02d})")
    return [Signal(
        action="BUY", symbol=sym, quantity=qty, price=price,
        reason=f"DCA instalment for {now.year}-{now.month:02d}",
        meta={"amount": instalment, "month": f"{now.year}-{now.month:02d}"},
    )]

on_fill(fill, ctx)

Log BUY fills at debug level.

Source code in src/cjtrade/pkgs/strategy/dca.py
280
281
282
283
284
def on_fill(self, fill: Fill, ctx: StrategyContext) -> None:
    """Log BUY fills at debug level."""
    if fill.action.upper() == "BUY":
        log.debug(f"@{fill.timestamp:%Y-%m-%d %H:%M} BUY filled "
                  f"{fill.symbol} px={fill.price:.2f}")

last_buy(symbol)

When this strategy last bought symbol, or None.

Exposed so a caller can hand it back as dca__last_buy_time and resume without buying twice in the same month.

Source code in src/cjtrade/pkgs/strategy/dca.py
286
287
288
289
290
291
292
def last_buy(self, symbol: str) -> Optional[datetime]:
    """When this strategy last bought `symbol`, or None.

    Exposed so a caller can hand it back as dca__last_buy_time and resume
    without buying twice in the same month.
    """
    return self._last_buy_at.get(symbol)

cjtrade.pkgs.strategy.donchian

pkgs/strategy/donchian.py ~~~~~~~~~~~~~~~~~~~~~~~~~ Pure Donchian Breakout Strategy.

Behavior
  • Calculate highest high and lowest low over the last N days
  • BUY when price breaks above the highest high (uptrend confirmation)
  • SELL when price breaks below the lowest low (downtrend confirmation)
  • Trend-following approach (works best in trending markets)

Parameters (via ctx.params or constructor defaults) - donchian__period: Lookback in BARS, excluding the current one (default: 20) - donchian__breakout_mode: 'close' (price closes above/below) or 'touch' (touches) (default: 'close') - donchian__trailing_stop_pct: Trailing stop as % below the peak since entry (default: 0.0 = disabled) - risk__max_position_pct: Max position size (default: 0.05)

Usage

from cjtrade.pkgs.strategy.donchian import DonchianBreakoutStrategy strategy = DonchianBreakoutStrategy(period=20, breakout_mode='close')

run_oneshot(symbol="2330", start="2023-01-01", strategy=strategy)

DonchianBreakoutStrategy(period=20, breakout_mode='close', trailing_stop_pct=0.0, max_position_pct=0.05)

Bases: BaseStrategy

Pure Donchian Channel breakout trending strategy.

Tracks the highest high and lowest low over a lookback period. - BUY when price breaks above the highest high (new N-day high) - SELL when price breaks below the lowest low (new N-day low)

This is a classic trend-following approach that works best in strongly trending markets.

Parameters:

Name Type Description Default
period int

Bars to look back for the channel, current bar excluded (default: 20).

20
breakout_mode str

'close' = close above/below, 'touch' = touches (default: 'close').

'close'
trailing_stop_pct float

Stop as % below the peak since entry (0.0 = disabled).

0.0
max_position_pct float

Max position size as fraction of equity (default: 0.05).

0.05
Notes

All can also be set via ctx.params (donchian__*, risk__max_position_pct).

Warnings

period is counted in bars, so its time span changes with the interval.

'touch' mode reads bar.high/bar.low. Both runners now deliver real bars, so it means the same in the trading engine as in BacktestEngine. Runs of the trading engine from before that change fed snapshots, whose high and low were the whole trading DAY so far, and are not comparable in 'touch' mode. 'close' mode reads only closes and is unaffected.

Source code in src/cjtrade/pkgs/strategy/donchian.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def __init__(
    self,
    period: int = 20,
    breakout_mode: str = "close",
    trailing_stop_pct: float = 0.0,
    max_position_pct: float = 0.05,
) -> None:
    self._period = period
    self._breakout_mode = breakout_mode  # 'close' or 'touch'
    self._trailing_stop_pct = trailing_stop_pct
    self._max_position_pct = max_position_pct

    # Per-symbol state
    self._prev_close: Dict[str, float] = {}
    self._entry_price: Dict[str, float] = {}
    # Highest close seen since entry, per symbol. A trailing stop has to
    # trail something, and measuring the drawdown from the entry price
    # instead -- which is what this did -- is a fixed stop wearing the
    # wrong name: it can never move up, so a position that doubled was
    # still stopped out at entry minus the same percentage.
    self._peak: Dict[str, float] = {}

on_start(ctx)

Initialize parameters from ctx.params.

Source code in src/cjtrade/pkgs/strategy/donchian.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def on_start(self, ctx: StrategyContext) -> None:
    """Initialize parameters from ctx.params."""
    p = ctx.params

    # Read Donchian parameters (support both old and new naming)
    self._period = int(p.get("donchian__period", p.get("donchian_period", self._period)))
    self._breakout_mode = p.get("donchian__breakout_mode", p.get("donchian_breakout_mode", self._breakout_mode))
    self._trailing_stop_pct = float(p.get("donchian__trailing_stop_pct", p.get("donchian_trailing_stop_pct", self._trailing_stop_pct)))
    self._max_position_pct = float(p.get("risk__max_position_pct", p.get("risk_max_position_pct", self._max_position_pct)))

    log.info(
        f"period={self._period} bars "
        f"breakout_mode={self._breakout_mode} "
        f"trailing_stop={self._trailing_stop_pct*100:.2f}% "
        f"max_pos={self._max_position_pct*100:.2f}%"
    )

on_bar(bar, ctx)

Process incoming bar and generate signals.

Parameters:

Name Type Description Default
bar Kbar

The bar that just closed.

required
ctx StrategyContext

Account and price history as of this bar.

required

Returns:

Type Description
list of Signal

Breakout or trailing-stop signals; empty while warming up.

Source code in src/cjtrade/pkgs/strategy/donchian.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def on_bar(self, bar, ctx: StrategyContext) -> List[Signal]:
    """Process incoming bar and generate signals.

    Parameters
    ----------
    bar : Kbar
        The bar that just closed.
    ctx : StrategyContext
        Account and price history as of this bar.

    Returns
    -------
    list of Signal
        Breakout or trailing-stop signals; empty while warming up.
    """
    symbol = bar.symbol
    close = bar.close
    high = bar.high
    low = bar.low
    ts_str = bar.timestamp.strftime("%Y-%m-%d %H:%M:%S")

    # `period` is a number of BARS, not days. It used to be multiplied by
    # bars_per_day, which at the 1m preset of 80 asked for 80 x 270 =
    # 21,600 bars -- about eighty trading days -- so the guard below was
    # still true after six months of 1m data and this strategy returned
    # early on every bar of every run. The preset values (1m 80, 5m 12,
    # 1h 18, 1d 20) only make sense as bars, and adx.py already reads the
    # same number that way.
    prices = ctx.prices(symbol)

    # The channel must EXCLUDE the current bar. price_history already has
    # this bar's close appended by the time on_bar is called, so a window
    # of prices[-period:] contains `close` itself; max() is then >= close
    # and `close > donchian_high` cannot ever be true. Together with the
    # lookback above that is why this strategy recorded zero fills over
    # 18,794 bars. The same off-by-one was fixed in the ADX template
    # earlier with bar.closes[:-1]; this is the strategy it was copied from.
    if len(prices) < self._period + 1:
        self._prev_close[symbol] = close
        return []

    recent_closes = prices[-self._period - 1:-1]
    donchian_high = max(recent_closes)
    donchian_low = min(recent_closes)

    prev_close = self._prev_close.get(symbol, close)
    signals: List[Signal] = []

    # --- BUY LOGIC ---
    # Breakout above Donchian high
    is_above_breakout = False
    if self._breakout_mode == "close":
        # Close above highest high
        is_above_breakout = prev_close <= donchian_high and close > donchian_high
    else:  # touch mode
        # Price touches or goes above
        is_above_breakout = high > donchian_high and not ctx.has_position(symbol)

    if is_above_breakout and not ctx.has_position(symbol):
        qty = ctx.calc_qty(close, self._max_position_pct)
        if qty > 0:
            self._entry_price[symbol] = close
            self._peak[symbol] = close
            log.info(
                f"@{ts_str} BUY {symbol} qty={qty} px={close:.2f} "
                f"(Donchian breakout above {donchian_high:.2f})"
            )
            signals.append(Signal(
                action="BUY",
                symbol=symbol,
                quantity=qty,
                price=close,
                reason=f"Donchian breakout above channel high {donchian_high:.2f}",
                meta={
                    "donchian_high": donchian_high,
                    "donchian_low": donchian_low,
                    "breakout": "up",
                }
            ))

    # --- SELL LOGIC ---
    # Check the trailing stop first, measured from the peak since entry.
    if ctx.has_position(symbol) and symbol in self._entry_price:
        entry_price = self._entry_price[symbol]
        peak = max(self._peak.get(symbol, entry_price), close)
        self._peak[symbol] = peak
        trailing_stop_level = peak * (1 - self._trailing_stop_pct)

        if self._trailing_stop_pct > 0 and close < trailing_stop_level:
            qty = ctx.position_qty(symbol)
            log.info(
                f"@{ts_str} SELL {symbol} qty={qty} px={close:.2f} "
                f"(trailing stop {self._trailing_stop_pct*100:.2f}% "
                f"below peak {peak:.2f}, entry was {entry_price:.2f})"
            )
            signals.append(Signal(
                action="SELL",
                symbol=symbol,
                quantity=qty,
                price=close,
                reason=(f"Trailing stop: {close:.2f} is more than "
                        f"{self._trailing_stop_pct*100:.2f}% below the "
                        f"peak of {peak:.2f}"),
                meta={"stop_type": "trailing", "peak": peak}
            ))
            del self._entry_price[symbol]
            self._peak.pop(symbol, None)
            self._prev_close[symbol] = close
            return signals

    # Breakout below Donchian low (hard stop)
    is_below_breakout = False
    if self._breakout_mode == "close":
        # Close below lowest low
        is_below_breakout = prev_close >= donchian_low and close < donchian_low
    else:  # touch mode
        # Price touches or goes below
        is_below_breakout = low < donchian_low

    if is_below_breakout and ctx.has_position(symbol):
        qty = ctx.position_qty(symbol)
        log.info(
            f"@{ts_str} SELL {symbol} qty={qty} px={close:.2f} "
            f"(Donchian breakout below {donchian_low:.2f})"
        )
        signals.append(Signal(
            action="SELL",
            symbol=symbol,
            quantity=qty,
            price=close,
            reason=f"Donchian breakout below channel low {donchian_low:.2f}",
            meta={
                "donchian_high": donchian_high,
                "donchian_low": donchian_low,
                "breakout": "down",
            }
        ))
        if symbol in self._entry_price:
            del self._entry_price[symbol]
        self._peak.pop(symbol, None)

    # Store state
    self._prev_close[symbol] = close
    return signals

on_fill(fill, ctx)

Called after a fill is executed.

Source code in src/cjtrade/pkgs/strategy/donchian.py
265
266
267
def on_fill(self, fill: Fill, ctx: StrategyContext) -> None:
    """Called after a fill is executed."""
    log.info(f"@{fill.timestamp:%Y-%m-%d %H:%M} {fill.action} filled {fill.symbol} qty={fill.quantity} px={fill.price}")

on_end(ctx)

Called at end of backtest.

Source code in src/cjtrade/pkgs/strategy/donchian.py
269
270
271
def on_end(self, ctx: StrategyContext) -> None:
    """Called at end of backtest."""
    log.info("backtest done")

cjtrade.pkgs.strategy.snr

pkgs/strategy/support_resistance.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Support & Resistance Level strategy.

Behavior
  • Calculate the highest high (resistance) and lowest low (support) over the last N days.
  • BUY near support levels (with breakout confirmation).
  • SELL near resistance levels.
  • Optional: BUY on breakout above resistance (trend following).
Usage

from cjtrade.pkgs.strategy.support_resistance import SupportResistanceStrategy strategy = SupportResistanceStrategy(lookback_days=20, breakout_mode=True)

run_oneshot(symbol="2330", start="2023-01-01", strategy=strategy)

SupportResistanceStrategy(lookback_days=20, support_threshold_pct=0.01, resistance_threshold_pct=0.01, breakout_mode=False, max_position_pct=0.05)

Bases: BaseStrategy

Support & Resistance levels strategy.

Tracks highest high and lowest low over a lookback period. - BUY when price approaches support (from above) - SELL when price approaches resistance (from below) - Optional: BUY on resistance breakout (if breakout_mode=True)

Parameters:

Name Type Description Default
lookback_days int

Number of days to look back for S/R levels (default: 20).

20
support_threshold_pct float

How close to support before buying (e.g. 0.01 = 1%).

0.01
resistance_threshold_pct float

How close to resistance before selling.

0.01
breakout_mode bool

If True, also buy when price breaks above resistance.

False
max_position_pct float

Max position size as fraction of equity.

0.05
Notes

All can also be set via ctx.params (sr__*, risk__max_position_pct).

Warnings

lookback_days is converted to bars with a fixed bars-per-day table keyed on sr__interval (default 1m); a wrong hint gives a wrong window.

Source code in src/cjtrade/pkgs/strategy/snr.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def __init__(
    self,
    lookback_days: int = 20,
    support_threshold_pct: float = 0.01,
    resistance_threshold_pct: float = 0.01,
    breakout_mode: bool = False,
    max_position_pct: float = 0.05,
) -> None:
    self._lookback_days = lookback_days
    self._support_threshold_pct = support_threshold_pct
    self._resistance_threshold_pct = resistance_threshold_pct
    self._breakout_mode = breakout_mode
    self._max_position_pct = max_position_pct
    # Track previous close and breakout state per symbol
    self._prev_close: Dict[str, float] = {}
    self._resistance_broken: Dict[str, bool] = {}
    # Will be set in on_start based on kbar interval detected from price history
    self._bars_per_day: int = 270  # default for 1m bars, will auto-detect

on_start(ctx)

Read parameters from ctx.params and set bars-per-day from sr__interval.

Source code in src/cjtrade/pkgs/strategy/snr.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def on_start(self, ctx: StrategyContext) -> None:
    """Read parameters from ctx.params and set bars-per-day from `sr__interval`."""
    p = ctx.params
    # Support both old and new param names for backward compatibility
    self._lookback_days = int(p.get("sr__lookback_days", p.get("sr_lookback_days", self._lookback_days)))
    self._support_threshold_pct = float(p.get("sr__support_threshold_pct", p.get("sr_support_threshold_pct", self._support_threshold_pct)))
    self._resistance_threshold_pct = float(p.get("sr__resistance_threshold_pct", p.get("sr_resistance_threshold_pct", self._resistance_threshold_pct)))
    self._breakout_mode = p.get("sr__breakout_mode", p.get("sr_breakout_mode", self._breakout_mode))
    self._max_position_pct = float(p.get("risk__max_position_pct", p.get("risk_max_position_pct", self._max_position_pct)))

    # Auto-detect bars per day based on kbar interval
    # This allows strategy to work with both 1m and 1d (or any interval)
    interval_hint = p.get("sr__interval", p.get("sr_interval", "1m"))
    if interval_hint.lower() == "1d":
        self._bars_per_day = 1  # 1d kbar = 1 bar per day
    elif interval_hint.lower() == "1h":
        self._bars_per_day = 7  # rough estimate for trading hours
    elif interval_hint.lower() == "5m":
        self._bars_per_day = 54  # ~54 bars per day for 5m interval
    else:  # default 1m
        self._bars_per_day = 270  # ~270 minutes per trading day

    log.info(
        f"lookback={self._lookback_days}d "
        f"support_thr={self._support_threshold_pct*100:.2f}% "
        f"resistance_thr={self._resistance_threshold_pct*100:.2f}% "
        f"breakout_mode={self._breakout_mode} "
        f"(bars_per_day={self._bars_per_day})"
    )

on_bar(bar, ctx)

Emit signals based on support/resistance levels.

Returns:

Type Description
list of Signal

Empty until lookback_days * bars_per_day bars have been seen.

Source code in src/cjtrade/pkgs/strategy/snr.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def on_bar(self, bar, ctx: StrategyContext) -> List[Signal]:
    """Emit signals based on support/resistance levels.

    Returns
    -------
    list of Signal
        Empty until `lookback_days * bars_per_day` bars have been seen.
    """
    prices = ctx.prices(bar.symbol)

    # Need enough history (based on detected/configured bars_per_day)
    min_bars_needed = self._lookback_days * self._bars_per_day
    if len(prices) < min_bars_needed:
        return []

    # Get the recent price window
    recent_prices = prices[-min_bars_needed:]

    # Calculate support (lowest low) and resistance (highest high)
    # Use pure Python min/max instead of numpy for efficiency
    support = float(min(recent_prices))
    resistance = float(max(recent_prices))

    price = bar.close
    ts_str = bar.timestamp.strftime("%Y-%m-%d %H:%M:%S")

    # Calculate thresholds
    support_buy_level = support * (1 + self._support_threshold_pct)
    resistance_sell_level = resistance * (1 - self._resistance_threshold_pct)

    signals: List[Signal] = []

    # --- BUY LOGIC ---
    # 1. Buy near support (price touches or goes slightly above support)
    if (price <= support_buy_level and
        not ctx.has_position(bar.symbol)):
        qty = ctx.calc_qty(price, self._max_position_pct)
        if qty > 0:
            log.info(
                f"@{ts_str} BUY {bar.symbol} px={price:.2f} "
                f"(near support={support:.2f})"
            )
            signals.append(Signal(
                action="BUY",
                symbol=bar.symbol,
                quantity=qty,
                price=price,
                reason=f"Support level buy (S={support:.2f} R={resistance:.2f})",
                meta={"support": support, "resistance": resistance, "price": price},
            ))

    # 2. Buy on breakout above resistance (if enabled and price breaks up)
    elif (self._breakout_mode and
          price > resistance and
          not self._resistance_broken.get(bar.symbol, False) and
          not ctx.has_position(bar.symbol)):
        qty = ctx.calc_qty(price, self._max_position_pct)
        if qty > 0:
            self._resistance_broken[bar.symbol] = True
            log.info(
                f"@{ts_str} BUY {bar.symbol} px={price:.2f} "
                f"(resistance breakout, R={resistance:.2f})"
            )
            signals.append(Signal(
                action="BUY",
                symbol=bar.symbol,
                quantity=qty,
                price=price,
                reason=f"Resistance breakout buy (R={resistance:.2f})",
                meta={"support": support, "resistance": resistance, "price": price},
            ))

    # --- SELL LOGIC ---
    # Sell near resistance (price approaches or touches resistance)
    if (price >= resistance_sell_level and
        ctx.has_position(bar.symbol)):
        qty = ctx.position_qty(bar.symbol)
        log.info(
            f"@{ts_str} SELL {bar.symbol} px={price:.2f} "
            f"(near resistance={resistance:.2f})"
        )
        signals.append(Signal(
            action="SELL",
            symbol=bar.symbol,
            quantity=qty,
            price=price,
            reason=f"Resistance level sell (S={support:.2f} R={resistance:.2f})",
            meta={"support": support, "resistance": resistance, "price": price},
        ))
        # Reset breakout flag after selling
        self._resistance_broken[bar.symbol] = False

    # Store previous close for trend detection (if needed in future)
    self._prev_close[bar.symbol] = price

    return signals

on_fill(fill, ctx)

Log fills for debugging.

Source code in src/cjtrade/pkgs/strategy/snr.py
217
218
219
220
221
222
223
224
225
226
227
228
def on_fill(self, fill: Fill, ctx: StrategyContext) -> None:
    """Log fills for debugging."""
    if fill.action.upper() == "BUY":
        log.debug(
            f"@{fill.timestamp:%Y-%m-%d %H:%M} BUY filled {fill.symbol} px={fill.price:.2f} "
            f"qty={fill.quantity}"
        )
    elif fill.action.upper() == "SELL":
        log.debug(
            f"@{fill.timestamp:%Y-%m-%d %H:%M} SELL filled {fill.symbol} px={fill.price:.2f} "
            f"qty={fill.quantity}"
        )

on_end(ctx)

Called at end of backtest.

Source code in src/cjtrade/pkgs/strategy/snr.py
230
231
232
233
234
235
236
def on_end(self, ctx: StrategyContext) -> None:
    """Called at end of backtest."""
    log.info(
        f"done, equity={ctx.equity:,.0f} "
        f"balance={ctx.balance:,.0f} "
        f"positions={[p['symbol'] for p in ctx.positions]}"
    )

cjtrade.pkgs.strategy.baseline_0050

pkgs/strategy/baseline_0050.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Baseline strategy that monthly buys 0050 (Taiwan Top 50 ETF) via DCA.

This strategy serves as a benchmark to compare against other trading strategies. It performs Dollar-Cost Averaging (DCA) on 0050 only, investing a fixed amount (NT$10,000) every 30 days, regardless of what symbols are in the backtest kbars. This allows fair comparison when testing multiple strategies on different symbols.

Behavior
  • BUY: Fixed NT$10,000 every 30 days on 0050 only
  • HOLD: No selling (pure accumulation)
  • IGNORE: All other symbols
Usage

from cjtrade.pkgs.strategy.baseline_0050 import BaselineStrategy

run_compare_strategies( symbol=["2330", "2454", "3008"], # Test symbols strategies={ "DCA_Monthly": DCA_Monthly(), "BollingerBands": BollingerStrategy(), "Baseline_0050": BaselineStrategy(), # DCA on 0050 only } )

Note: The baseline symbol (0050) will be automatically added to the kbars if it's not already in the symbol list, so you don't need to include it manually.

BaselineStrategy(baseline_symbol=BASELINE_SYMBOL, monthly_amount=BASELINE_MONTHLY_AMOUNT)

Bases: BaseStrategy

DCA baseline strategy that monthly buys 0050 (Taiwan Top 50 ETF).

This strategy is used as a benchmark to compare active trading strategies against a simple buy-and-hold DCA approach on 0050. It ignores all other symbols in the backtest and only trades 0050.

Behavior: - Every 30 days: buy NT$10,000 worth of 0050 - All other symbols: ignored - No selling: pure accumulation

Parameters:

Name Type Description Default
baseline_symbol str

Override the hardcoded symbol (default: "0050"). Also read from ctx.params["baseline_symbol"].

BASELINE_SYMBOL
monthly_amount float

Amount to invest per month in NT$ (default: 10000). Also read from ctx.params["baseline_monthly_amount"].

BASELINE_MONTHLY_AMOUNT
Warnings

The code does not match the text above: the default amount is BASELINE_MONTHLY_AMOUNT (4,888,888) and on_bar waits 2001 days, not 30, between buys.

Source code in src/cjtrade/pkgs/strategy/baseline_0050.py
83
84
85
86
87
88
89
90
91
def __init__(
    self,
    baseline_symbol: str = BASELINE_SYMBOL,
    monthly_amount: float = BASELINE_MONTHLY_AMOUNT,
) -> None:
    self._baseline_symbol = baseline_symbol
    self._monthly_amount = monthly_amount
    # Track last buy time per symbol
    self._last_buy_time: Dict[str, datetime] = {}

on_start(ctx)

Read baseline_symbol and baseline_monthly_amount from ctx.params.

Source code in src/cjtrade/pkgs/strategy/baseline_0050.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
def on_start(self, ctx: StrategyContext) -> None:
    """Read `baseline_symbol` and `baseline_monthly_amount` from ctx.params."""
    p = ctx.params
    self._baseline_symbol = p.get("baseline_symbol", self._baseline_symbol)
    self._monthly_amount = float(p.get("baseline_monthly_amount", self._monthly_amount))

    log.info(
        f"baseline symbol={self._baseline_symbol}, "
        f"monthly_amount=NT${self._monthly_amount:,.0f}"
    )

on_bar(bar, ctx)

Monthly DCA: buy NT$10,000 worth of 0050 every 30 days.

Returns:

Type Description
list of Signal

One BUY when due, otherwise empty. Other symbols are ignored.

Source code in src/cjtrade/pkgs/strategy/baseline_0050.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def on_bar(self, bar, ctx: StrategyContext) -> List[Signal]:
    """Monthly DCA: buy NT$10,000 worth of 0050 every 30 days.

    Returns
    -------
    list of Signal
        One BUY when due, otherwise empty. Other symbols are ignored.
    """
    # Ignore all symbols except the baseline
    if bar.symbol != self._baseline_symbol:
        return []

    now = ctx.timestamp
    sym = bar.symbol
    price = bar.close

    # Check if we've bought this symbol before
    last = self._last_buy_time.get(sym)
    if last is not None and (now - last) < timedelta(days=2001):
        # Not 30 days yet since last buy
        return []

    # Buy NT$10,000 worth of shares
    qty = int(self._monthly_amount / price)
    if qty <= 0:
        return []

    # Update last buy time NOW (when signal is issued, not when filled)
    # This prevents repeated signals if the order is rejected
    self._last_buy_time[sym] = now

    # Emit BUY signal
    reason = f"Baseline DCA monthly on {self._baseline_symbol} (since={last.isoformat() if last else 'never'})"
    sig = Signal(
        action="BUY",
        symbol=sym,
        quantity=qty,
        price=price,
        reason=reason,
    )
    ts_str = bar.timestamp.strftime("%Y-%m-%d %H:%M:%S")
    log.info(
        f"@{ts_str} BUY {bar.symbol} qty={qty} px={price:.2f} "
        f"(monthly_amount=NT${self._monthly_amount:,.0f})"
    )
    return [sig]

on_fill(fill, ctx)

Log fills for debugging.

Source code in src/cjtrade/pkgs/strategy/baseline_0050.py
151
152
153
154
def on_fill(self, fill: Fill, ctx: StrategyContext) -> None:
    """Log fills for debugging."""
    if fill.action.upper() == "BUY":
        log.debug(f"@{fill.timestamp:%Y-%m-%d %H:%M} BUY filled {fill.symbol} px={fill.price:.2f}")

on_end(ctx)

Called at end of backtest.

Source code in src/cjtrade/pkgs/strategy/baseline_0050.py
156
157
158
def on_end(self, ctx: StrategyContext) -> None:
    """Called at end of backtest."""
    log.info(f"backtest done, positions: {ctx.positions}")