Skip to content

Loading strategy files

How a file written against the authoring module is checked, loaded and run.

Danger

load() and collect_params() execute the file with full builtins. Only load files you trust.

cjtrade.pkgs.strategy.user_strategy

pkgs/strategy/user_strategy.py ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Assembles a hand-written strategy module into a BaseStrategy the engine can drive.

The user writes on_bar(bar, account) and returns buy() / sell() / hold(). Everything between that and the engine happens here: building Bar and Account, turning an Intent into a Signal with a size, collecting watch/plot into monitors(), tracking which shares are this bot's, and making sure a strategy that raises takes down the bar rather than the run.

Nothing in this module is part of the vocabulary a strategy may use -- that is authoring.py, and keeping the two apart is what lets the editor's completion list be generated from one module and be exactly right.

Security posture: executing a user's module is running their Python in this process. FinHub is a single trust domain -- an account on it is permission to run code on the host -- so this is not a sandbox and does not pretend to be one. __builtins__ is left intact, because stripping it stops len() and range() without stopping __import__, which is the worst of both.

StrategyError(message, line=None, offset=None)

Bases: Exception

A strategy's source could not be used.

line and offset are 1-based and may be None -- a SyntaxError has them, a missing on_bar does not. The editor turns them into a marker.

Parameters:

Name Type Description Default
message str

What is wrong.

required
line int

1-based line in the strategy source.

None
offset int

1-based column in that line.

None
Source code in src/cjtrade/pkgs/strategy/user_strategy.py
74
75
76
77
78
79
def __init__(self, message: str, line: Optional[int] = None,
             offset: Optional[int] = None):
    super().__init__(message)
    self.message = message
    self.line = line
    self.offset = offset

to_dict()

Return message, line and offset as a dict.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
81
82
83
84
def to_dict(self) -> dict:
    """Return message, line and offset as a dict."""
    return {"message": self.message, "line": self.line,
            "offset": self.offset}

Diagnostic(message, line, offset=1, severity='error') dataclass

One problem found in a strategy, at a position in the source.

Parameters:

Name Type Description Default
message str

What is wrong.

required
line int

1-based line.

required
offset int

1-based column (default 1).

1
severity str

'error' or 'warning'.

'error'

to_dict()

Return all fields as a dict.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
107
108
109
110
def to_dict(self) -> dict:
    """Return all fields as a dict."""
    return {"message": self.message, "line": self.line,
            "offset": self.offset, "severity": self.severity}

UserStrategy(namespace, name='')

Bases: BaseStrategy

Drives a hand-written strategy module through the BaseStrategy contract.

One instance per strategy module. Holds the module's namespace and the bookkeeping the module is deliberately not given: how many shares are this bot's, what the last bar reported, and how many bars in a row have raised.

Parameters:

Name Type Description Default
namespace dict

The executed module's namespace; must contain on_bar.

required
name str

Display name (default "Custom").

''
Warnings

Every hook calls the user's code. After MAX_CONSECUTIVE_ERRORS bars in a row raise, the strategy disables itself for the rest of the run.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
def __init__(self, namespace: dict, name: str = "") -> None:
    self._ns = namespace
    self.name = name or "Custom"
    self._on_bar: Callable = namespace["on_bar"]
    self._init: Optional[Callable] = namespace.get("init")
    self._on_fill: Optional[Callable] = namespace.get("on_fill")
    self._on_end: Optional[Callable] = namespace.get("on_end")

    self._sink = authoring._Sink()
    self._max_pct = 0.05
    self._n_bars = 0
    self._n_signals = 0
    self._errors = 0
    self._consecutive_errors = 0
    self._disabled_reason = ""
    # Shares this bot bought and has not sold. Not the account's position:
    # a strategy that sold the account's position would sell shares it
    # never bought. Clamped against what master reports, so it can never
    # ask to sell more than exists.
    self._own_shares = 0
    self._own_cost = 0.0
    # What the last bar's plot() calls asked for. Only the latest bar:
    # accumulating the series here would grow without bound over a long
    # run, and the runner that samples it is the thing that keeps history.
    self.plotted: Dict[str, float] = {}
    # symbol -> (session date, high so far, low so far), for bar.day_high
    # and bar.day_low. Built from the bars themselves, so they mean the
    # same under both runners: the trading engine and BacktestEngine both
    # deliver real per-bar highs and lows now.
    self._day_range: Dict[str, tuple] = {}

