← Nyx

Writing a custom strategy

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.

On this page
  1. Where strategy files live
  2. The file contract
  3. The parameter table
  4. What signal() receives
  5. What signal() returns
  6. Exit modes
  7. Built-in indicators
  8. Making backtests faster
  9. Run it: rescan, backtest, optimise, go live
  10. Troubleshooting

1. Where strategy files live

Strategies are loaded from the strategies folder next to Nyx.exe (inside the installed folder it is _internal\strategies\). Rules:

Ready-made examples ship in strategies\_templates\<lang>\ — one per UI language. Copy one out, rename it, start editing.

2. The file contract

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.

3. The parameter table

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"),
]
PositionMeaning
1key — read it in signal() via p.get("key")
2type — "int" / "float" / "bool" only
3default
4, 5min, max — the slider bounds
6desc — "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}

4. What signal() receives

def signal(candles, p, symbol=""):
ArgumentContent
candlesList of closed candles, oldest first. Each is a dict {"t", "o", "h", "l", "c", "v"}. candles[-1] is the candle that just closed.
pCurrent parameter values, keyed by your PARAMS keys.
symbolSymbol 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:

5. What signal() returns

Four accepted shapes:

ReturnEffect
NoneNo 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.

Execution keys

KeyMeaning
sl_atrStop distance = N × ATR. Defaults to 2.0.
strategyExit branch: "trend" / "range" / "manual". Defaults to "range". See section 6.
tp_rrTake-profit = entry ± stop distance × RR. The usual choice.
tp_atrTake-profit = entry ± ATR × N.
tpAbsolute take-profit price. 0 means "no take-profit".
pyramidTrue / 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.

6. Exit modes

The strategy key decides how the framework closes the position. Choosing it correctly matters more than most parameters:

ValueBehaviourUse for
"trend"Break-even trailing plus Donchian reversal exit; no fixed take-profit by defaultBreakout / 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 actFully 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.

7. Built-in indicators

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)
FunctionReturns
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

Hard rules

8. Making backtests faster

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:

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.

9. Run it: rescan, backtest, optimise, go live

  1. Save the file as strategies\my_strategy.py, UTF-8, no leading underscore.
  2. Rescan strategies — in the app it sits next to the strategy dropdown. The strategy appears in the list; a load error is shown there with its reason.
  3. Parameters (参数) in the left sidebar → pick your strategy in the dropdown → tune the auto-generated fields → save.
  4. Run a backtest on a symbol to check the equity curve and trade list.
  5. Optionally run the optimiser over the parameters you flagged.
  6. Only then enable live trading for that strategy.

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.

10. Troubleshooting

SymptomCause
Strategy does not appear in the listFile 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 selectedsignal() missing or not callable; PARAMS not 6-tuples; a type other than int/float/bool; duplicate key
Coin shows strategy errorThe 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 tradesNot enough candles for the lookback (len(candles) < period + 1 returns early), or a filter is too strict
Backtest is very slow, optimiser worseIndicators recomputed on every call — add build_pre_data() / signal_at() from section 8
Trend trades exit early at a small pullbackstrategy key omitted, so "range" applies. Set "trend"
Signal appears one candle late in backtestLook-ahead in indicator indexing — check that loops never read candles[i + 1]