A Nyx strategy is a single Python file. Drop it into the
strategies folder, rescan, and it shows up in the app — parameters,
backtest, optimiser and live trading included. No rebuild, no plugin API, no UI code.
Strategies are loaded from the strategies folder next to Nyx.exe
(inside the installed folder it is _internal\strategies\). Rules:
.py file, saved as UTF-8._ — those files are skipped.Ready-made examples ship in strategies\_templates\<lang>\ — one per
UI language. Copy one out, rename it, start editing.
Four module-level names and one function. If any of them is missing or malformed, the strategy shows up in the list with an error instead of loading.
NAME = "My strategy" # required, display name
DESC = "One-line summary" # optional
PARAMS = [ ... ] # required, 6-tuple per parameter (see below)
def signal(candles, p, symbol=""):
... # required, returns a signal or None
Load-time validation covers: signal exists and is callable, PARAMS
is a list/tuple of 6-tuples, types are only int / float / bool,
keys are non-empty and unique, and each min/max pair is ordered.
There is one optional declaration:
DONCHIAN_PREFILTER_PARAM = "lookback"
Only for strategies where every valid signal sits near a Donchian channel edge. It lets the backtester skip candles that cannot possibly produce a signal, which speeds up parameter optimisation a lot. Leave it out unless that is true of your strategy — a wrong value makes the backtest miss trades.
Every tunable becomes an input field in the app automatically. This is what makes a strategy usable without editing code:
PARAMS = [
("lookback", "int", 100, 20, 300, "Breakout period|How many candles back"),
("vol_mult", "float", 1.2, 0.5, 5.0, "Volume multiplier|>= average x this"),
("sl_atr", "float", 3.0, 0.5, 5.0, "Stop ATR|Stop = N x ATR"),
("use_vol", "bool", True, 0, 1, "Volume filter|Require volume expansion"),
]
| Position | Meaning |
|---|---|
| 1 | key — read it in signal() via p.get("key") |
| 2 | type — "int" / "float" / "bool" only |
| 3 | default |
| 4, 5 | min, max — the slider bounds |
| 6 | desc — "short|long": the part before | is the label,
the part after it becomes the tooltip |
Parameters are stored per strategy, so switching strategies never
pollutes another strategy's settings. If you rename a key, the user's saved
value for it is lost.
Optional CFG_MAP maps your keys onto existing global config keys when
you deliberately want to share a value instead of keeping a private copy:
CFG_MAP = {k: k for k, *_ in PARAMS}
signal() receivesdef signal(candles, p, symbol=""):
| Argument | Content |
|---|---|
candles | List of closed candles, oldest first. Each is a dict
{"t", "o", "h", "l", "c", "v"}. candles[-1] is the candle that just closed. |
p | Current parameter values, keyed by your PARAMS keys. |
symbol | Symbol name, e.g. "BTCUSDT". Use it to keep per-coin
caches apart in multi-coin mode; single-coin strategies can ignore it. |
Two hard rules about the input:
p.get(key, default), never from globals —
the optimiser calls the same function with different values thousands of times.signal() returnsFour accepted shapes:
| Return | Effect |
|---|---|
None | No signal. Also accepts "", 0, False,
empty list / tuple / dict — all treated as "no signal", silently. |
"long" / "short" | Open with the app's default stop distance. |
{"dir": "long", ...} | Open and override execution details (keys below). |
("long", {...}) | Same as above, tuple form. |
| Key | Meaning |
|---|---|
sl_atr | Stop distance = N × ATR. Defaults to 2.0. |
strategy | Exit branch: "trend" / "range" / "manual".
Defaults to "range". See section 6. |
tp_rr | Take-profit = entry ± stop distance × RR. The usual choice. |
tp_atr | Take-profit = entry ± ATR × N. |
tp | Absolute take-profit price. 0 means "no take-profit". |
pyramid | True / False — allow adding to this position
while it is in profit. |
Give at most one of tp_rr / tp_atr / tp. If the strategy gives one,
it wins; if it gives none, the global take-profit RR from the Parameters page applies.
trend positions have no fixed take-profit by default.
Mistakes are reported, not swallowed. A wrong key ({"side": "long"}),
a wrong value ("buy", "LONG") or a wrong type writes a clear error to the
log and marks that coin as strategy error, which also blocks live entries for it.
Until recently these cases looked exactly like "no signal", which made them impossible
to debug.
The strategy key decides how the framework closes the position. Choosing it
correctly matters more than most parameters:
| Value | Behaviour | Use for |
|---|---|---|
"trend" | Break-even trailing plus Donchian reversal exit; no fixed take-profit by default | Breakout / momentum strategies |
"range" | Timeout, pullback take-profit and the global fixed TP | Mean-reversion strategies |
"manual" | The app never closes it automatically — only stop-loss and take-profit orders act | Fully hand-managed trades |
Omitting the key means "range", which will cut a trend trade short at the first
normal pullback. Trend strategies should always set it explicitly.
Import from core. There is no numpy or pandas in a strategy — these are plain
Python lists, and they are already optimised for the backtest loop. Do not reimplement them.
from core import (ema, sma, boll, atr, macd, rsi, kdj, adx, adx_full,
rolling_max_h, rolling_min_l, nwe,
calc_pivot_points, calc_vwap, calc_supertrend, calc_donchian)
| Function | Returns |
|---|---|
ema(series, n) / sma(series, n) | List, aligned with the input |
boll(series, n=20, k=2.0) | (upper, mid, lower) |
rsi(closes, n=14) | List |
macd(closes, fast=12, slow=26, signal=9) | (DIF, DEA, hist) |
kdj(candles, n=9, ks=3, ds=3) | (K, D, J) |
atr(candles, n=14) | Single float (latest value) |
adx(candles, n=14) / adx_full(candles, n=14) | Float / full list |
rolling_max_h(candles, period) / rolling_min_l(candles, period) |
Highest high / lowest low of the period bars before each bar |
calc_donchian(candles, period=20) | (upper, lower) as
[(idx, value), ...] |
calc_supertrend(candles, period=10, mult=3.0) |
[(idx, value, direction), ...], direction 1 long / -1 short |
calc_vwap(candles) | [(idx, vwap), ...], reset per UTC day |
calc_pivot_points(candles) | Dict of pivot / R1-R3 / S1-S3 from the last
complete UTC day, or None |
nwe(src, bandwidth=8.0, mult=3.0) | Nadaraya-Watson envelope |
core, math and plain stdlib helpers.PARAMS.By default the backtester calls signal() once per candle, and each call
recomputes indicators over history — O(n²) overall. For long backtests and parameter
sweeps, add two optional functions so every indicator is computed once:
def build_pre_data(candles_1h, params):
"""Runs ONCE before the backtest. Return a dict of precomputed arrays."""
from core import adx_full, rolling_max_h, rolling_min_l
period = int((params or {}).get("lookback", 100))
return {
"candles_1h": candles_1h,
"don_hi": rolling_max_h(candles_1h, period),
"don_lo": rolling_min_l(candles_1h, period),
"adx14": adx_full(candles_1h, 14),
}
def signal_at(pre_data, i, params):
"""Signal at the close of candle i — table lookups only, O(1)."""
candles = pre_data["candles_1h"]
if i < 1 or i >= len(candles):
return None
...
return {"dir": "long", "sl_atr": 3.0, "strategy": "trend"}
Two things to keep straight:
pre_data["candles_1h"] must be present — the framework reads it to build
its own context. If build_pre_data() raises, the backtest falls back to
signal() and records the error.i is an index into the same candle list; candles[i] is the
current bar, and everything at > i is future data you must not touch.If signal_at() is absent the framework falls back to signal()
with a truncated list, so both interfaces always work. Whenever you change the logic in
one, change it in the other.
strategies\my_strategy.py, UTF-8, no leading underscore.The app ships a Copy template for AI button. It puts a complete annotated template on the clipboard together with a one-line request, so you can paste it into any chat model and describe your idea in plain language. Review the result before running it.
| Symptom | Cause |
|---|---|
| Strategy does not appear in the list | File name starts with _, or the
file is not .py, or it is in a subfolder — only the top level of
strategies\ is scanned |
| Appears with an error and cannot be selected | signal() missing or not
callable; PARAMS not 6-tuples; a type other than int/float/bool; duplicate key |
| Coin shows strategy error | The return value broke the contract — wrong key
(side instead of dir), wrong value ("buy",
"LONG"), or an exception inside signal(). The log names it |
| Backtest produces no trades | Not enough candles for the lookback
(len(candles) < period + 1 returns early), or a filter is too strict |
| Backtest is very slow, optimiser worse | Indicators recomputed on every call —
add build_pre_data() / signal_at() from section 8 |
| Trend trades exit early at a small pullback | strategy key omitted, so
"range" applies. Set "trend" |
| Signal appears one candle late in backtest | Look-ahead in indicator indexing — check
that loops never read candles[i + 1] |