Plugin SDK
What the neurotrader-sdk crate holds, module by module, what it deliberately leaves out, and where the crate and its API documentation live.
You are writing a plugin and want to know what the SDK gives you, where a type lives and what you should not expect to find. This page is the map. For how the parts are used together, see Plugin authoring.
Crate
| Crate name | neurotrader-sdk (library name neurotrader_sdk) |
| Source | github.com/sigmastone-io/neurotrader-sdk |
| Licence | Mozilla Public License 2.0 |
| Rust | 2024 edition, toolchain 1.85 or newer |
| Starting project | github.com/sigmastone-io/neurotrader-plugin-skeleton (MIT No Attribution) |
Add the SDK to a plugin as a git dependency:
[dependencies.neurotrader-sdk]
branch = "dev"
git = "https://github.com/sigmastone-io/neurotrader-sdk.git"The repository is public and cargo fetches it over HTTPS. The two crates
the SDK itself depends on, neurotrader-market-data and id-type, are public
in the same way. No key or account is needed.
The licence applies file by file. Changes to the SDK's own files are shared under the same terms. A plugin you build on the SDK is your own work, and you can license it as you choose, closed source included.
API documentation
The API documentation is the crate's own rustdoc. Every public item carries a comment that says what it is for and why it is shaped the way it is. Build it from your plugin project, for the exact SDK version your plugin uses:
cargo doc --no-deps -p neurotrader-sdk --openPrelude
One import brings in what nearly every algorithm needs:
use neurotrader_sdk::prelude::*;| From | Names |
|---|---|
quant::algorithm | Adapter, AlgorithmError, AlgorithmId, Category, Definition |
quant::indicators | CURRENT_VERSION, Handle, IndicatorSet |
quant | Interval, OHLC, Period, Schedule, Timestamp |
trading | AccountView, Action, Holding, Liability, MarginTerms, OcoGroupId, Order, OrderId, OrderSide, OrderStatus, OrderType, TimeInForce |
algorithm_instance | AlgorithmInstanceId |
determinism | Prng |
logging | targets |
neurotrader_market_data | AssetId, Ticker, TickerId |
Modules
quant::algorithm
The contract itself.
| Item | Description |
|---|---|
Adapter | The trait every algorithm implements |
Definition | The catalog entry: id, name, description, category, parameter_schema, indicators |
AlgorithmId | The UUID you choose for an algorithm |
Category | Ai, Stochastic, TechnicalAnalysis, EventDriven, Fundamental, VolatilityBased, SimpleBaseline, Test |
AlgorithmError | NotFound, InvalidParameters, ValidationError, ExecutionError |
Adapter at a glance:
fn definition(&self) -> &Definition;
fn parameters(&self) -> Option<Value>;
fn validate(&self, tickers: Vec<Ticker>) -> Result<(), AlgorithmError>;
fn setup(&mut self, tickers: Vec<Ticker>) -> Result<(), AlgorithmError>;
fn step(
&mut self,
holdings: &HashMap<AssetId, Holding>,
open_orders: &[Order],
market_state: &HashMap<TickerId, OHLC>,
account: &AccountView,
) -> Vec<Action>;
// Optional, with defaults.
fn indicators(&self) -> Option<&str>;
fn indicator_set(&self) -> Option<&IndicatorSet>;
fn indicator_set_mut(&mut self) -> Option<&mut IndicatorSet>;
fn seed(&mut self, seed: u64);
fn fills(&mut self, fills: &[FillReport]);
fn store_state(&self) -> Option<Value>;
fn restore_state(&mut self, state: &Value) -> Result<(), AlgorithmError>;The trait also provides initialize, run, capture and restore, which
the engine calls and which wrap your setup, step, store_state and
restore_state with the indicator handling. Do not override them.
quant::indicators
The declaration format, the indicators and the set that holds them.
| Item | Description |
|---|---|
Declaration, Entry, Source | The JSON document an algorithm returns from indicators() |
CURRENT_VERSION | The declaration version to write in the document |
Kind | The registry of indicator kinds |
IndicatorSet | The built indicators of one instance |
Handle | An index to one series in a set |
SMA, EMA, BollingerBands, RSI, ROC, MACD, Donchian, ATR | The indicators themselves |
Indicator kinds a declaration can name:
kind | Indicator | Reads |
|---|---|---|
sma | Simple moving average | Close |
ema | Exponential moving average | Close |
bollinger | Bollinger bands: upper, middle, lower | Close |
rsi | Relative strength index, Wilder smoothing | Close |
roc | Rate of change | Close |
macd | MACD, three series | Close |
donchian | Donchian channel, including the current candle | High and low |
atr | Average true range, Wilder smoothing | High, low and the previous close |
IndicatorSet methods an algorithm uses:
| Method | Returns |
|---|---|
handle(name) | The handle of a single-value indicator |
handle_on(name, ticker) | The same, for one instrument of a fanned-out entry |
handle_output(name, output) | One output of a multi-value indicator |
handle_output_on(name, output, ticker) | One output for one instrument |
value(handle) | The current value, NaN during warm-up |
value_of(name) | The current value by name, for occasional use |
A lookup that matches more than one series returns None, not the first
match.
quant
| Item | Description |
|---|---|
OHLC | One candle. Accessors: open_time, close_time, open, high, low, close, volume, quote_asset_volume, number_of_trades, taker_buy_base_asset_volume, taker_buy_quote_asset_volume |
Timestamp | A point in time |
Interval | A candle interval |
Period, Schedule | A calendar or candle-count period, and a schedule that says once per period that the period has begun. For rules such as "every month". |
Bucketing | Where a candle's period begins, weeks and months included |
A Schedule carries its position and can be serialized. Save it in
store_state, or a resumed run acts twice in one period or skips one.
trading
Plain data: what an algorithm is told and what it asks for.
| Item | Description |
|---|---|
Action | SubmitOrder, CancelOrder, CloseOrder |
Order | An order. Built with new_market_order, new_limit_order, new_stop_market_order, new_stop_limit_order, new_take_profit_order, new_stop_loss_order; with_leverage sets the leverage |
OrderSide | Buy, Sell |
OrderType | Market, Limit, StopMarket, StopLimit, TakeProfit, StopLoss |
OrderStatus | Pending, Open, Triggered, PartiallyFilled, Filled, Canceled, Rejected, Expired |
TimeInForce | GoodTillCanceled, ImmediateOrCancel, FillOrKill, GoodTillDate |
Holding | One asset's balance: free(), frozen(), sum() |
Fill, FillReport | One execution, and the report that names its order |
AccountView | assets, liabilities, equity, margin_level, margin_call, liquidated, borrowings, terms; methods is_margin_account, offers, liability, borrowing_capacity |
Liability, MarginTerms | What is owed in one asset, and the account's leverage levels and margin bars |
Order fields are private. Read them through accessors such as id(),
ticker(), side(), order_type(), quantity(), status(),
filled_quantity() and average_fill_price().
determinism
| Item | Description |
|---|---|
Prng | The seeded random generator an algorithm draws from. Prng::new(seed), state(). |
RunSeed | The seed of a whole run, which the engine holds |
See Determinism rules.
algorithm_instance
AlgorithmInstanceId identifies one instance of an algorithm in a run. An
algorithm never creates one. It leaves Action::initiator at the default and
the engine fills in the real value.
logging
logging::targets::ALGORITHM is the one target an algorithm logs under. The
tracing crate is re-exported at the crate root as neurotrader_sdk::tracing
so that a plugin's log events reach the engine's log.
abi
The boundary between a plugin and the engine: ABI_VERSION, the record
layouts and the export_algorithms! macro. A plugin author uses the macro
and nothing else from this module.
neurotrader_sdk::export_algorithms!(TrendAlgorithm);Deliberate absences
The SDK holds what an algorithm author needs and nothing else. These are not in it, on purpose:
| Not in the SDK | Reason |
|---|---|
| Order simulation, fills and fees | The engine decides them the same way for every algorithm. A plugin that simulated its own fills could flatter itself. |
| Brokers and venue connections | An algorithm is the same in every operation mode. Where orders go is the engine's concern. |
| The data store and data providers | An algorithm is handed candles. It never reads a file or fetches data. |
| Runners, run records and result files | They belong to the engine. |
| The HTTP API, configuration and stored credentials | A plugin has no need to reach them. |
| The registry that loads algorithms | Loading is done by the engine through the Algorithms page or the API. |
| The built-in algorithms | They ship with the engine. Use the skeleton as a starting point. |
| An order amend | Moving an order is a cancel followed by a submit. See Order timing. |
| The run's interval | An algorithm is not told the candle interval of its run. A count of candles is a count, not a length of time. Use Period for calendar rules. |
The test for anything new is whether it makes sense in every operation mode. The same plugin runs on historical prices, on live prices with a simulated account, and with a broker.
Related
- Plugin authoring: how the parts are used
- Determinism rules
- First plugin
- Built-in algorithms
Plugin authoring
The anatomy of a Neurotrader algorithm plugin: the trait you implement, parameters, indicators, orders, state, tests, builds and compatibility with the engine.
Determinism rules
What a plugin must not do if the same run is to give the same result twice, and the seeded generator it draws its random decisions from.