sim-cli 0.23.0

CLI tool for running and comparing Solana simulator backtests
Documentation
mod commands;
mod output;
mod subscription;

use clap::{Args, Parser, Subcommand};
use commands::{
    bundle::{self, BundleBuildArgs, BundleDeleteArgs, BundleListArgs, BundleStatusArgs},
    compare::{self, CompareArgs},
    datasets::{
        self, DatasetCredentialsArgs, DatasetDeleteArgs, DatasetJobArgs, DatasetJobsArgs,
        DatasetListArgs, DatasetShowArgs, DepthArgs, DepthUniverseArgs, EstimatedFillsArgs,
        PredictArgs,
    },
    ranges::{self, RangesArgs},
    run::{self, RunArgs},
    summarize::{self, SummarizeArgs},
    update,
    usage::{self, UsageArgs},
};
use console::style;
use sim_cli::signals::{EXIT_INTERRUPTED, Interrupted, spawn_os_signal_handler};
use tokio_util::sync::CancellationToken;

const GETTING_STARTED: &str = "\
Getting started:
  export SIMULATOR_API_KEY=<your key>
  sim ranges              # slot ranges the server can replay
  sim run --start-slot <slot> --end-slot <slot> --program-id <program> \\
    --output-file baseline.ndjson
  sim summarize baseline.ndjson

Set RUST_LOG (e.g. RUST_LOG=info) for detailed logs.

Exit status:
  0    Success
  1    Error, or --fail-on-diff found a difference
  2    Usage error (unknown flag, missing or invalid value)
  130  `sim run` was stopped by Ctrl+C, SIGTERM or SIGQUIT before it finished;
       the output file is partial and has no `summary` line

Documentation: https://docs.termina.technology/documentation";

/// Run and compare Termina simulator backtests against historical Solana slots.
#[derive(Parser)]
#[command(name = "sim", version, after_help = GETTING_STARTED)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

/// The server a networked command talks to; local-file commands don't take it.
#[derive(Args)]
struct ServerArg {
    /// Server host, or a full ws:// or wss:// URL. A bare host connects over
    /// TLS.
    #[arg(
        long,
        env = "SIMULATOR_URL",
        default_value = "simulator.termina.technology"
    )]
    url: String,
}

