### Execute REST Spot Public Example with ts-node Source: https://github.com/tiagosiebler/bybit-api/blob/master/examples/README.md Run the REST Spot public API example using ts-node. Ensure you have ts-node installed and the example file is present. ```bash ts-node ./examples/rest-spot-public.ts ``` -------------------------------- ### Install Bybit SDK with pnpm or yarn Source: https://github.com/tiagosiebler/bybit-api/blob/master/docs/BYBIT_SDK_QUICKSTART_GUIDE.md Alternative installation methods using pnpm or yarn. Choose the package manager that best suits your project setup. ```bash pnpm install bybit-api ``` ```bash yarn add bybit-api ``` -------------------------------- ### RestClientV5 Usage Example Source: https://github.com/tiagosiebler/bybit-api/blob/master/README.md This example demonstrates how to initialize and use the RestClientV5 for making API calls. It shows how to set up API credentials, connect to the testnet, and make sample calls to get account information and order book data. ```APIDOC ## REST API Usage Create API credentials on Bybit's website: - [Livenet](https://bybit.com/app/user/api-management?affiliate_id=9410&language=en-US&group_id=0&group_type=1) - [Testnet](https://testnet.bybit.com/app/user/api-management) The following is a minimal example for using the REST clients included with this SDK. For more detailed examples, refer to the [examples](./examples/) folder in the repository on GitHub: ```typescript const { RestClientV5 } = require('bybit-api'); // or // import { RestClientV5 } from 'bybit-api'; const restClientOptions = { /** supports HMAC & RSA API keys - automatically detected */ /** Your API key */ key: 'apiKeyHere', /** Your API secret */ secret: 'apiSecretHere', /** Set to `true` to connect to testnet. Uses the live environment by default. */ // testnet: true, /** * Set to `true` to use Bybit's V5 demo trading: * https://bybit-exchange.github.io/docs/v5/demo * * Note: to use demo trading, you should have `testnet` disabled. * * You can find a detailed demoTrading example in the examples folder on GitHub. */ // demoTrading: true, /** Override the max size of the request window (in ms) */ // recv_window: 5000, // 5000 = 5 seconds /** * Enable keep alive for REST API requests (via axios). * See: https://github.com/tiagosiebler/bybit-api/issues/368 */ // keepAlive: true, /** * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over * sockets being kept alive. Only relevant if keepAlive is set to true. * Default: 1000 (defaults comes from https agent) */ // keepAliveMsecs: 1000, // 1000 = 1 second /** * Optionally override API domain used: * apiRegion: 'default' | 'bytick' | 'NL' | 'HK' | 'TK', **/ // apiRegion: 'bytick', /** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */ // parseAPIRateLimits: true, /** * Allows you to provide a custom "signMessage" function, * e.g. to use node crypto's much faster createHmac method * * Look at examples/fasterHmacSign.ts for a demonstration: */ // customSignMessageFn: (message: string, secret: string) => Promise; }; const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const client = new RestClientV5( { key: API_KEY, secret: API_SECRET, // demoTrading: true, // Optional: enable to try parsing rate limit values from responses // parseAPIRateLimits: true }, // requestLibraryOptions ); // For public-only API calls, simply don't provide a key & secret or set them to undefined // const client = new RestClientV5(); client .getAccountInfo() .then((result) => { console.log('getAccountInfo result: ', result); }) .catch((err) => { console.error('getAccountInfo error: ', err); }); client .getOrderbook({ category: 'linear', symbol: 'BTCUSDT' }) .then((result) => { console.log('getOrderBook result: ', result); }) .catch((err) => { console.error('getOrderBook error: ', err); }); ``` ``` -------------------------------- ### Install Bybit SDK with npm Source: https://github.com/tiagosiebler/bybit-api/blob/master/docs/BYBIT_SDK_QUICKSTART_GUIDE.md Install the SDK using npm. This is the standard way to add the library to your Node.js project. ```bash npm install bybit-api ``` -------------------------------- ### Example API Key Source: https://github.com/tiagosiebler/bybit-api/blob/master/examples/Auth/RSA-sign.md This is an example of the API Key provided by Bybit after submitting your public key. ```text your-api-key-here ``` -------------------------------- ### Get Account Information using RestClientV5 Source: https://github.com/tiagosiebler/bybit-api/blob/master/README.md A minimal example demonstrating how to fetch account information using the RestClientV5. This requires valid API credentials to be configured in the client. ```typescript client .getAccountInfo() .then((result) => { console.log('getAccountInfo result: ', result); }) .catch((err) => { console.error('getAccountInfo error: ', err); }); ``` -------------------------------- ### TypeScript Examples Configuration Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Configuration for compiling example TypeScript files, allowing JavaScript files and outputting to 'distExamples'. ```json { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "distExamples", "allowJs": true }, "include": ["examples/**/*.ts", "examples/**/*.js"] } ``` -------------------------------- ### Example RSA Public Key Format Source: https://github.com/tiagosiebler/bybit-api/blob/master/examples/Auth/RSA-sign.md This is an example of the RSA public key format that should be submitted to Bybit when creating API credentials. ```pem -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxFd5fW6r6GVOt9pHJVBe BjUyob6JTfXXVvmi/RXOH1NB/4JgjlCxqdZDBYf8O8FnBFFSLuXfiEcSfuYPaSpa vgwwboJSXPyhhtyJVF4HCbNiVVxSOjBoDxL3a1LL33NQ/UJZiH4SZIGl81T4TviN TcsX1PzKRVxeDpentzUEWw7A5Uv+TseLcjUkh4H/IS2UZ2mVVDwL4Zce3oRTzQ5P RtW+QaLaDdgYoteJATMBvkf619QAIJelnaDzT0/PDLKFvtNaiPd4/RxqbDEwH6JS w7QQx8FFpcMzKCuJPiT75lHKINxIiclbjrWpPQw73/ZZkteeiuqJEJQ0JRzZskza PQIDAQAB -----END PUBLIC KEY----- ``` -------------------------------- ### Example of Stringifying Data with Target Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt An example demonstrating how to stringify data, specifically including a 'target' property set to 'WebSocket'. This might be used for logging or debugging purposes. ```typescript // JSON.stringify({ ...data, target: 'WebSocket' }), ``` -------------------------------- ### Initialize RestClientV5 with Options Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Demonstrates how to initialize the RestClientV5 with various configuration options including API keys, testnet, demo trading, and request window settings. Ensure API keys are correctly set for authentication. ```typescript const { RestClientV5 } = require('bybit-api'); // or // import { RestClientV5 } from 'bybit-api'; const restClientOptions = { /** supports HMAC & RSA API keys - automatically detected */ /** Your API key */ key: 'apiKeyHere', /** Your API secret */ secret: 'apiSecretHere', /** Set to `true` to connect to testnet. Uses the live environment by default. */ // testnet: true, /** * Set to `true` to use Bybit's V5 demo trading: * https://bybit-exchange.github.io/docs/v5/demo * * Note: to use demo trading, you should have `testnet` disabled. * * You can find a detailed demoTrading example in the examples folder on GitHub. */ // demoTrading: true, /** Override the max size of the request window (in ms) */ // recv_window: 5000, // 5000 = 5 seconds /** * Enable keep alive for REST API requests (via axios). * See: https://github.com/tiagosiebler/bybit-api/issues/368 */ // keepAlive: true, /** * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over * sockets being kept alive. Only relevant if keepAlive is set to true. * Default: 1000 (defaults comes from https agent) */ // keepAliveMsecs: 1000, // 1000 = 1 second /** * Optionally override API domain used: * apiRegion: 'default' | 'bytick' | 'NL' | 'HK' | 'TK', **/ // apiRegion: 'bytick', /** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */ // parseAPIRateLimits: true, /** * Allows you to provide a custom "signMessage" function, * e.g. to use node crypto's much faster createHmac method * * Look at examples/fasterHmacSign.ts for a demonstration: */ // customSignMessageFn: (message: string, secret: string) => Promise; }; const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const client = new RestClientV5( { key: API_KEY, secret: API_SECRET, // demoTrading: true, // Optional: enable to try parsing rate limit values from responses // parseAPIRateLimits: true }, // requestLibraryOptions ); // For public-only API calls, simply don't provide a key & secret or set them to undefined // const client = new RestClientV5(); client .getAccountInfo() .then((result) => { console.log('getAccountInfo result: ', result); }) .catch((err) => { console.error('getAccountInfo error: ', err); }); client .getOrderbook({ category: 'linear', symbol: 'BTCUSDT' }) .then((result) => { console.log('getOrderBook result: ', result); }) .catch((err) => { console.error('getOrderBook error: ', err); }); ``` -------------------------------- ### Get SMP Group - Bybit API v5 Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Retrieves the SMP group information for the account. No specific setup required beyond authentication. ```typescript getSMPGroup(): Promise< APIResponseV3WithTime<{ smpGroup: number; }> > { return this.getPrivate('/v5/account/smp-group'); } ``` -------------------------------- ### Initialize RestClientV5 with Options Source: https://github.com/tiagosiebler/bybit-api/blob/master/README.md Demonstrates how to initialize the RestClientV5 with various configuration options, including API keys, testnet, demo trading, and request window settings. Ensure API keys are valid for the chosen environment (live or testnet). ```typescript const { RestClientV5 } = require('bybit-api'); // or // import { RestClientV5 } from 'bybit-api'; const restClientOptions = { /** supports HMAC & RSA API keys - automatically detected */ /** Your API key */ key: 'apiKeyHere', /** Your API secret */ secret: 'apiSecretHere', /** Set to `true` to connect to testnet. Uses the live environment by default. */ // testnet: true, /** * Set to `true` to use Bybit's V5 demo trading: * https://bybit-exchange.github.io/docs/v5/demo * * Note: to use demo trading, you should have `testnet` disabled. * * You can find a detailed demoTrading example in the examples folder on GitHub. */ // demoTrading: true, /** Override the max size of the request window (in ms) */ // recv_window: 5000, // 5000 = 5 seconds /** * Enable keep alive for REST API requests (via axios). * See: https://github.com/tiagosiebler/bybit-api/issues/368 */ // keepAlive: true, /** * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over * sockets being kept alive. Only relevant if keepAlive is set to true. * Default: 1000 (defaults comes from https agent) */ // keepAliveMsecs: 1000, // 1000 = 1 second /** * Optionally override API domain used: * apiRegion: 'default' | 'bytick' | 'NL' | 'HK' | 'TK', **/ // apiRegion: 'bytick', /** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */ // parseAPIRateLimits: true, /** * Allows you to provide a custom "signMessage" function, * e.g. to use node crypto's much faster createHmac method * * Look at examples/fasterHmacSign.ts for a demonstration: */ // customSignMessageFn: (message: string, secret: string) => Promise; }; const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const client = new RestClientV5( { key: API_KEY, secret: API_SECRET, // demoTrading: true, // Optional: enable to try parsing rate limit values from responses // parseAPIRateLimits: true }, // requestLibraryOptions ); ``` -------------------------------- ### Get Institutional Lending Repay Orders Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Retrieves institutional lending repay orders, with options to filter by start time, end time, and limit. ```typescript getInstitutionalLendingRepayOrders(params?: { startTime?: number; endTime?: number; limit?: number; }): Promise { console.log('getOrderBook result: ', result); }) .catch((err) => { console.error('getOrderBook error: ', err); }); ``` -------------------------------- ### RestClientV5 Initialization and Usage Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Demonstrates how to initialize the RestClientV5 with API keys and make basic calls to get account information and order book data. ```APIDOC ## RestClientV5 Initialization and Usage ### Description This section shows how to instantiate the `RestClientV5` class, configure it with API credentials (key and secret), and perform common operations like fetching account information and retrieving order book data. It also includes examples for public-only API calls. ### Initialization ```typescript const { RestClientV5 } = require('bybit-api'); // or // import { RestClientV5 } from 'bybit-api'; const restClientOptions = { key: 'apiKeyHere', secret: 'apiSecretHere', // testnet: true, // Uncomment to use testnet // demoTrading: true, // Uncomment to use demo trading (ensure testnet is disabled) // recv_window: 5000, // Optional: Override request window size // keepAlive: true, // Optional: Enable keep alive for requests // apiRegion: 'bytick', // Optional: Override API region // parseAPIRateLimits: true, // Optional: Parse rate limits from responses // customSignMessageFn: async (message: string, secret: string): Promise => { // // Custom signing function implementation // return 'signedMessage'; // }, }; const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const client = new RestClientV5( { key: API_KEY, secret: API_SECRET, // demoTrading: true, // parseAPIRateLimits: true }, // requestLibraryOptions ); // For public-only API calls, initialize without key and secret: // const client = new RestClientV5(); ``` ### Example Calls #### Get Account Info ```typescript client .getAccountInfo() .then((result) => { console.log('getAccountInfo result: ', result); }) .catch((err) => { console.error('getAccountInfo error: ', err); }); ``` #### Get Orderbook ```typescript client .getOrderbook({ category: 'linear', symbol: 'BTCUSDT' }) .then((result) => { console.log('getOrderBook result: ', result); }) .catch((err) => { console.error('getOrderBook error: ', err); }); ``` ``` -------------------------------- ### Get Institutional Lending Loan Orders Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Retrieves institutional lending loan orders, with options to filter by order ID, start time, end time, and limit. ```typescript getInstitutionalLendingLoanOrders(params?: { orderId?: string; startTime?: number; endTime?: number; limit?: number; }): Promise { return this.getPrivate('/v5/asset/deposit/query-internal-record', params); } ``` -------------------------------- ### Initialize RestClientV5 for Demo Trading Source: https://github.com/tiagosiebler/bybit-api/blob/master/docs/BYBIT_SDK_QUICKSTART_GUIDE.md Set up the RestClientV5 for demo trading using a mainnet demo account. This requires setting the 'demoTrading' option to true. ```typescript const client = new RestClientV5({ key: process.env.BYBIT_API_KEY!, secret: process.env.BYBIT_API_SECRET!, demoTrading: true, }); ``` -------------------------------- ### Order Examples Source: https://github.com/tiagosiebler/bybit-api/blob/master/docs/BYBIT_SDK_QUICKSTART_GUIDE.md Illustrates how to submit, amend, cancel, and batch orders using the SDK, including different order types like Market and Limit. ```APIDOC ## Submit Market Order ### Description Submits a market order to buy or sell. ### Method `client.submitOrder(params: { category: string, symbol: string, side: string, orderType: 'Market', qty: string, orderLinkId?: string })` ### Parameters #### Request Body - **category** (string) - Required - The category of the instrument. - **symbol** (string) - Required - The trading symbol. - **side** (string) - Required - 'Buy' or 'Sell'. - **orderType** (string) - Required - Must be 'Market'. - **qty** (string) - Required - The quantity to trade. - **orderLinkId** (string) - Optional - A unique identifier for the order. ## Submit Limit Order ### Description Submits a limit order to buy or sell at a specific price. ### Method `client.submitOrder(params: { category: string, symbol: string, side: string, orderType: 'Limit', qty: string, price: string, timeInForce?: string, orderLinkId?: string })` ### Parameters #### Request Body - **category** (string) - Required - The category of the instrument. - **symbol** (string) - Required - The trading symbol. - **side** (string) - Required - 'Buy' or 'Sell'. - **orderType** (string) - Required - Must be 'Limit'. - **qty** (string) - Required - The quantity to trade. - **price** (string) - Required - The price at which to place the order. - **timeInForce** (string) - Optional - Time in force (e.g., 'GTC', 'PostOnly'). - **orderLinkId** (string) - Optional - A unique identifier for the order. ## Submit Post-Only Limit Order ### Description Submits a limit order that will only be executed if it does not immediately match with an existing order. ### Method `client.submitOrder(params: { category: string, symbol: string, side: string, orderType: 'Limit', qty: string, price: string, timeInForce: 'PostOnly', orderLinkId?: string })` ### Parameters #### Request Body - **category** (string) - Required - The category of the instrument. - **symbol** (string) - Required - The trading symbol. - **side** (string) - Required - 'Buy' or 'Sell'. - **orderType** (string) - Required - Must be 'Limit'. - **qty** (string) - Required - The quantity to trade. - **price** (string) - Required - The price at which to place the order. - **timeInForce** (string) - Required - Must be 'PostOnly'. - **orderLinkId** (string) - Optional - A unique identifier for the order. ## Amend Order ### Description Amends an existing order by modifying its price or quantity. ### Method `client.amendOrder(params: { category: string, symbol: string, orderId: string, price?: string, qty?: string })` ### Parameters #### Request Body - **category** (string) - Required - The category of the instrument. - **symbol** (string) - Required - The trading symbol. - **orderId** (string) - Required - The ID of the order to amend. - **price** (string) - Optional - The new price for the order. - **qty** (string) - Optional - The new quantity for the order. ## Cancel Order ### Description Cancels a specific order. ### Method `client.cancelOrder(params: { category: string, symbol: string, orderId: string })` ### Parameters #### Request Body - **category** (string) - Required - The category of the instrument. - **symbol** (string) - Required - The trading symbol. - **orderId** (string) - Required - The ID of the order to cancel. ## Cancel All Orders ### Description Cancels all active orders for a given category and symbol. ### Method `client.cancelAllOrders(params: { category: string, symbol: string })` ### Parameters #### Request Body - **category** (string) - Required - The category of the instrument. - **symbol** (string) - Required - The trading symbol. ## Batch Submit Orders ### Description Submits multiple orders in a single request. ### Method `client.batchSubmitOrders(category: string, orders: Array)` ### Parameters #### Request Body - **category** (string) - Required - The category for all orders in the batch. - **orders** (Array) - Required - An array of order objects, each with properties like `symbol`, `side`, `orderType`, `qty`, `price`, etc. ## Pre-check Order ### Description Pre-checks an order before submission to verify its validity. ### Method `client.preCheckOrder(params: { category: string, symbol: string, side: string, orderType: string, qty: string, price?: string })` ### Parameters #### Request Body - **category** (string) - Required - The category of the instrument. - **symbol** (string) - Required - The trading symbol. - **side** (string) - Required - 'Buy' or 'Sell'. - **orderType** (string) - Required - The type of order. - **qty** (string) - Required - The quantity to trade. - **price** (string) - Optional - The price for limit orders. ``` -------------------------------- ### Get RFQ Public Trade Information Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Get the recently executed RFQ successfullys. ```APIDOC ## GET /v5/rfq/public-trades ### Description Get the recently executed RFQ successfullys. ### Method GET ### Endpoint /v5/rfq/public-trades ### Parameters #### Query Parameters - **params** (GetRFQPublicTradesParamsV5) - Optional - Parameters for retrieving public RFQ trade information. ### Response #### Success Response (200) - **cursor** (string) - Page turning mark - **list** (array) - Array of public trade items (RFQPublicTradeV5). ``` -------------------------------- ### Get Option Delivery Price V5 Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Get the delivery price for options. Covers Option contracts. ```typescript getDeliveryPrice( params: GetDeliveryPriceParamsV5, ): Promise< APIResponseV3WithTime> > { return this.get('/v5/market/delivery-price', params); } ``` -------------------------------- ### Prepare and Use Websocket Client for V5 Public Topics Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Demonstrates setting up a WebsocketClient for V5 public topics. The client automatically handles connections, authentication, routing, and reconnections. Subscriptions require specifying the API category. ```typescript import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../../src'; // or // import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api'; /** * Prepare an instance of the WebSocket client. This client handles all aspects of connectivity for you: * - Connections are opened when you subscribe to topics * - If key & secret are provided, authentication is handled automatically * - If you subscribe to topics from different v5 products (e.g. spot and linear perps), * subscription events are automatically routed to the different ws endpoints on bybit's side * - Heartbeats/ping/pong/reconnects are all handled automatically. * If a connection drops, the client will clean it up, respawn a fresh connection and resubscribe for you. */ ``` ```typescript /** * For public V5 topics, use the subscribeV5 method and include the API category this topic is for. * Category is required, since each category has a different websocket endpoint. */ ``` ```typescript // Linear v5 // -> Just one topic per call // wsClient.subscribeV5('orderbook.50.BTCUSDT', 'linear'); ``` ```typescript // -> Or multiple topics in one call // wsClient.subscribeV5( // ['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], // 'linear' // ); ``` ```typescript // Inverse v5 // wsClient.subscribeV5('orderbook.50.BTCUSD', 'inverse'); ``` ```typescript // Spot v5 // wsClient.subscribeV5('orderbook.50.BTCUSDT', 'spot'); ``` ```typescript // Option v5 // wsClient.subscribeV5('publicTrade.BTC', 'option'); ``` ```typescript // Use the subscribeV5() call for most subscribe calls with v5 websockets ``` ```typescript // Alternatively, you can also use objects in the wsClient.subscribe() call // wsClient.subscribe({ // topic: 'orderook.50.BTCUSDT', // category: 'spot', // }); ``` ```typescript /** * For private V5 topics, just call the same subscribeV5() method on the ws client or use the original subscribe() method. * * Note: for private endpoints the "category" field is ignored since there is only one private endpoint * (compared to one public one per category) */ ``` ```typescript // wsClient.subscribeV5('position', 'linear'); // wsClient.subscribeV5('execution', 'linear'); // wsClient.subscribeV5(['order', 'wallet', 'greek'], 'linear'); ``` ```typescript // To unsubscribe from topics (after a 5 second delay, in this example): ``` ```typescript // Topics are tracked per websocket type // Get a list of subscribed topics (e.g. for public v3 spot topics) (after a 5 second delay) ``` -------------------------------- ### Initialize and Subscribe to WebSocket Topics Source: https://github.com/tiagosiebler/bybit-api/blob/master/README.md Configure and instantiate the WebsocketClient to connect to Bybit's WebSocket API. Subscribe to multiple topics simultaneously or individually. API credentials are optional for public topics but required for private ones. ```javascript const { WebsocketClient } = require('bybit-api'); // or // import { WebsocketClient } from 'bybit-api'; const API_KEY = 'xxx'; const PRIVATE_KEY = 'yyy'; const wsConfig = { /** * API credentials are optional. They are only required if you plan on using * any account-specific topics or the WS API * supports HMAC & RSA API keys - automatically detected */ key: 'yourAPIKeyHere', secret: 'yourAPISecretHere', /* The following parameters are optional: */ /** * Set to `true` to connect to Bybit's testnet environment. * - If demo trading, `testnet` should be set to false! * - If testing a strategy, use demo trading instead. Testnet market * data is very different from real market conditions. */ // testnet: true /** * Set to `true` to connect to Bybit's V5 demo trading: * https://bybit-exchange.github.io/docs/v5/demo * * Refer to the examples folder on GitHub for a more detailed demonstration. */ // demoTrading: true, // recv window size for websocket authentication (higher latency connections // (VPN) can cause authentication to fail if the recv window is too small) // recvWindow: 5000, /** How often to check if the connection is alive (in ms) */ // pingInterval: 10000, /** * How long to wait (in ms) for a pong (heartbeat reply) before assuming the * connection is dead */ // pongTimeout: 1000, /** Delay in milliseconds before respawning the connection */ // reconnectTimeout: 500, // override which URL to use for websocket connections // wsUrl: 'wss://stream.bytick.com/realtime' /** * Allows you to provide a custom "signMessage" function, e.g. to use node's * much faster createHmac method * * Look at examples/fasterHmacSign.ts for a demonstration: */ // customSignMessageFn: (message: string, secret: string) => Promise; }; const ws = new WebsocketClient(wsConfig); // (v5) subscribe to multiple topics at once ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear'); // Or one at a time ws.subscribeV5('kline.5.BTCUSDT', 'linear'); ws.subscribeV5('kline.5.ETHUSDT', 'linear'); // Private/public topics can be used in the same WS client instance, even for // different API groups (linear, options, spot, etc) ws.subscribeV5('position', 'linear'); ws.subscribeV5('publicTrade.BTC', 'option'); ``` -------------------------------- ### Get Open Interest V5 Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Get open interest of each symbol. Covers Linear contract and Inverse contract. ```typescript getOpenInterest( params: GetOpenInterestParamsV5, ): Promise> ``` -------------------------------- ### Create a public RestClientV5 Source: https://github.com/tiagosiebler/bybit-api/blob/master/docs/BYBIT_SDK_QUICKSTART_GUIDE.md Initializes a public `RestClientV5` instance. Public market calls do not require API keys. ```APIDOC ## REST API Most Bybit integrations start with `RestClientV5`. It covers the current REST API surface and uses Bybit's `category` parameter to distinguish product groups where the endpoint requires it. ### Create a public `RestClientV5` ```typescript import { RestClientV5 } from 'bybit-api'; const client = new RestClientV5(); ``` Public market calls do not require keys. ``` -------------------------------- ### Get Earn Token Product Source: https://github.com/tiagosiebler/bybit-api/blob/master/docs/endpointFunctionList.md Retrieves information about available Earn Token products. ```APIDOC ## GET /v5/earn/token/product ### Description Retrieves information about available Earn Token products. ### Method GET ### Endpoint /v5/earn/token/product ``` -------------------------------- ### Wallet, Assets, and Transfers Source: https://github.com/tiagosiebler/bybit-api/blob/master/docs/BYBIT_SDK_QUICKSTART_GUIDE.md Examples of how to retrieve wallet balances, coin balances, and transaction records using the SDK. ```APIDOC ## Wallet Operations ### Get Wallet Balance This method retrieves the wallet balance for a specified account type. ```typescript const wallet = await client.getWalletBalance({ accountType: 'UNIFIED', }); ``` ### Get All Coins Balance Retrieves the balance for all specified coins across account types. ```typescript const allCoins = await client.getAllCoinsBalance({ accountType: 'UNIFIED', coin: 'USDT,BTC', }); ``` ### Get Coin Balance Fetches the balance for a specific coin within an account type. ```typescript const coinBalance = await client.getCoinBalance({ accountType: 'UNIFIED', coin: 'USDT', }); ``` ### Get Transferable Coin List Lists coins that are transferable between specified account types. ```typescript const transferableCoins = await client.getTransferableCoinList('UNIFIED', 'FUND'); ``` ### Get Deposit Records Retrieves historical deposit records for a given coin. ```typescript const deposits = await client.getDepositRecords({ coin: 'USDT', }); ``` ### Get Withdrawal Records Fetches historical withdrawal records for a specified coin. ```typescript const withdrawals = await client.getWithdrawalRecords({ coin: 'USDT', }); ``` ``` -------------------------------- ### Get Borrow Order Quote Fixed Params V5 Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Parameters for getting a quote for a fixed borrow order. ```APIDOC ## Get Borrow Order Quote Fixed Params V5 ### Description Parameters for getting a quote for a fixed borrow order. ### Parameters #### Query Parameters - **orderCurrency** (string) - Required - The currency to borrow. - **term** (string) - Optional - The loan term. - **orderBy** ('apy' | 'term' | 'quantity') - Required - The field to order by. - **sort** (number) - Optional - The sort order (1 for ascending, -1 for descending). - **limit** (number) - Optional - The number of items to return. ``` -------------------------------- ### Get Supply Order Quote Fixed Params V5 Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Parameters for getting a quote for a fixed supply order. ```APIDOC ## Get Supply Order Quote Fixed Params V5 ### Description Parameters for getting a quote for a fixed supply order. ### Parameters #### Query Parameters - **orderCurrency** (string) - Required - The currency to supply. - **term** (string) - Optional - The loan term. - **orderBy** ('apy' | 'term' | 'quantity') - Required - The field to order by. - **sort** (number) - Optional - The sort order (1 for ascending, -1 for descending). - **limit** (number) - Optional - The number of items to return. ``` -------------------------------- ### WebSocket Client Initialization and Subscription Source: https://github.com/tiagosiebler/bybit-api/blob/master/README.md Demonstrates how to initialize the WebsocketClient with configuration options and subscribe to various topics. The client automatically manages connectivity and authentication. ```APIDOC ## WebSocket Client Initialization and Subscription ### Description Initialize the `WebsocketClient` with optional configuration parameters such as API keys, testnet/demo trading flags, and connection timeouts. Then, subscribe to public or private topics using the `subscribeV5` method. ### Initialization ```javascript const { WebsocketClient } = require('bybit-api'); const wsConfig = { key: 'yourAPIKeyHere', secret: 'yourAPISecretHere', // testnet: true, // Uncomment for testnet // demoTrading: true, // Uncomment for demo trading // recvWindow: 5000, // Optional: Adjust for latency // pingInterval: 10000, // Optional: Heartbeat interval // pongTimeout: 1000, // Optional: Heartbeat timeout // reconnectTimeout: 500, // Optional: Reconnection delay // wsUrl: 'wss://stream.bytick.com/realtime' // Optional: Override WebSocket URL // customSignMessageFn: async (message, secret) => { /* custom signing logic */ } }; const ws = new WebsocketClient(wsConfig); ``` ### Subscribing to Topics Subscribe to multiple topics at once or individually. Public and private topics can be mixed within the same client instance. **Subscribe to multiple topics (V5):** ```javascript ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear'); ``` **Subscribe to a single topic (V5):** ```javascript ws.subscribeV5('kline.5.BTCUSDT', 'linear'); ws.subscribeV5('kline.5.ETHUSDT', 'linear'); ``` **Subscribe to private/account topics:** ```javascript ws.subscribeV5('position', 'linear'); // Example private topic ws.subscribeV5('publicTrade.BTC', 'option'); // Example public topic on different API group ``` ### Automatic Reconnection The `WebsocketClient` automatically handles network issues by detecting dead connections, replacing them, and resubscribing to all topics. The `reconnected` event is emitted when this occurs. ``` -------------------------------- ### Get Max Loan Amount Params V5 Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Parameters for getting the maximum loan amount for a given currency and collateral. ```APIDOC ## Get Max Loan Amount Params V5 ### Description Parameters for getting the maximum loan amount for a given currency and collateral. ### Parameters #### Request Body - **currency** (string) - Required - The coin to borrow. - **collateralList** (array) - Optional - List of collateral details. - **ccy** (string) - Required - The collateral coin. - **amount** (string) - Required - The collateral amount. ``` -------------------------------- ### Initialize RestClientV5 for Live Environment Source: https://github.com/tiagosiebler/bybit-api/blob/master/docs/BYBIT_SDK_QUICKSTART_GUIDE.md Instantiate the RestClientV5 for the default live trading environment. Ensure your API key and secret are set as environment variables. ```typescript const client = new RestClientV5({ key: process.env.BYBIT_API_KEY!, secret: process.env.BYBIT_API_SECRET!, }); ``` -------------------------------- ### WebsocketClient Initialization and Subscription Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Demonstrates how to initialize the WebsocketClient with configuration options and subscribe to multiple topics, including public and private data streams. ```APIDOC ## WebsocketClient Initialization and Subscription ### Description Initialize the `WebsocketClient` with optional API credentials and configuration. Subscribe to public and private topics using `subscribeV5`. ### Initialization ```javascript const { WebsocketClient } = require('bybit-api'); const wsConfig = { key: 'yourAPIKeyHere', secret: 'yourAPISecretHere', // testnet: true, // Uncomment for testnet // demoTrading: true, // Uncomment for demo trading // recvWindow: 5000, // Optional: receive window size // pingInterval: 10000, // Optional: ping interval // pongTimeout: 1000, // Optional: pong timeout // reconnectTimeout: 500, // Optional: reconnect delay // wsUrl: 'wss://stream.bytick.com/realtime' // Optional: custom WebSocket URL // customSignMessageFn: async (message, secret) => { /* custom signing logic */ } }; const ws = new WebsocketClient(wsConfig); ``` ### Subscriptions Subscribe to multiple topics at once: ```javascript ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear'); ``` Subscribe to topics one at a time: ```javascript ws.subscribeV5('kline.5.BTCUSDT', 'linear'); ws.subscribeV5('kline.5.ETHUSDT', 'linear'); ``` Subscribe to private/public topics for different API groups: ```javascript ws.subscribeV5('position', 'linear'); ws.subscribeV5('publicTrade.BTC', 'option'); ``` ### Automatic Reconnection The `WebsocketClient` automatically manages connectivity. It detects network issues, replaces dead connections, resubscribes to topics, and emits a 'reconnected' event. ``` -------------------------------- ### Get Loan Borrowable Coins (New) Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Retrieves a list of coins that are available for crypto loans. Uses a public GET request. ```typescript return this.get('/v5/crypto-loan-common/loanable-data', params); ``` -------------------------------- ### AccountSpotInstrumentInfoV5 Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Extends SpotInstrumentInfoV5 with account-specific RPI permissions. ```APIDOC ## AccountSpotInstrumentInfoV5 ### Description Extends the `SpotInstrumentInfoV5` interface with additional fields related to account-specific RPI (Real-time Price Information) permissions. ### Fields Inherits all fields from `SpotInstrumentInfoV5` and includes: - **isPublicRpi** (boolean): Indicates if RPI data for this instrument is publicly available. - **myRpiPermission** (boolean): Indicates if the current account has permission to access RPI data for this instrument. ``` -------------------------------- ### Get Max Collateral Amount (New) Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Queries the maximum allowed collateral amount for crypto loans. Uses a private GET request. ```typescript return this.getPrivate('/v5/crypto-loan-common/max-collateral-amount', params); ``` -------------------------------- ### First REST API order in demo trading Source: https://github.com/tiagosiebler/bybit-api/blob/master/docs/BYBIT_SDK_QUICKSTART_GUIDE.md Demonstrates how to place an order in Bybit's demo trading environment using the REST API. It includes requesting demo funds and submitting a limit order for BTCUSDT. ```APIDOC ## First REST API order in demo trading Use demo trading before placing live orders. Demo trading uses a separate Bybit demo account and separate API keys. ```typescript import { RestClientV5 } from 'bybit-api'; const client = new RestClientV5({ key: process.env.BYBIT_API_KEY!, secret: process.env.BYBIT_API_SECRET!, demoTrading: true, }); async function placeDemoOrder() { await client.requestDemoTradingFunds(); const orderRequest = { category: 'linear', symbol: 'BTCUSDT', side: 'Buy', orderType: 'Limit', qty: '0.001', price: '10000', timeInForce: 'PostOnly', orderLinkId: `demo-${Date.now()}`, } as const; const result = await client.submitOrder(orderRequest); console.log(result); } placeDemoOrder().catch(console.error); ``` This submits to Bybit demo trading because `demoTrading: true` is set. Do not remove that option or switch to live keys until you are ready to place real orders. See also: [Demo trading example](../examples/Rest/demo-trading.ts) ``` -------------------------------- ### Get Loan Collateral Coins (New) Source: https://github.com/tiagosiebler/bybit-api/blob/master/llms.txt Retrieves a list of coins that can be used as collateral for crypto loans. Uses a public GET request. ```typescript return this.getPrivate('/v5/crypto-loan-common/collateral-data', params); ```