Skip to content

Strategy authoring

The vocabulary a strategy file written for the trading engine may use. See Writing a strategy for usage.

cjtrade.pkgs.strategy.authoring

pkgs/strategy/authoring.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The whole vocabulary a hand-written strategy may use. Nothing else.

A strategy written against this module is a file like:

from cjtrade.pkgs.strategy.authoring import *

WINDOW = param.int(100, "Bollinger window", min=5, max=500)
MIN_WIDTH = param.float(0.01, "Minimum band width", min=0.0, max=0.5)

def on_bar(bar, account):
    upper, middle, lower = ta.bb(bar.closes, WINDOW)
    if upper is None:
        return hold("warming up")

    width = (upper - lower) / middle
    watch(upper=upper, middle=middle, lower=lower, width=width)
    plot(upper=upper, middle=middle, lower=lower)

    if width < MIN_WIDTH:
        return hold(f"squeeze: {width:.3%} under {MIN_WIDTH:.3%}")
    if bar.close <= lower and not account.holding:
        return buy(reason="lower band touch")
    if bar.close >= upper and account.holding:
        return sell(reason="upper band touch")
    return hold("price inside the bands")

init(), on_fill(fill, account) and on_end(account) are optional.

Why buy() here does not place an order

A buy() that called client.buy_stock(...) would hold a broker session and place the order itself. That is right for a human at a REPL and wrong for a bot, where it would give every bot process its own broker session, put every order outside the RiskGate, and create a second answer for balance and positions alongside master's ledger. So the control flow is inverted: here buy() returns an intent and master's ExecutionEngine decides.

So this module imports no broker client and nothing that opens a socket: no name in a strategy's namespace, and no attribute of any name in it, reaches a broker session.

Be precise about what that is worth. It is NOT a sandbox. A strategy is Python: it can import os, and because cjtrade/__init__.py imports the shell the broker client is already in sys.modules of any process that loaded this module, so a determined strategy can reach one in two lines. FinHub is a single trust domain and an account on it is permission to run code on the host, which is the only reason that is acceptable. What the narrow namespace buys is different and still worth having: nobody reaches a broker by accident, every order goes through master's RiskGate because that is the only path that exists for the names on offer, and the editor's completion list is exactly the supported surface rather than everything that happens to be importable.

What this module deliberately does NOT expose, and why

ta.adx, ta.atr and ta.stoch take a series of (high, low, close) per bar. Bar carries a history of closes only, and its day_high / day_low are the trading day's range so far, not this bar's. Re-exporting them would have a strategy feed the day's range in as if it were each bar's, computing the indicator off the wrong numbers -- the bug adx.py carried until it was measured, back when the engine's feed was snapshots. They raise an explanatory error instead.

Bar(symbol, time, open, close, volume, closes, day_high, day_low) dataclass

One closed bar, plus the history behind it.

closes is ordered oldest-first, so closes[-1] == close and ta.bb(bar.closes, 20) reads the way every other Python series does. Pine Script indexes the other way round (close[1] is the previous bar); use bar.ago(1) for that, which cannot be confused with closes[1].

Parameters:

Name Type Description Default
symbol str

Stock ticker.

required
time datetime

Time of this bar.

required
open float

This bar's open.

required
close float

This bar's close.

required
volume int

This bar's volume, in lots.

required
closes sequence of float

Close prices seen so far, oldest first, including this bar.

required
day_high float

The trading day's high up to this bar, not this bar's own.

required
day_low float

The trading day's low up to this bar, not this bar's own.

required
Warnings

day_high / day_low are day-to-date extremes, built from the day's bars; this bar's own high and low are not exposed. History length in closes is counted in bars.

bars_seen property

Number of closes seen so far, including this bar.

ago(n)

The close n bars before this one. ago(0) is this bar.

None rather than an IndexError when the history is not that long yet: every strategy's first bars are short, and a crash there is a crash on bar 1 of every run.

Parameters:

Name Type Description Default
n int

How many bars back to look.

required

Returns:

Type Description
float or None

The close n bars ago, or None if n is negative or the history is shorter than that.

Source code in src/cjtrade/pkgs/strategy/authoring.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def ago(self, n: int) -> Optional[float]:
    """The close `n` bars before this one. `ago(0)` is this bar.

    None rather than an IndexError when the history is not that long yet:
    every strategy's first bars are short, and a crash there is a crash on
    bar 1 of every run.

    Parameters
    ----------
    n : int
        How many bars back to look.

    Returns
    -------
    float or None
        The close `n` bars ago, or None if `n` is negative or the history
        is shorter than that.
    """
    if n < 0 or n >= len(self.closes):
        return None
    return float(self.closes[-1 - n])

