Skip to Content
NeurotraderDocs
Developer guide

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 nameneurotrader-sdk (library name neurotrader_sdk)
Sourcegithub.com/sigmastone-io/neurotrader-sdk
LicenceMozilla Public License 2.0
Rust2024 edition, toolchain 1.85 or newer
Starting projectgithub.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 --open

Prelude

One import brings in what nearly every algorithm needs:

use neurotrader_sdk::prelude::*;
FromNames
quant::algorithmAdapter, AlgorithmError, AlgorithmId, Category, Definition
quant::indicatorsCURRENT_VERSION, Handle, IndicatorSet
quantInterval, OHLC, Period, Schedule, Timestamp
tradingAccountView, Action, Holding, Liability, MarginTerms, OcoGroupId, Order, OrderId, OrderSide, OrderStatus, OrderType, TimeInForce
algorithm_instanceAlgorithmInstanceId
determinismPrng
loggingtargets
neurotrader_market_dataAssetId, Ticker, TickerId

Modules

quant::algorithm

The contract itself.

ItemDescription
AdapterThe trait every algorithm implements
DefinitionThe catalog entry: id, name, description, category, parameter_schema, indicators
AlgorithmIdThe UUID you choose for an algorithm
CategoryAi, Stochastic, TechnicalAnalysis, EventDriven, Fundamental, VolatilityBased, SimpleBaseline, Test
AlgorithmErrorNotFound, 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.

ItemDescription
Declaration, Entry, SourceThe JSON document an algorithm returns from indicators()
CURRENT_VERSIONThe declaration version to write in the document
KindThe registry of indicator kinds
IndicatorSetThe built indicators of one instance
HandleAn index to one series in a set
SMA, EMA, BollingerBands, RSI, ROC, MACD, Donchian, ATRThe indicators themselves

Indicator kinds a declaration can name:

kindIndicatorReads
smaSimple moving averageClose
emaExponential moving averageClose
bollingerBollinger bands: upper, middle, lowerClose
rsiRelative strength index, Wilder smoothingClose
rocRate of changeClose
macdMACD, three seriesClose
donchianDonchian channel, including the current candleHigh and low
atrAverage true range, Wilder smoothingHigh, low and the previous close

IndicatorSet methods an algorithm uses:

MethodReturns
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

ItemDescription
OHLCOne 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
TimestampA point in time
IntervalA candle interval
Period, ScheduleA calendar or candle-count period, and a schedule that says once per period that the period has begun. For rules such as "every month".
BucketingWhere 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.

ItemDescription
ActionSubmitOrder, CancelOrder, CloseOrder
OrderAn 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
OrderSideBuy, Sell
OrderTypeMarket, Limit, StopMarket, StopLimit, TakeProfit, StopLoss
OrderStatusPending, Open, Triggered, PartiallyFilled, Filled, Canceled, Rejected, Expired
TimeInForceGoodTillCanceled, ImmediateOrCancel, FillOrKill, GoodTillDate
HoldingOne asset's balance: free(), frozen(), sum()
Fill, FillReportOne execution, and the report that names its order
AccountViewassets, liabilities, equity, margin_level, margin_call, liquidated, borrowings, terms; methods is_margin_account, offers, liability, borrowing_capacity
Liability, MarginTermsWhat 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

ItemDescription
PrngThe seeded random generator an algorithm draws from. Prng::new(seed), state().
RunSeedThe 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 SDKReason
Order simulation, fills and feesThe engine decides them the same way for every algorithm. A plugin that simulated its own fills could flatter itself.
Brokers and venue connectionsAn algorithm is the same in every operation mode. Where orders go is the engine's concern.
The data store and data providersAn algorithm is handed candles. It never reads a file or fetches data.
Runners, run records and result filesThey belong to the engine.
The HTTP API, configuration and stored credentialsA plugin has no need to reach them.
The registry that loads algorithmsLoading is done by the engine through the Algorithms page or the API.
The built-in algorithmsThey ship with the engine. Use the skeleton as a starting point.
An order amendMoving an order is a cancel followed by a submit. See Order timing.
The run's intervalAn 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.

On this page