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::LogSubscriptionHandle;
pub use subscriptions::RerouteContext;
pub use subscriptions::RerouteLegNotification;
pub use subscriptions::RerouteNotification;
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_program_diffs;
pub use subscriptions::subscribe_program_logs;
pub use subscriptions::subscribe_reroutes;
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.
rpc
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
Aggregated compute totals for a usage window.
Continue
Builder for Continue requests.
ContinueResult
Summary of responses collected while advancing a backtest.
CreateSession
Builder for CreateBacktestSession.
DiscoveryPause
A batch discovery paired with the pause location immediately before it.
SessionCounts
Raw backtest_session_* point counts for this api key in the window, by outcome — not session-deduplicated, so the three need not balance (a pre-start failure has no started; a cross-manager handoff re-emits started). Billing uses the compute totals, which derive only from the terminal completed/failed points.
SessionCoverage
Coverage of a session’s observed slot notifications and completion state.
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.
UsageReport
Response body of GET /usage.

Enums§

BacktestClientError
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.
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.
SerializeEncodeError
Error serializing a transaction for injection.

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