plots()

See BaseStrategy.plots -- whatever plot() was called with.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
744
745
746
def plots(self) -> Dict[str, float]:
    """See BaseStrategy.plots -- whatever plot() was called with."""
    return dict(self.plotted)

on_start(ctx)

Read risk__max_position_pct, reset state, and call the user's init().

Warnings

Clears the module-global authoring.state.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def on_start(self, ctx: StrategyContext) -> None:
    """Read `risk__max_position_pct`, reset `state`, and call the user's init().

    Warnings
    --------
    Clears the module-global `authoring.state`.
    """
    self._max_pct = float(ctx.params.get(
        "risk__max_position_pct",
        ctx.params.get("risk_max_position_pct", self._max_pct)))
    authoring.state._reset()
    self._day_range = {}
    self._sink = authoring._Sink()
    self._sink.decision = "no bars yet"
    if self._init is None:
        return
    with self._active():
        try:
            self._init()
        except Exception as exc:
            self._note_error("init", exc)

on_bar(bar, ctx)

Call the user's on_bar and turn its intents into sized 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

Empty if the strategy held, raised, or is disabled.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def on_bar(self, bar, ctx: StrategyContext) -> List[Signal]:
    """Call the user's on_bar and turn its intents into sized signals.

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

    Returns
    -------
    list of Signal
        Empty if the strategy held, raised, or is disabled.
    """
    self._n_bars += 1
    if self._disabled_reason:
        return []

    closes = ctx.prices(bar.symbol)
    account = self._account(ctx, bar)
    day_high, day_low = self._day_extremes(bar)
    user_bar = authoring.Bar(
        symbol=bar.symbol, time=bar.timestamp, open=float(bar.open),
        close=float(bar.close), volume=int(bar.volume or 0),
        closes=closes, day_high=day_high, day_low=day_low,
    )

    self._sink.plotted = {}
    with self._active():
        try:
            returned = self._on_bar(user_bar, account)
            self._consecutive_errors = 0
        except Exception as exc:
            self._note_error("on_bar", exc)
            return []

    self.plotted = dict(self._sink.plotted)
    return self._to_signals(returned, bar, account)

on_fill(fill, ctx)

Update this bot's own share count, then call the user's on_fill.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
def on_fill(self, fill: EngineFill, ctx: StrategyContext) -> None:
    """Update this bot's own share count, then call the user's on_fill."""
    # Before the callback, so a strategy reading account.shares inside
    # on_fill sees the position the fill produced rather than the one
    # before it.
    if fill.action.upper() == "BUY":
        self._own_shares += int(fill.quantity)
        self._own_cost += fill.quantity * fill.price
    else:
        sold = min(self._own_shares, int(fill.quantity))
        if self._own_shares:
            self._own_cost -= self._own_cost * (sold / self._own_shares)
        self._own_shares -= sold
        if self._own_shares <= 0:
            self._own_shares, self._own_cost = 0, 0.0

    if self._on_fill is None or self._disabled_reason:
        return
    with self._active():
        try:
            self._on_fill(
                authoring.Fill(symbol=fill.symbol, action=fill.action,
                               quantity=int(fill.quantity),
                               price=float(fill.price), time=fill.timestamp,
                               reason=fill.reason),
                self._account(ctx, None))
        except Exception as exc:
            self._note_error("on_fill", exc)

on_end(ctx)

Call the user's on_end, if defined and not disabled.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
851
852
853
854
855
856
857
858
859
def on_end(self, ctx: StrategyContext) -> None:
    """Call the user's on_end, if defined and not disabled."""
    if self._on_end is None or self._disabled_reason:
        return
    with self._active():
        try:
            self._on_end(self._account(ctx, None))
        except Exception as exc:
            self._note_error("on_end", exc)

monitors()

