### Install Ostium SDK Source: https://docs.ostium.com/developer/sdk/overview Install the required SDK and viem dependencies. ```bash npm install @ostium/builder-sdk viem ``` -------------------------------- ### Setup and Delegation Source: https://docs.ostium.com/developer/client-modes/self-and-gasless Required one-time setup steps to enable gasless trading for a trader EOA. ```APIDOC ## Setup and Delegation ### Description Before gasless trading can occur, the trader must perform a one-time setup to approve USDC and delegate gasless submission rights. ### Methods - **approveUsdc('max')**: Approves the maximum amount of USDC for the trading contract. - **setupGaslessDelegation()**: Configures the delegation required for the Safe to submit trades on behalf of the EOA. ### Example ```ts await client.approveUsdc('max'); await client.setupGaslessDelegation(); ``` ``` -------------------------------- ### Trader Setup Source: https://docs.ostium.com/developer/client-modes/delegated-and-self Required setup steps for the trader before delegated execution can occur. ```APIDOC ## Trader Setup ### Description Before trading can occur, the trader must approve USDC and set the delegate address on-chain. ### Usage Example ```ts await traderClient.approveUsdc('max'); await traderClient.setDelegate('0xDelegateAddress'); ``` ``` -------------------------------- ### Calculate Liquidation Threshold Example Source: https://docs.ostium.com/traders/trading/liquidation Example calculation for a 20x long position on a pair with 200x maximum leverage. ```text 100% − (20 / 200 × 25%) = 97.5% ``` -------------------------------- ### Trader Setup Methods Source: https://docs.ostium.com/developer/client-modes/delegated-and-gasless Methods required for the trader to authorize the delegate Safe. ```APIDOC ## traderClient.approveUsdc ### Description Approves the spending of USDC for the trader. ### Usage ```ts await traderClient.approveUsdc('max'); ``` ## traderClient.setDelegate ### Description Registers the delegate Safe address for the trader. ### Usage ```ts await traderClient.setDelegate('0xDelegateSafeAddress'); ``` ``` -------------------------------- ### Perform One-time Setup Source: https://docs.ostium.com/developer/client-modes/self-and-gasless The trader must execute these two EOA-signed transactions once to enable gasless delegation. ```ts await client.approveUsdc('max'); await client.setupGaslessDelegation(); ``` -------------------------------- ### OstiumClient Initialization Source: https://docs.ostium.com/developer/client-modes/configuration The OstiumClient is initialized via async factory methods. Below is an example of initializing a client with shared configuration options. ```APIDOC ## OstiumClient.createSelfAndSelf ### Description Initializes an OstiumClient instance. All factory methods return a Promise and must be awaited. ### Parameters - **traderPrivateKey** (string) - Required - The private key of the trader. - **rpcUrl** (string) - Required - The RPC URL for the Arbitrum network. - **testnet** (boolean) - Optional - If true, uses Arbitrum Sepolia. Default: false. - **slippageBps** (number) - Optional - Default slippage tolerance in basis points. Default: 25. - **builder** (object) - Optional - Builder fee sharing configuration containing address (string) and feeBps (number). - **subgraphUrl** (string) - Optional - Override for the Ostium subgraph endpoint. - **builderApiUrl** (string) - Optional - Override for the builder API base URL. - **alchemyApiKey** (string) - Optional - Alchemy API key required for streamAccountUpdates(). ### Example ```ts import { OstiumClient } from '@ostium/builder-sdk'; const client = await OstiumClient.createSelfAndSelf({ traderPrivateKey: process.env.TRADER_PRIVATE_KEY as `0x${string}`, rpcUrl: process.env.ARB_RPC_URL!, testnet: false, slippageBps: 25, builder: { address: '0xBuilderAddress', feeBps: 10 }, alchemyApiKey: process.env.ALCHEMY_API_KEY!, }); ``` ``` -------------------------------- ### GET /v1/prices Source: https://docs.ostium.com/developer/builder-api/get-prices Fetches the current Ostium live price snapshot from the Builder API. ```APIDOC ## GET /v1/prices ### Description Fetch the current Ostium live price snapshot directly from the Builder API. ### Method GET ### Endpoint https://builder.prod.bedrock.ostium.io/v1/prices ### Response #### Success Response (200) - **prices** (Array) - List of price objects containing feed_id, pair, from, to, bid, mid, ask, isMarketOpen, isDayTradingClosed, secondsToToggleIsDayTradingClosed, timestampSeconds, and schedule. - **stale** (boolean) - Indicates if the data is stale. - **generatedAt** (number) - Timestamp of when the response was generated. ### Response Example { "prices": [ { "feed_id": "string", "pair": "string", "from": "string", "to": "string", "bid": 0, "mid": 0, "ask": 0, "isMarketOpen": true, "isDayTradingClosed": false, "secondsToToggleIsDayTradingClosed": 0, "timestampSeconds": 0, "schedule": { "id": 0, "alwaysOpen": true, "timezone": "string", "openingHours": ["string"] } } ], "stale": false, "generatedAt": 0 } ``` -------------------------------- ### Perform one-time trader setup Source: https://docs.ostium.com/developer/client-modes/delegated-and-self The trader must approve USDC and set the delegate address before trading can occur. ```ts await traderClient.approveUsdc('max'); await traderClient.setDelegate('0xDelegateAddress'); ``` -------------------------------- ### Initialize Build-only Client Source: https://docs.ostium.com/developer/client-modes/self-and-gasless Create a client for building transactions without submitting them. get*Tx() methods return Safe-style requests. ```ts const client = await OstiumClient.createSelfAndGasless({ traderAddress: '0xTraderAddress', safeAddress: '0xSafeAddress', }); const tx = client.getOpenTradeTx({ pairId: 0, buy: true, price: '65000', collateral: '100', leverage: '5', type: OrderType.Market, }); ``` -------------------------------- ### Perform One-time Trader Setup Source: https://docs.ostium.com/developer/client-modes/delegated-and-gasless The trader must approve USDC and register the delegate Safe address before delegated actions can be performed. ```ts await traderClient.approveUsdc('max'); await traderClient.setDelegate('0xDelegateSafeAddress'); ``` -------------------------------- ### GET /v1/prices Source: https://docs.ostium.com/developer/builder-api/overview Fetches current market prices. ```APIDOC ## GET /v1/prices ### Description Fetches current market prices. ### Method GET ### Endpoint /v1/prices ``` -------------------------------- ### Initialize OstiumClient with self-managed keys Source: https://docs.ostium.com/developer/client-modes/configuration Demonstrates creating a client instance using the createSelfAndSelf factory method with required authentication and configuration options. ```ts import { OstiumClient } from '@ostium/builder-sdk'; const client = await OstiumClient.createSelfAndSelf({ traderPrivateKey: process.env.TRADER_PRIVATE_KEY as `0x${string}`, rpcUrl: process.env.ARB_RPC_URL!, // shared options below are accepted by every write mode testnet: false, slippageBps: 25, builder: { address: '0xBuilderAddress', feeBps: 10 }, alchemyApiKey: process.env.ALCHEMY_API_KEY!, }); ``` -------------------------------- ### Initialize OstiumClient with delegated gasless configuration Source: https://docs.ostium.com/developer/builders/getting-keys-from-the-app Use this snippet to initialize the client after exporting the delegate private key from the Ostium app. Ensure the private key is never committed to source control. ```ts import { OstiumClient } from '@ostium/builder-sdk'; const client = await OstiumClient.createDelegatedAndGasless({ delegatePrivateKey: '0xYourDelegateKey', // paste the key you saved in step 2 traderAddress: '0xa02fa4da932f616975f258ce0a9077f8ed3564', // pimlicoUrl is optional — defaults to Ostium's sponsored Pimlico bundler on Arbitrum One // pimlicoUrl: 'https://builder.prod.bedrock.ostium.io/v1/pimlico/sponsor?chainId=42161', // testnet: true, // Arbitrum Sepolia — uses the 421614 sponsor URL when pimlicoUrl is omitted // sponsorshipPolicyId: '...', // optional Pimlico sponsorship policy id // rpcUrl: 'https://arb-mainnet.g.alchemy.com/v2/...', // optional; public Arbitrum RPC for reads if omitted }); ``` -------------------------------- ### Get Trader Address Source: https://docs.ostium.com/developer/reference/get-trader-address Retrieves the address of the connected trader. This method requires a write-enabled client. ```ts const trader = client.getTraderAddress(); ``` -------------------------------- ### Initialize a submit-capable client Source: https://docs.ostium.com/developer/client-modes/delegated-and-self Creates a client that can sign and submit transactions using the delegate's private key. ```ts const client = await OstiumClient.createDelegatedAndSelf({ delegatePrivateKey: process.env.DELEGATE_PRIVATE_KEY as `0x${string}`, traderAddress: '0xTraderAddress', rpcUrl: process.env.ARB_RPC_URL!, }); ``` -------------------------------- ### Initialize Gasless Client Source: https://docs.ostium.com/developer/builder-api/pimlico-sponsor Creates a gasless client using the default Pimlico-compatible endpoint. ```ts const client = await OstiumClient.createDelegatedAndGasless({ delegatePrivateKey: process.env.DELEGATE_PRIVATE_KEY as `0x${string}`, traderAddress: '0xTraderAddress', }); ``` -------------------------------- ### OstiumClient.createReadOnly() Source: https://docs.ostium.com/developer/client-modes/read-only Initializes a client instance in read-only mode, which does not require a private key or signer. ```APIDOC ## OstiumClient.createReadOnly() ### Description Initializes the OstiumClient in a no-signing, no-submission mode. This mode is suitable for applications that only need to fetch market or account data. ### Parameters - **rpcUrl** (string) - Optional - Arbitrum RPC URL for reads/simulation. - **testnet** (boolean) - Optional - If true, uses Arbitrum Sepolia. - **subgraphUrl** (string) - Optional - Override the default subgraph endpoint. - **builderApiUrl** (string) - Optional - Override the builder API base URL. - **alchemyApiKey** (string) - Optional - Required for streamAccountUpdates(). ### Usage Example ```ts const client = await OstiumClient.createReadOnly(); const { pairs } = await client.getPairs(); const { prices } = await client.getAllPrices(); const positions = await client.getOpenPositions({ user: '0xTraderAddress' }); ``` ``` -------------------------------- ### Fetch Fills by Time Range with TypeScript Source: https://docs.ostium.com/developer/traders/track-fills-and-history Retrieves fills within a specific time window by providing a start time. ```ts const weeklyFills = await client.getFillsByTime({ startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, }); ``` -------------------------------- ### Initialize a submit-capable client Source: https://docs.ostium.com/developer/client-modes/self-and-self Creates a client instance that can sign and submit transactions directly to Arbitrum using a private key. ```ts const client = await OstiumClient.createSelfAndSelf({ traderPrivateKey: process.env.TRADER_PRIVATE_KEY as `0x${string}`, rpcUrl: process.env.ARB_RPC_URL!, }); ``` -------------------------------- ### Initialize Ostium Client Source: https://docs.ostium.com/developer/traders/approvals-and-first-trade Creates a new Ostium client instance using a private key and RPC URL. ```ts import { OrderType, OstiumClient } from '@ostium/builder-sdk'; const client = await OstiumClient.createSelfAndSelf({ traderPrivateKey: process.env.TRADER_PRIVATE_KEY as `0x${string}`, rpcUrl: process.env.ARB_RPC_URL!, }); ``` -------------------------------- ### Initialize OstiumClient Source: https://docs.ostium.com/developer/builders/react-quickstart Create a build-only client using trader and builder addresses to construct transaction calldata. ```ts import { OrderType, OstiumClient } from '@ostium/builder-sdk'; const client = await OstiumClient.createSelfAndSelf({ traderAddress: '0xTraderAddress', builder: { address: '0xYourBuilderAddress', feeBps: 20, }, }); ``` -------------------------------- ### Open a trade with the Builder SDK Source: https://docs.ostium.com/developer/reference/open-trade Executes a market order using the client's default configuration. ```ts const result = await client.openTrade({ pairId: 0, buy: true, price: '65000', collateral: '100', leverage: '10', type: OrderType.Market, }); ``` -------------------------------- ### Initialize account stream Source: https://docs.ostium.com/developer/reference/stream-account-updates Create a client instance and subscribe to account updates using the default self-address configuration. ```ts const client = await OstiumClient.createSelfAndSelf({ traderPrivateKey: process.env.TRADER_PRIVATE_KEY as `0x${string}`, rpcUrl: process.env.ARB_RPC_URL!, alchemyApiKey: process.env.ALCHEMY_API_KEY!, }); const stream = client.streamAccountUpdates(); stream.onUpdate(snapshot => { const account = snapshot[client.getTraderAddress().toLowerCase()]; console.log(account.positions); console.log(account.orders); console.log(account.limits); }); stream.onError(error => console.error(error)); ``` -------------------------------- ### Client Creation Source: https://docs.ostium.com/developer/api-and-sdk Methods used to initialize the Ostium client based on the desired execution mode. ```APIDOC ## Client Creation Methods ### Description Factory methods to initialize an Ostium client. Construction is lazy, and read methods will populate market metadata on first use. ### Methods - `createSelfAndSelf` - `createSelfAndGasless` - `createDelegatedAndSelf` - `createDelegatedAndGasless` - `createReadOnly` ``` -------------------------------- ### getSetupGaslessDelegationTx Source: https://docs.ostium.com/developer/reference/transaction-builders Builds a transaction to set up gasless delegation. ```APIDOC ## getSetupGaslessDelegationTx() ### Description Builds the transaction required to enable gasless delegation for the client. ### Signature `getSetupGaslessDelegationTx()` ``` -------------------------------- ### Initialize a build-only client Source: https://docs.ostium.com/developer/client-modes/self-and-self Creates a client instance that generates transaction payloads for external signing, useful for wallet-driven applications. ```ts const client = await OstiumClient.createSelfAndSelf({ traderAddress: '0xTraderAddress', }); const tx = client.getOpenTradeTx({ pairId: 0, buy: true, price: '65000', collateral: '100', leverage: '5', type: OrderType.Market, }); ``` -------------------------------- ### Initialize Submit-capable Client Source: https://docs.ostium.com/developer/client-modes/self-and-gasless Create a client capable of submitting gasless trades. Providing a safeAddress is optional if you wish to skip smart-account derivation. ```ts const client = await OstiumClient.createSelfAndGasless({ traderPrivateKey: process.env.TRADER_PRIVATE_KEY as `0x${string}`, pimlicoUrl: 'https://builder.prod.bedrock.ostium.io/v1/pimlico/sponsor?chainId=42161', }); ``` ```ts const client = await OstiumClient.createSelfAndGasless({ traderPrivateKey: process.env.TRADER_PRIVATE_KEY as `0x${string}`, safeAddress: '0xSafeAddress', }); ``` -------------------------------- ### Open a market trade with Builder SDK Source: https://docs.ostium.com/developer/traders/open-market-trade Executes a market order using the client.openTrade method with specified pair, direction, price, collateral, and leverage. ```ts import { OrderType } from '@ostium/builder-sdk'; const result = await client.openTrade({ pairId: 0, buy: true, price: '65000', collateral: '100', leverage: '10', type: OrderType.Market, takeProfit: '72000', stopLoss: '61000', }); ``` -------------------------------- ### OstiumClient.createDelegatedAndGasless Source: https://docs.ostium.com/developer/client-modes/delegated-and-gasless Initializes a client for delegated and gasless execution. This method supports both submit-capable clients (using a private key) and build-only clients. ```APIDOC ## OstiumClient.createDelegatedAndGasless ### Description Creates a new client instance configured for delegated execution. This allows a delegate to perform actions on behalf of a trader, with transactions submitted via a Safe smart account. ### Parameters - **delegatePrivateKey** (0x${string}) - Submit-capable - The private key of the delegate EOA. - **traderAddress** (0x${string}) - Required - The address of the trader the delegate acts for. - **delegateAddress** (0x${string}) - Build-only - The address of the delegate EOA. - **safeAddress** (0x${string}) - Build-only/Optional - The address of the delegate's Safe smart account. - **pimlicoUrl** (string) - Optional - The URL for the bundler/paymaster. - **rpcUrl** (string) - Optional - The RPC URL for reads and simulation. - **sponsorshipPolicyId** (string) - Optional - The Pimlico sponsorship policy ID. ### Usage Example ```ts const client = await OstiumClient.createDelegatedAndGasless({ delegatePrivateKey: '0x...', traderAddress: '0xTraderAddress', pimlicoUrl: 'https://builder.prod.bedrock.ostium.io/v1/pimlico/sponsor?chainId=42161', }); ``` ``` -------------------------------- ### OstiumClient.createSelfAndSelf Source: https://docs.ostium.com/developer/client-modes/self-and-self Initializes a client instance in Self + Self mode. This method supports both submit-capable (with private key) and build-only (with address) configurations. ```APIDOC ## OstiumClient.createSelfAndSelf ### Description Initializes the Ostium client for Self + Self mode. This mode is designed for bots, server-side systems, or wallet-driven applications where the trader EOA manages assets and gas payments. ### Parameters - **traderPrivateKey** (0x${string}) - Submit-capable - The trader EOA private key. Required for submitting transactions directly. - **traderAddress** (0x${string}) - Build-only - The trader EOA address. Used when the client is only generating transaction payloads. - **rpcUrl** (string) - Optional - The Arbitrum RPC URL. Required for submit-capable clients; defaults to public RPC for build-only mode. ### Usage Example ```ts // Submit-capable client const client = await OstiumClient.createSelfAndSelf({ traderPrivateKey: process.env.TRADER_PRIVATE_KEY as `0x${string}`, rpcUrl: process.env.ARB_RPC_URL!, }); // Build-only client const client = await OstiumClient.createSelfAndSelf({ traderAddress: '0xTraderAddress', }); ``` ``` -------------------------------- ### Fetch Open Positions with Various Filters Source: https://docs.ostium.com/developer/reference/get-open-positions Demonstrates how to retrieve positions for the connected wallet, specific traders, or all traders, including pagination options. ```ts // Connected wallet (default) const { pairPositions, marginSummary } = await client.getOpenPositions(); // Specific trader (read-only mode) await client.getOpenPositions({ user: '0xTraderAddress' }); // All traders — no user filter await client.getOpenPositions({ user: 'ALL' }); // Paginated — first page of 50 await client.getOpenPositions({ user: 'ALL', limit: 50, skip: 0 }); // Paginated — second page await client.getOpenPositions({ user: 'ALL', limit: 50, skip: 50 }); ``` -------------------------------- ### setupGaslessDelegation() Source: https://docs.ostium.com/developer/reference/setup-gasless-delegation Registers the Safe address as a delegate for the trader EOA to enable gasless trading. This method should be called after initializing the client with createSelfAndGasless(). ```APIDOC ## setupGaslessDelegation() ### Description Registers the Safe returned by getSmartAccountAddress() as the delegate for the trader EOA, enabling gasless trading operations. ### Usage ```ts await client.approveUsdc('max'); await client.setupGaslessDelegation(); ``` ### Response - **txHash** (`0x${string}`) - The transaction hash of the delegation registration. - **smartAccountAddress** (`0x${string}`, optional) - The address of the registered smart account. ``` -------------------------------- ### OstiumClient.createDelegatedAndSelf Source: https://docs.ostium.com/developer/client-modes/delegated-and-self Initializes a client in Delegated and Self mode. This can be configured as a submit-capable client (providing a private key) or a build-only client (providing only addresses). ```APIDOC ## OstiumClient.createDelegatedAndSelf ### Description Creates a client instance configured for delegated execution. The delegate EOA signs and pays gas on behalf of the trader EOA. ### Parameters - **delegatePrivateKey** (0x${string}) - Submit-capable - The private key of the delegate EOA. - **traderAddress** (0x${string}) - Required - The address of the trader the delegate acts for. - **delegateAddress** (0x${string}) - Build-only - The address of the delegate EOA. - **rpcUrl** (string) - Optional - The Arbitrum RPC URL to use. ### Usage Example ```ts // Submit-capable client const client = await OstiumClient.createDelegatedAndSelf({ delegatePrivateKey: process.env.DELEGATE_PRIVATE_KEY as `0x${string}`, traderAddress: '0xTraderAddress', rpcUrl: process.env.ARB_RPC_URL!, }); // Build-only client const client = await OstiumClient.createDelegatedAndSelf({ traderAddress: '0xTraderAddress', delegateAddress: '0xDelegateAddress', }); ``` ``` -------------------------------- ### Initialize Build-only Client Source: https://docs.ostium.com/developer/client-modes/delegated-and-gasless Creates a client that returns Safe-style requests with call data wrapped for delegated execution, without submitting transactions directly. ```ts const client = await OstiumClient.createDelegatedAndGasless({ traderAddress: '0xTraderAddress', delegateAddress: '0xDelegateAddress', safeAddress: '0xDelegateSafeAddress', }); ``` -------------------------------- ### Configure Builder Fees at Client Creation Source: https://docs.ostium.com/developer/builders/overview Sets the builder address and fee basis points during the initial client instantiation. Fees are applied automatically to all opening trades. ```ts const client = await OstiumClient.createSelfAndSelf({ traderPrivateKey: userPrivateKey, rpcUrl: process.env.ARB_RPC_URL!, builder: { address: '0xYourBuilderAddress', feeBps: 20, }, }); ``` -------------------------------- ### Configure builder fees during client creation Source: https://docs.ostium.com/developer/builder-codes Initialize the Ostium client with a builder address and fee in basis points. Fees are applied automatically to all trades opened through this client. ```typescript const client = await OstiumClient.createSelfAndSelf({ traderPrivateKey: userPrivateKey, rpcUrl: process.env.ARB_RPC_URL!, builder: { address: '0xYourBuilderAddress', feeBps: 20, }, }); ``` -------------------------------- ### getPairs() Source: https://docs.ostium.com/developer/traders/discover-pairs Fetches the complete market catalog including market state, leverage limits, and pricing information. ```APIDOC ## getPairs() ### Description Retrieves the list of available Ostium markets. This method provides essential data including pair IDs, leverage limits, and market status required for trading operations. ### Method SDK Method ### Signature `client.getPairs()` ### Returns - **pairs** (Array) - A list of market objects containing: - **pairId** (string) - Unique identifier for the market. - **pairFrom** (string) - The base asset. - **pairTo** (string) - The quote asset. - **maxLeverage** (number) - Maximum allowed leverage. - **overnightMaxLeverage** (number) - Maximum leverage allowed for overnight positions. - **midPx** (number) - Current mid-price of the pair. - **isMarketOpen** (boolean) - Indicates if the market is currently accepting trades. ``` -------------------------------- ### Initialize Submit-capable Client Source: https://docs.ostium.com/developer/client-modes/delegated-and-gasless Creates a client capable of submitting transactions. You can optionally provide a pre-derived Safe address to skip the SDK's derivation process. ```ts const client = await OstiumClient.createDelegatedAndGasless({ delegatePrivateKey: process.env.DELEGATE_PRIVATE_KEY as `0x${string}`, traderAddress: '0xTraderAddress', pimlicoUrl: 'https://builder.prod.bedrock.ostium.io/v1/pimlico/sponsor?chainId=42161', }); ``` ```ts const client = await OstiumClient.createDelegatedAndGasless({ delegatePrivateKey: process.env.DELEGATE_PRIVATE_KEY as `0x${string}`, traderAddress: '0xTraderAddress', safeAddress: '0xDelegateSafeAddress', }); ``` -------------------------------- ### Enable Testnet in OstiumClient Source: https://docs.ostium.com/developer/client-modes/testnet Configure the client for Arbitrum Sepolia by setting the testnet property to true during initialization. ```ts const client = await OstiumClient.createDelegatedAndGasless({ delegatePrivateKey: process.env.DELEGATE_PRIVATE_KEY as `0x${string}`, traderAddress: '0xTraderAddress', testnet: true, }); ``` -------------------------------- ### SDK Configuration Source: https://docs.ostium.com/developer/builder-api/subgraph How to override the default subgraph URL when initializing the Ostium client. ```APIDOC ## SDK Configuration ### Description To use a custom subgraph, override the default endpoint by providing the `subgraphUrl` parameter when creating the client. ### Example ```ts const client = await OstiumClient.createReadOnly({ subgraphUrl: 'https://your-subgraph.example.com/graphql', }); ``` ``` -------------------------------- ### Initialize Read-only Client Source: https://docs.ostium.com/developer/client-modes/read-only Basic initialization of the read-only client and retrieval of market data. ```ts const client = await OstiumClient.createReadOnly(); const { pairs } = await client.getPairs(); const { prices } = await client.getAllPrices(); const positions = await client.getOpenPositions({ user: '0xTraderAddress' }); ``` -------------------------------- ### Open a Limit Order with Builder SDK Source: https://docs.ostium.com/developer/traders/open-limit-or-stop-order Use the openTrade method with OrderType.Limit to place a limit order. Ensure the price is set as the trigger price. ```ts await client.openTrade({ pairId: 0, buy: true, price: '64000', collateral: '100', leverage: '5', type: OrderType.Limit, }); ``` -------------------------------- ### Initialize and Listen to Price Streams Source: https://docs.ostium.com/developer/reference/stream-prices Opens a WebSocket stream for specific pair IDs and registers handlers for snapshots and individual tick updates. ```ts const stream = client.streamPrices([0, 1]); stream.onSnapshot(ticks => { console.log(ticks); }); stream.onTick(tick => { console.log(tick.pair, tick.mid); }); ``` -------------------------------- ### getBalances() Source: https://docs.ostium.com/developer/reference/get-balances Fetches the USDC balance, ETH balance, and USDC allowance for an Ostium trader. ```APIDOC ## getBalances ### Description Fetches USDC balance, ETH balance, and USDC allowance for an Ostium trader. ### Method SDK Method ### Parameters - **address** (string) - Optional - The address of the trader to fetch balances for. If not provided, it defaults to the authenticated client. ### Response - **usdc** (string) - The USDC balance. - **eth** (string) - The ETH balance. - **allowance** (string) - The USDC allowance. ### Response Example { "usdc": "string", "eth": "string", "allowance": "string" } ``` -------------------------------- ### Fetch prices via SDK Source: https://docs.ostium.com/developer/builder-api/get-prices Retrieve all prices using the client SDK method. ```ts const { prices } = await client.getAllPrices(); ``` -------------------------------- ### Initialize a build-only client Source: https://docs.ostium.com/developer/client-modes/delegated-and-self Creates a client that generates transaction requests with calldata wrapped for delegated execution without submitting them. ```ts const client = await OstiumClient.createDelegatedAndSelf({ traderAddress: '0xTraderAddress', delegateAddress: '0xDelegateAddress', }); ``` -------------------------------- ### SDK Price Stream Subscription Source: https://docs.ostium.com/developer/builder-api/ws-prices-stream Simplified method to initiate a price stream using the SDK. ```ts const stream = client.streamPrices([0, 1]); ``` -------------------------------- ### OstiumClient.createSelfAndGasless Source: https://docs.ostium.com/developer/client-modes/self-and-gasless Initializes an OstiumClient instance configured for Self + Gasless mode. This method supports both submit-capable clients (using a private key) and build-only clients (using an address). ```APIDOC ## OstiumClient.createSelfAndGasless ### Description Creates a client instance that enables gasless trading by routing transactions through a Safe smart account. The client can be initialized for direct submission or for building transaction payloads. ### Parameters - **traderPrivateKey** (0x${string}) - Submit-capable - The trader's EOA private key used to derive the Safe and sign trades. - **traderAddress** (0x${string}) - Build-only - The trader's EOA address. - **safeAddress** (0x${string}) - Build-only; optional submit-capable - The address of the Safe smart account. Required for build-only mode. - **pimlicoUrl** (string) - Optional - The URL for the bundler/paymaster service. - **rpcUrl** (string) - Optional - The RPC URL for blockchain interactions. - **sponsorshipPolicyId** (string) - Optional - The Pimlico sponsorship policy ID. ### Usage Example ```ts // Submit-capable client const client = await OstiumClient.createSelfAndGasless({ traderPrivateKey: '0x...', pimlicoUrl: 'https://...' }); // Build-only client const client = await OstiumClient.createSelfAndGasless({ traderAddress: '0x...', safeAddress: '0x...' }); ``` ``` -------------------------------- ### getOpenPositions(params?: { user?: Address | 'ALL', blockNumber?: bigint, limit?: number, skip?: number }) Source: https://docs.ostium.com/developer/reference/get-open-positions Fetches live Ostium positions and margin summary for a specific user or all traders. ```APIDOC ## getOpenPositions ### Description Fetches live Ostium positions, margin summary, and withdrawable collateral. The returned `pairId` and `idx` values are used by position-management methods. ### Parameters - **user** (Address | 'ALL') - Optional - Trader address to scope results to. Pass 'ALL' to fetch open positions across every trader. Defaults to the connected wallet. - **blockNumber** (bigint) - Optional - Arbitrum block number used for live PnL projection. Defaults to the current block. - **limit** (number) - Optional - Maximum number of positions to return. Defaults to Infinity. - **skip** (number) - Optional - Number of positions to skip for pagination. Defaults to 0. ### Response - **pairPositions** (Array) - List of open positions including pair details, entry price, leverage, and PnL metrics. - **marginSummary** (Object) - Summary of account value, collateral used, and total PnL. - **time** (number) - Timestamp of the response. ``` -------------------------------- ### Include builder fee Source: https://docs.ostium.com/developer/reference/get-pairs Calculates openFee values using a custom builder fee in basis points. ```ts const { pairs } = await client.getPairs({ builderFeeBps: 20 }); ``` -------------------------------- ### getAllPrices() Source: https://docs.ostium.com/developer/reference/get-all-prices Fetches current mid, bid, and ask prices for all Ostium pairs. This method is ideal for retrieving price quotes without the overhead of the full getPairs payload. ```APIDOC ## getAllPrices() ### Description Fetches current mid, bid, and ask prices for all Ostium pairs. The response is keyed by `pairId`. ### Method SDK Method ### Response - **prices** (Record) - A dictionary of price data keyed by pairId. ### Example ```ts const { prices } = await client.getAllPrices(); console.log(prices['0']); ``` ``` -------------------------------- ### getPairs Source: https://docs.ostium.com/developer/reference/get-pairs Fetches all Ostium pairs along with their associated market metadata, leverage limits, and live price fields. ```APIDOC ## getPairs ### Description Returns the current list of trading pairs with market metadata and live price fields. This method is used for populating pair pickers, market tables, and discovering pair IDs or leverage limits before executing trades. ### Method client.getPairs(params?: GetPairsParams) ### Parameters - **pairIds** (Array) - Optional - Filter the returned pairs by specific IDs. - **builderFeeBps** (number) - Optional - Include a builder fee in the computed openFee values. Defaults to the configured builder.feeBps if omitted. ### Response - **pairs** (Array) - A list of pair objects containing: - **pairId** (string) - **pairTo** (string) - **pairFrom** (string) - **minSz** (string) - **maxBSz** (string) - **maxSSz** (string) - **minNtl** (string) - **maxLeverage** (number) - **overnightMaxLeverage** (number) - **rolloverFeePerBlock** (string) - **openInterest** (string) - **buyOpenInterest** (string) - **sellOpenInterest** (string) - **maxOpenInterest** (string) - **category** (string) - **rolloverRate** (Object: { long: string, short: string }) - **midPx** (string) - **askPx** (string) - **bidPx** (string) - **isMarketOpen** (boolean) - **isDayTradingClosed** (boolean) - **secondsToToggleIsDayTradingClosed** (number) - **schedule** (PairSchedule) - Optional - **openFee** (number) - Pair taker fee plus builder fee in basis points - **closeFee** (number) ``` -------------------------------- ### client.openTrade Source: https://docs.ostium.com/developer/traders/open-market-trade Opens a new market position on the Ostium platform. ```APIDOC ## client.openTrade ### Description Opens a market position on Ostium with the Builder SDK. ### Method SDK Method ### Parameters - **pairId** (number) - Required - The ID of the trading pair, obtained from getPairs(). - **buy** (boolean) - Required - Set to true for a long position, false for a short position. - **price** (string) - Required - The current market price. - **collateral** (string) - Required - The amount of collateral in USD. - **leverage** (string) - Required - The leverage amount. - **type** (OrderType) - Required - The order type (e.g., OrderType.Market). - **takeProfit** (string) - Optional - The take profit price level. - **stopLoss** (string) - Optional - The stop loss price level. ### Usage Example ```ts import { OrderType } from '@ostium/builder-sdk'; const result = await client.openTrade({ pairId: 0, buy: true, price: '65000', collateral: '100', leverage: '10', type: OrderType.Market, takeProfit: '72000', stopLoss: '61000', }); ``` ### Notes - Slippage applies to market orders. - Builder fees apply automatically if configured at client construction. ``` -------------------------------- ### Implement Optimistic Open Source: https://docs.ostium.com/developer/reference/stream-account-updates Adds an optimistic overlay to the UI immediately after trade submission and reconciles it once the on-chain order ID is available. ```ts import { extractOrderIdFromReceipt } from '@ostium/builder-sdk'; const result = await client.openTrade(params); const localId = stream.addOptimisticOpen(params, result); const receipt = await publicClient.waitForTransactionReceipt({ hash: result.txHash, }); const orderId = extractOrderIdFromReceipt(receipt); if (orderId) { stream.attachOrderId(localId, orderId, { initiatedTx: result.txHash, }); } ``` -------------------------------- ### client.openTrade(params) Source: https://docs.ostium.com/developer/reference/open-trade Executes a trade on the Ostium platform using the provided parameters. ```APIDOC ## client.openTrade(params) ### Description Opens a market, limit, or stop trade on the Ostium platform. The method requires specific trade parameters and returns a transaction hash. ### Parameters - **pairId** (string | number) - Required - The ID of the trading pair, obtained from getPairs(). - **buy** (boolean) - Required - True for a long position, false for a short position. - **price** (string) - Required - The execution price for the trade. - **collateral** (string) - Required - The amount of collateral for the trade (minimum 5 USD). - **leverage** (string) - Required - The leverage multiplier for the trade. - **type** (OrderType) - Required - The type of order (Market, Limit, or Stop). - **takeProfit** (string) - Optional - The take profit price level. - **stopLoss** (string) - Optional - The stop loss price level. - **slippage** (number) - Optional - Slippage tolerance for market orders. - **isDayTrade** (boolean) - Optional - Required if leverage exceeds the pair's overnight limit. - **builder** (object) - Optional - Override builder fee configuration. - **address** (string) - Optional - The builder address. - **feeBps** (number) - Optional - The builder fee in basis points. ### Response - **txHash** (string) - The transaction hash of the submitted trade. - **smartAccountAddress** (string) - Optional - The address of the smart account used for the trade. ``` -------------------------------- ### Fetch OHLC candles via SDK Source: https://docs.ostium.com/developer/builder-api/post-ohlc Use the SDK to retrieve candles; it automatically handles pagination via the 'sets' parameter. ```typescript const candles = await client.getCandles({ pairId: 0, from: Date.now() - 30 * 24 * 60 * 60 * 1000, resolution: '1D', sets: 3, }); ``` -------------------------------- ### Fetch and iterate open positions in TypeScript Source: https://docs.ostium.com/developer/traders/manage-positions Retrieves current positions and logs key details like pair ID, index, side, and PnL. Requires an initialized client instance. ```ts const { pairPositions, marginSummary, withdrawable } = await client.getOpenPositions(); for (const { position } of pairPositions) { console.log( position.pairId, position.idx, position.side, position.entryPx, position.unrealizedPnl, position.liquidationPx, ); } console.log(marginSummary.accountValue, withdrawable); ``` -------------------------------- ### client.closeTrade Source: https://docs.ostium.com/developer/reference/close-trade Closes a position fully or partially using the Builder SDK. ```APIDOC ## client.closeTrade ### Description Fully or partially close an Ostium position. ### Parameters - **pairId** (string) - Required - The identifier for the trading pair. - **idx** (number) - Required - The index of the position. - **price** (string) - Required - The price at which to close the trade. - **closePercent** (number) - Required - The percentage of the position to close (e.g., 100 for full, 50 for partial). ### Response - **txHash** (string) - The transaction hash of the close operation. - **smartAccountAddress** (string, optional) - The address of the smart account used. ``` -------------------------------- ### streamPrices(pairIds) Source: https://docs.ostium.com/developer/reference/stream-prices Initializes a live WebSocket price stream for the specified pair IDs. ```APIDOC ## streamPrices(pairIds) ### Description Opens a live WebSocket price stream from the Ostium Builder SDK. You can call this method immediately after client creation, and it handles subscription filtering automatically even if metadata is still loading. ### Parameters - **pairIds** (Array) - Required - A list of pair identifiers to subscribe to. ### Methods - **onSnapshot(handler)**: Registers a callback for the initial snapshot of ticks. - **onTick(handler)**: Registers a callback for individual price tick updates. - **subscribe(pairIds)**: Dynamically adds new pairs to the existing stream. - **unsubscribe(pairIds)**: Dynamically removes pairs from the existing stream. - **close()**: Closes the WebSocket connection. ### Response Schema (PriceTick) - **pairId** (string) - Optional - The ID of the trading pair. - **feedId** (string) - The ID of the price feed. - **pair** (string) - The trading pair symbol. - **bid** (number) - The current bid price. - **mid** (number) - The current mid price. - **ask** (number) - The current ask price. - **isMarketOpen** (boolean) - Indicates if the market is currently open. - **timestampSeconds** (number) - The timestamp of the tick in seconds. ``` -------------------------------- ### Fetch and display opening fees in React Source: https://docs.ostium.com/traders/reference/fees A React component that fetches market fee data from the Ostium subgraph and renders a formatted table. It includes logic for market name normalization and fee calculation. ```javascript export const OpeningFeeTable = () => { const [rows, setRows] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [expanded, setExpanded] = useState(new Set()); useEffect(() => { let cancelled = false; const pairLabel = (from, to) => { const raw = `${from}/${to}`; const overrides = { "CL/USD": "WTI/USD", "HG/USD": "XCU/USD", "SPX/USD": "US500/USD", "NDX/USD": "US100/USD", "DJI/USD": "US30/USD", "DAX/EUR": "GER40/EUR", "FTSE/GBR": "UK100/GBR", "HSI/HKD": "HK50/HKD", "NIK/JPY": "JP225/JPY" }; return overrides[raw] ?? raw; }; (async () => { try { const res = await fetch("https://api.subgraph.ormilabs.com/api/public/67a599d5-c8d2-4cc4-9c4d-2975a97bc5d8/subgraphs/ost-prod/live/gn", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: `query { pairs(first: 100) { takerFeeP from to group { name } } }` }) }); const json = await res.json(); if (json.errors?.length) throw new Error(json.errors.map(e => e.message).join("; ")); if (!cancelled) setRows((json.data?.pairs ?? []).map(p => ({ market: pairLabel(p.from, p.to), group: p.group?.name ?? "other", feeBps: parseFloat(p.takerFeeP) / 1e4 }))); } catch (e) { if (!cancelled) setError(e.message || "Failed to load fees"); } finally { if (!cancelled) setLoading(false); } })(); return () => { cancelled = true; }; }, []); const fmtGroup = name => { if (!name) return "Other"; if (name.toLowerCase() === "etf") return "ETF"; return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); }; const fmtBps = n => { if (!Number.isFinite(n)) return "—"; return `${Math.round(n * 100) / 100} bps`; }; const groups = useMemo(() => { const map = new Map(); for (const r of rows) { if (!map.has(r.group)) map.set(r.group, []); map.get(r.group).push(r); } return Array.from(map.entries()).map(([name, pairs]) => { const fees = pairs.map(p => p.feeBps).filter(Number.isFinite); const minRaw = fees.length ? Math.min(...fees) : null; const maxRaw = fees.length ? Math.max(...fees) : null; const minR = minRaw != null ? Math.round(minRaw * 100) / 100 : null; const maxR = maxRaw != null ? Math.round(maxRaw * 100) / 100 : null; const feeRange = minR === maxR ? fmtBps(minRaw) : `${fmtBps(minRaw)} – ${fmtBps(maxRaw)}`; return { name, label: fmtGroup(name), pairs: [...pairs].sort((a, b) => a.market.localeCompare(b.market)), feeRange }; }).sort((a, b) => a.label.localeCompare(b.label)); }, [rows]); const toggle = name => setExpanded(prev => { const next = new Set(prev); next.has(name) ? next.delete(name) : next.add(name); return next; }); if (error) return

{error}

; const headCell = "px-3 py-2 text-xs font-semibold uppercase tracking-wide text-zinc-500 dark:text-zinc-500"; const bodyCell = "px-3 py-1.5 text-sm text-zinc-700 dark:text-zinc-300"; const feeHead = `${headCell} w-[1%] whitespace-nowrap tabular-nums !text-right`; const feeBody = `${bodyCell} w-[1%] whitespace-nowrap text-right tabular-nums`; return
{loading && Array.from({ length: 6 }).map((_, i) =>
Group / market Opening Closing
```