### Rest Private Spot Example Setup Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Example setup for using RestClientV2 for private spot trading. Shows how to import the client and provides commented-out examples for API key configuration and CLI environment variable usage. ```typescript import { RestClientV2 } from '../../../src/index.js'; // or // import { RestClientV2 } from 'bitget-api'; // read from environmental variables // If running from CLI in unix, you can pass env vars as such: // API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-private-spot.ts // note the single quotes, preventing special characters such as $ from being incorrectly passed // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', /** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ ``` -------------------------------- ### Rest Private Futures Example Setup Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Example setup for using RestClientV2 for private futures trading. Shows how to import the client and provides commented-out examples for API key configuration and CLI environment variable usage. ```typescript import { RestClientV2 } from '../../../src/index.js'; // or // import { RestClientV2 } from 'bitget-api'; // read from environmental variables // If running from CLI in unix, you can pass env vars as such: // API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-private-futures.ts // note the single quotes, preventing special characters such as $ from being incorrectly passed // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', /** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ startTime: fromTime.getTime() + '', // should be sent as a string endTime: now.getTime() + '', // should be sent as a string ``` -------------------------------- ### Rest Public Spot Example Setup Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Example setup for using RestClientV2 for public spot market data. Includes import statement and an alternative import path. ```typescript import { RestClientV2 } from '../../../src/index.js'; // or // import { RestClientV2 } from 'bitget-api'; ``` -------------------------------- ### Install Bitget API SDK Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/README.md Install the Bitget API SDK using npm. This is the first step before using the SDK in your project. ```bash npm install bitget-api ``` -------------------------------- ### Complete WebSocket API Client Example Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/websocket-api-client.md A full example demonstrating how to initialize the WebSocket API client, subscribe to order updates, and place a new order. Ensure your API credentials are set in environment variables. ```typescript import { WebsocketAPIClient, WS_KEY_MAP } from 'bitget-api'; const wsClient = new WebsocketAPIClient({ apiKey: process.env.API_KEY, apiSecret: process.env.API_SECRET, apiPass: process.env.API_PASS, demoTrading: false, }); // Subscribe to order updates wsClient.getWSClient().subscribe( { topic: 'order', payload: { instType: 'UTA' } }, WS_KEY_MAP.v3Private ); wsClient.getWSClient().on('update', (data) => { if (data.arg?.topic === 'order') { console.log('Order update:', data.data); } }); // Place an order via WebSocket try { const response = await wsClient.submitNewOrder('spot', { symbol: 'BTCUSDT', orderType: 'limit', side: 'buy', qty: '0.01', price: '50000', timeInForce: 'gtc', }); console.log('Order ID:', response.args[0].orderId); } catch (error) { console.error('Failed to place order:', error); } ``` -------------------------------- ### Execute Public REST API Example Source: https://github.com/tiagosiebler/bitget-api/blob/master/examples/README.md Run a public REST API example using ts-node. Ensure the script path is correct. ```bash ts-node ./examples/rest-spot-public.ts ``` -------------------------------- ### Install Dependencies for Browser Usage Source: https://github.com/tiagosiebler/bitget-api/blob/master/README.md Install these dependencies for modern browser integration with TypeScript support. ```sh npm install crypto-browserify stream-browserify ``` -------------------------------- ### Execute Authenticated Futures Trade Example Source: https://github.com/tiagosiebler/bitget-api/blob/master/examples/README.md Run an authenticated futures trade example using ts-node. Set API keys and secrets as environment variables. ```bash API_KEY_COM='yourkeyhere' API_SECRET_COM='yoursecrethere' API_PASS_COM='yourapipasshere' ts-node examples/rest-trade-futures.ts ``` -------------------------------- ### WebSocket Subscription Request Example Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt This example shows the structure of a V2 WebSocket subscription request, including the operation type and arguments for subscribing to ticker and candle data for BTCUSDT. ```APIDOC ## WebSocket Subscription Request Example ### Description This example demonstrates the structure for subscribing to real-time market data using the Bitget WebSocket API. It specifies the operation as 'subscribe' and provides arguments for different data channels like 'ticker' and 'candle5m' for a specific instrument. ### Operation `subscribe` ### Arguments - **instType** (string) - Required - The type of instrument (e.g., "SPOT"). - **channel** (string) - Required - The data channel to subscribe to (e.g., "ticker", "candle5m"). - **instId** (string) - Required - The instrument ID (e.g., "BTCUSDT"). ### Request Example ```json { "op": "subscribe", "args": [ { "instType": "SPOT", "channel": "ticker", "instId": "BTCUSDT" }, { "instType": "SPOT", "channel": "candle5m", "instId": "BTCUSDT" } ] } ``` ``` -------------------------------- ### Example RSA Private Key Format Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt This is an example of what your RSA private key should look like. It is crucial to keep this key private and never share it. ```pem -----BEGIN RSA PRIVATE KEY----- uayyi6wFTaNeG1/WCqhrowj2kCx8eB6NDZYl+OS9ZI9WC q/44iFERNuP0TXvQx8tgvSZXyu4/G618QzKh0Ii1uAATt2upa8dp1uGl2U7EqBE8 p5y4pPzJuwvB3j6LQON20u2Wpbg8PQZACMfKym7lYDO+9MloK/gAQpyeYJzbw92C YE/ymq4JVjCMCQKCAQEA4/X0I9TO8vT0D0l83o693QA3C09uSZ6j9Obx5UrtDnA9 sMkkRoe+R/vvIpVDzukMEEOmCuxbcdPoniVUKlTooK0Llo6JJ1l8CdFzQsOR97Pe csB6pxkLLH2qHx05xPBy4PyoB -----END RSA PRIVATE KEY----- ``` -------------------------------- ### Get Spot Trader Configuration Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves the configuration for spot traders. ```typescript getSpotTraderConfiguration(): Promise> ``` -------------------------------- ### Get Withdraw Records Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves withdrawal records. No specific setup or constraints mentioned. ```typescript getWithdrawRecords( params: GetWithdrawRecordsRequestV3, ): Promise> ``` -------------------------------- ### Get Product Infos Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves information about a specific loan product. ```APIDOC ## GET /api/v3/loan/product/infos ### Description Retrieves information about a specific loan product. ### Method GET ### Endpoint /api/v3/loan/product/infos ### Parameters #### Query Parameters - **productId** (string) - Required - The ID of the product. ### Response #### Success Response (200) - **data** (object) - Product information. - **code** (string) - API response code. - **msg** (string) - API response message. - **timestamp** (string) - Timestamp of the response. - **success** (boolean) - Indicates if the request was successful. ``` -------------------------------- ### Get Announcements Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves announcements with optional filtering by type, start time, end time, and language. ```APIDOC ## GET /api/v2/common/announcements ### Description Retrieves announcements with optional filtering by type, start time, end time, and language. ### Method GET ### Endpoint /api/v2/common/announcements ### Parameters #### Query Parameters - **annType** (string) - Optional - Type of announcement. - **startTime** (string) - Optional - The start time for filtering announcements. - **endTime** (string) - Optional - The end time for filtering announcements. - **language** (string) - Required - The language for the announcements. ### Response #### Success Response (200) - Announcements data structure (details not provided in source). ``` -------------------------------- ### Complete Example: V2 Spot Trading WebSocket Client Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/websocket-client-v2.md Demonstrates setting up the V2 WebSocket client for spot trading, including event handlers for connection status and data updates, and subscribing to various market and account data topics. ```typescript import { WebsocketClientV2, WS_KEY_MAP } from 'bitget-api'; const wsClient = new WebsocketClientV2({ apiKey: process.env.BITGET_API_KEY, apiSecret: process.env.BITGET_API_SECRET, apiPass: process.env.BITGET_API_PASS, }); // Event handlers wsClient.on('open', (data) => { console.log('WebSocket opened:', data.wsKey); }); wsClient.on('update', (data) => { console.log('Update received:', data); }); wsClient.on('reconnected', (data) => { console.log('Reconnected:', data.wsKey); }); wsClient.on('exception', (error) => { console.error('WebSocket error:', error); }); // Subscribe to market data wsClient.subscribeTopic('SPOT', 'ticker', 'BTCUSDT'); wsClient.subscribeTopic('SPOT', 'candle1h', 'ETHUSDT'); wsClient.subscribeTopic('SPOT', 'depth5', 'BTCUSDT'); // Subscribe to account data wsClient.subscribeTopic('SPOT', 'account'); wsClient.subscribeTopic('SPOT', 'order'); ``` -------------------------------- ### Initialize and Use RestClientV3 Source: https://github.com/tiagosiebler/bitget-api/blob/master/README.md Demonstrates how to initialize the RestClientV3 with API credentials and submit a market order. Ensure your API key, secret, and pass are correctly configured. ```javascript import { RestClientV3 } from 'bitget-api'; // or if you prefer require: // const { RestClientV3 } = require('bitget-api'); // note the single quotes, preventing special characters such as $ from being incorrectly passed const client = new RestClientV3({ apiKey: process.env.API_KEY_COM || 'insert_api_key_here', apiSecret: process.env.API_SECRET_COM || 'insert_api_secret_here', apiPass: process.env.API_PASS_COM || 'insert_api_pass_here', }); (async () => { try { console.log(await client.getBalances()); const newOrder = await client.submitNewOrder({ category: 'USDT-FUTURES', orderType: 'market', side: 'buy', qty: '0.001', symbol: 'BTCUSDT', }); console.log('Order submitted: ', newOrder); } catch (e) { console.error('request failed: ', e); } })(); ``` -------------------------------- ### Get Spot to Perpetual Conversion Records Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v3.md Fetch records of conversions between spot and perpetual trading. Optional parameters include start time, end time, and the number of records to retrieve. ```typescript getConvertRecords(params: GetConvertRecordsRequestV3): Promise> ``` -------------------------------- ### Get Union Transfer Limits V2 Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Get union transfer limits. ```APIDOC ## GET /api/v2/broker/union/transfer/limit ### Description Get union transfer limits. ### Method GET ### Endpoint /api/v2/broker/union/transfer/limit ### Query Parameters - **coin** (string) - Required - Currency. ``` -------------------------------- ### Initialize WebSocket Client for Trading (V2) Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt This example shows how to initialize a V2 WebSocket client for trading purposes. It demonstrates setting up API keys, optional REST options, and enabling demo trading. It also shows how to handle raw WebSocket messages. ```typescript import { DefaultLogger, WebsocketClientV2 } from '../../../src/index.js'; // or // import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; // If running from CLI in unix, you can pass env vars as such: // API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts // restOptions: { // optionally provide rest options, e.g. to pass through a proxy // }, // Set demoTrading to true, to route all connections to the demo trading wss URLs: // If using private topics, make sure to include API keys // console.log('WS raw message received ', JSON.stringify(data, null, 2)); /** * Public events */ // --- Configuration --- const API_KEY = process.env.API_KEY_COM; const API_SECRET = process.env.API_SECRET_COM; const API_PASSPHRASE = process.env.API_PASSPHRASE_COM; // --- Initialize WebSocket Client --- const ws = new WebsocketClientV2({ apiKey: API_KEY, apiSecret: API_SECRET, apiPass: API_PASSPHRASE, // Set demoTrading to true to use the demo trading environment // demoTrading: true, // Optionally, provide REST options // restOptions: { // proxy: 'http://localhost:8080', // }, // Set logger to true to enable logging // logger: true, }); // --- Event Handlers --- // Handle raw websocket messages ws.on('open', () => { console.log('Websocket connection opened'); }); ws.on('update', (data) => { console.log('WS raw message received ', JSON.stringify(data, null, 2)); }); ws.on('error', (err) => { console.error('Websocket error:', err); }); ws.on('close', () => { console.log('Websocket connection closed'); }); // --- Example Subscription (replace with your desired topics) --- // Subscribe to a public ticker channel for BTCUSDT // ws.subscribe('market_btc-usdt_ticker'); // Subscribe to a private account channel (requires API keys) // ws.subscribe('private_account.futures.balance'); // Keep the script running to maintain the websocket connection // setInterval(() => {}, 1000); ``` -------------------------------- ### Get Sharkfin Products Source: https://github.com/tiagosiebler/bitget-api/blob/master/docs/endpointFunctionList.md Retrieves a list of available Sharkfin products. ```APIDOC ## GET /api/v2/earn/sharkfin/product ### Description Retrieves a list of available Sharkfin products. ### Method GET ### Endpoint /api/v2/earn/sharkfin/product ``` -------------------------------- ### Get Instruments Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v3.md Retrieves instrument information. Use this to get details about available trading instruments. ```typescript getInstruments(params: GetInstrumentsRequestV3): Promise> ``` -------------------------------- ### Initialize and Use RestClientV2 Source: https://github.com/tiagosiebler/bitget-api/blob/master/README.md Shows how to initialize the RestClientV2 with API credentials for V2 APIs. It also demonstrates making public API calls without credentials. Error handling is included. ```javascript import { RestClientV2 } from 'bitget-api'; // or if you prefer require: // const { RestClientV2 } = require('bitget-api'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const API_PASS = 'zzz'; const client = new RestClientV2({ apiKey: API_KEY, apiSecret: API_SECRET, apiPass: API_PASS, }); // For public-only API calls, simply don't provide a key & secret or set them to undefined // const client = new RestClientV2(); client .getSpotAccount() .then((result) => { console.log('getSpotAccount result: ', result); }) .catch((err) => { console.error('getSpotAccount error: ', err); }); client .getSpotCandles({ symbol: 'BTCUSDT', granularity: '1min', limit: '1000', }) .then((result) => { console.log('getCandles result: ', result); }) .catch((err) => { console.error('getCandles error: ', err); }); ``` -------------------------------- ### getFuturesTickers(params) Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v2.md Get futures market ticker data. You can specify a symbol for a specific ticker or omit it to get all tickers. ```APIDOC ## getFuturesTickers(params) ### Description Get futures market ticker data. ### Method GET ### Endpoint /api/v2/futures/market/tickers ### Parameters #### Query Parameters - **symbol** (string) - Optional - Specific symbol or all if omitted ### Response #### Success Response (200) - **data** (FuturesTickerV2[]) - An array of futures market ticker data. ``` -------------------------------- ### Configure WebsocketAPIClient for Demo Trading and Custom Settings Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/configuration.md This example shows how to configure the WebsocketAPIClient with custom settings for demo trading, heartbeat intervals, reconnection behavior, and event listeners. It then demonstrates placing a limit order. ```typescript import { WebsocketAPIClient } from 'bitget-api'; const wsApiClient = new WebsocketAPIClient({ apiKey: process.env.BITGET_API_KEY, apiSecret: process.env.BITGET_API_SECRET, apiPass: process.env.BITGET_API_PASS, demoTrading: true, // Use demo trading heartbeatMs: 20000, // More frequent heartbeat reconnectMs: 3000, // Faster reconnection maxReconnectAttempts: 5, // Limit reconnection attempts attachEventListeners: true, // Log connection events }); // Place orders via WebSocket const order = await wsApiClient.submitNewOrder('spot', { symbol: 'BTCUSDT', orderType: 'limit', side: 'buy', qty: '0.01', price: '50000', }); ``` -------------------------------- ### getSpotTickers(params) Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v2.md Get spot market ticker data. You can specify a symbol for a specific ticker or omit it to get all tickers. ```APIDOC ## getSpotTickers(params) ### Description Get spot market ticker data. ### Method GET ### Endpoint /api/v2/spot/market/tickers ### Parameters #### Query Parameters - **symbol** (string) - Optional - Specific symbol or all if omitted ### Response #### Success Response (200) - **data** (SpotTickerV2[]) - An array of spot market ticker data. ``` -------------------------------- ### Bitget REST Client Basic Usage Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/README.md Demonstrates how to initialize the RestClientV3 and perform common operations like fetching balances and submitting a new limit order. Ensure API credentials are set as environment variables. ```typescript import { RestClientV3 } from 'bitget-api'; const client = new RestClientV3({ apiKey: process.env.BITGET_API_KEY, apiSecret: process.env.BITGET_API_SECRET, apiPass: process.env.BITGET_API_PASS, }); // Get balances const balances = await client.getBalances(); console.log(balances.data.assets); // Place order const order = await client.submitNewOrder({ category: 'SPOT', symbol: 'BTCUSDT', orderType: 'limit', side: 'buy', qty: '0.01', price: '50000', }); console.log('Order ID:', order.data.orderId); ``` -------------------------------- ### Bitget WebSocket Client Real-Time Updates Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/README.md Shows how to set up the WebsocketClientV3 to receive real-time market data. This example subscribes to the 'ticker' topic for BTCUSDT on spot markets. ```typescript import { WebsocketClientV3, WS_KEY_MAP } from 'bitget-api'; const wsClient = new WebsocketClientV3({ apiKey: process.env.BITGET_API_KEY, apiSecret: process.env.BITGET_API_SECRET, apiPass: process.env.BITGET_API_PASS, }); wsClient.on('update', (data) => console.log('Update:', data)); wsClient.subscribe( { topic: 'ticker', payload: { instType: 'spot', symbol: 'BTCUSDT' } }, WS_KEY_MAP.v3Public ); ``` -------------------------------- ### Get Spot Trader Order Summary Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves the total order details for a spot trader. Use this to get a summary of all spot orders. ```typescript getSpotTraderOrder(): Promise> ``` -------------------------------- ### Example Usage of getBalances Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v3.md Demonstrates how to fetch and log account balances using the getBalances method. ```typescript const balances = await client.getBalances(); console.log(balances.data.assets); ``` -------------------------------- ### Complete Example: V2 Futures Trading WebSocket Client Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/websocket-client-v2.md Shows how to initialize the V2 WebSocket client for futures trading. It includes subscribing to futures market data, positions, orders, and funding rates, along with handling specific data updates. ```typescript import { WebsocketClientV2 } from 'bitget-api'; const wsClient = new WebsocketClientV2({ apiKey: process.env.BITGET_API_KEY, apiSecret: process.env.BITGET_API_SECRET, apiPass: process.env.BITGET_API_PASS, }); // Subscribe to futures data wsClient.subscribeTopic('FUTURES', 'ticker', 'BTCUSDT'); wsClient.subscribeTopic('FUTURES', 'candle4h', 'ETHUSDT'); // Subscribe to positions wsClient.subscribeTopic('FUTURES', 'position', 'default'); // Subscribe to orders wsClient.subscribeTopic('FUTURES', 'order'); // Subscribe to funding rates wsClient.subscribeTopic('FUTURES', 'fundingRate'); wsClient.on('update', (data) => { if (data.arg?.channel === 'position') { console.log('Position update:', data.data); } else if (data.arg?.channel === 'order') { console.log('Order update:', data.data); } }); ``` -------------------------------- ### Get Futures Market Tickers Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v2.md Fetch futures market ticker data. Optionally, specify a symbol to get data for a particular market. ```typescript getFuturesTickers(params?: { symbol?: string }): Promise> ``` -------------------------------- ### Get Spot Market Tickers Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v2.md Fetch spot market ticker data. Optionally, specify a symbol to get data for a particular market. ```typescript getSpotTickers(params?: { symbol?: string }): Promise> ``` -------------------------------- ### Constructor Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/websocket-client-v2.md Initializes a new instance of the WebsocketClientV2. It accepts optional configuration options and a custom logger. ```APIDOC ## Constructor ### Description Initializes a new instance of the WebsocketClientV2. It accepts optional configuration options and a custom logger. ### Parameters #### Options - **options** (WSClientConfigurableOptions) - Optional - WebSocket client configuration options. - **logger** (DefaultLogger) - Optional - Custom logger for debug output. ### Configuration Options See [Configuration Reference](../configuration.md#wsclientconfigurableoptions) for complete options. ``` -------------------------------- ### Environment Configuration (.env file) Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/INDEX.md Example of environment variables for API keys, secrets, and passphrases, including demo accounts and a trace flag. These are typically loaded into the application's environment. ```bash # .env file BITGET_API_KEY=your_api_key BITGET_API_SECRET=your_api_secret BITGET_API_PASS=your_api_passphrase BITGET_DEMO_KEY=demo_api_key BITGET_DEMO_SECRET=demo_api_secret BITGET_DEMO_PASS=demo_api_passphrase BITGETTRACE=false ``` -------------------------------- ### Example WebSocket Error Response Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt An example of an error response received from the WebSocket API, including event type, ID, error code, and message. ```javascript // const eg1 = { // event: 'error', // id: '1', // code: '43012', // msg: 'Insufficient balance', // }; ``` -------------------------------- ### Initialize REST Client for Demo Trading Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/INDEX.md Use this snippet to initialize the V3 REST client for demo trading. Ensure your environment variables for API key, secret, and passphrase are set. ```typescript const client = new RestClientV3({ apiKey: process.env.BITGET_DEMO_KEY, apiSecret: process.env.BITGET_DEMO_SECRET, apiPass: process.env.BITGET_DEMO_PASS, demoTrading: true, }); ``` -------------------------------- ### Demo Trading Configuration Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/configuration.md Enable paper trading by setting the `demoTrading` option to `true` during client initialization. ```typescript const client = new RestClientV3({ apiKey: process.env.BITGET_DEMO_KEY, apiSecret: process.env.BITGET_DEMO_SECRET, apiPass: process.env.BITGET_DEMO_PASS, demoTrading: true, // Enable paper trading }); ``` -------------------------------- ### Get Futures Trader Order Summary Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves the total order summary for a futures trader. Use this endpoint to get an overview of a trader's orders. ```typescript getFuturesTraderOrder(): Promise> { return this.getPrivate('/api/v2/copy/mix-trader/order-total-detail'); } ``` -------------------------------- ### Batch Place Order Response (V3 WebSocket) Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Example response for batch order placement via V3 WebSocket. Individual order results are within the 'args' array, check 'code' and 'msg' for each. ```json { "event": "trade", "id": "1750035029506", "category": "spot", "topic": "batch-place", "args": [ { "code": "0", "msg": "Success", "symbol": "BTCUSDT", "orderId": "xxxxxxxx", "clientOid": "xxxxxxxx" }, { "code": "0", "msg": "Success", "symbol": "BTCUSDT", "orderId": "xxxxxxxx", "clientOid": "xxxxxxxx" } ], "code": "0", "msg": "Success", "ts": "1750035029925" } ``` -------------------------------- ### Demo Trading WebSocket Configuration Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Enable connection to Bitget's demo trading WebSockets by setting the appropriate flag. Refer to the provided URLs for V2 and V3/UTA documentation. ```typescript /** * Set to `true` to connect to Bitget's demo trading WebSockets: * * - V2: https://www.bitget.com/api-doc/common/demotrading/websocket * - V3/UTA: https://www.bitget.com/api-doc/uta/guide#demo-trading */ ``` -------------------------------- ### Get Spot BGB Deduct Info Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves information about the BGB (Bitget Token) deduction status for fees in spot trading. This is a GET request to the private API endpoint. ```typescript getSpotBGBDeductInfo(): Promise> { return this.getPrivate('/api/v2/spot/account/deduct-info'); } ``` -------------------------------- ### Example WebSocket Subscribe Arguments Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Illustrates the structure of arguments for a WebSocket subscribe operation in the Bitget V2 API, including instrument type, channel, and instrument ID. ```json { "op":"subscribe", "args":[ { "instType":"SPOT", "channel":"ticker", "instId":"BTCUSDT" }, { "instType":"SPOT", "channel":"candle5m", "instId":"BTCUSDT" } ] } ``` -------------------------------- ### Documentation File Structure Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/GENERATION_REPORT.md This tree displays the generated documentation files and their locations. The README.md and INDEX.md are recommended starting points. ```text /workspace/home/output/ ├── README.md (Start here) ├── INDEX.md (Complete navigation) ├── configuration.md (Setup guide) ├── types.md (Type reference) ├── errors.md (Error codes) ├── SUMMARY.txt (Statistics) ├── GENERATION_REPORT.md (This file) └── api-reference/ ├── rest-client-v3.md (V3 REST API) ├── rest-client-v2.md (V2 REST API) ├── websocket-client-v3.md (V3 WebSocket) ├── websocket-client-v2.md (V2 WebSocket) └── websocket-api-client.md (WebSocket Orders) ``` -------------------------------- ### Get Spot Copy Trading Followers Info Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v2.md Retrieves information about spot copy trading followers. Use this method to get data related to users following spot traders. ```typescript getSpotFollowersInfo(params: GetSpotTraderFollowersRequestV2): Promise> ``` -------------------------------- ### Get Spot Account Information Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v2.md Retrieves detailed information about the user's spot account, including coin balances. Use this method to get a comprehensive overview of your spot holdings. ```typescript getSpotAccount(): Promise> ``` -------------------------------- ### batchCreateVirtualSubaccountAndAPIKey Source: https://github.com/tiagosiebler/bitget-api/blob/master/docs/endpointFunctionList.md Batches creation of virtual subaccounts and API keys, requires authentication. ```APIDOC ## POST /api/v2/user/batch-create-subaccount-and-apikey ### Description Batches creation of virtual subaccounts and API keys, requires authentication. ### Method POST ### Endpoint /api/v2/user/batch-create-subaccount-and-apikey ``` -------------------------------- ### Rest Public Futures Example - Fetch Candles Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Example of fetching historical candle data for a symbol using RestClientV2. Includes import statement and a constant for milliseconds per candle. ```typescript import { RestClientV2 } from '../../../src/index.js'; // or // import { RestClientV2 } from 'bitget-api'; // Fetch the last 1000 1min candles for a symbol const msPerCandle = 60 * 1000; // 60 seconds x 1000 ``` -------------------------------- ### Example WebSocket Subscription Request Structure Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Illustrates the expected JSON structure for a WebSocket subscription request, including topic details and parameters. ```json { "op":"subscribe", "args":[ { "instType":"spot", "topic":"ticker", "symbol":"BTCUSDT" }, { "instType":"spot", "topic":"candle5m", "symbol":"BTCUSDT" } ] } ``` -------------------------------- ### Sell Spot Balance (V2 REST) Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt This script demonstrates how to check for available BTC balance and immediately sell the full amount for USDT using the V2 REST API. It also shows how to subscribe to private websocket channels for account and order updates. ```typescript import { RestClientV2, SpotOrderRequestV2, WebsocketClientV2, } from '../../../src/index.js'; // import { RestClientV2, WebsocketClient } from '../src/index'; // read from environmental variables // If running from CLI in unix, you can pass env vars as such: // API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-trade-spot.ts // note the single quotes, preventing special characters such as $ from being incorrectly passed // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', function logWSEvent(type: string, data: any) { console.log(type, data); } // simple sleep function function promiseSleep(milliseconds: number): Promise { return new Promise((resolve) => setTimeout(resolve, milliseconds)); } /** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ (async () => { // --- Configuration --- const API_KEY = process.env.API_KEY_COM; const API_SECRET = process.env.API_SECRET_COM; const API_PASSPHRASE = process.env.API_PASSPHRASE_COM; const symbol = 'BTCUSDT'; const orderType = 'market'; // 'limit' | 'market' const side = 'sell'; // 'buy' | 'sell' // --- Initialize Clients --- const ws = new WebsocketClientV2({ apiKey: API_KEY, apiSecret: API_SECRET, apiPass: API_PASSPHRASE, // If you want to use the demo trading environment, uncomment the following line: // demoTrading: true, }); const rest = new RestClientV2({ apiKey: API_KEY, apiSecret: API_SECRET, apiPass: API_PASSPHRASE, // If you want to use the demo trading environment, uncomment the following line: // demoTrading: true, }); // --- Event Listeners --- // Add event listeners to log websocket events on account // Subscribe to private account topics // spot private // : account updates ws.on('update', (data) => { if (data.topic.includes('account')) { logWSEvent('Account Update', data.data); } }); // : order updates (note: symbol is required) ws.on('update', (data) => { if (data.topic.includes('order')) { logWSEvent('Order Update', data.data); } }); // --- Workflow --- try { // wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) await promiseSleep(2000); // Subscribe to private account topics ws.subscribe(`private_${symbol}@account`); ws.subscribe(`private_${symbol}@order`); // Check for available BTC balance const accountInfo = await rest.getAccountInfo(); const btcBalance = accountInfo.data.balances.find( (bal: any) => bal.coin === 'BTC' ); console.log('BTC Balance:', btcBalance); if (!btcBalance || Number(btcBalance.available) === 0) { console.log('No available BTC balance for spot trading.'); return; } // Place a sell order for the full available BTC balance console.log(`Placing a ${side} ${orderType} order for ${btcBalance.available} ${symbol}...`); const orderParams: SpotOrderRequestV2 = { symbol: symbol, orderType: orderType, side: side, size: btcBalance.available, // For limit orders, you would also specify 'price' // price: '30000', }; const placeOrderResult = await rest.placeOrderV2(orderParams); console.log('Place Order Result:', JSON.stringify(placeOrderResult, null, 2)); // console.log('balance: ', JSON.stringify(balances, null, 2)); } catch (error) { console.error('An error occurred:', error); } finally { // Close websocket connection ws.close(); console.log('Websocket connection closed.'); } })(); ``` -------------------------------- ### getServerTime() Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/rest-client-v2.md Get the current server timestamp. ```APIDOC ## getServerTime() ### Description Get the current server timestamp. ### Method GET ### Endpoint /api/v2/public/time ### Response #### Success Response (200) - **serverTime** (number) - The current server timestamp. ``` -------------------------------- ### Place a Spot Limit Order with REST API V3 Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/INDEX.md Demonstrates placing a limit buy order for BTCUSDT on the spot market using RestClientV3. API credentials must be configured. ```typescript import { RestClientV3 } from 'bitget-api'; const client = new RestClientV3({ apiKey: process.env.BITGET_API_KEY, apiSecret: process.env.BITGET_API_SECRET, apiPass: process.env.BITGET_API_PASS, }); // Place a spot order const order = await client.submitNewOrder({ category: 'SPOT', symbol: 'BTCUSDT', orderType: 'limit', side: 'buy', qty: '0.01', price: '50000', }); ``` -------------------------------- ### Get Futures Active Buy Sell Volume Data Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves data on the volume of buy and sell orders in futures markets. This endpoint appears to be a duplicate or similar to 'Get Futures Active Taker Buy Sell Volume Data'. ```APIDOC ## GET /api/v2/futures/market/active-buy-sell-volume ### Description Retrieves data on the volume of buy and sell orders in futures markets. ### Method GET ### Endpoint /api/v2/futures/market/active-buy-sell-volume ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., 'BTCUSDT'). - **period** (string) - Optional - The period for the data (e.g., '1d', '1w'). ``` -------------------------------- ### Basic REST Client Configuration Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/configuration.md Initialize the RestClientV3 with your API key, secret, and passphrase for authenticated requests. ```typescript import { RestClientV3 } from 'bitget-api'; const client = new RestClientV3({ apiKey: process.env.BITGET_API_KEY, apiSecret: process.env.BITGET_API_SECRET, apiPass: process.env.BITGET_API_PASS, }); ``` -------------------------------- ### Get Tickers V3 Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieve ticker information. ```APIDOC ## GET /api/v3/public/tickers ### Description Retrieve ticker information. ### Method GET ### Endpoint /api/v3/public/tickers ### Query Parameters - **category** ('SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES') - Required - Category. - **symbol** (string) - Optional - Trading pair. ``` -------------------------------- ### Instantiate and Subscribe to V2 WebSocket Client Source: https://github.com/tiagosiebler/bitget-api/blob/master/README.md This snippet shows how to create an instance of the V2 WebSocket client with API credentials and subscribe to public and private data streams. It also demonstrates handling connection and message events. ```javascript import { WebsocketClientV2 } from 'bitget-api'; // or if you prefer require: // const { WebsocketClientV2 } = require('bitget-api'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const API_PASS = 'zzz'; const wsClient = new WebsocketClientV2({ apiKey: API_KEY, apiSecret: API_SECRET, apiPass: API_PASS, // Optional: connect to demo trading environment // demoTrading: true, }); // Handle incoming messages wsClient.on('update', (data) => { console.log('WS update received: ', data); }); wsClient.on('open', (data) => { console.log('WS connection opened: ', data.wsKey); }); wsClient.on('reconnected', (data) => { console.log('WS reconnected: ', data?.wsKey); }); wsClient.on('exception', (data) => { console.log('WS error: ', data); }); // Subscribe to public data streams wsClient.subscribeTopic('SPOT', 'ticker', symbol); // Subscribe to private data streams (requires authentication) wsClient.subscribeTopic('SPOT', 'account'); ``` -------------------------------- ### Get Instruments V3 Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieve instrument information. ```APIDOC ## GET /api/v3/public/instruments ### Description Retrieve instrument information. ### Method GET ### Endpoint /api/v3/public/instruments ### Query Parameters - **category** ('SPOT' | 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES') - Required - Category. - **symbol** (string) - Optional - Trading pair. ``` -------------------------------- ### Get Candles V3 Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieve candle data. ```APIDOC ## GET /api/v3/public/candles ### Description Retrieve candle data. ### Method GET ### Endpoint /api/v3/public/candles ### Query Parameters - **category** ('SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES') - Required - Category. - **symbol** (string) - Required - Trading pair. - **interval** ('1m' | '3m' | '5m' | '15m' | '30m' | '1H' | '4H' | '6H' | '12H' | '1D') - Required - Interval. - **startTime** (string) - Optional - Start time. - **endTime** (string) - Optional - End time. - **type** ('MARKET' | 'MARK' | 'INDEX') - Optional - Type. - **limit** (string) - Optional - Limit. ``` -------------------------------- ### Initiate Margin Flash Repay Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Starts a flash repayment process for margin positions. Requires coin and symbol. ```typescript marginFlashRepay( marginType: MarginType, params: { coin: string }, ): Promise< APIResponse<{ repayId: string; coin?: string; symbol?: string; result?: string; }> > { assertMarginType(marginType); ``` -------------------------------- ### getSpotTraderConfiguration() Source: https://github.com/tiagosiebler/bitget-api/blob/master/docs/endpointFunctionList.md Retrieves the current configuration settings for a spot trader. ```APIDOC ## GET /api/v2/copy/spot-trader/config-query-settings ### Description Fetches the current configuration settings for a spot trader. ### Method GET ### Endpoint /api/v2/copy/spot-trader/config-query-settings ``` -------------------------------- ### Convert Quote Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Gets a quote for a currency conversion. ```APIDOC ## GET /api/v2/common/convert-quote ### Description Gets a quote for a currency conversion. ### Method GET ### Endpoint /api/v2/common/convert-quote ### Parameters #### Query Parameters - **fromCoin** (string) - Required - The currency to convert from. - **fromCoinSize** (string) - Optional - The amount of the source currency. - **toCoin** (string) - Required - The currency to convert to. - **toCoinSize** (string) - Optional - The amount of the target currency. ### Response #### Success Response (200) - Conversion quote details (details not provided in source). ``` -------------------------------- ### Instantiate WebsocketClientV3 Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/websocket-client-v3.md Create a new instance of the WebsocketClientV3. Optionally, provide configuration options or a custom logger. ```typescript constructor( options?: WSClientConfigurableOptions, logger?: DefaultLogger ) ``` -------------------------------- ### Get Sharkfin Records Source: https://github.com/tiagosiebler/bitget-api/blob/master/docs/endpointFunctionList.md Retrieves the records for Sharkfin. ```APIDOC ## GET /api/v2/earn/sharkfin/records ### Description Retrieves the records for Sharkfin. ### Method GET ### Endpoint /api/v2/earn/sharkfin/records ``` -------------------------------- ### Get Futures Positions Source: https://github.com/tiagosiebler/bitget-api/blob/master/docs/endpointFunctionList.md Retrieves all futures positions. ```APIDOC ## GET /api/v2/mix/position/all-position ### Description Retrieves all futures positions. ### Method GET ### Endpoint /api/v2/mix/position/all-position ``` -------------------------------- ### Instantiate WebsocketAPIClient Source: https://github.com/tiagosiebler/bitget-api/blob/master/_autodocs/api-reference/websocket-api-client.md Instantiate the WebsocketAPIClient with optional configuration options and a custom logger. ```typescript constructor( options?: WSClientConfigurableOptions & WSAPIClientConfigurableOptions, logger?: DefaultLogger ) ``` -------------------------------- ### Use llms.txt with LLMs Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Utilize the provided 'llms.txt' file with your Large Language Models to enhance their understanding of the SDK's functions and parameters. This file is optimized for AI. ```txt This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. ``` -------------------------------- ### Get Union Config Source: https://github.com/tiagosiebler/bitget-api/blob/master/docs/endpointFunctionList.md Retrieves the union configuration. ```APIDOC ## GET /api/v2/mix/account/union-config ### Description Retrieves the union configuration. ### Method GET ### Endpoint /api/v2/mix/account/union-config ``` -------------------------------- ### Topic Transformation Example Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Shows the transformation of a topic object from a generic format to a Bitget V2 API specific format for WebSocket requests. ```javascript // const request = { // topic: 'ticker', // payload: { instType: 'SPOT', instId: 'BTCUSDT' }, // }; // becomes: // const request = { // channel: 'ticker', // instType: 'SPOT', // instId: 'BTCUSDT', // }; ``` -------------------------------- ### Get Loan Orders Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves a list of loan orders. ```APIDOC ## GET /api/v3/ins-loan/loan-order ### Description Retrieves a list of loan orders. ### Method GET ### Endpoint /api/v3/ins-loan/loan-order ### Parameters #### Query Parameters - **params** (GetLoanOrderRequestV3) - Optional - Parameters for filtering loan orders. ### Response #### Success Response (200) - **data** (APIResponse) - An array of loan orders. ``` -------------------------------- ### Get Loan Symbols Source: https://github.com/tiagosiebler/bitget-api/blob/master/llms.txt Retrieves available symbols for lending. ```APIDOC ## GET /api/v3/ins-loan/symbols ### Description Retrieves available symbols for lending. ### Method GET ### Endpoint /api/v3/ins-loan/symbols ### Parameters #### Query Parameters - **params** (GetSymbolsRequestV3) - Required - Parameters for fetching loan symbols. ### Response #### Success Response (200) - **data** (APIResponse) - The response contains a list of loan symbols. ```