Bybit REST JavaScript SDK example: demo-trading.ts

Bybit REST demo trading JavaScript example. Read the source code, review its SDK calls, and browse related exchange integration examples.

This example uses bybit-api, the JavaScript and TypeScript SDK for Bybit. Install it with npm install bybit-api.

We use environment variables in our examples for API keys. It is your responsibility to manage and secure your keys appropriately.

examples/Bybit/Rest/demo-trading.ts

What this example covers

  • Bybit REST API JavaScript example.
  • Uses the Siebly Bybit SDK package bybit-api instead of hand-written HTTP request plumbing.
  • Source path: Bybit/Rest/demo-trading.ts.
  • Example category: REST.
  • Imports SDK symbols including DefaultLogger, RestClientV5, WebsocketClient.
  • Calls SDK methods such as on(), subscribeV5(), getWalletBalance(), requestDemoTradingFunds(), getPositionInfo(), submitOrder().

How to use this example

  • Start here for the specific request or stream pattern, then check the matching SDK guide for install, credentials, and operational notes.
  • Open the repository source when you need the latest committed version: GitHub source file.
import { DefaultLogger, RestClientV5, WebsocketClient } from 'bybit-api'; const key = process.env.API_KEY_COM;const secret = process.env.API_SECRET_COM; /** * * * This example demonstrates how to use Bybit's demo trading functionality, both for REST and WS. * * Refer to the API docs for more information: https://bybit-exchange.github.io/docs/v5/demo * * */ const restClient = new RestClientV5({  key: key,  secret: secret,  parseAPIRateLimits: true,  /**   * Set this to true to enable demo trading:   */  demoTrading: true,}); // Optional, uncomment the "trace" override to log a lot more info about what the WS client is doingconst customLogger = {  ...DefaultLogger,  // trace: (...params) => console.log('trace', ...params),}; const wsClient = new WebsocketClient(  {    key: key,    secret: secret,     /**     * Set this to true to enable demo trading for the private account data WS     * Topics: order,execution,position,wallet,greeks     */    demoTrading: true,  },  customLogger,); function setWsClientEventListeners(  websocketClient: WebsocketClient,  accountRef: string,): Promise<void> {  return new Promise((resolve) => {    websocketClient.on('update', (data) => {      console.log(new Date(), accountRef, 'data ', JSON.stringify(data));      // console.log('raw message received ', JSON.stringify(data, null, 2));    });     websocketClient.on('open', (data) => {      console.log(        new Date(),        accountRef,        'connection opened open:',        data.wsKey,      );    });    websocketClient.on('response', (data) => {      console.log(        new Date(),        accountRef,        'log response: ',        JSON.stringify(data, null, 2),      );       if (typeof data.req_id === 'string') {        const topics = data.req_id.split(',');        if (topics.length) {          console.log(new Date(), accountRef, 'Subscribed to topics: ', topics);          return resolve();        }      }    });    websocketClient.on('reconnect', ({ wsKey }) => {      console.log(        new Date(),        accountRef,        'ws automatically reconnecting.... ',        wsKey,      );    });    websocketClient.on('reconnected', (data) => {      console.log(new Date(), accountRef, 'ws has reconnected ', data?.wsKey);    });    websocketClient.on('exception', (data) => {      console.error(new Date(), accountRef, 'ws exception: ', data);    });  });} (async () => {  try {    const onSubscribed = setWsClientEventListeners(wsClient, 'demoAcc');     wsClient.subscribeV5(['position', 'execution', 'wallet'], 'linear');     // Simple promise to ensure we're subscribed before trying anything else    await onSubscribed;     // Start trading    const balResponse1 = await restClient.getWalletBalance({      accountType: 'UNIFIED',    });    console.log('balResponse1: ', JSON.stringify(balResponse1, null, 2));     const demoFunds = await restClient.requestDemoTradingFunds();    console.log('requested demo funds: ', demoFunds);     const balResponse2 = await restClient.getWalletBalance({      accountType: 'UNIFIED',    });    console.log('balResponse2: ', JSON.stringify(balResponse2, null, 2));     /** Simple examples for private REST API calls with bybit's V5 REST APIs */    const response = await restClient.getPositionInfo({      category: 'linear',      symbol: 'BTCUSDT',    });     console.log('response:', response);     // Trade USDT linear perps    const buyOrderResult = await restClient.submitOrder({      category: 'linear',      symbol: 'BTCUSDT',      orderType: 'Market',      qty: '1',      side: 'Buy',    });    console.log('buyOrderResult:', buyOrderResult);     const sellOrderResult = await restClient.submitOrder({      category: 'linear',      symbol: 'BTCUSDT',      orderType: 'Market',      qty: '1',      side: 'Sell',    });    console.log('sellOrderResult:', sellOrderResult);     const balResponse3 = await restClient.getWalletBalance({      accountType: 'UNIFIED',    });    console.log('balResponse2: ', JSON.stringify(balResponse3, null, 2));  } catch (e) {    console.error('request failed: ', e);  }})(); 

Subscribe on Substack

Complete the Substack form below to join our newsletter. Substack handles all subscriber data directly.