Account(cash, equity, shares, avg_cost) dataclass

What this bot owns and may spend.

shares, avg_cost and holding describe THIS BOT's position, not the whole account's. That distinction is the point: a strategy that sold whatever the account holds would sell shares another bot bought, or a long-term holding seeded into a paper account, and the chain that did so had no provenance check anywhere. cash and equity are the account's, because they genuinely are shared.

Parameters:

Name Type Description Default
cash float

The account's available cash.

required
equity float

The account's equity.

required
shares int

Shares held by this bot.

required
avg_cost float

Average cost of this bot's shares.

required

holding property

True if this bot holds any shares.

market_value property

This bot's shares valued at avg_cost (not at the current price).

Fill(symbol, action, quantity, price, time, reason='') dataclass

An order of this bot's that executed.

Parameters:

Name Type Description Default
symbol str

Stock ticker.

required
action str

'BUY' or 'SELL'.

required
quantity int

Shares filled.

required
price float

Fill price.

required
time datetime

Fill time.

required
reason str

Reason carried from the intent.

''

Intent(action, shares=None, amount=None, price=None, reason='', meta=dict()) dataclass

A request, not an order. Master's ExecutionEngine decides if and how it reaches the broker, and the RiskGate may refuse it outright.

shares is None means "whatever the risk budget allows", which is the normal case and the reason position sizing is not a thing a strategy computes: the budget is risk policy and it lives with the risk gate.

Parameters:

Name Type Description Default
action str

'BUY' or 'SELL'.

required
shares int

Exact share count; None means whatever the risk budget allows.

None
amount float

NT$ to spend, converted at the bar's close.

None
price float

Limit price; None means the bar's close.

None
reason str

Human-readable explanation.

''
meta dict

Extra data attached to the intent.

dict()

ParamSpec(kind, default, label, minimum=None, maximum=None, choices=()) dataclass

A declared parameter: its default, and enough to render a form field.

Collected by reading the module in a declaration pass (see user_strategy.collect_params), which is how the editor gets a parameters panel without anyone maintaining a second list of what is tunable.

Parameters:

Name Type Description Default
kind str

'int', 'float', 'bool' or 'choice'.

required
default Any

Default value.

required
label str

Form label.

required
minimum float

Bounds, if any.

None
maximum float

Bounds, if any.

None
choices tuple

Allowed values for a 'choice' parameter.

()

to_dict()

Return a JSON-friendly dict; bounds and choices only when set.

Source code in src/cjtrade/pkgs/strategy/authoring.py
453
454
455
456
457
458
459
460
461
462
def to_dict(self) -> dict:
    """Return a JSON-friendly dict; bounds and choices only when set."""
    out = {"kind": self.kind, "default": self.default, "label": self.label}
    if self.minimum is not None:
        out["min"] = self.minimum
    if self.maximum is not None:
        out["max"] = self.maximum
    if self.choices:
        out["choices"] = list(self.choices)
    return out

buy(shares=None, *, amount=None, price=None, reason='', **meta)

Ask to buy.

buy() -> as much as the risk budget allows buy(100) -> exactly 100 shares buy(amount=10_000) -> about NT$10,000 worth, whole shares, rounded down buy(price=250.0) -> limit at 250 instead of the bar's close

Parameters:

Name Type Description Default
shares int

Exact share count. Mutually exclusive with amount.

None
amount float

NT$ to spend; whole shares, rounded down.

None
price float

Limit price; defaults to the bar's close.

None
reason str

Human-readable explanation.

''
**meta

Extra data attached to the intent.

{}

Returns:

Type Description
Intent

A BUY intent.

Raises:

Type Description
ValueError

If both shares and amount are given.