See BaseStrategy.monitors; adds the values passed to watch().

A watched name that clashes with a built-in key is prefixed with w_.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
def monitors(self) -> Dict[str, Any]:
    """See BaseStrategy.monitors; adds the values passed to watch().

    A watched name that clashes with a built-in key is prefixed with `w_`.
    """
    out: Dict[str, Any] = {
        "bars_seen": self._n_bars,
        "signals_emitted": self._n_signals,
        "own_shares": self._own_shares,
        "own_avg_cost": (round(self._own_cost / self._own_shares, 2)
                         if self._own_shares else 0.0),
        "last_decision": self._sink.decision,
    }
    if self._errors:
        out["errors"] = self._errors
    if self._disabled_reason:
        out["disabled"] = self._disabled_reason
    # The strategy's own values last, so a name it chose cannot quietly
    # overwrite one of the above and leave the runner reporting a number
    # that means something else.
    for key, value in self._sink.watched.items():
        out[f"w_{key}" if key in out else key] = _wire_safe(value)
    return out

check(source)

Everything that can be known about a strategy without running it.

Deliberately short of a type checker: a syntax error, a missing on_bar, a wrong signature, and the handful of shapes that are always a mistake. The editor runs this on every save, so it has to be fast and it has to never report a false problem -- a red squiggle on correct code teaches people to ignore squiggles.

Parameters:

Name Type Description Default
source str

The strategy file's source.

required

Returns:

Type Description
list of Diagnostic

Empty if nothing was found.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
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
def check(source: str) -> List[Diagnostic]:
    """Everything that can be known about a strategy without running it.

    Deliberately short of a type checker: a syntax error, a missing on_bar, a
    wrong signature, and the handful of shapes that are always a mistake. The
    editor runs this on every save, so it has to be fast and it has to never
    report a false problem -- a red squiggle on correct code teaches people to
    ignore squiggles.

    Parameters
    ----------
    source : str
        The strategy file's source.

    Returns
    -------
    list of Diagnostic
        Empty if nothing was found.
    """
    try:
        tree = ast.parse(source, filename=MODULE_NAME)
    except SyntaxError as exc:
        return [Diagnostic(exc.msg or "invalid syntax",
                           line=exc.lineno or 1, offset=exc.offset or 1)]

    out: List[Diagnostic] = []
    functions = {node.name: node for node in tree.body
                 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}

    on_bar = functions.get("on_bar")
    if on_bar is None:
        out.append(Diagnostic(
            "a strategy needs a function called on_bar(bar, account)", line=1))
    else:
        if isinstance(on_bar, ast.AsyncFunctionDef):
            out.append(Diagnostic(
                "on_bar must be a plain function, not async -- the engine "
                "calls it inside one bar and cannot await it",
                line=on_bar.lineno))
        got = [a.arg for a in on_bar.args.args]
        if len(got) != 2:
            out.append(Diagnostic(
                f"on_bar takes exactly two arguments, (bar, account); "
                f"this one takes {len(got)}"
                + (f": {', '.join(got)}" if got else ""),
                line=on_bar.lineno))

    for name, expected in (("on_fill", 2), ("on_end", 1), ("init", 0)):
        node = functions.get(name)
        if node is None:
            continue
        got = [a.arg for a in node.args.args]
        if len(got) != expected:
            shape = {"on_fill": "(fill, account)", "on_end": "(account)",
                     "init": "()"}[name]
            out.append(Diagnostic(
                f"{name} takes {expected} argument(s), {shape}; this one "
                f"takes {len(got)}", line=node.lineno))

    out.extend(_undefined_names(tree))
    return out

load(source)

Compile and execute a strategy module, and wrap it for the engine.

Parameters:

Name Type Description Default
source str

The strategy file's source.

required

Returns:

Type Description
UserStrategy

The loaded strategy.

Raises:

Type Description
StrategyError

For anything that makes the source unusable, with a line number where one exists. Problems the static check found are raised first, because "name is not defined on line 12" is a better answer than the NameError the same file produces on bar 1.

Warnings

