Skip to main content

Crate simulator_client

Crate simulator_client 

Source
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:

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_session sends CreateBacktestSession and waits for SessionCreated, buffering other responses until the session is ready.
  • BacktestSession::close sends CloseBacktestSession and then closes the WebSocket.
  • Dropping BacktestSession sends a best-effort WebSocket close frame if a Tokio runtime is available. Call close explicitly to ensure server-side session cleanup.
  • connect_timeout governs the initial handshake; request_timeout applies to send/receive operations and can be overridden per call.
  • For streaming workflows, use BacktestSession::responses (consumes the session) or next_event to 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 replacementSubscribe notifications. The computation — records, pricing, the reports themselves — lives in simulator_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§

AdvanceState
Mutable state for driving a session with advance_step.
AvailableRange
One contiguous block range available on the history clerk.
BacktestClient
Backtest WebSocket client configured with a base URL and API key.
BacktestSession
Active backtest session over a WebSocket connection.
ComputeTotals
A session contributes wholly to the window — or UsageBucket — its run ended in, even when it ran across the boundary.
Continue
Builder for Continue requests.
ContinueResult
Summary of responses collected while advancing a backtest.
CreateSession
Builder for CreateBacktestSession.
DatasetCredentialsResponse
Response of POST /datasets/credentials: temporary, read-only credentials plus a path, so a caller doesn’t need to reconstruct the S3 layout.
DepthCoverageResponse
What a depth request will actually sample, per source.
DepthRequest
Request body of POST /generate-depth.
DepthStatusResponse
Response body of POST /generate-depth and GET /generate-depth/{request_id}.
DirectFillNotification
One direct-fill probe’s result - the DirectFill shape of ReplacementNotification: a single hop re-priced through a direct-fill template, simulated against the state it would have traded on.
DirectFillTemplate
One instruction the caller serialized, with the slots the server rewrites per probe and the offset it writes the amount at. Matches hops of mode originals trading inputMint → outputMint and is priced against each such hop’s realized fill.
DiscoveryPause
A batch discovery paired with the pause location immediately before it.
L1Score
What the original filled on L1, and how the shape carrying this scored against it.
OriginalNotification
One replayed original - the Original shape of ReplacementNotification: 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.
ProbedHop
The hop a probe re-priced, as L1 and as the replay ran it.
ReplacementContext
The slot the payload was produced at, in the shape every other subscription’s context takes.
ReplacementCore
The identity and ending every replacement payload carries, whatever kind it is.
RequoteNotification
One rerouted transaction’s simulation result - the Requote shape of ReplacementNotification. The historical original still executed; this is the counterfactual, committed nowhere.
RerouteLegNotification
One re-quoted swap within a rerouted transaction’s simulation.
RouteHop
RoutePlan
A whole route in the order its hops run. Deserialization bypasses RoutePlan::new, so a plan read off the wire can still be empty.
SessionCounts
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.
SessionCoverage
Coverage of a session’s observed slot notifications and completion state.
SessionUsage
One session that ran under the key, as its terminal event reported it.
SessionUsagePage
Response body of GET /usage/sessions.
SnapshotSlotResponse
Response of the management /snapshot-slot endpoint. The chosen source and import state are internal, so only the resolved slot is exposed.
SubscribeConfig
Cross-cutting subscribe options the client sets in the config object.
TakerSlots
The account slots a probe rewrites, as indices into instruction.accounts.
TemplateAccount
TemplateInstruction
The template’s single instruction, sent verbatim except the role slots’ addresses and the amount bytes.
UsageBucket
One UTC day of a UsageReport, covering (start, end]. end is the following midnight, except for a last bucket that ends at the report’s until.
UsageReport
Response body of GET /usage.

Enums§

BacktestClientError
BundleBuildStatus
BundleKind
What a bundle build produces.
Compression
Compression negotiated for notification frames. lowercase so the variant matches the on-wire token ("zstd").
CoverageError
Coverage validation failures for a backtest session.
DepthGranularity
How often a depth run samples its source; each publishes its own dataset under the source.
DepthSource
Which side of a venue a depth run measures.
DiscoveryFilter
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 a DiscoveryBatch so the client can pause immediately before it.
DiscoveryStepResult
Result of a single BacktestSession::advance_to_discovery call.
RangeBound
A slot number or a UTC timestamp, used to filter available ranges.
ReadyOutcome
Outcome of waiting for readiness on a backtest session.
ReplacementNotification
What stood in for a historical swap, streamed over replacementSubscribe. Internally tagged on kind: 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.
SerializeEncodeError
Error serializing a transaction for injection.
SwapMode
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 ranges to 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.

Type Aliases§

BacktestClientResult