Source code in src/cjtrade/pkgs/strategy/authoring.py
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
300
301
302
303
304
305
306
307
308
309
def buy(shares: Optional[int] = None, *, amount: Optional[float] = None,
        price: Optional[float] = None, reason: str = "", **meta) -> Intent:
    """Ask to buy.

    buy()                -> as much as the risk budget allows
    buy(100)             -> exactly 100 shares
    buy(amount=10_000)   -> about NT$10,000 worth, whole shares, rounded down
    buy(price=250.0)     -> limit at 250 instead of the bar's close

    Parameters
    ----------
    shares : int, optional
        Exact share count. Mutually exclusive with `amount`.
    amount : float, optional
        NT$ to spend; whole shares, rounded down.
    price : float, optional
        Limit price; defaults to the bar's close.
    reason : str, optional
        Human-readable explanation.
    **meta
        Extra data attached to the intent.

    Returns
    -------
    Intent
        A BUY intent.

    Raises
    ------
    ValueError
        If both `shares` and `amount` are given.
    """
    if shares is not None and amount is not None:
        raise ValueError("buy() takes shares or amount, not both")
    return Intent("BUY", shares=shares, amount=amount, price=price,
                  reason=reason, meta=meta)

sell(shares=None, *, price=None, reason='', **meta)

Ask to sell.

sell() -> everything THIS BOT holds (account.shares), not everything the account holds sell(50) -> exactly 50 shares

Parameters:

Name Type Description Default
shares int

Exact share count; None sells everything this bot holds.

None
price float

Limit price; defaults to the bar's close.

None
reason str

Human-readable explanation.

''
**meta

Extra data attached to the intent.

{}

Returns:

Type Description
Intent

A SELL intent.

Source code in src/cjtrade/pkgs/strategy/authoring.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def sell(shares: Optional[int] = None, *, price: Optional[float] = None,
         reason: str = "", **meta) -> Intent:
    """Ask to sell.

    sell()      -> everything THIS BOT holds (account.shares), not everything
                   the account holds
    sell(50)    -> exactly 50 shares

    Parameters
    ----------
    shares : int, optional
        Exact share count; None sells everything this bot holds.
    price : float, optional
        Limit price; defaults to the bar's close.
    reason : str, optional
        Human-readable explanation.
    **meta
        Extra data attached to the intent.

    Returns
    -------
    Intent
        A SELL intent.
    """
    return Intent("SELL", shares=shares, price=price, reason=reason, meta=meta)

hold(reason='')

Do nothing this bar, and say why.

The reason is not decoration. on_bar declines for several different reasons and a caller looking at "no signal" cannot tell them apart, so this is what makes a quiet run explainable -- it becomes monitors()["last_decision"], which the engine's status API and FinHub both show. Returning None without calling hold() is allowed and simply leaves the previous reason standing.

Parameters:

Name Type Description Default
reason str

Why nothing happened this bar.

''

Returns:

Type Description
None
Source code in src/cjtrade/pkgs/strategy/authoring.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def hold(reason: str = "") -> None:
    """Do nothing this bar, and say why.

    The reason is not decoration. on_bar declines for several different
    reasons and a caller looking at "no signal" cannot tell them apart, so
    this is what makes a quiet run explainable -- it becomes
    monitors()["last_decision"], which the engine's status API and FinHub both
    show. Returning None without calling hold() is allowed and simply leaves
    the previous reason standing.

    Parameters
    ----------
    reason : str, optional
        Why nothing happened this bar.

    Returns
    -------
    None
    """
    _sink().decision = reason
    return None

watch(**values)

Name values to be shown alongside this bot's state.

Call it as often as you like per bar; the last value for a name wins. The runner handles everything that makes these safe to put on a wire -- numpy scalars, rounding, dropping anything that is not a number or a string -- so there is no formatting to do here.

Source code in src/cjtrade/pkgs/strategy/authoring.py
366
367
368
369
370
371
372
373
374
def watch(**values: Any) -> None:
    """Name values to be shown alongside this bot's state.

    Call it as often as you like per bar; the last value for a name wins. The
    runner handles everything that makes these safe to put on a wire --
    numpy scalars, rounding, dropping anything that is not a number or a
    string -- so there is no formatting to do here.
    """
    _sink().watched.update(values)

plot(**series)

Name values to be drawn on the price chart, against this bar's time.

Separate from watch() because the two are consumed differently: a watched value is a number to read now, a plotted one is a series accumulated over the run. Only numbers can be plotted.

Source code in src/cjtrade/pkgs/strategy/authoring.py
377
378
379
380
381
382
383
384
385
386
def plot(**series: float) -> None:
    """Name values to be drawn on the price chart, against this bar's time.

    Separate from watch() because the two are consumed differently: a watched
    value is a number to read now, a plotted one is a series accumulated over
    the run. Only numbers can be plotted.
    """
    for key, value in series.items():
        if isinstance(value, (int, float)) and not isinstance(value, bool):
            _sink().plotted[key] = float(value)