Runs the user's code with exec() in this process, with full builtins. This is not a sandbox.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
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
300
301
302
303
304
305
306
307
308
309
310
311
312
def load(source: str) -> "UserStrategy":
    """Compile and execute a strategy module, and wrap it for the engine.

    Parameters
    ----------
    source : str
        The strategy file's source.

    Returns
    -------
    UserStrategy
        The loaded strategy.

    Raises
    ------
    StrategyError
        For anything that makes the source unusable, with a line number where
        one exists. Problems the static check found are raised first, because
        "name is not defined on line 12" is a better answer than the NameError
        the same file produces on bar 1.

    Warnings
    --------
    Runs the user's code with exec() in this process, with full builtins.
    This is not a sandbox.
    """
    problems = [d for d in check(source) if d.severity == "error"]
    if problems:
        first = problems[0]
        raise StrategyError(first.message, line=first.line, offset=first.offset)

    ns = _namespace()
    try:
        code = compile(source, MODULE_NAME, "exec")
        exec(code, ns)
    except SyntaxError as exc:
        raise StrategyError(exc.msg or "invalid syntax",
                            line=exc.lineno, offset=exc.offset) from exc
    except Exception as exc:
        raise StrategyError(f"the strategy failed while loading: "
                            f"{type(exc).__name__}: {exc}",
                            line=_traceback_line(exc)) from exc

    return UserStrategy(ns)

collect_params(source)

The parameters a strategy declares, in the order it declares them.

Works by running the module, because param.int(100, "Window") is an ordinary call whose side effect is the declaration -- there is no separate manifest to keep in step with the code. Running it is acceptable here for the same reason it is acceptable at all: single trust domain.

Parameters:

Name Type Description Default
source str

The strategy file's source.

required

Returns:

Type Description
list of dict

One ParamSpec.to_dict() per declaration; empty if the source does not load.

Warnings

Executes the user's module (via load) to find the declarations.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def collect_params(source: str) -> List[dict]:
    """The parameters a strategy declares, in the order it declares them.

    Works by running the module, because `param.int(100, "Window")` is an
    ordinary call whose side effect is the declaration -- there is no separate
    manifest to keep in step with the code. Running it is acceptable here for
    the same reason it is acceptable at all: single trust domain.

    Parameters
    ----------
    source : str
        The strategy file's source.

    Returns
    -------
    list of dict
        One ParamSpec.to_dict() per declaration; empty if the source does not
        load.

    Warnings
    --------
    Executes the user's module (via load) to find the declarations.
    """
    authoring.param._drain()                 # discard anything left over
    try:
        load(source)
    except StrategyError:
        return []
    return [spec.to_dict() for spec in authoring.param._drain()]

template(kind='bb', name='My strategy', symbol='2317')

A complete, runnable strategy of the asked-for kind.

These live here rather than in FinHub because they are demonstrations of this module's API: if buy() grows an argument or ta loses an indicator, the files that teach it should be the thing that changes with it.

Each one is a working strategy rather than a skeleton of comments. The first thing anyone does is press run, and a file that does nothing teaches nothing about what went wrong.

bb, dca and adx are the same three strategies the engine's built-in bot_c, bot_a and bot_b run -- written against this API instead of as BaseStrategy subclasses, which is what makes them editable in a browser. They are not the same code: a subclass with 200 lines of machinery and a 25-line on_bar are different artifacts for different readers, and these are the ones a person is meant to read.

Parameters:

Name Type Description Default
kind str

One of TEMPLATE_KINDS: 'bb', 'dca', 'adx' or 'blank'.

'bb'
name str

Title written into the template's docstring.

'My strategy'
symbol str

Symbol written into the template's docstring.

'2317'

Returns:

Type Description
str

The strategy source.

Raises:

Type Description
ValueError

