Expand description
Ergonomic async client for the simulator backtest WebSocket API.
This wraps the simulator-api request/response protocol with helpers for common
workflows (create session, wait ready, continue/advance, close), while still allowing full
access to raw BacktestRequest / BacktestResponse when needed.
The crate has two layers, and picking the right one matters:
ManagedBacktestSession(andmanaged::ManagedParallelSession) own the control and subscription WebSockets, keepalives, and — critically — reconnect and reattach. Use this layer.BacktestClient/BacktestSessionare one raw WebSocket with no reconnect and no reattach. A dropped connection ends the run. Reach for it only when driving the protocol by hand.
A backtest session outlives its WebSocket, but only if something reattaches to it — see Reconnects and session handoff.
§Quickstart
use simulator_client::{Continue, CreateSession, ManagedBacktestSession, managed::ManagedEvent};
let create = CreateSession::builder()
.start_slot(100)
.slot_count(10)
.build()
.into_request()?;
let mut session = ManagedBacktestSession::start(
"wss://simulator.termina.technology/backtest".to_string(),
"my-api-key".to_string(),
create,
)
.await?;
loop {
match session.next_event().await? {
ManagedEvent::ReadyForContinue => {
let advance = Continue::builder().advance_count(1).build().into_params();
session.send_continue(advance).await?;
}
ManagedEvent::Completed { .. } => break,
_ => {}
}
}
session.shutdown().await;§Reconnects and session handoff
The management service is a proxy: the session itself runs on a separate host and survives the loss of your control WebSocket. What it does not survive is nobody coming back for it.
The management service is redeployed routinely. On shutdown it pauses each
live session, records it as handed off, and closes the control WebSocket
with code 1012 (management handoff). The session then waits to be
claimed. A client that reconnects and sends AttachBacktestSession +
ResumeAttachedSession picks it up where it left off, replaying any
responses it missed from last_sequence. A client that treats the close as
fatal loses the run: the server reclaims the unclaimed session once
disconnect_timeout_secs elapses.
Not every disconnect is that graceful — a load balancer draining a target can reset the socket with no close frame at all — so treat any transport error as “reconnect and reattach”, not as a failed run.
ManagedBacktestSession does all of this for you: its control task
reconnects with backoff (managed::RECONNECT_MAX_ATTEMPTS attempts within
managed::RECONNECT_MAX_TOTAL) and re-handshakes with attach + resume. It
also defaults disconnect_timeout_secs to
managed::DEFAULT_DISCONNECT_TIMEOUT_SECS so the server holds the session
for at least as long as the client will keep trying.
On the raw BacktestSession this is yours to implement: reconnect with
BacktestClient::attach_session, passing the last sequence number you
observed, then BacktestSession::resume_attached_session. Set
disconnect_timeout_secs on the create request to a window that covers your
retry policy — the server’s own default is deliberately short (tens of
seconds).
§Low-level lifecycle notes
These describe BacktestClient / BacktestSession; the managed layer
handles all of it internally.
BacktestClient::create_sessionsendsCreateBacktestSessionand waits forSessionCreated, buffering other responses until the session is ready.BacktestSession::closesendsCloseBacktestSessionand then closes the WebSocket.- Dropping
BacktestSessionsends a best-effort WebSocket close frame if a Tokio runtime is available. Callcloseexplicitly to ensure server-side session cleanup. connect_timeoutgoverns the initial handshake;request_timeoutapplies to send/receive operations and can be overridden per call.- For streaming workflows, use
BacktestSession::responses(consumes the session) ornext_eventto keep readiness state in sync while consuming responses.
§Subscribe options
SubscribeConfig carries the cross-cutting options every subscribe accepts
(replayFromSlot, compression, intraSlotUpdates); merge it into a raw
subscribe’s params with SubscribeConfig::apply_to. This crate leaves every
field it doesn’t itself need unset, so those follow the server’s defaults —
notably accountSubscribe / programSubscribe deliver Agave-parity one
notification per account per slot unless you set intra_slot_updates.
use simulator_client::SubscribeConfig;
let mut params = serde_json::json!([ "<pubkey>", { "encoding": "base64" } ]);
SubscribeConfig {
intra_slot_updates: true,
..SubscribeConfig::default()
}
.apply_to(&mut params);Re-exports§
pub use geyser::SessionGeyserChannel;pub use injection::ProgramModError;pub use injection::build_program_injection;pub use injection::modify_program_via_rpc;pub use managed::ControlEvent;pub use managed::ManagedBacktestSession;pub use managed::ManagedEvent;pub use managed::ManagedSessionError;pub use subscriptions::AccountDiffContext;pub use subscriptions::AccountDiffNotification;pub use subscriptions::AccountDiffSubscriptionHandle;pub use subscriptions::ActionResultContext;pub use subscriptions::ActionResultNotification;pub use subscriptions::ActionSubscriptionHandle;pub use subscriptions::ActionTransactionOutcome;pub use subscriptions::DiagnosticContext;pub use subscriptions::DiagnosticNotification;pub use subscriptions::DiagnosticSubscriptionHandle;pub use subscriptions::LogSubscriptionHandle;pub use subscriptions::RoutedAccountDiffNotification;pub use subscriptions::SubscriptionError;pub use subscriptions::SubscriptionHandle;pub use subscriptions::SubscriptionRuntimeError;pub use subscriptions::UiAccountConversionError;pub use subscriptions::account_data_from_ui;pub use subscriptions::subscribe_account_diffs;pub use subscriptions::subscribe_account_diffs_many;pub use subscriptions::subscribe_actions;pub use subscriptions::subscribe_diagnostics;pub use subscriptions::subscribe_program_diffs;pub use subscriptions::subscribe_program_logs;pub use subscriptions::subscribe_replacements;pub use urls::UrlError;pub use urls::backtest_ws_url;pub use urls::http_to_ws_url;
Modules§
- geyser
- Reaching a session’s Yellowstone endpoint through the manager.
- injection
- managed
- Connection-managed wrappers over the backtest WebSocket protocol.
- recipes
- reroute_
report - The reroute-report core fed from
replacementSubscribenotifications. The computation — records, pricing, the reports themselves — lives insimulator_api::reroute_report; this module only maps the wire shape onto it. - rpc
- self
- One route, hop by hop: what the router quotes, what a decoded transaction reports, and what both are recorded and streamed as. Only the router names a pool; only a transaction’s route events name the program that ran a hop.
- subscriptions
- urls
Structs§
- Advance
State - Mutable state for driving a session with
advance_step. - Available
Range - One contiguous block range available on the history clerk.
- Backtest
Client - Backtest WebSocket client configured with a base URL and API key.
- Backtest
Session - Active backtest session over a WebSocket connection.
- Compute
Totals - A session contributes wholly to the window — or
UsageBucket— its run ended in, even when it ran across the boundary. - Continue
- Builder for
Continuerequests. - Continue
Result - Summary of responses collected while advancing a backtest.
- Create
Session - Builder for
CreateBacktestSession. - Depth
Coverage Response - What a depth request will actually sample, per source.
- Depth
Request - Request body of
POST /generate-depth. - Depth
Status Response - Response body of
POST /generate-depthandGET /generate-depth/{request_id}. - Direct
Fill Notification - One direct-fill probe’s result - the
DirectFillshape ofReplacementNotification: a single hop re-priced through a direct-fill template, simulated against the state it would have traded on. - Direct
Fill Template - One instruction the caller serialized, with the slots the server rewrites per probe and the
offset it writes the amount at. Matches hops of
modeoriginals tradinginputMint→outputMintand is priced against each such hop’s realized fill. - Discovery
Pause - A batch discovery paired with the pause location immediately before it.
- Original
Notification - One replayed original - the
Originalshape ofReplacementNotification: the historical transaction itself, re-run against the state it was quoted at, so the other two kinds are scored against a number produced the same way rather than against the chain’s. - Replacement
Context - The slot the payload was produced at, in the shape every other subscription’s context takes.
- Replacement
Core - The identity and ending every replacement payload carries, whatever kind it is.
- Requote
Notification - One rerouted transaction’s simulation result - the
Requoteshape ofReplacementNotification. The historical original still executed; this is the counterfactual, committed nowhere. - Reroute
LegNotification - One re-quoted swap within a rerouted transaction’s simulation.
- Route
Hop - Route
Plan - A whole route in the order its hops run. Deserialization bypasses
RoutePlan::new, so a plan read off the wire can still be empty. - Session
Counts - Point counts by outcome, not session-deduplicated, so the three need not
balance: a pre-start failure has no
started, a cross-manager handoff re-emits it. Billing uses the compute totals, which derive only from the terminal points. - Session
Coverage - Coverage of a session’s observed slot notifications and completion state.
- Session
Usage - One session that ran under the key, as its terminal event reported it.
- Session
Usage Page - Response body of
GET /usage/sessions. - Snapshot
Slot Response - Response of the management
/snapshot-slotendpoint. The chosen source and import state are internal, so only the resolved slot is exposed. - Subscribe
Config - Cross-cutting subscribe options the client sets in the config object.
- Taker
Slots - The account slots a probe rewrites, as indices into
instruction.accounts. - Template
Account - Template
Instruction - The template’s single instruction, sent verbatim except the role slots’ addresses and the amount bytes.
- Usage
Bucket - One UTC day of a
UsageReport, covering(start, end].endis the following midnight, except for a last bucket that ends at the report’suntil. - Usage
Report - Response body of
GET /usage.
Enums§
- Backtest
Client Error - Bundle
Build Status - Bundle
Kind - What a bundle build produces.
- Compression
- Compression negotiated for notification frames.
lowercaseso the variant matches the on-wire token ("zstd"). - Coverage
Error - Coverage validation failures for a backtest session.
- Depth
Source - Which side of a venue a depth run measures.
- Discovery
Filter - A filter registered at session creation describing which upcoming batches
the session should announce ahead of execution via
BacktestResponse::DiscoveryBatch(and its session-event twins). Each filter describes an event of interest (e.g. a specific program executing); the session “discovers” the batch in which that event will occur and emits aDiscoveryBatchso the client can pause immediately before it. - Discovery
Step Result - Result of a single
BacktestSession::advance_to_discoverycall. - Range
Bound - A slot number or a UTC timestamp, used to filter available ranges.
- Ready
Outcome - Outcome of waiting for readiness on a backtest session.
- Replacement
Notification - What stood in for a historical swap, streamed over
replacementSubscribe. Internally tagged onkind: three mechanisms answer different questions - metis re-routing a whole transaction, a probe re-pricing one hop, and the original replayed as its own baseline - so they carry different shapes rather than one union. - Serialize
Encode Error - Error serializing a transaction for injection.
- Swap
Mode - Whether the swap fixes the input amount (
ExactIn) or the output amount (ExactOut).
Constants§
- FULL_
PERCENT - The whole trade through one hop; anything less is a split.
Functions§
- filter_
ranges - Filter
rangesto those bookended by[after, before]: - split_
range - Split a user-requested
[start_slot, end_slot]range across the available bundle ranges, returning a list of contiguous, non-overlapping(start, end)pairs — one per bundle that the server can serve as its own session.