Plugin authoring
The anatomy of a Neurotrader algorithm plugin: the trait you implement, parameters, indicators, orders, state, tests, builds and compatibility with the engine.
You want to write a trading algorithm of your own in Rust and have Neurotrader run it like a built-in one. This page describes every part of a plugin and what the engine expects from it. For a guided first build, follow First plugin and come back here for the detail.
The examples are taken from the plugin skeleton, a public project made to be copied: github.com/sigmastone-io/neurotrader-plugin-skeleton.
Plugin shape
A plugin is a Rust library built as a native dynamic library (.dll on
Windows, .so on Linux, .dylib on macOS). The engine loads it into its own
process. One library can publish any number of algorithms.
Two things make a crate a plugin:
- It is built as a
cdylib. - It invokes
export_algorithms!once at the crate root, naming every algorithm it publishes.
[dependencies]
serde_json = "1.0.154"
[dependencies.serde]
features = ["derive"]
version = "1.0.229"
[dependencies.neurotrader-sdk]
branch = "dev"
git = "https://github.com/sigmastone-io/neurotrader-sdk.git"
[lib]
crate-type = ["cdylib"]
[profile.release]
panic = "unwind"pub mod trend;
use trend::TrendAlgorithm;
neurotrader_sdk::export_algorithms!(TrendAlgorithm);The macro generates everything the engine needs to find and call your
algorithms. You write no extern "C" code yourself. To publish several
algorithms from one library, name them all in the one invocation:
neurotrader_sdk::export_algorithms!(TrendAlgorithm, MeanReversionAlgorithm, BreakoutAlgorithm);Each named type must offer two associated functions and implement the
Adapter trait:
pub fn new(parameters: Option<Value>) -> Self
pub fn definition() -> Definitionnew must not fail. Bad parameters are refused later, in validate, where
the engine can report them to the user.
No panic = abort
The generated functions catch a panic in your code and report it to the
engine as an error. With panic = "abort" there is nothing to catch, and a
panic in your algorithm ends the whole engine. Nothing can detect that
setting at load, so keep panic = "unwind" in every profile.
Adapter trait
An algorithm implements neurotrader_sdk::quant::algorithm::Adapter. Import
the names you need from the prelude:
use neurotrader_sdk::prelude::*;| Method | Required | Call time | Purpose |
|---|---|---|---|
definition | Yes | Any time | The catalog entry: id, name, description, parameters |
parameters | Yes | Any time | The parameters this instance was created with |
validate | Yes | Before a run starts | Refuse a setup this strategy cannot trade |
setup | Yes | Once, before the first step | Resolve tickers and indicator handles, reset state |
step | Yes | Once per step | The strategy: candles in, actions out |
indicators, indicator_set, indicator_set_mut | If you use indicators | Before and during a run | Declare indicators and give them a place to live |
seed | No | Once, before setup | Receive the seed for random decisions |
fills | No | Before step, when orders traded | Learn which order each execution belongs to |
store_state, restore_state | No | On pause and on resume | Keep what only the algorithm knows |
The trait also has two provided methods, initialize and run. These are
what the engine really calls. initialize builds the indicators you declared
and then calls your setup. run feeds the new candles to those indicators
and then calls your step.
setup and step, not initialize and run
If you override initialize or run, your indicators are never built or
never updated, and nothing tells you. Write setup and step and leave the
provided methods alone.
Definition and identity
definition() returns what the Algorithms page shows about your
algorithm.
pub fn definition() -> Definition {
Definition {
id: Self::id(),
name: "Trend".to_owned(),
description: "Buys when the price crosses above its moving average, and sells when it crosses back below.".to_owned(),
category: HashSet::from([Category::TechnicalAnalysis]),
parameter_schema: Some(json!({
"type": "object",
"properties": {
"period": {
"type": "integer",
"title": "Period",
"description": "Window of the moving average, in candles",
"minimum": 2,
"default": 20,
"ui:widget": "spinbox",
"ui:step": 1
}
},
"required": ["period"]
})),
indicators: Some(declaration(Parameters::default())),
}
}
pub fn id() -> AlgorithmId {
"9c1f0a52-4d3b-4e77-9a10-2f6b8c5d1e40".into()
}| Field | Meaning |
|---|---|
id | A UUID you choose once and never change |
name, description | Shown in the catalog and wherever the algorithm is picked |
category | One or more of Ai, Stochastic, TechnicalAnalysis, EventDriven, Fundamental, VolatilityBased, SimpleBaseline, Test |
parameter_schema | The form the app shows for the parameters, or None |
indicators | The indicator declaration with default parameters, or None |
The id is the durable name of the algorithm. Simulations store it, and so do the records of finished runs. You choose it, so a simulation set up on one computer still finds the algorithm on another. Generate a fresh UUID for every new algorithm. The engine refuses a library that publishes an id another library already provides.
The library itself has a name too: the package name in your Cargo.toml. The
engine files the library under that name. Building again under the same name
is an update of the same plugin. A different package name is a different
plugin.
Parameters
Parameters arrive in new as JSON, or as None when the user set nothing.
Deserialize them into a struct of your own with defaults for every field:
#[derive(Serialize, Deserialize, Clone, Copy, Debug)]
#[serde(default)]
pub struct Parameters {
/// Window of the moving average, in candles.
pub period: usize,
}
impl Default for Parameters {
fn default() -> Self {
Self { period: 20 }
}
}pub fn new(parameters: Option<Value>) -> Self {
let parameters: Parameters = serde_json::from_value(parameters.unwrap_or(json!({}))).unwrap_or_default();
// ...
}parameters() returns the same values back as JSON, so a run's record says
what the instance was configured with:
fn parameters(&self) -> Option<Value> {
serde_json::to_value(self.parameters).ok()
}Parameter schema
parameter_schema is a JSON Schema object. The app builds the parameter form
from it: one field per property, with title as the label and description
as the help text. default, minimum, maximum, exclusiveMinimum,
exclusiveMaximum, enum and required are honoured.
Two extra keys choose the control:
| Key | Values |
|---|---|
ui:widget | spinbox, slider, text, checkbox, switch, dropdown |
ui:step | The amount a spinbox or slider moves by |
Without ui:widget the control follows the property's type. A slider needs
both a minimum and a maximum. Without them the app shows a spinbox. The form
is flat: nested objects are not rendered as groups.
A user can leave a field that is not required empty, and then it is not
sent. Give every field a default in your struct so an omitted one still has a
value.
Validation
validate receives the tickers this instance will read and decides whether
the strategy can trade them. It runs before the run starts, so a refusal
reaches the user as a message and not as a run that does nothing.
fn validate(&self, tickers: Vec<Ticker>) -> Result<(), AlgorithmError> {
if tickers.len() != 1 {
return Err(AlgorithmError::ValidationError(format!(
"Trend trades exactly one pair, but it was given {}.",
tickers.len()
)));
}
Ok(())
}Write the message for the person who set up the simulation. Check here what only your algorithm has an opinion about: how many instruments it needs, which roles they play, whether the parameters make sense together. Indicator parameters are checked for you against the indicator's own rules.
Indicators
You declare the indicators you need and read their values. You do not compute them, feed them candles or save them across a pause. The SDK does all three inside your plugin.
The declaration is a JSON document returned as a string from indicators():
fn declaration(parameters: Parameters) -> Value {
json!({
"version": CURRENT_VERSION,
"indicators": [
{
"name": "trend",
"kind": "sma",
"params": { "period": parameters.period },
"source": "first",
"label": format!("SMA {}", parameters.period)
}
]
})
}It belongs to the instance, because a parameter can change a period. Build it
from the parameters in new, keep it as a String, and give the trait the
three accessors:
fn indicators(&self) -> Option<&str> {
Some(&self.declaration)
}
fn indicator_set(&self) -> Option<&IndicatorSet> {
Some(&self.indicators)
}
fn indicator_set_mut(&mut self) -> Option<&mut IndicatorSet> {
Some(&mut self.indicators)
}The struct holds an IndicatorSet field, created with
IndicatorSet::default(). An algorithm that declares indicators without
giving them this place to live is refused before the run starts.
| Entry field | Meaning |
|---|---|
name | Your name for the indicator. It is also the column in the run's indicator data and the label of the line on a chart. It cannot contain . or @. |
kind | sma, ema, bollinger, rsi, roc, macd, donchian or atr |
params | The kind's own parameters, for example { "period": 20 }. An unknown key is refused. |
source | Which instrument feeds it: "first" (the default), "all" for one copy per instrument, { "ticker_id": "..." } or { "symbol": "...", "market": "..." } |
label | Optional display name |
A kind that produces several values names each one <name>.<output>. A
Bollinger entry named bb gives bb.upper, bb.middle and bb.lower. A
kind with one value keeps exactly the name you gave it. With "source": "all"
each series also carries the instrument, as in bb.upper@BTCEUR.
Look the handle up once in setup and read the value in step:
// in setup
self.trend = self.indicators.handle("trend");
// in step
let average = self.indicators.value(handle);
if !average.is_finite() {
return vec![];
}handle_output("bb", "upper") addresses one output of a multi-value kind.
handle_on and handle_output_on take a ticker id for a fanned-out entry.
NaN before a full window
An indicator returns NaN, never 0.0, while it is warming up. Zero would
be a plausible reading. Test with is_finite() before you trade on a value.
The value you read in step already includes the candle that just closed.
Step input
fn step(
&mut self,
holdings: &HashMap<AssetId, Holding>,
open_orders: &[Order],
market_state: &HashMap<TickerId, OHLC>,
account: &AccountView,
) -> Vec<Action>| Argument | Content |
|---|---|
holdings | The account's balance per asset. free() is what you can spend, frozen() is held against resting orders. |
open_orders | Every order of this instance that is still working: not filled, not cancelled, not expired. Oldest first. |
market_state | The candles that closed at this step, by ticker id |
account | The account beyond its balances: equity, liabilities, margin_level, margin_call, liquidated, what is borrowed per asset, and the margin terms |
Three rules follow from how the engine steps.
A step is a moment in time, not a candle. market_state holds only the
candles that closed at this moment. An instrument can be missing: it has a
coarser interval, the data has a gap, or a live feed is quiet. The map can
even be empty. Never index it by a ticker you assume is there. Use get, and
decide what a missing price means for your rule. Skipping the step is the
usual answer.
Open orders are given to you, not remembered by you. You know what you
asked for. Only the broker knows what became of it: whether an entry filled,
whether a stop is still in place. Read open_orders on every step instead of
keeping your own list.
On a spot account the account view is harmless. margin_level is
infinite, terms is None and borrowing_capacity returns zero. A strategy
written for margin does not misbehave on a spot account.
If your strategy works several orders on one instrument and must know which
order each execution belongs to, implement fills. The engine calls it just
before step whenever orders traded, with one FillReport per execution
(the order, its parent if the broker created it, the ticker, the side and the
fill). Most strategies do not need it.
Step output
step returns a list of actions. An empty list is a decision to do nothing.
| Action | Effect |
|---|---|
Action::SubmitOrder { initiator, order } | Place a new order |
Action::CancelOrder { initiator, order_id } | Withdraw a pending order and release what it froze |
Action::CloseOrder { initiator, order_id } | Close an open order, taking the gain or loss |
Leave initiator at AlgorithmInstanceId::default(). The engine stamps the
real instance on every action you return.
vec![Action::SubmitOrder {
initiator: AlgorithmInstanceId::default(),
order: Order::new_market_order(ticker, side, quantity, TimeInForce::GoodTillCanceled),
}]Orders
Build an order with one of the constructors. Each takes the ticker, the side
(OrderSide::Buy or OrderSide::Sell), the quantity in the base asset, its
prices, and the time in force.
| Constructor | Prices |
|---|---|
Order::new_market_order | None |
Order::new_limit_order | price |
Order::new_stop_market_order | stop_price |
Order::new_stop_limit_order | stop_price, limit_price |
Order::new_take_profit_order | trigger_price |
Order::new_stop_loss_order | trigger_price |
Time in force is GoodTillCanceled, ImmediateOrCancel, FillOrKill or
GoodTillDate(timestamp).
To trade with borrowed funds on a margin account, add
.with_leverage(level) to the order. The level must be one the account
offers (account.offers(level)). Every constructor defaults to 1.0, which
borrows nothing.
Order timing
- An order never fills on the candle that produced it. Actions you return while looking at one candle are worked against the next one. A market order fills at the next candle's open.
- Size a buy with headroom. The quantity is computed from the close you saw, and the fill happens at the next open. A buy sized to the last cent is rejected if the price opened higher. The skeleton leaves 1% aside.
- Actions are worked in the order you return them.
- There is no amend. To move a resting order, cancel it and submit a new one, with the cancel first in the list. The cancel releases the frozen balance before the replacement asks for it. A strategy that recomputes a level on every candle should replace the order only when the level has moved enough to matter.
State across a pause
A paused run is written to disk and the algorithm instance is discarded. On
resume a new instance is created, setup runs, and then restore_state
receives what store_state returned.
Store only what the algorithm alone knows:
fn store_state(&self) -> Option<Value> {
serde_json::to_value(self.state).ok()
}
fn restore_state(&mut self, state: &Value) -> Result<(), AlgorithmError> {
self.state =
serde_json::from_value(state.clone()).map_err(|error| AlgorithmError::InvalidParameters("Trend".to_owned(), error.to_string()))?;
Ok(())
}What does not belong there:
- Indicators. The SDK saves and restores the declared indicators for you.
- Orders and balances. They come back from the broker.
Typical state is small: which side of an average the price was on, a position
in a schedule, the cursor of a random generator. Return an error from
restore_state if you cannot read the payload. A run that resumes half
restored makes different decisions from the ones it was making, which is worse
than a run that refuses to resume.
Reset your state in setup, so an instance starts every run clean.
Instances and shared state
The library is loaded once. Two runs at the same time, or one comparison, can hold several instances of your algorithm at once.
- An instance's own fields need no locking. The engine never has two threads inside one instance.
- Anything in a
staticis shared by every instance. Synchronize it yourself, or better, do not use one. - Do not start threads or timers that outlive the call that started them. The engine can unload the library when no instance is alive, and code still scheduled at that moment crashes.
A plugin runs with the engine's memory and the engine's permissions. There is
no sandbox, no time limit on step and no memory limit. Load only plugins you
trust, and keep step fast.
Logging
Log through the tracing crate that the SDK re-exports, under the one target
the engine keeps for algorithms:
use neurotrader_sdk::tracing;
tracing::debug!(target: targets::ALGORITHM, "Trend: {} crossed while an order was working; skipping.", ticker);Do not add tracing as a dependency of your own: your events would go to a
second logger nobody reads. Write target: with a colon. target = also
compiles, and the event is then filed where the engine's filter drops it.
Tests
An algorithm is a plain struct, so cargo test can exercise it without an
engine. Call the same methods the engine calls: new, parameters,
indicators, and the provided run.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_parameters_fall_back_to_the_defaults() {
let algorithm = TrendAlgorithm::new(None);
assert_eq!(algorithm.parameters(), Some(json!({ "period": 20 })));
}
#[test]
fn the_declaration_follows_the_period() {
let algorithm = TrendAlgorithm::new(Some(json!({ "period": 50 })));
let declaration: Value = serde_json::from_str(algorithm.indicators().unwrap()).unwrap();
assert_eq!(declaration["indicators"][0]["params"]["period"], 50);
}
#[test]
fn a_step_before_setup_does_nothing() {
let mut algorithm = TrendAlgorithm::new(None);
let actions = algorithm.run(&HashMap::new(), &[], &HashMap::new(), &AccountView::default());
assert!(actions.is_empty());
}
}Tests show that the code does what the tests cover. Whether the strategy trades as you intend is shown by a simulation: run the plugin over real data and read every order it places.
Builds
cargo build --releaseThe library lands in target/release/, named after the [lib] name:
neurotrader_plugin_skeleton.dll, libneurotrader_plugin_skeleton.so or
libneurotrader_plugin_skeleton.dylib.
Build for the platform the engine runs on. A library for another platform is refused with a message saying so.
You need Rust 1.85 or newer (the SDK uses the 2024 edition) and, on Windows,
Microsoft's C++ Build Tools. cargo fetches the SDK from its public
repository over HTTPS. No key or account is needed.
To get the built library into the engine, see Plugin upload.
Versions and compatibility
The SDK carries the version of the boundary between a plugin and the engine,
neurotrader_sdk::abi::ABI_VERSION. Your library reports the version it was
built with, and the engine reads that before anything else.
- A different boundary version is refused at load, never in the middle of a run. Rebuild the plugin against the SDK version the engine accepts.
- The Rust compiler version does not matter. The plugin and the engine can be built by different compilers.
- The SDK crate version is recorded, not checked. The engine keeps it with the plugin's entry so you can tell which build is loaded.
- Additions do not break older plugins. A plugin built before a newer optional feature (fill reports, the margin account view) still loads and runs. It is not told about fills, and it places spot orders.
The engine checks a new library in a separate process before it keeps it: the version matches, the required functions are there, and the list of algorithms can be read. A library that crashes while loading is refused and the engine keeps running.
Related
- First plugin: the walkthrough
- Plugin SDK: the crate's modules and types
- Determinism rules: what keeps a run repeatable
- Plugin upload: loading the built library
- Remote algorithms: the alternative in any language