Remote algorithms
An algorithm as your own program in any language, called by the engine over HTTP or WebSocket on every step: the messages, the timeouts, the failures and a minimal server.
You have a strategy in Python, or in any language that is not Rust, and you want Neurotrader to run it without rewriting it as a plugin. A remote algorithm does that. You run a small server. The engine calls it on every step with the candles and the account, and your program answers with the orders it wants.
Remote and plugin compared
| Plugin | Remote algorithm | |
|---|---|---|
| Language | Rust | Anything that speaks HTTP or WebSocket |
| Where it runs | Inside the engine | Your own process, on any machine the engine can reach |
| If it crashes | It can take the engine down | The engine keeps running |
| Cost of a step | A function call | A network round trip |
| Indicators | Computed inside the plugin | Computed by the engine and sent to you |
The round trip is the price. A backtest over millions of candles belongs in a plugin. A remote algorithm suits research code, models with heavy dependencies, and strategies on coarse intervals.
Remote algorithm setup
Your program is the server. The engine is the client. You start your program and it listens. The engine connects out to the address you give it.
In Neurotrader a remote algorithm is the built-in algorithm named Remote. Add it to a simulation like any other algorithm and set its parameters:
| Parameter | Field name | Meaning |
|---|---|---|
| URL | url | Where your program listens. Required. |
| Encoding | encoding | json (the default) or msgpack |
| Protocol version | version | Optional. Pins the protocol version instead of negotiating it. |
{
"url": "http://127.0.0.1:9000/",
"encoding": "json"
}Your strategy's own settings (periods, thresholds) belong to your program, not to these parameters. To compare one strategy under two settings, run two programs on two addresses and add Remote twice.
URL scheme
The scheme of the URL chooses how the engine talks to your program:
| Scheme | Transport |
|---|---|
http://, https:// | One POST request per call |
ws://, wss:// | One WebSocket connection for the whole run |
Any other scheme is refused when the run starts.
Messages
Every message is JSON-RPC 2.0. A
request has a method, params and an id. Your reply repeats the id and
carries either result or error.
{"jsonrpc": "2.0", "id": 7, "method": "step", "params": {"session": "...", "seq": 1}}{"jsonrpc": "2.0", "id": 7, "result": {"actions": []}}{"jsonrpc": "2.0", "id": 7, "error": {"code": -32000, "message": "need two tickers, got one"}}A request without an id is a notification. Do not answer it.
With msgpack the messages have exactly the same structure, encoded as
MessagePack: maps with string keys, and ids and timestamps still as strings.
Sessions
Every request carries session, a UUID the engine creates for one algorithm
instance in one run. Keep a table of sessions and treat each as independent.
Two runs at once, or two Remote algorithms pointing at the same URL in one
comparison, are two sessions with their own state and their own seed.
Within one session the engine sends one request at a time and waits for the answer.
Methods
The engine calls these in order. step repeats for the whole run.
| Method | Case | Result |
|---|---|---|
initialize | First contact, before the run starts | The protocol version, your name, the indicators you want |
validate | Before the run starts | {}, or an error to refuse the instruments |
setup | Before the first step | {} |
step | Once per step | {"actions": [...]} |
parameters | When the run is recorded | {"parameters": ...}: your own settings, any JSON or null |
store_state | When the run is paused | {"state": ...}: any JSON or null |
restore_state | When a paused run resumes | {}, or an error if you cannot read the state |
terminate | When the run ends (a notification) | Nothing |
initialize
{"method": "initialize", "params": {
"session": "6f1c2d9e-3b7a-4c58-9e21-0d4f5a6b7c8d",
"protocol": [1],
"seed": 1234567890123456789,
"engine": {"version": "0.1.0"}
}}Reply with one of the offered protocol versions. This page describes version
1.
{"result": {
"protocol": 1,
"name": "mean-reversion-py",
"description": "Bollinger reversion, research build",
"indicators": {"version": 1, "indicators": [
{"name": "bb", "kind": "bollinger", "params": {"period": 20, "multiplier": 2.0}}
]}
}}name and description appear in the engine's log and in the run's summary
of the instance. indicators is optional.
seed is an unsigned 64-bit integer. In a language whose numbers are
floating point, parse it as an integer or you lose its low digits.
validate and setup
{"method": "validate", "params": {"session": "...", "tickers": [
{"id": "...", "symbol": "BTCEUR", "base": "<asset id>", "quote": "<asset id>", "market": "binance"}
]}}tickers are the instruments this instance reads. Answer {} to accept
them, or error -32000 with a message for the user. setup carries the same
tickers and is where you prepare for the first step.
step
{"method": "step", "params": {
"session": "...",
"seq": 1041,
"candles": {"<ticker id>": {
"open_time": "2026-10-09T14:00:00Z", "close_time": "2026-10-09T14:59:59.999Z",
"open": 100.0, "high": 101.5, "low": 99.2, "close": 101.0,
"volume": 12.5, "quote_asset_volume": 1256.0, "number_of_trades": 42,
"taker_buy_base_asset_volume": 6.2, "taker_buy_quote_asset_volume": 623.0}},
"holdings": {"<asset id>": {"free": 1000.0, "frozen": 0.0}},
"open_orders": [],
"fills": [],
"account": {"assets": 1000.0, "liabilities": 0.0, "equity": 1000.0,
"margin_level": null, "margin_call": false, "liquidated": false,
"borrowings": {}, "terms": null},
"indicators": {"bb.upper": 101.2, "bb.middle": 100.0, "bb.lower": 98.8}
}}| Field | Meaning |
|---|---|
seq | The step counter for this session, from 1. The engine never sends one twice. |
candles | The candles that closed at this step, by ticker id. An instrument with no candle at this moment is absent, and the map can be empty. |
holdings | The balance of every asset in the account. free is what you can spend. |
open_orders | Your orders that are still working, oldest first |
fills | What traded since your previous step, each naming its order |
account | Equity, liabilities and margin figures. margin_level is null while nothing is owed, and terms is null on a spot account. |
indicators | The current value of each indicator you declared, null while it is warming up. Absent if you declared none. |
Reply with the actions you want, in the order they should be worked:
{"result": {"actions": [
{"type": "submit_order", "order": {
"ticker": "<ticker id>", "side": "buy",
"order_type": {"type": "market"},
"quantity": 0.01,
"time_in_force": {"type": "good_till_canceled"}}}
]}}An empty list means "do nothing". New fields can be added to a request without a new protocol version, so ignore fields you do not know.
Actions and orders
| Action | Shape |
|---|---|
| Place an order | {"type": "submit_order", "order": NewOrder} |
| Cancel a pending order | {"type": "cancel_order", "order_id": "..."} |
| Close an open order | {"type": "close_order", "order_id": "..."} |
There is no amend. To move a resting order, send the cancel and then the new order, in that order, in one reply.
A new order has ticker, side (buy or sell), order_type, quantity
and time_in_force, and optionally leverage on a margin account. The engine
assigns its id. You learn the id from open_orders on the next step.
order_type | Extra fields |
|---|---|
{"type": "market"} | None |
{"type": "limit"} | price |
{"type": "stop_market"} | stop_price |
{"type": "stop_limit"} | stop_price, limit_price |
{"type": "take_profit"} | trigger_price |
{"type": "stop_loss"} | trigger_price |
time_in_force is {"type": "good_till_canceled"},
{"type": "immediate_or_cancel"}, {"type": "fill_or_kill"} or
{"type": "good_till_date", "until": "2026-10-10T00:00:00Z"}.
An order in open_orders has the same fields plus id, parent_id,
oco_group, status, created_at, updated_at and
filled (quantity, notional, fees).
As for every algorithm, an order placed at one step is worked against the next candle, never the one that produced it.
Error codes
| Code | Meaning |
|---|---|
-32000 | Your algorithm's own refusal, with a message for the user |
-32001 | You do not know this session |
-32002 | You speak none of the offered protocol versions (initialize only) |
-32700, -32600, -32601, -32602, -32603 | The standard JSON-RPC errors |
Transport details
HTTP. Each call is a POST to your URL with
Content-Type: application/json (or application/msgpack). Answer 200 with
the JSON-RPC reply in the body, also when the reply is an error. Any other
status counts as a failed call.
WebSocket. The engine asks for the subprotocol neurotrader.algorithm
and your server must select it. Each message is one text frame (json) or
one binary frame (msgpack). If the connection drops, the engine reconnects
once and carries on under the same session.
Log messages. Your program can write to the engine's log. Over WebSocket, send a notification at any time:
{"jsonrpc": "2.0", "method": "log", "params": {"session": "...", "level": "info", "message": "crossed the upper band"}}Over HTTP, add a log array of {"level": ..., "message": ...} entries to
any result. level is error, warn, info, debug or trace.
Indicators
Declaring an indicator asks the engine to compute it for you. Name what you
need in your initialize reply, in the same declaration format a plugin uses
(see Plugin authoring), and every step
request carries the current values by series name.
The engine computes them, keeps them across a pause, warms them up before a live run and records them with the run, so they appear on the run's charts.
A program that computes its own indicators declares none and receives none.
Timeouts and failures
A network call can hang, so every call has a time limit. The limits are
settings of the engine, under remote_algorithm in its configuration file,
and apply to every remote algorithm:
| Setting | Default | Covers |
|---|---|---|
connect_timeout_ms | 5000 | Reaching your server |
call_timeout_ms | 30000 | Every call except step |
step_timeout_ms | 10000 | step |
What a failure does depends on when it happens:
| Case | Outcome |
|---|---|
Before the run (initialize, validate, setup) | The run does not start, and you are told why: the server was not there, the version was not accepted, or your refusal with its message. |
During the run (step) | The step fails. The algorithm places no orders at that step, the engine logs an error, and the run continues. |
| The server forgets the session, or cannot be reached again | The algorithm is dead for the rest of the run. Every later step is empty and logged. The run itself goes on until it ends or you stop it. |
On pause or resume (store_state, restore_state) | The pause or the resume fails, and you are told. |
A failed step is not a decision to do nothing, which is why it is logged
every time. Nothing is ever sent twice: a step whose answer was lost is
simply a failed step.
A dead algorithm is not revived, because a program that lost its session has lost the state it was carrying. The one exception is a paused run: it resumes under a new session and hands your stored state back.
Program availability during a live run
If your program stops during a live run, the algorithm stops trading and its open orders stay where they are. Run the program where it stays up, and watch the run.
Security
The connection is not authenticated. The engine sends no key or token to your program, and your program has no way to check who is calling it.
- Run your program on the same computer as the engine and listen on
127.0.0.1, or keep it on a network you control. - Anyone who can reach your program's port can call it.
- With
http://andws://the messages travel unencrypted. They contain your balances and orders.
Determinism
The same rules apply as for a plugin. Draw every random decision from the
seed you receive in initialize, and save your generator's position in
store_state. Do not decide from the clock: the time of a step is the time
of its candles. See Determinism rules.
Minimal server
This Python program needs only the standard library. It asks the engine for a 20-candle moving average and buys once, with nearly all of the quote balance, when the close is above the average.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
sessions = {}
DECLARATION = {
"version": 1,
"indicators": [{"name": "trend", "kind": "sma", "params": {"period": 20}}],
}
def refuse(message):
raise ValueError(message)
def initialize(params):
sessions[params["session"]] = {"ticker": None, "bought": False}
return {"protocol": 1, "name": "minimal-trend", "indicators": DECLARATION}
def validate(params):
if len(params["tickers"]) != 1:
refuse("minimal-trend trades exactly one instrument")
return {}
def setup(params):
sessions[params["session"]]["ticker"] = params["tickers"][0]
return {}
def step(params):
state = sessions[params["session"]]
ticker = state["ticker"]
candle = params["candles"].get(ticker["id"])
average = (params.get("indicators") or {}).get("trend")
if candle is None or average is None or state["bought"] or params["open_orders"]:
return {"actions": []}
if candle["close"] <= average:
return {"actions": []}
cash = params["holdings"].get(ticker["quote"], {"free": 0.0})["free"]
quantity = cash * 0.99 / candle["close"]
if quantity <= 0:
return {"actions": []}
state["bought"] = True
return {"actions": [{
"type": "submit_order",
"order": {
"ticker": ticker["id"],
"side": "buy",
"order_type": {"type": "market"},
"quantity": quantity,
"time_in_force": {"type": "good_till_canceled"},
},
}]}
def store_state(params):
return {"state": {"bought": sessions[params["session"]]["bought"]}}
def restore_state(params):
sessions[params["session"]]["bought"] = bool(params["state"]["bought"])
return {}
METHODS = {
"initialize": initialize,
"validate": validate,
"setup": setup,
"step": step,
"parameters": lambda params: {"parameters": {"period": 20}},
"store_state": store_state,
"restore_state": restore_state,
}
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
request = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
method, params = request["method"], request.get("params", {})
reply = {"jsonrpc": "2.0", "id": request.get("id")}
if method == "terminate":
sessions.pop(params.get("session"), None)
reply["result"] = {}
elif method not in METHODS:
reply["error"] = {"code": -32601, "message": "method not found"}
elif method != "initialize" and params.get("session") not in sessions:
reply["error"] = {"code": -32001, "message": "unknown session"}
else:
try:
reply["result"] = METHODS[method](params)
except ValueError as refusal:
reply["error"] = {"code": -32000, "message": str(refusal)}
body = json.dumps(reply).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
HTTPServer(("127.0.0.1", 9000), Handler).serve_forever()Run it:
python minimal_trend.pyThen add the Remote algorithm to a simulation with one instrument, set
URL to http://127.0.0.1:9000/, and start the run. The moving average
appears on the run's chart, drawn from the values the engine computed.
The example leaves out what a real program needs: removing sessions it has
not heard from for a while (the terminate notification is sent on a best
effort and can be lost), and a seeded generator if it decides anything at
random.
Related
- Plugin authoring: the same contract in Rust, inside the engine
- Determinism rules
- Algorithm setup: adding an algorithm to a simulation in the app
- Built-in algorithms
- API reference: the algorithm catalog over the API