### Quick Start: Lighter Rust SDK Usage Source: https://github.com/yongkangc/lighter-rust/blob/master/README.md A basic example demonstrating how to initialize the LighterClient, configure API settings, and perform common operations like fetching account info and market data. ```rust use lighter_rust::{LighterClient, Config}; #[tokio::main] async fn main() -> Result<(), Box> { // Create configuration let config = Config::new() .with_api_key("your-api-key") .with_base_url("https://api.lighter.xyz")?; // Initialize client with private key for trading let client = LighterClient::new(config, "your-private-key")?; // Get account info let account = client.account().get_account().await?; println!("Account: {:?}", account); // Get market data let ticker = client.market_data().get_ticker("BTC-USDC").await?; println!("BTC-USDC Price: {}", ticker.price); Ok(()) } ``` -------------------------------- ### Basic Lighter Rust Client Setup Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Initialize logging, configure the Lighter client with an API key and timeout, and create a client instance using a private key. Demonstrates fetching account information. ```rust use lighter_rust::{LighterClient, Config, init_logging}; #[tokio::main] async fn main() -> Result<(), Box> { // Initialize logging init_logging(); // Configure the client let config = Config::new() .with_api_key("your-api-key") .with_timeout(30); // Create client with private key let client = LighterClient::new(config, "your-private-key-hex")?; // Fetch account information let account = client.account().get_account().await?; println!("Account ID: {}", account.id); Ok(()) } ``` -------------------------------- ### Run Lighter Rust SDK Examples Source: https://github.com/yongkangc/lighter-rust/blob/master/README.md Commands to run various examples provided with the Lighter Rust SDK, including basic usage, WebSocket streaming, and trading bots. ```bash cargo run --example basic_usage ``` ```bash cargo run --example websocket_example ``` ```bash cargo run --example trading_bot ``` -------------------------------- ### Lighter Rust Order Creation Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Provides examples for creating market and limit orders using the Lighter Rust SDK. Includes specifying symbol, side, order type, quantity, price, and time-in-force. ```rust use lighter_rust::{OrderType, Side, TimeInForce}; // Market order client.orders().create_order( "BTC-USDC", Side::Buy, OrderType::Market, "0.1", None, // No price for market orders None, None, None, None, ).await?; // Limit order with post-only client.orders().create_order( "ETH-USDC", Side::Sell, OrderType::Limit, "1.0", Some("3000.50"), None, Some(TimeInForce::Gtc), Some(true), // post_only None, ).await?; ``` -------------------------------- ### OpenAPI Generator Configuration Example Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md An example YAML configuration file for OpenAPI Generator, specifying Rust as the target language and various properties. ```yaml generatorName: rust outputDir: ../ inputSpec: https://api.lighter.xyz/openapi.json # or local file additionalProperties: packageName: lighter-rust packageVersion: 0.1.0 library: reqwest # HTTP client library supportAsync: true # Enable async/await supportMultipleResponses: true preferUnsignedInt: false bestFitInt: true hideGenerationTimestamp: true useSingleRequestParameter: false avoidBoxedModels: true ``` -------------------------------- ### Generate Documentation (Rust) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Generates and opens the project documentation using Cargo. ```bash cargo doc --open ``` -------------------------------- ### Install OpenAPI Generator (Homebrew) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Installs the OpenAPI Generator CLI using Homebrew, a package manager for macOS and Linux. ```bash brew install openapi-generator ``` -------------------------------- ### Install OpenAPI Generator (npm) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Installs the OpenAPI Generator CLI globally using npm, the Node Package Manager. ```bash npm install -g @openapitools/openapi-generator-cli ``` -------------------------------- ### Install Lighter Rust SDK Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Add the Lighter Rust SDK and Tokio to your Cargo.toml file. Supports specifying a version or using the latest development version from GitHub. ```toml [dependencies] lighter-rust = "0.1.0" tokio = { version = "1.0", features = ["full"] } ``` ```toml [dependencies] lighter-rust = { git = "https://github.com/yongkangc/lighter-rust" } tokio = { version = "1.0", features = ["full"] } ``` -------------------------------- ### Install OpenAPI Generator (Download JAR) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Downloads the OpenAPI Generator CLI JAR file directly using wget. ```bash wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.0.1/openapi-generator-cli-7.0.1.jar -O openapi-generator-cli.jar ``` -------------------------------- ### Build and Test Lighter Rust SDK Source: https://github.com/yongkangc/lighter-rust/blob/master/README.md Commands for building the project, running tests, executing examples, and generating documentation for the Lighter Rust SDK. ```bash # Build cargo build # Run tests cargo test # Run with examples cargo run --example basic_usage # Build documentation cargo doc --open ``` -------------------------------- ### OpenAPI Generator Ignore File Example Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md An example `.openapi-generator-ignore` file to prevent overwriting custom implementations during regeneration. ```bash # Custom implementations - do not overwrite src/signers/** src/nonce.rs src/lib.rs examples/** tests/** Cargo.toml README.md ``` -------------------------------- ### Rust Account Structure Example Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/Account.md Demonstrates how to create an instance of the Account structure in Rust, initializing its properties with sample data including nested structures for balances. This example utilizes the chrono crate for timestamps. ```rust use lighter_rust::Account; use chrono::Utc; // Example of Account structure let account = Account { id: "acc_123456".to_string(), address: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1".to_string(), tier: AccountTier::Premium, created_at: Utc::now(), updated_at: Utc::now(), balances: vec![ Balance { asset: "USDC".to_string(), total: "10000.50".to_string(), available: "9000.50".to_string(), locked: "1000.00".to_string(), }, ], positions: vec![], tier_switch_allowed_at: None, }; ``` -------------------------------- ### Install OpenAPI Generator (Docker) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Pulls the latest Docker image for the OpenAPI Generator CLI. ```bash docker pull openapitools/openapi-generator-cli ``` -------------------------------- ### Install Lighter Rust SDK Source: https://github.com/yongkangc/lighter-rust/blob/master/README.md Instructions for adding the Lighter Rust SDK to your project's Cargo.toml file, either from crates.io or directly from GitHub. ```toml [dependencies] lighter-rust = "0.1.0" ``` ```toml [dependencies] lighter-rust = { git = "https://github.com/yongkangc/lighter-rust" } ``` -------------------------------- ### Run Tests (Rust) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Executes the tests for the Rust project using Cargo. ```bash cargo test ``` -------------------------------- ### Example Usage: WebSocket Client Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/WebSocketClient.md Demonstrates connecting to a WebSocket, subscribing to order book and trade feeds, processing incoming messages, and cleaning up subscriptions. ```rust use lighter_rust::{Config, WebSocketClient}; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new() .with_ws_url("wss://ws.lighter.xyz")?; let mut ws_client = WebSocketClient::new(config); // Connect to WebSocket ws_client.connect().await?; println!("Connected to WebSocket"); // Subscribe to order book updates let orderbook_sub = ws_client.subscribe( "orderbook", Some(json!({ "symbol": "BTC-USDC", "depth": 10 })) ).await?; // Subscribe to trade feed let trades_sub = ws_client.subscribe( "trades", Some(json!({ "symbol": "BTC-USDC" })) ).await?; // Process messages loop { match ws_client.next_message().await? { Some(message) => { // Handle different message types if let Some(msg_type) = message.get("type") { match msg_type.as_str() { Some("orderbook") => handle_orderbook_update(&message), Some("trade") => handle_trade(&message), Some("error") => handle_error(&message), _ => {} } } } None => { println!("Connection closed"); break; } } } // Clean up ws_client.unsubscribe(&orderbook_sub).await?; ws_client.unsubscribe(&trades_sub).await?; ws_client.close().await?; Ok(()) } fn handle_orderbook_update(message: &serde_json::Value) { println!("Order book update: {:?}", message); } fn handle_trade(message: &serde_json::Value) { println!("New trade: {:?}", message); } fn handle_error(message: &serde_json::Value) { eprintln!("WebSocket error: {:?}", message); } ``` -------------------------------- ### Handle Comprehensive Error Types Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Provides an example of how to handle various errors returned by the SDK, including rate limiting, insufficient balance, API errors, and network issues, using a match statement. ```rust use lighter_rust::{LighterError, Result}; match client.orders().create_order(...).await { Ok(order) => println!("Order placed: {}", order.id), Err(e) => match e { LighterError::RateLimit => { println!("Rate limited, waiting before retry..."); tokio::time::sleep(Duration::from_secs(1)).await; }, LighterError::InsufficientBalance(msg) => { println!("Insufficient balance: {}", msg); }, LighterError::Api { status, message } => { println!("API error {}: {}", status, message); }, LighterError::Network(e) => { println!("Network error: {}", e); }, _ => println!("Unexpected error: {}", e), } } ``` -------------------------------- ### Initialize Custom Logging Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Shows how to initialize the SDK's logging system with custom log level filters to control the verbosity of output for different components. ```rust use lighter_rust::init_logging_with_filter; // Set custom log levels init_logging_with_filter("lighter_rust=debug,my_app=info"); // Logs will include: // - API requests and responses (debug level) // - WebSocket messages (trace level) // - Errors and warnings ``` -------------------------------- ### Lighter Rust Authentication with Private Key Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Demonstrates authenticating the Lighter client using a hex-encoded private key. ```rust let client = LighterClient::new(config, "0xYOUR_PRIVATE_KEY_HEX")?; ``` -------------------------------- ### Review Code Changes Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Reviews the changes made to the project after SDK generation using git diff. ```bash git diff ``` -------------------------------- ### GitHub Actions Workflow for SDK Generation Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md A GitHub Actions workflow that automatically triggers on a schedule to regenerate the Rust SDK. It installs OpenAPI Generator, generates the SDK, and commits/pushes changes if any are detected. ```yaml name: Generate SDK on: schedule: - cron: '0 0 * * 0' # Weekly workflow_dispatch: jobs: generate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install OpenAPI Generator run: npm install -g @openapitools/openapi-generator-cli - name: Generate SDK run: | cd .openapi-generator openapi-generator-cli generate -c generator-config.yaml - name: Check for changes run: | if [ -n "$(git status --porcelain)" ]; then git config user.name "GitHub Actions" git config user.email "actions@github.com" git add . git commit -m "chore: regenerate SDK from OpenAPI spec" git push fi ``` -------------------------------- ### Configure Lighter Rust SDK Source: https://github.com/yongkangc/lighter-rust/blob/master/README.md Example of configuring the Lighter SDK using the `Config` struct, including setting API keys, base URLs, WebSocket URLs, timeouts, and retry counts. ```rust use lighter_rust::Config; let config = Config::new() .with_api_key("your-api-key") .with_base_url("https://api.lighter.xyz")?; .with_ws_url("wss://ws.lighter.xyz")?; .with_timeout(30) .with_max_retries(3); ``` -------------------------------- ### Configure SDK with Retry Logic Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Shows how to configure the SDK client with custom settings, including API keys, maximum retries for failed requests, and request timeouts. ```rust let config = Config::new() .with_api_key("your-api-key") .with_max_retries(3) // Automatic retries .with_timeout(30); ``` -------------------------------- ### Generate SDK using Docker Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Generates the Rust SDK using Docker, mounting the current directory and specifying the configuration file. ```bash docker run --rm \ -v ${PWD}:/local openapitools/openapi-generator-cli generate \ -i /local/openapi.yaml \ -g rust \ -o /local \ -c /local/.openapi-generator/generator-config.yaml ``` -------------------------------- ### Lighter Rust Environment-Based Configuration Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Configures the Lighter client using environment variables for API key, private key, and API base URL, which is a recommended practice for production environments. ```rust use std::env; let api_key = env::var("LIGHTER_API_KEY")?; let private_key = env::var("LIGHTER_PRIVATE_KEY")?; let config = Config::new() .with_api_key(&api_key) .with_base_url(&env::var("LIGHTER_API_URL").unwrap_or_else(|_| "https://api.lighter.xyz/api".to_string() )); let client = LighterClient::new(config, &private_key)?; ``` -------------------------------- ### Generate SDK using Configuration File Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Generates the Rust SDK using a pre-configured YAML file within the .openapi-generator directory. ```bash # Navigate to the .openapi-generator directory cd .openapi-generator # Generate using the configuration openapi-generator-cli generate \ -c generator-config.yaml ``` -------------------------------- ### Lighter Rust Open Positions Retrieval Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Retrieves and displays information about open positions, including symbol, quantity, and average entry price. ```rust // Get open positions let positions = client.account().get_positions().await?; for position in positions { println!("{}: {} @ avg price {}", position.symbol, position.quantity, position.average_price); } ``` -------------------------------- ### Install Lighter Rust SDK Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/README.md This snippet shows how to add the Lighter Rust SDK as a dependency in your Rust project's Cargo.toml file. ```toml [dependencies] lighter-rust = "0.1.0" ``` -------------------------------- ### Generate Specific Files (Rust) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Generates specific supporting files for the Rust SDK, such as Cargo.toml and lib.rs. ```bash openapi-generator-cli generate \ -i openapi.yaml \ -g rust \ -o . \ --global-property supportingFiles="Cargo.toml,lib.rs" ``` -------------------------------- ### Manual SDK Generation (Rust) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Manually generates the Rust SDK with specified input, output, package name, library, and additional properties. ```bash openapi-generator-cli generate \ -i openapi.yaml \ -g rust \ -o . \ --package-name lighter-rust \ --library reqwest \ --additional-properties=supportAsync=true,supportMultipleResponses=true ``` -------------------------------- ### Lighter Rust Read-Only Client Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Creates a read-only Lighter client for accessing market data and public endpoints without the ability to place orders. ```rust let client = LighterClient::new_read_only(config)?; // Can fetch market data but cannot place orders ``` -------------------------------- ### Generate SDK with Custom Templates (Rust) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Generates the Rust SDK using custom templates located in the 'templates' directory. ```bash openapi-generator-cli generate \ -i openapi.yaml \ -g rust \ -o . \ -t templates ``` -------------------------------- ### Lighter Rust Account Balance Retrieval Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Fetches and displays account balances, including currency, total amount, and available amount. ```rust // Get account balances let balances = client.account().get_balances().await?; for balance in balances { println!("{}: {} (available: {})", balance.currency, balance.total, balance.available); } ``` -------------------------------- ### Implement Rate Limiting Awareness with Delays Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Demonstrates a best practice for handling rate limits by introducing small delays between batch operations to avoid exceeding API request limits. ```rust use tokio::time::{sleep, Duration}; // Batch operations with delays for order_id in order_ids { client.orders().cancel_order(Some(&order_id), None, None).await?; sleep(Duration::from_millis(100)).await; // Prevent rate limiting } ``` -------------------------------- ### Leverage Automatic Connection Pooling Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Explains that the SDK automatically manages connection pooling for efficient reuse of network connections when performing multiple operations. ```rust // Connections are reused automatically for symbol in ["BTC-USDC", "ETH-USDC", "SOL-USDC"] { let orders = client.orders().get_orders_for_symbol(symbol).await?; } ``` -------------------------------- ### Lighter Rust Authentication with Mnemonic Phrase Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Shows how to authenticate the Lighter client using a BIP39 mnemonic phrase, supporting different account indices for multiple wallets. ```rust // Using mnemonic with account index 0 let client = LighterClient::from_mnemonic( config, "your twelve word mnemonic phrase here...", 0 // account index )?; // Using different account indices for multiple accounts let client1 = LighterClient::from_mnemonic(config.clone(), mnemonic, 0)?; let client2 = LighterClient::from_mnemonic(config.clone(), mnemonic, 1)?; ``` -------------------------------- ### Lighter Rust Account Tier Management Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Checks the current account tier and demonstrates how to switch account tiers if no positions are open. Supports Standard and Premium tiers. ```rust use lighter_rust::{AccountTier, AccountApi}; // Check current tier let account = client.account().get_account().await?; match account.tier { AccountTier::Standard => println!("Standard tier - Basic features"), AccountTier::Premium => println!("Premium tier - Advanced features"), } // Switch tiers (requires no open positions) if client.account().can_switch_tier().await? { client.account().change_account_tier(AccountTier::Premium).await?; } ``` -------------------------------- ### Rust Balance Structure Example Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/Balance.md Demonstrates how to create and use the `Balance` struct in Rust. It includes initializing a `Balance` object with asset details and calculating the percentage of the balance that is locked. ```rust use lighter_rust::Balance; let balance = Balance { asset: "USDC".to_string(), total: "10000.50".to_string(), available: "8500.50".to_string(), locked: "1500.00".to_string(), }; // Calculate percentage locked let total: f64 = balance.total.parse().unwrap(); let locked: f64 = balance.locked.parse().unwrap(); let locked_percentage = (locked / total) * 100.0; println!("{}% of {} is locked", locked_percentage, balance.asset); ``` -------------------------------- ### Rust Project Setup with Cargo Source: https://github.com/yongkangc/lighter-rust/blob/master/plans/implementation-plan.md Initializes a new Rust project using Cargo, the Rust build system and package manager. This includes setting up the Cargo.toml file for dependency management and defining the basic project structure. ```bash cargo new lighter-rust-sdk cd lighter-rust-sdk # Edit Cargo.toml to add dependencies like tokio, reqwest, serde, alloy ``` -------------------------------- ### Place, Query, Cancel, and List Orders Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Demonstrates how to interact with the order management system. This includes placing a new limit order, querying its status, canceling it, and retrieving a list of open orders with specific filters. ```rust use lighter_rust::{OrderFilter, OrderStatus}; // Place an order let order = client.orders().create_order( "BTC-USDC", Side::Buy, OrderType::Limit, "0.01", Some("45000"), None, Some(TimeInForce::Gtc), None, None, ).await?; // Query order status let order_status = client.orders().get_order(&order.id).await?; println!("Order status: {:?}", order_status.status); // Cancel order client.orders().cancel_order(Some(&order.id), None, None).await?; // Get all open orders let filter = OrderFilter { status: Some(OrderStatus::Open), symbol: Some("BTC-USDC".to_string()), ..Default::default() }; let (orders, pagination) = client.orders().get_orders(Some(filter)).await?; ``` -------------------------------- ### Connect and Subscribe to WebSocket Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/README.md Shows how to establish a WebSocket connection using the Lighter Rust SDK, subscribe to real-time data like order books, and process incoming messages. ```rust use futures_util::StreamExt; use serde_json::json; let mut ws = client.websocket(); ws.connect().await?; let sub_id = ws.subscribe("orderbook", Some(json!({ "symbol": "BTC-USDC", "depth": 10 }))).await?; while let Some(msg) = ws.next_message().await? { println!("Received: {:?}", msg); } ``` -------------------------------- ### Migration Comparison: Python vs. Rust SDK Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Compares the initialization and order creation process between the Python and Rust SDKs. Highlights key differences such as async/await, error handling, type safety, memory management, and performance. ```Python from lighter import LighterClient client = LighterClient(api_key="key", private_key="0x...") account = client.get_account() order = client.create_order( symbol="BTC-USDC", side="buy", order_type="limit", quantity="0.1", price="45000" ) ``` ```Rust use lighter_rust::{LighterClient, Config, Side, OrderType}; let config = Config::new().with_api_key("key"); let client = LighterClient::new(config, "0x...")?; let account = client.account().get_account().await?; let order = client.orders().create_order( "BTC-USDC", Side::Buy, OrderType::Limit, "0.1", Some("45000"), None, None, None, None, ).await?; ``` -------------------------------- ### Initialize Lighter Client with API Key Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/README.md Demonstrates how to initialize the Lighter Rust SDK client with API key authentication and a base URL for making authenticated requests. ```rust use lighter_rust::{LighterClient, Config}; #[tokio::main] async fn main() -> Result<(), Box> { // Configure the client let config = Config::new() .with_api_key("your-api-key") .with_base_url("https://api.lighter.xyz")?; // Initialize with private key for trading let client = LighterClient::new(config, "your-private-key")?; // Get account information let account = client.account().get_account().await?; println!("Account: {:?}", account); Ok(()) } ``` -------------------------------- ### Get Open Positions - Rust Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/AccountApi.md Returns all open positions for the account. Requires an API key for authentication. ```rust use lighter_rust::{LighterClient, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new() .with_api_key("your-api-key"); let client = LighterClient::new(config, "your-private-key")?; let positions = client.account().get_positions().await?; for position in positions { println!("Symbol: {}, Side: {}, Size: {}", position.symbol, position.side, position.size ); } Ok(()) } ``` -------------------------------- ### Real-time Market Data via WebSocket Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Demonstrates establishing a WebSocket connection to receive real-time market data. It includes subscribing to order book updates and trades, and processing incoming messages. ```rust use lighter_rust::{WebSocketClient, WsMessage}; use futures::StreamExt; let mut ws_client = client.websocket(); // Connect to WebSocket ws_client.connect().await?; // Subscribe to order book updates ws_client.subscribe_order_book("BTC-USDC").await?; // Subscribe to trades ws_client.subscribe_trades("ETH-USDC").await?; // Process messages while let Some(message) = ws_client.stream.as_mut().unwrap().next().await { match message? { WsMessage::OrderBook(book) => { println!("Order book update for {}", book.symbol); }, WsMessage::Trade(trade) => { println!("Trade: {} {} @ {}", trade.quantity, trade.symbol, trade.price); }, WsMessage::Error(e) => { eprintln!("WebSocket error: {}", e); }, _ => {} } } ``` -------------------------------- ### Get Account Balances - Rust Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/AccountApi.md Returns all asset balances for the account. Requires an API key for authentication. ```rust use lighter_rust::{LighterClient, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new() .with_api_key("your-api-key"); let client = LighterClient::new(config, "your-private-key")?; let balances = client.account().get_balances().await?; for balance in balances { println!("{}: {} (Available: {})", balance.asset, balance.total, balance.available ); } Ok(()) } ``` -------------------------------- ### Lighter Rust Account Statistics Retrieval Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/IntegrationGuide.md Fetches and displays account statistics, such as total trading volume. ```rust // Get account statistics let stats = client.account().get_account_stats().await?; println!("Total volume: {}", stats.total_volume); ``` -------------------------------- ### Signature Authentication Initialization Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/README.md Demonstrates initializing the Lighter Rust SDK client for trading operations using signature authentication with a private key. ```rust let client = LighterClient::new(config, "your-private-key")?; ``` -------------------------------- ### Validate OpenAPI Specification Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Validates the OpenAPI specification file using the OpenAPI Generator CLI. ```bash openapi-generator-cli validate -i openapi.yaml ``` -------------------------------- ### Create and Analyze OrderBook Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OrderBook.md Demonstrates how to create an OrderBook instance with sample bids and asks, calculate the spread between the best bid and ask prices, and display it. It requires the `lighter_rust` and `chrono` crates. ```rust use lighter_rust::{OrderBook, PriceLevel}; use chrono::Utc; let order_book = OrderBook { bids: vec![ PriceLevel { price: "45000.00".to_string(), quantity: "2.5".to_string() }, PriceLevel { price: "44999.00".to_string(), quantity: "5.0".to_string() }, PriceLevel { price: "44998.00".to_string(), quantity: "3.2".to_string() }, ], asks: vec![ PriceLevel { price: "45001.00".to_string(), quantity: "1.8".to_string() }, PriceLevel { price: "45002.00".to_string(), quantity: "4.5".to_string() }, PriceLevel { price: "45003.00".to_string(), quantity: "2.1".to_string() }, ], timestamp: Utc::now(), }; // Calculate spread let best_bid: f64 = order_book.bids[0].price.parse().unwrap(); let best_ask: f64 = order_book.asks[0].price.parse().unwrap(); let spread = best_ask - best_bid; let spread_percentage = (spread / best_ask) * 100.0; println!("Spread: ${:.2} ({:.3}%)", spread, spread_percentage); ``` -------------------------------- ### Generate Only Models (Rust) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Generates only the model files for the Rust SDK, specifying the desired models. ```bash openapi-generator-cli generate \ -i openapi.yaml \ -g rust \ -o . \ --global-property models="Account,Order,Balance" ``` -------------------------------- ### API Key Authentication Configuration Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/README.md Illustrates the configuration step for using API key authentication with the Lighter Rust SDK, suitable for read operations. ```rust let config = Config::new().with_api_key("your-api-key"); ``` -------------------------------- ### Export Generator Templates (Rust) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Exports the default generator templates for Rust to a local 'templates' directory. ```bash openapi-generator-cli author template -g rust -o templates ``` -------------------------------- ### Fix Compilation Issues (Rust) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Checks, formats, and lints the Rust code using Cargo commands. ```bash cargo check cargo fmt cargo clippy ``` -------------------------------- ### Rust Development Workflow: Testing and Building Source: https://github.com/yongkangc/lighter-rust/blob/master/CLAUDE.md This snippet outlines the commands for running tests with `cargo test` and building the project for all targets using `cargo build --all-targets`, essential steps in the development cycle. ```bash cargo fmt --all cargo clippy --all-targets --all-features -- -D warnings cargo test cargo build --all-targets ``` -------------------------------- ### Generate Only APIs (Rust) Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OPENAPI_GENERATION.md Generates only the API client files for the Rust SDK, specifying the desired APIs. ```bash openapi-generator-cli generate \ -i openapi.yaml \ -g rust \ -o . \ --global-property apis="AccountApi,OrderApi" ``` -------------------------------- ### Get Account Information - Rust Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/AccountApi.md Retrieves the current account information, including tier, balances, and positions. Requires an API key for authentication. ```rust use lighter_rust::{LighterClient, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new() .with_api_key("your-api-key"); let client = LighterClient::new(config, "your-private-key")?; let account = client.account().get_account().await?; println!("Account ID: {}", account.id); println!("Account Tier: {:?}", account.tier); Ok(()) } ``` -------------------------------- ### Get Account Statistics - Rust Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/AccountApi.md Returns trading statistics for the account, including volume, fees, and performance metrics. Requires an API key for authentication. ```rust use lighter_rust::{LighterClient, Config}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new() .with_api_key("your-api-key"); let client = LighterClient::new(config, "your-private-key")?; let stats = client.account().get_account_stats().await?; println!("Total Volume: {}", stats.total_volume); println!("Total Trades: {}", stats.total_trades); println!("Win Rate: {}%", stats.win_rate); Ok(()) } ``` -------------------------------- ### Create Order with Lighter Rust SDK Source: https://github.com/yongkangc/lighter-rust/blob/master/docs/OrderApi.md Demonstrates how to create a new order using the Lighter Rust SDK. It includes setting order parameters like symbol, side, type, quantity, and price. The example shows a limit buy order for BTC-USDC. ```rust use lighter_rust::{LighterClient, Config, Side, OrderType, TimeInForce}; #[tokio::main] async fn main() -> Result<(), Box> { let config = Config::new() .with_api_key("your-api-key"); let client = LighterClient::new(config, "your-private-key")?; // Place a limit buy order let order = client.orders().create_order( "BTC-USDC", Side::Buy, OrderType::Limit, "0.1", // quantity Some("45000"), // price None, // client_order_id Some(TimeInForce::Gtc), Some(true), // post_only None, // reduce_only ).await?; println!("Order placed: {}", order.id); println!("Status: {:?}", order.status); Ok(()) } ```