If kind is not a known template.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def template(kind: str = "bb", name: str = "My strategy",
             symbol: str = "2317") -> str:
    """A complete, runnable strategy of the asked-for kind.

    These live here rather than in FinHub because they are demonstrations of
    this module's API: if `buy()` grows an argument or `ta` loses an indicator,
    the files that teach it should be the thing that changes with it.

    Each one is a working strategy rather than a skeleton of comments. The
    first thing anyone does is press run, and a file that does nothing teaches
    nothing about what went wrong.

    `bb`, `dca` and `adx` are the same three strategies the engine's built-in
    bot_c, bot_a and bot_b run -- written against this API instead of as
    BaseStrategy subclasses, which is what makes them editable in a browser.
    They are not the same code: a subclass with 200 lines of machinery and a
    25-line on_bar are different artifacts for different readers, and these are
    the ones a person is meant to read.

    Parameters
    ----------
    kind : str, optional
        One of TEMPLATE_KINDS: 'bb', 'dca', 'adx' or 'blank'.
    name : str, optional
        Title written into the template's docstring.
    symbol : str, optional
        Symbol written into the template's docstring.

    Returns
    -------
    str
        The strategy source.

    Raises
    ------
    ValueError
        If `kind` is not a known template.
    """
    if kind not in TEMPLATE_KINDS:
        raise ValueError(f"unknown template {kind!r}; "
                         f"try one of {', '.join(TEMPLATE_KINDS)}")
    title = name.strip() or "My strategy"
    body = _TEMPLATES[kind]
    return body.replace("%TITLE%", title).replace("%SYMBOL%", symbol) \
               .replace("%CHEAT_SHEET%", _CHEAT_SHEET)

starter_source(name='My strategy', symbol='2317')

The Bollinger template. Kept as the name the first callers used.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
600
601
602
def starter_source(name: str = "My strategy", symbol: str = "2317") -> str:
    """The Bollinger template. Kept as the name the first callers used."""
    return template("bb", name, symbol)

api_reference()

Every name a strategy may use, with its signature and its docstring.

Generated by introspecting authoring.all, which is what keeps the editor's completion list from drifting away from the code: there is no second list to maintain, and a name that is added or removed here changes the editor on the next request.

Returns:

Type Description
list of dict

Each with 'name', 'qualified', 'kind', 'signature' and 'doc'.

Source code in src/cjtrade/pkgs/strategy/user_strategy.py
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def api_reference() -> List[dict]:
    """Every name a strategy may use, with its signature and its docstring.

    Generated by introspecting authoring.__all__, which is what keeps the
    editor's completion list from drifting away from the code: there is no
    second list to maintain, and a name that is added or removed here changes
    the editor on the next request.

    Returns
    -------
    list of dict
        Each with 'name', 'qualified', 'kind', 'signature' and 'doc'.
    """
    import inspect

    out: List[dict] = []

    def describe(name: str, obj: Any, kind: str, owner: str = "") -> None:
        try:
            signature = f"{name}{inspect.signature(obj)}"
        except (TypeError, ValueError):
            signature = name
        doc = inspect.getdoc(obj) or ""
        out.append({
            "name": name,
            "qualified": f"{owner}.{name}" if owner else name,
            "kind": kind,
            "signature": signature,
            "doc": doc.strip(),
        })

    for name in authoring.__all__:
        obj = getattr(authoring, name)
        if inspect.isfunction(obj):
            describe(name, obj, "function")
        elif inspect.isclass(obj):
            describe(name, obj, "class")
            for attr, value in vars(obj).items():
                if attr.startswith("_"):
                    continue
                kind = ("property" if isinstance(value, property)
                        else "method" if callable(value) else "field")
                describe(attr, value, kind, owner=name)
            # Dataclass fields are annotations, not class attributes.
            for attr in getattr(obj, "__annotations__", {}):
                if not attr.startswith("_"):
                    out.append({"name": attr, "qualified": f"{name}.{attr}",
                                "kind": "field", "signature": attr, "doc": ""})
        elif inspect.ismodule(obj):
            describe(name, obj, "module")
        else:
            # ta, param, state: instances whose public methods are the API.
            describe(name, obj, "namespace")
            for attr in dir(obj):
                if attr.startswith("_"):
                    continue
                try:
                    value = getattr(obj, attr)
                except AttributeError:
                    continue        # ta.adx and friends refuse on purpose
                describe(attr, value,
                         "method" if callable(value) else "field", owner=name)
    return out