#[derive(Subcommand)]
enum Command {
    /// Run a backtest simulation over a slot range
    ///
    /// When the server is busy, the run waits up to 15 minutes for capacity
    /// before failing.
    Run {
        #[command(flatten)]
        args: Box<RunArgs>,
        #[command(flatten)]
        server: ServerArg,
    },
    /// Compare two simulation output files (baseline vs experiment)
    Compare(CompareArgs),
    /// Extract and print a summary of a simulation output file
    Summarize(SummarizeArgs),
    /// Replace the sim binary with the latest build for this platform
    Update,
    /// List the slot ranges the server can replay
    Ranges {
        #[command(flatten)]
        args: RangesArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// Show API key usage metrics for a time window
    Usage {
        #[command(flatten)]
        args: UsageArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// Build, inspect and delete your custom bundles
    #[command(subcommand)]
    Bundle(BundleCommand),
    /// Generate, track and access datasets
    #[command(subcommand)]
    Datasets(DatasetsCommand),
}

#[derive(Subcommand)]
enum BundleCommand {
    /// Issue a bundle build over a slot range
    Build {
        #[command(flatten)]
        args: BundleBuildArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// Check the status of a previously-issued bundle build
    Status {
        #[command(flatten)]
        args: BundleStatusArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// List your bundle builds and custom bundles
    List {
        #[command(flatten)]
        args: BundleListArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// Delete one of your custom bundles
    Delete {
        #[command(flatten)]
        args: BundleDeleteArgs,
        #[command(flatten)]
        server: ServerArg,
    },
}

#[derive(Subcommand)]
enum DatasetsCommand {
    /// Print temporary read-only S3 credentials for the shared and this key's datasets
    Credentials {
        #[command(flatten)]
        args: DatasetCredentialsArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// Generate a dataset over a slot range
    #[command(subcommand)]
    Generate(GenerateCommand),
    /// What a dataset job samples
    #[command(subcommand)]
    Universe(UniverseCommand),
    /// Check the status of a dataset job
    Status {
        #[command(flatten)]
        args: DatasetJobArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// List this API key's dataset jobs, newest first
    Jobs {
        #[command(flatten)]
        args: DatasetJobsArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// Cancel a dataset job; rows it already wrote stay
    Cancel {
        #[command(flatten)]
        args: DatasetJobArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// List your own datasets
    List {
        #[command(flatten)]
        args: DatasetListArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// Show one dataset's versions, and with --date a date's partitions
    Show {
        #[command(flatten)]
        args: DatasetShowArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// Delete a slot range of your own dataset
    Delete {
        #[command(flatten)]
        args: DatasetDeleteArgs,
        #[command(flatten)]
        server: ServerArg,
    },
}

#[derive(Subcommand)]
enum UniverseCommand {
    /// Markets, venues and size rungs per depth source
    Depth {
        #[command(flatten)]
        args: DepthUniverseArgs,
        #[command(flatten)]
        server: ServerArg,
    },
}

#[derive(Subcommand)]
enum GenerateCommand {
    /// What each direct-fill template of a curated set would have filled
    EstimatedFills {
        #[command(flatten)]
        args: EstimatedFillsArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// The World BTC 5-minute prediction markets' tables across the range
    Predict {
        #[command(flatten)]
        args: PredictArgs,
        #[command(flatten)]
        server: ServerArg,
    },
    /// What each venue's liquidity would have filled, or the router quoted, at each size
    Depth {
        #[command(flatten)]
        args: DepthArgs,
        #[command(flatten)]
        server: ServerArg,
    },
}

/// Logs go to stderr, keeping them out of stdout's output. `RUST_LOG` sets the
/// level for every command; without it, `sim run --verbose` logs at `info`
/// and everything else at `warn`.
fn init_logging(verbose: bool) {
    let default_filter = if verbose { "info" } else { "warn" };
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(default_filter)),
        )
        .init();
}

#[tokio::main]
async fn main() {
    let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

    let cli = Cli::parse();
    init_logging(matches!(&cli.command, Command::Run { args, .. } if args.verbose));

    let cancellation = CancellationToken::new();
    // Only `run` observes the token; installing the tokio signal handler for
    // the other commands would swallow Ctrl+C instead of terminating them
    // (tokio replaces the OS SIGINT disposition process-wide).
    if matches!(cli.command, Command::Run { .. }) {
        spawn_os_signal_handler(cancellation.clone());
    }

    let result = match cli.command {
        Command::Compare(args) => compare::compare(args).await,
        Command::Summarize(args) => summarize::summarize(args),
        Command::Update => update::update().await,

        // With API key usage
        Command::Bundle(BundleCommand::Build { args, server }) => {
            bundle::build_bundle(args, server.url).await
        }
        Command::Bundle(BundleCommand::Status { args, server }) => {
            bundle::get_status(args, server.url).await
        }
        Command::Bundle(BundleCommand::List { args, server }) => {
            bundle::list_builds(args, server.url).await
        }
        Command::Bundle(BundleCommand::Delete { args, server }) => {
            bundle::delete_bundle(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::Credentials { args, server }) => {
            datasets::credentials(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::Generate(GenerateCommand::EstimatedFills {
            args,
            server,
        })) => datasets::generate_estimated_fills(args, server.url).await,
        Command::Datasets(DatasetsCommand::Generate(GenerateCommand::Predict { args, server })) => {
            datasets::generate_predict(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::Generate(GenerateCommand::Depth { args, server })) => {
            datasets::generate_depth(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::Universe(UniverseCommand::Depth { args, server })) => {
            datasets::depth_universe(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::Status { args, server }) => {
            datasets::status(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::Jobs { args, server }) => {
            datasets::jobs(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::Cancel { args, server }) => {
            datasets::cancel(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::List { args, server }) => {
            datasets::list(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::Show { args, server }) => {
            datasets::show(args, server.url).await
        }
        Command::Datasets(DatasetsCommand::Delete { args, server }) => {
            datasets::delete(args, server.url).await
        }
        Command::Ranges { args, server } => ranges::ranges(args, server.url).await,
        Command::Run { args, server } => run::run(*args, server.url, cancellation).await,
        Command::Usage { args, server } => usage::usage(args, server.url).await,
    };

    // Render failures as a single clean line (the error chain joined with `: `)
    // and exit non-zero. Avoids eyre's default `{:?}` dump with its `Location:`
    // and backtrace, which is noise for an operator reading run output.
    if let Err(e) = result {
        eprintln!("{} {:#}", style("✖").red().bold(), e);
        let code = if e.is::<Interrupted>() {
            EXIT_INTERRUPTED
        } else {
            1
        };
        std::process::exit(code);
    }
}