### Complete BpxClient Initialization Example Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClientBuilder.md Demonstrates the full process of building a BpxClient with custom settings and making an initial API call to get assets. Requires `tokio` for async execution and `bpx_api_client` crate. ```rust use bpx_api_client::BpxClient; #[tokio::main] async fn main() -> Result<(), Box> { let client = BpxClient::builder() .base_url("https://api.backpack.exchange") .secret("your_base64_secret") .timeout(45) .build()?; // Use client for API calls let assets = client.get_assets().await?; println!("Assets: {:?}", assets); Ok(()) } ``` -------------------------------- ### Quick Start Example: Initialize Client and Fetch Data Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/00_START_HERE.txt This example demonstrates how to initialize the BpxClient using an environment variable for the secret key, fetch account information, and retrieve open orders. Ensure the BPX_SECRET environment variable is set. ```rust use bpx_api_client::BpxClient; use std::env; #[tokio::main] async fn main() -> Result<()> { // Initialize client let client = BpxClient::builder() .secret(env::var("BPX_SECRET")?) .build()?; // Get account info let account = client.get_account().await?; println!("Account: {:?}", account); // Get open orders let orders = client.get_open_orders(None).await?; println!("Open orders: {}", orders.len()); Ok(()) } ``` -------------------------------- ### REST API Example: Get Open Orders Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/client/README.md Example of how to initialize the BpxClient and fetch open orders for a specific symbol using the REST API. Ensure the SECRET environment variable is set. ```rust use bpx_api_client::{BpxClient, BACKPACK_API_BASE_URL}; use std::env; #[tokio::main] async fn main() { let base_url = env::var("BASE_URL").unwrap_or_else(|_| BACKPACK_API_BASE_URL.to.string()); let secret = env::var("SECRET").expect("Missing SECRET environment variable"); let client = BpxClient::init(base_url, secret, None) .expect("Failed to initialize Backpack API client"); match client.get_open_orders(Some("SOL_USDC")).await { Ok(orders) => println!("Open Orders: {:?}", orders), Err(err) => tracing::error!("Error: {:?}", err), } } ``` -------------------------------- ### Navigate to Examples Directory Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/README.md Move into the 'examples' directory within the Rust client project. This is typically done after building to run or inspect example code. ```bash cd examples ``` -------------------------------- ### WebSocket API Example: Subscribe to RFQs Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/client/README.md Example of initializing the BpxClient with WebSocket support and subscribing to Request For Quote (RFQ) streams. Requires SECRET, BASE_URL, and WS_URL environment variables. ```rust use anyhow::Result; use bpx_api_client::{BpxClient, BACKPACK_API_BASE_URL, BACKPACK_WS_URL}; use bpx_api_types::rfq::RequestForQuote; use std::env; use tokio::sync::mpsc; #[tokio::main] async fn main() -> Result<()> { let base_url = env::var("BASE_URL").unwrap_or_else(|_| BACKPACK_API_BASE_URL.to.string()); let ws_url = env::var("WS_URL").unwrap_or_else(|_| BACKPACK_WS_URL.to.string()); let secret = env::var("SECRET").expect("Missing SECRET environment variable"); let client = BpxClient::init_with_ws(base_url, ws_url, &secret, None)?; let (tx, mut rx) = mpsc::channel::(100); tokio::spawn(async move { while let Some(rfq) = rx.recv().await { println!("Received RFQ: {:?}", rfq); } }); client.subscribe_to_rfqs(tx).await; Ok(()) } ``` -------------------------------- ### Install 'just' Task Runner Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/README.md Install the 'just' command-line tool, which is used for managing build and development tasks. Ensure Rust and Cargo are installed first. ```bash cargo install just ``` -------------------------------- ### Handle BpxApiError Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/errors.md Example showing how to match and handle BpxApiError, inspecting the status code and message for specific API issues. ```rust match client.execute_order(payload).await { Ok(order) => println!("Order: {}", order.id), Err(Error::BpxApiError { status_code, message }) => { match status_code.as_u16() { 400 => println!("Bad request: {}", message), 401 => println!("Auth failed: {}", message), 429 => println!("Rate limited"), _ => println!("API error: {}", message), } } Err(e) => println!("Other error: {}", e), } ``` -------------------------------- ### Install Backpack Exchange API Client Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/client/README.md Add the bpx_api_client crate to your Cargo.toml. Replace x.y.z with the latest version. ```toml [dependencies] bpx_api_client = "x.y.z" ``` -------------------------------- ### Minimal Setup for Public API Calls Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/configuration.md Initializes the client with default settings for accessing public market data. Uses tokio for async operations. ```rust use bpx_api_client::BpxClient; #[tokio::main] async fn main() -> Result<()> { let client = BpxClient::builder().build()?; let markets = client.get_markets().await?; println!("Markets: {}", markets.len()); Ok(()) } ``` -------------------------------- ### Navigate to Rust Folder Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/README.md Change the current directory to the 'rust' folder. This is a prerequisite for subsequent build and installation steps. ```bash cd rust ``` -------------------------------- ### Send a Signed GET Request Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClient.md Sends a signed GET request to a specified URL. Ensure the client is properly initialized. ```rust let response = client.get("https://api.backpack.exchange/api/v1/assets").await?; ``` -------------------------------- ### Install Backpack Exchange API Client with WebSocket Support Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/client/README.md To enable WebSocket support, include the 'ws' feature flag in your Cargo.toml. ```toml [dependencies] bpx_api_client = { version = "x.y.z", features = ["ws"] } ``` -------------------------------- ### Handle Base64Decode Error Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/errors.md Example demonstrating how a Base64Decode error might occur during client initialization with an invalid secret. ```rust // This will fail with Base64Decode error let result = BpxClient::init( "https://api.backpack.exchange".to_string(), "invalid!!!base64", // Not valid Base64 None ); // Error: Base64Decode(...) ``` -------------------------------- ### Initialize Client with Invalid Secret Key Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/errors.md This example demonstrates how to trigger a `SecretKey` error by providing an invalid or incorrectly formatted secret key during client initialization. Ensure the secret key is a valid Base64-encoded ED25519 private key. ```rust // Valid Base64 but not a valid ED25519 key let result = BpxClient::init( "https://api.backpack.exchange".to_string(), "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", // 32 A's (32 bytes) None ); // Error: SecretKey (if not valid ED25519) ``` -------------------------------- ### Batch Operations Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Execute multiple operations in a single request to improve efficiency. This example shows placing multiple orders. ```rust use bpx_api_client::BpxClient; use bpx_api_client::orders::OrderSide; use bpx_api_client::orders::OrderType; use rust_decimal::Decimal; let client = BpxClient::new_with_auth( "YOUR_API_KEY", "YOUR_API_SECRET", "YOUR_PASSPHRASE", ); let orders_to_place = vec![ client.place_order_request( "BTC-USD", OrderSide::Buy, OrderType::Limit, Decimal::from_str("0.05").unwrap(), Decimal::from_str("29000.0").unwrap(), ), client.place_order_request( "ETH-USD", OrderSide::Sell, OrderType::Limit, Decimal::from_str("0.2").unwrap(), Decimal::from_str("1800.0").unwrap(), ), ]; let batch_result = client.batch_orders(orders_to_place).await; match batch_result { Ok(results) => println!("Batch orders processed: {:#?}", results), Err(e) => eprintln!("Batch order failed: {:#?}", e), } ``` -------------------------------- ### Get Deposits with Pagination Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/capital.md Retrieves a list of deposits, supporting pagination with limit and offset parameters. Use this to fetch deposit history. ```rust // Get first 50 deposits let deposits = client.get_deposits(Some(50), None).await?; // Get next 50 (offset) let next_batch = client.get_deposits(Some(50), Some(50)).await?; for deposit in deposits { println!("Deposit: {} {} -> {}", deposit.symbol, deposit.quantity, deposit.status); } ``` -------------------------------- ### Get Account Settings Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/account.md Fetches the account's current settings and configuration, including fees, limits, and flags. Use this to understand your account's operational parameters. ```rust let account = client.get_account().await?; println!("Account settings:"); println!(" Auto-lend: {}", account.auto_lend); println!(" Spot maker fee: {}%", account.spot_maker_fee * 100); println!(" Spot taker fee: {}%", account.spot_taker_fee * 100); println!(" Futures maker fee: {}%", account.futures_maker_fee * 100); println!(" Futures taker fee: {}%", account.futures_taker_fee * 100); println!(" Borrow limit: {}", account.borrow_limit); println!(" Position limit: {}", account.position_limit); println!(" Liquidating: {}", account.liquidating); ``` -------------------------------- ### Get Configured Base URL Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClient.md Returns the API base URL that the `BpxClient` is configured to use. This is the URL set during client construction. ```rust pub fn base_url(&self) -> &Url ``` -------------------------------- ### Fetch All Trading Markets Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/markets.md Retrieves a list of all available trading markets. Useful for getting an overview of all active trading pairs. ```rust let markets = client.get_markets().await?; println!("Available markets: {}", markets.len()); ``` -------------------------------- ### Get Historical Fills with Default Parameters Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/fills.md Fetches all historical fills using default query parameters. Ensure the client is initialized and authenticated. ```rust use bpx_api_types::fill::FillsHistoryParams; // Get all fills let fills = client.get_historical_fills(FillsHistoryParams::default()).await?; ``` -------------------------------- ### Get Account Balances Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/capital.md Fetches the current balances for all assets in the account. Returns a map of asset symbols to their available and locked balances. ```rust let balances = client.get_balances().await?; for (symbol, balance) in balances { println!("{}: Available: {}, Locked: {}", symbol, balance.available, balance.locked); } ``` -------------------------------- ### Get Borrow/Lend Positions Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/borrow-lend.md Retrieves all open borrow/lending positions for the authenticated account. This method requires authentication and uses the `borrowLendPositionQuery` instruction for signing. ```APIDOC ## GET /api/v1/borrow-lend/positions ### Description Retrieves all open borrow/lending positions for the account. ### Method GET ### Endpoint /api/v1/borrow-lend/positions ### Parameters #### Query Parameters None ### Request Example ```rust let positions = client.get_borrow_lend_positions().await?; ``` ### Response #### Success Response (200) - **positions** (array of BorrowLendPosition) - Array of active borrow and lend positions #### Response Example ```json [ { "symbol": "BTC", "position_type": "Borrow", "quantity": "0.001", "interest_rate": 0.05 }, { "symbol": "ETH", "position_type": "Lend", "quantity": "1.0", "interest_rate": 0.02 } ] ``` ``` -------------------------------- ### Get Historical Trades (First Batch) Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/trades.md Fetches the first batch of historical trades for a symbol with a specified limit. Requires the trading pair symbol and limit. ```rust let trades = client.get_historical_trades("BTC_USDC", Some(100), None).await?; ``` -------------------------------- ### Get Borrow/Lend Positions Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/borrow-lend.md Retrieves all open borrow/lending positions for the account. Iterate through the results to access details like symbol, type, quantity, and interest rate. ```rust let positions = client.get_borrow_lend_positions().await?; for position in positions { println!("Symbol: {}", position.symbol); println!(" Type: {:?}", position.position_type); // Borrow or Lend println!(" Quantity: {}", position.quantity); println!(" Interest rate: {}%", position.interest_rate * 100); } ``` -------------------------------- ### Automatic Error Conversion Example Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/errors.md Demonstrates how the `From` implementations allow for automatic conversion of various errors to the `Error` type within a `Result` context. This simplifies error handling by reducing the need for explicit conversions. ```rust // These all convert to Error automatically fn process() -> Result<()> { let _decoded = base64ct::Base64::decode_vec(&secret)?; // From let _client = reqwest::Client::new(); // From let _url = Url::parse("http://...")?; // From Ok(()) } ``` -------------------------------- ### Get Open Future Positions Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/futures.md Retrieves all open futures positions for the authenticated account. Iterates through the positions to print details like symbol, side, quantity, entry price, unrealized PnL, and leverage. ```rust let positions = client.get_open_future_positions().await?; for position in positions { println!("Symbol: {}", position.symbol); println!(" Side: {:?}", position.side); println!(" Quantity: {}", position.quantity); println!(" Entry price: {}", position.entry_price); println!(" Unrealized PnL: {}", position.unrealized_pnl); println!(" Leverage: {}", position.leverage); } ``` -------------------------------- ### GET collateral Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/capital.md Retrieves collateral information. ```APIDOC ## GET collateral ### Description Retrieves information about the user's collateral. ### Method GET ### Endpoint /collateral ### Response #### Success Response (200) - **data** (array) - List of collateral items. - **asset** (string) - The asset used as collateral. - **amount** (string) - The amount of the asset used as collateral. - **value** (string) - The current value of the collateral. - **borrowable** (string) - The amount that can be borrowed against this collateral. ### Response Example { "data": [ { "asset": "BTC", "amount": "0.1", "value": "3000.00", "borrowable": "1500.00" } ] } ``` -------------------------------- ### Create .env File Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/examples/README.md Create a .env file to store your API credentials and configuration. ```bash touch .env ``` -------------------------------- ### GET withdrawals Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/capital.md Retrieves a list of withdrawal records with their statuses. ```APIDOC ## GET withdrawals ### Description Retrieves a list of withdrawal records, including their status. ### Method GET ### Endpoint /withdrawals ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of items to return. - **offset** (integer) - Optional - The number of items to skip before starting to collect the result set. - **status** (WithdrawalStatus) - Optional - Filters withdrawals by their status. ### Response #### Success Response (200) - **data** (array) - List of withdrawal objects. - **id** (string) - The unique identifier for the withdrawal. - **asset** (string) - The asset withdrawn. - **amount** (string) - The amount withdrawn. - **status** (WithdrawalStatus) - The current status of the withdrawal. - **address** (string) - The destination address for the withdrawal. - **txid** (string) - The transaction ID of the withdrawal. - **createdAt** (string) - The timestamp when the withdrawal was created. ### Response Example { "data": [ { "id": "wd_123", "asset": "USDC", "amount": "50.00", "status": "COMPLETED", "address": "0xdef...", "txid": "0xghi...", "createdAt": "2023-10-27T11:00:00Z" } ] } ``` -------------------------------- ### BpxClient Initialization Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClient.md Initializes a new BpxClient instance with the provided base URL, API secret for signing requests, and optional custom headers. ```APIDOC ## `init` Constructor ### Description Initializes a new client with the given base URL, API secret, and optional headers. ### Method `pub fn init( base_url: String, secret: &str, headers: Option ) -> Result ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use bpx_api_client::{BpxClient, BACKPACK_API_BASE_URL}; let client = BpxClient::init( BACKPACK_API_BASE_URL.to_string(), "your_base64_secret", None )?; ``` ### Response #### Success Response (Result) - `BpxClient` - The configured client instance. #### Response Example (See Request Example for usage) ### Error Handling - `Error::SecretKey` — if the secret cannot be decoded as a valid ED25519 key - `Error::UrlParseError` — if the base URL is invalid - `Reqwest` — if client initialization fails ``` -------------------------------- ### GET deposits Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/capital.md Retrieves a list of deposit records with their statuses. ```APIDOC ## GET deposits ### Description Retrieves a list of deposit records, including their status. ### Method GET ### Endpoint /deposits ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of items to return. - **offset** (integer) - Optional - The number of items to skip before starting to collect the result set. - **status** (DepositStatus) - Optional - Filters deposits by their status. ### Response #### Success Response (200) - **data** (array) - List of deposit objects. - **id** (string) - The unique identifier for the deposit. - **asset** (string) - The asset deposited. - **amount** (string) - The amount deposited. - **status** (DepositStatus) - The current status of the deposit. - **address** (string) - The deposit address used. - **txid** (string) - The transaction ID of the deposit. - **createdAt** (string) - The timestamp when the deposit was created. ### Response Example { "data": [ { "id": "dep_123", "asset": "USDC", "amount": "100.00", "status": "COMPLETED", "address": "0xabc...", "txid": "0xdef...", "createdAt": "2023-10-27T10:00:00Z" } ] } ``` -------------------------------- ### Full BpxClient Configuration Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/configuration.md Initializes the BpxClient with custom settings for base URL, authentication secret, and request timeout. Ensure the secret is base64-encoded. ```rust use bpx_api_client::BpxClient; let client = BpxClient::builder() .base_url("https://api.backpack.exchange") .secret("your_base64_encoded_secret") .timeout(60) .build()?; ``` -------------------------------- ### GET balances Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/capital.md Retrieves the asset balances (available and locked) for the authenticated user. ```APIDOC ## GET balances ### Description Retrieves the asset balances (available and locked) for the authenticated user. ### Method GET ### Endpoint /balances ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of items to return. - **offset** (integer) - Optional - The number of items to skip before starting to collect the result set. ### Response #### Success Response (200) - **data** (array) - List of balance objects. - **asset** (string) - The asset symbol. - **available** (string) - The available amount of the asset. - **locked** (string) - The locked amount of the asset. ### Response Example { "data": [ { "asset": "USDC", "available": "100.00", "locked": "10.00" } ] } ``` -------------------------------- ### Minimal BpxClient Configuration Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/configuration.md Initializes the BpxClient using all default settings. This configuration is suitable for public access only. ```rust use bpx_api_client::BpxClient; let client = BpxClient::builder().build()?; // Uses all defaults, public access only ``` -------------------------------- ### GET deposit address Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/capital.md Retrieves an on-chain deposit address for a given asset and blockchain. ```APIDOC ## GET deposit address ### Description Retrieves an on-chain deposit address for a specified asset and blockchain. ### Method GET ### Endpoint /deposit/address ### Parameters #### Query Parameters - **asset** (string) - Required - The asset for which to get a deposit address. - **blockchain** (Blockchain) - Required - The blockchain network for the deposit address. ### Response #### Success Response (200) - **address** (string) - The generated on-chain deposit address. - **asset** (string) - The asset for which the address was generated. - **blockchain** (Blockchain) - The blockchain network of the address. ### Response Example { "address": "0x123...", "asset": "USDC", "blockchain": "Ethereum" } ``` -------------------------------- ### Get Order Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/orders.md Retrieves information about a specific order. The signature instruction name for this operation is `orderQuery`. ```APIDOC ## GET /order ### Description Retrieves information about a specific order. ### Method GET ### Endpoint /order ### Parameters #### Query Parameters - **orderId** (string) - Required - The unique identifier of the order. ### Response #### Success Response (200) - **orderId** (string) - The unique identifier of the order. - **status** (string) - The current status of the order (e.g., 'open', 'filled', 'canceled'). - **symbol** (string) - The trading symbol for the order. - **side** (string) - The side of the order ('buy' or 'sell'). - **type** (string) - The type of order ('limit', 'market'). - **price** (number) - The price of the order (if applicable). - **amount** (number) - The amount of the asset to be traded. - **filledAmount** (number) - The amount of the asset already filled. - **timestamp** (string) - The timestamp when the order was created. ``` -------------------------------- ### Initialize BpxClient Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClient.md Initializes a new BpxClient instance. Requires the API base URL and a Base64-encoded ED25519 private key for signing requests. Optional custom headers can be provided. ```rust use bpx_api_client::{BpxClient, BACKPACK_API_BASE_URL}; let client = BpxClient::init( BACKPACK_API_BASE_URL.to_string(), "your_base64_secret", None )?; ``` -------------------------------- ### Type Conversion (Numeric) Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt All numeric values in the API use rust_decimal::Decimal. This example shows a basic conversion. ```rust use rust_decimal::Decimal; use std::str::FromStr; let price_str = "30000.50"; let price_decimal = Decimal::from_str(price_str).expect("Failed to parse decimal"); println!("Parsed Decimal: {}", price_decimal); // Use price_decimal in API calls where Decimal is expected. ``` -------------------------------- ### Development Tasks with Just Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/client/README.md View available build and development commands by running 'just' in the project directory. ```shell just ``` -------------------------------- ### Create New BpxClientBuilder Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClientBuilder.md Initializes a new builder instance. Defaults will be applied when build() is called. ```rust let builder = BpxClientBuilder::new(); ``` -------------------------------- ### Client Initialization (Public) Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Initialize the BPX client for public API access. No authentication is required for these operations. ```rust use bpx_api_client::BpxClient; let client = BpxClient::new(); ``` -------------------------------- ### Initialize Public API Client Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/markets.md Initialize the BpxClient for public market data access. No API key or signature is required for these endpoints. ```rust let client = BpxClient::builder() .build()?; // No secret - public access only ``` -------------------------------- ### Get Vault Redeems Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/vault.md Retrieves historical redeem records for vaults. This operation requires authentication and is signed with the `vaultRedeemHistoryQueryAll` instruction. ```APIDOC ## GET /vault/redeems ### Description Retrieves historical redeem records. ### Method GET ### Endpoint /vault/redeems ### Parameters #### Query Parameters - **params** (VaultRedeemHistoryParams) - Optional - Parameters for querying redeem history. ### Response #### Success Response (200) - **redeems** (array) - An array of historical redeem records. #### Response Example ```json { "redeems": [ { "redeem_id": "redeem_xyz789", "amount": "500", "asset": "BTC", "vault_token_amount": "500", "timestamp": "2023-10-27T11:00:00Z" } ] } ``` ``` -------------------------------- ### Project File Structure Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/INDEX.md Illustrates the directory and file organization of the BPX API client project. This helps in navigating and understanding the project's components. ```tree output/ ├── INDEX.md (this file) ├── README.md (main entry point) ├── configuration.md ├── types.md ├── errors.md └── api-reference/ ├── BpxClient.md ├── BpxClientBuilder.md ├── markets.md ├── orders.md ├── account.md ├── capital.md ├── trades.md ├── fills.md ├── rfq.md ├── vault.md ├── futures.md ├── borrow-lend.md └── user.md ``` -------------------------------- ### Core Client and Builder Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for the main client struct (BpxClient) and its builder (BpxClientBuilder), covering HTTP methods, authentication, signing, and configuration options. ```APIDOC ## BpxClient and BpxClientBuilder ### Description Documentation for the main client struct, `BpxClient`, and its associated builder, `BpxClientBuilder`. This section covers essential aspects like HTTP method invocation, authentication mechanisms, signature generation, and various configuration methods available through the builder pattern. ### Core Client (`BpxClient`) - **Purpose**: The primary interface for interacting with the Backpack Exchange API. - **Features**: Handles HTTP requests, manages authentication, and signs requests. ### Client Builder (`BpxClientBuilder`) - **Purpose**: Facilitates the creation and configuration of `BpxClient` instances. - **Features**: Provides methods for setting configuration options, defining defaults, and constructing the client. ### Authentication - **Methods**: Supports ED25519 signature generation for authenticated requests. - **Details**: Covers header construction and the distinction between public and private client initialization. ``` -------------------------------- ### Get Vault History Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/vault.md Retrieves historical snapshots of vault states. This operation requires authentication and is signed with the `vaultHistoryQueryAll` instruction. ```APIDOC ## GET /vault/history ### Description Retrieves historical vault snapshots. ### Method GET ### Endpoint /vault/history ### Parameters #### Query Parameters - **params** (VaultHistoryParams) - Optional - Parameters for querying vault history. ### Response #### Success Response (200) - **history** (array) - An array of historical vault snapshots. #### Response Example ```json { "history": [ { "timestamp": "2023-10-27T10:00:00Z", "nav": "10000", "supply": "1000" } ] } ``` ``` -------------------------------- ### Create BpxClient for Development or Production Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/configuration.md Dynamically sets the base URL based on the ENVIRONMENT variable. Defaults to testnet if the variable is not set or not 'production'. Requires the BPX_SECRET environment variable. ```rust use std::env; async fn create_client() -> Result { let is_prod = env::var("ENVIRONMENT") .map(|e| e == "production") .unwrap_or(false); let url = if is_prod { "https://api.backpack.exchange" } else { "https://testnet-api.backpack.exchange" }; let secret = env::var("BPX_SECRET")?; Ok(BpxClient::builder() .base_url(url) .secret(secret) .build()?) } ``` -------------------------------- ### Get Vault Mints Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/vault.md Retrieves historical mint records for vaults. This operation requires authentication and is signed with the `vaultMintHistoryQueryAll` instruction. ```APIDOC ## GET /vault/mints ### Description Retrieves historical mint records. ### Method GET ### Endpoint /vault/mints ### Parameters #### Query Parameters - **params** (VaultMintHistoryParams) - Optional - Parameters for querying mint history. ### Response #### Success Response (200) - **mints** (array) - An array of historical mint records. #### Response Example ```json { "mints": [ { "mint_id": "mint_abc123", "amount": "100", "asset": "BTC", "vault_token_amount": "1000", "timestamp": "2023-10-27T10:00:00Z" } ] } ``` ``` -------------------------------- ### Client Initialization (Authenticated) Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Initialize the BPX client for authenticated API access. Requires API key and secret, and ED25519 signatures for requests. ```rust use bpx_api_client::BpxClient; let client = BpxClient::new_with_auth( "YOUR_API_KEY", "YOUR_API_SECRET", "YOUR_PASSPHRASE", ); // Request signing happens automatically. ``` -------------------------------- ### Get Vaults Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/vault.md Retrieves a list of available vaults. This operation is used to browse options before performing mint or redeem actions. ```APIDOC ## GET /vaults ### Description Retrieves a list of available vaults. ### Method GET ### Endpoint /vaults ### Response #### Success Response (200) - **vaults** (array) - An array of vault definitions. - **nav** (string) - Net Asset Value of the vault. - **supply** (string) - Current supply of vault tokens. #### Response Example ```json { "vaults": [ { "nav": "10000", "supply": "1000" } ] } ``` ``` -------------------------------- ### Running Integration Tests with Cargo Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/README.md These commands demonstrate how to execute integration tests for the project using Cargo. Options include running all tests, running tests with captured output, and running specific named tests. ```bash # Run all tests car go test # Run with output car go test -- --nocapture # Run specific test car go test test_name ``` -------------------------------- ### Get All Open Orders - Rust Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/orders.md Retrieves all open orders. You can optionally filter the results by a specific trading pair symbol. ```rust let all_orders = client.get_open_orders(None).await?; ``` ```rust let sol_orders = client.get_open_orders(Some("SOL_USDC")).await?; ``` -------------------------------- ### Fetch All Vaults Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/vault.md Retrieves information about all available vaults on the exchange. Use this to get definitions, current NAV, and parameters for each vault. ```rust let vaults = client.get_vaults().await?; for vault in vaults { println!("Vault: {}", vault.symbol); println!(" NAV: {}", vault.nav); println!(" Total supply: {}", vault.circulating_supply); } ``` -------------------------------- ### Build BpxClient with Custom Configuration Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClient.md Use the builder pattern to construct a BpxClient instance. You can customize the base URL, API secret, and request timeout. ```rust let client = BpxClient::builder() .base_url("https://api.backpack.exchange") .secret("your_secret") .timeout(60) .build()?; ``` -------------------------------- ### Build BpxClient Instance Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClientBuilder.md Constructs and returns a configured BpxClient instance. This method can return an error if the secret key is invalid, URLs are malformed, or underlying HTTP client creation fails. ```rust let client = BpxClientBuilder::new() .base_url("https://api.backpack.exchange") .secret("your_secret") .timeout(60) .build()?; ``` -------------------------------- ### Get Maximum Borrowable Amount Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/account.md Fetches the maximum amount that can be borrowed for a specific asset symbol. Requires the asset symbol as a parameter. ```rust let max_borrow = client.get_account_max_borrow("USDC").await?; println!("Max borrow USDC: {}", max_borrow.max_borrow_quantity); ``` -------------------------------- ### Get Withdrawals with Pagination Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/capital.md Retrieves a list of withdrawals, supporting pagination with limit and offset parameters. Use this to fetch withdrawal history. ```rust let withdrawals = client.get_withdrawals(Some(100), None).await?; for withdrawal in withdrawals { println!("Withdrawal: {} {} -> {} ({})", withdrawal.symbol, withdrawal.quantity, withdrawal.destination_address, withdrawal.status); } ``` -------------------------------- ### Construct BpxClient Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/configuration.md Constructs the BpxClient instance. Returns an error if the configuration is invalid. ```rust pub fn build(self) -> Result ``` -------------------------------- ### Initialize Authenticated BPX Client Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/borrow-lend.md Initializes the BpxClient for authenticated requests. Ensure you have your API base URL and a valid base64 secret key. ```rust let client = BpxClient::init( BACKPACK_API_BASE_URL.to_string(), "your_base64_secret", None )?; ``` -------------------------------- ### Get Deposit Address for Blockchain Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/capital.md Fetches the deposit address for a specified blockchain. Ensure the correct Blockchain enum variant is used. ```rust use bpx_api_types::Blockchain; let sol_address = client.get_deposit_address(Blockchain::Solana).await?; println!("Solana address: {}", sol_address.address); let eth_address = client.get_deposit_address(Blockchain::Ethereum).await?; println!("Ethereum address: {}", eth_address.address); ``` -------------------------------- ### BpxClientBuilder Constructor Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClientBuilder.md Creates a new BpxClientBuilder instance with default values. ```APIDOC ## `new` Constructor ### Description Creates a new builder with all fields set to `None`. Defaults will be applied during the `build()` process. ### Signature ```rust pub fn new() -> Self ``` ### Example ```rust let builder = BpxClientBuilder::new(); ``` ``` -------------------------------- ### Initialize Authenticated BPX Client Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/README.md Initialize the BPX client with a Base64-encoded ED25519 private key for authenticated requests. The client automatically signs each request. ```rust let client = BpxClient::builder() .secret("base64_encoded_private_key") .build()?; ``` -------------------------------- ### Custom Configuration for High-Latency Network Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/configuration.md Sets up the client with a custom base URL and an extended timeout for high-latency network conditions. ```rust let client = BpxClient::builder() .base_url("https://api.backpack.exchange") .secret(api_secret) .timeout(120) // 2 minute timeout .build()?; ``` -------------------------------- ### Docker Build and Run Configuration Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/README.md This Dockerfile defines a multi-stage build process. It first builds a Rust application using the latest Rust image and then copies the compiled binary to a slim Debian image for the final runtime environment. ```dockerfile FROM rust:latest as builder WORKDIR /app COPY . . RUN cargo build --release FROM debian:bookworm-slim COPY --from=builder /app/target/release/my-app /usr/local/bin/ CMD ["my-app"] ``` -------------------------------- ### Get Verifying Key Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClient.md Retrieves the ED25519 public verifying key associated with the client. Returns `None` if the client was not initialized with a secret. ```rust pub const fn verifying_key(&self) -> Option<&VerifyingKey> ``` -------------------------------- ### BpxClientBuilder Methods Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClientBuilder.md Methods for configuring the BpxClient. All methods consume `self` and return `Self` for chaining. ```APIDOC ## `base_url` Method ### Description Sets the base URL for API requests. ### Signature ```rust pub fn base_url(mut self, base_url: impl ToString) -> Self ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **base_url** (impl ToString) - Required - The API endpoint root. Defaults to `BACKPACK_API_BASE_URL`. ### Example ```rust BpxClientBuilder::new() .base_url("https://api.backpack.exchange") ``` ``` ```APIDOC ## `ws_url` Method ### Description Sets the WebSocket URL for real-time data streams. This method is only available when the `ws` feature is enabled. ### Signature ```rust #[cfg(feature = "ws")] pub fn ws_url(mut self, ws_url: impl ToString) -> Self ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **ws_url** (impl ToString) - Required - The WebSocket endpoint root. Defaults to `BACKPACK_WS_URL`. ### Example ```rust BpxClientBuilder::new() .ws_url("wss://ws.backpack.exchange") ``` ``` ```APIDOC ## `secret` Method ### Description Sets the API secret, which is a Base64-encoded ED25519 private key, used for request signing. If not provided, the client will be unauthenticated and can only access public endpoints. ### Signature ```rust pub fn secret(mut self, secret: impl ToString) -> Self ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **secret** (impl ToString) - Optional - Base64-encoded ED25519 private key. ### Example ```rust BpxClientBuilder::new() .secret("your_base64_encoded_secret") ``` ``` ```APIDOC ## `headers` Method ### Description Sets custom HTTP headers to be included with all requests. ### Signature ```rust pub fn headers(mut self, headers: BpxHeaders) -> Self ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **headers** (BpxHeaders) - Optional - Additional HTTP headers (HeaderMap). Defaults to an empty HeaderMap. ### Example ```rust use reqwest::header::HeaderMap; let mut headers = HeaderMap::new(); headers.insert("User-Agent", "myapp/1.0".parse()?); BpxClientBuilder::new() .headers(headers) ``` ``` ```APIDOC ## `timeout` Method ### Description Sets the HTTP request timeout in seconds. ### Signature ```rust pub fn timeout(mut self, timeout: u64) -> Self ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **timeout** (u64) - Required - Timeout in seconds for each HTTP request. Defaults to 30 seconds. ### Example ```rust BpxClientBuilder::new() .timeout(60) ``` ``` -------------------------------- ### Get Historical Fills with Pagination Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/fills.md Fetches historical fills with specified limit and offset for pagination. This allows retrieving results in chunks. ```rust use bpx_api_types::fill::FillsHistoryParams; // Get with pagination let mut params = FillsHistoryParams::default(); params.limit = Some(100); params.offset = Some(100); let fills = client.get_historical_fills(params).await?; ``` -------------------------------- ### Get Fill History Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/README.md Retrieves a history of your fills (executed orders) for a specific symbol, with a configurable limit. Requires BPX_SECRET environment variable. ```rust use bpx_api_client::BpxClient; use bpx_api_types::fill::FillsHistoryParams; #[tokio::main] async fn main() -> Result<()> { let client = BpxClient::builder() .secret(std::env::var("BPX_SECRET")?) .build()?; let mut params = FillsHistoryParams::default(); params.symbol = Some("SOL_USDC".to_string()); params.limit = Some(50); let fills = client.get_historical_fills(params).await?; for fill in fills { println!("{}: {} {} @ {}", fill.id, fill.side, fill.quantity, fill.price); } Ok(()) } ``` -------------------------------- ### Build All Rust Packages Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/README.md Execute the 'build' command using 'just' to compile all packages within the Rust project. This command aggregates build tasks. ```bash just build ``` -------------------------------- ### Get Underlying Reqwest Client Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/BpxClient.md Provides access to the internal `reqwest::Client` instance used by `BpxClient`. This can be useful for advanced `reqwest` configurations. ```rust pub const fn client(&self) -> &reqwest::Client ``` -------------------------------- ### Systemd Service Configuration for Trading Bot Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/README.md This configuration sets up a systemd service to run the Backpack API trading bot. It specifies the user, working directory, environment variables, and execution command, with automatic restart on failure. ```ini [Unit] Description=Backpack API Trading Bot After=network.target [Service] Type=simple User=bpx WorkingDirectory=/opt/bpx Environment="BPX_SECRET=/etc/bpx/secret" Environment="RUST_LOG=info" ExecStart=/opt/bpx/bin/trading-bot Restart=on-failure RestartSec=10 [Install] WantedBy=multi-user.target ``` -------------------------------- ### Configure BPX Client with API Secret Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/configuration.md Initialize the BPX client using your Base64-encoded API secret. Ensure the secret is a 32-byte ED25519 private key. Never commit secrets directly into your code. ```rust let client = BpxClient::builder() .secret("your_base64_encoded_secret_here") .build()?; ``` -------------------------------- ### Get Open Future Positions Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/_autodocs/api-reference/futures.md Retrieves all open futures positions for the authenticated account. This method is part of the futures module and requires authentication. ```APIDOC ## GET /positions ### Description Retrieves all open futures positions for the account. ### Method GET ### Endpoint /positions ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```rust let positions = client.get_open_future_positions().await?; for position in positions { println!("Symbol: {}", position.symbol); println!(" Side: {:?}", position.side); println!(" Quantity: {}", position.quantity); println!(" Entry price: {}", position.entry_price); println!(" Unrealized PnL: {}", position.unrealized_pnl); println!(" Leverage: {}", position.leverage); } ``` ### Response #### Success Response (200) - **Symbol** (string) - The futures contract symbol - **Side** (string) - Long or short direction - **Quantity** (string) - Position size in base asset - **Entry price** (string) - Average entry price - **Unrealized PnL** (string) - Current profit/loss - **Leverage** (string) - Current leverage applied - **Liquidation price** (string) - Price at which position liquidates - **Funding** (string) - Accumulated funding payments #### Response Example ```json [ { "symbol": "BTC-PERPETUAL", "side": "Buy", "quantity": "0.001", "entry_price": "30000.00", "unrealized_pnl": "10.50", "leverage": "10x", "liquidation_price": "28000.00", "funding": "0.05" } ] ``` ``` -------------------------------- ### Add Environment Variables to .env File Source: https://github.com/backpack-exchange/bpx-api-client/blob/master/examples/README.md Add your API key, secret, and optional base URLs to the .env file. ```bash BPX_API_KEY=your_api_key_here SECRET=your_api_secret_here BASE_URL=https://api.backpack.exchange WS_URL=wss://ws.backpack.exchange ```