Skip to Content
NeurotraderDocs
Developer guide

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.

You run a backtest twice and expect the same orders, the same fills and the same final balance. Neurotrader guarantees that for everything the engine controls. The rest is your algorithm's part. This page lists the rules a plugin follows to keep its half of the promise, and shows the seeded generator to use when a strategy needs chance.

Engine promise

Everything the engine controls depends on two things only: the market data and one number, the run's seed.

  • The order in which candles arrive
  • Which orders fill, at what price, with what fee
  • The values of the indicators you declared
  • The one random choice the simulator makes: when a single candle reaches both orders of a one-cancels-the-other pair, nothing in the candle says which price came first, so the simulator draws the winner from the seed

Each run records its seed with its results. The same simulation over the same data with the same seed is the same run.

The engine cannot make the same promise for your code. A plugin is native code, and nothing stops it from reading the clock or the network. The engine gives every algorithm instance a seed and records it. Using that seed, and nothing else that varies, is the author's side of the contract.

Rules

Do notReasonAlternative
Read the system clockThe time of a backtest is the candle's time, not today'sUse candle.open_time() and candle.close_time() from market_state
Use rand::rng() or any generator you did not seed from seedIts values differ on every runDraw from a Prng seeded in seed
Call the networkThe answer can change, arrive late or failDecide from the candles, holdings, orders and account you are handed
Read or write filesA file can change between two runs, and a plugin is given no storage of its ownTake configuration as parameters, and keep state in store_state
Start threads or timersTheir timing is not repeatable, and code still scheduled when the library is unloaded crashes the engineDo all work inside the call, on the thread that called you
Keep run state in a staticIt is shared by every instance in the process and survives from one run to the nextKeep state in the instance's own fields and reset it in setup
Depend on the iteration order of a HashMapIt differs from run to run, and adding floating-point numbers in a different order gives a different sumIterate in a sorted order, or look up by key
Remember your own ordersWhat you asked for is not what happenedRead open_orders on every step

The engine checks none of these. A plugin that breaks one still loads and still runs. Its runs simply stop being repeatable, and the first sign is two backtests of the same setup that disagree.

holdings and market_state are HashMaps. Looking a key up is safe. Looping over one and summing, or emitting orders in loop order, is not. Sort the keys first:

let mut tickers: Vec<&TickerId> = market_state.keys().collect();
tickers.sort_by_key(|ticker| ticker.to_string());

open_orders is a slice in the broker's queue order, oldest first, and the fills handed to fills are sorted by order and then by time. Both are safe to iterate as they come.

Seeded generator

A strategy that decides something by chance draws from neurotrader_sdk::determinism::Prng. The engine calls seed once on every instance, before setup, with a number derived from the run's seed for that instance alone. Seed your generator there:

use neurotrader_sdk::prelude::*;
use rand::RngExt as _;
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Serialize, Deserialize, Clone, Copy)]
struct State {
    rng: Prng,
}

// A field of the algorithm: `state: State`, created with
// `State { rng: Prng::default() }`.

// Inside `impl Adapter for ...`:

fn seed(&mut self, seed: u64) {
    self.state.rng = Prng::new(seed);
}

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::ExecutionError(format!("saved state is not readable: {error}")))?;
    Ok(())
}

Then draw from it in step:

let roll: f64 = self.state.rng.random();
if roll < 0.5 {
    return vec![];
}

Prng implements the rand crate's generator trait, so every distribution and sampling helper in rand works with it. Add rand to your plugin at the version the SDK uses (0.10) to call them.

Three facts about Prng:

  • Its whole state is one number. state() returns it, and the type serializes as that number. That is what makes it possible to save.
  • Prng::default() is not random. It is a fixed stream, a placeholder an instance holds until seed is called. An algorithm that forgets to implement seed produces the same draws in every run, which shows up in a test at once.
  • It is not cryptographic. It is a fair, repeatable source of simulation decisions and nothing more.

Generator state across a pause

A paused run that is resumed gets the same seed again, not a new one. If you only seeded the generator in seed, the resumed run would repeat every draw the run had already made.

So save the generator in store_state and put it back in restore_state, as the example does. restore_state runs after seed and setup on a resumed run, so the restored position replaces the fresh one.

Independent instances

Every instance gets its own seed, derived from the run's seed and the instance's identity. Two instances of your algorithm in one comparison draw different numbers, and an instance draws the same numbers whether it runs alone or beside ten others. Adding a draw to one algorithm never changes what another does.

Do not share one generator between instances through a static. That would make each instance's numbers depend on how many the others drew first.

Repeatability and its limits

A run is repeatable when the simulation, the data and the seed are the same, and the plugin is the same build.

  • A rebuilt plugin is a different algorithm. Changing the code changes the run, by design.
  • A live run is not replayed. Live prices arrive once. The rules still matter there: a strategy that behaves the same way given the same inputs is the one whose backtest tells you something about its live behaviour.
  • A remote algorithm follows the same rules. Your program receives the seed in its first message. See Remote algorithms. A step that failed because the program could not be reached is part of that run's record, so a later run in which it answers is a different run.

On this page