Skip to content

Commit

Permalink
v3.9.9: feat() support demo trading apis
Browse files Browse the repository at this point in the history
  • Loading branch information
tiagosiebler committed Apr 9, 2024
1 parent 185f02a commit cc362c4
Show file tree
Hide file tree
Showing 9 changed files with 160 additions and 22 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Check out my related projects:
- [binance](https://www.npmjs.com/package/binance)
- [okx-api](https://www.npmjs.com/package/okx-api)
- [bitget-api](https://www.npmjs.com/package/bitget-api)
- [bitmart-api](https://www.npmjs.com/package/bitmart-api)
- Try my misc utilities:
- [orderbooks](https://www.npmjs.com/package/orderbooks)
- [accountstate](https://www.npmjs.com/package/accountstate)
Expand Down
115 changes: 115 additions & 0 deletions examples/demo-trading.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { RestClientV5, WebsocketClient } from '../src/index';

// or
// import { RestClientV5 } from 'bybit-api';

const key = process.env.API_KEY_COM;
const secret = process.env.API_SECRET_COM;

const restClient = new RestClientV5({
key: key,
secret: secret,
parseAPIRateLimits: true,
/**
* Set this to true to enable demo trading:
*/
demoTrading: true,
});

const wsClient = new WebsocketClient({
market: 'v5',
/**
* Set this to true to enable demo trading for the private account data WS
* Topics: order,execution,position,wallet,greeks
*/
demoTrading: true,
});

function setWsClientEventListeners(
websocketClient: WebsocketClient,
accountRef: string,
): void {
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),
);
});
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('error', (data) => {
console.error(new Date(), accountRef, 'ws exception: ', data);
});
}

(async () => {
try {
setWsClientEventListeners(wsClient, 'demoAcc');

const balResponse1 = await restClient.getWalletBalance({
accountType: 'CONTRACT',
});
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: 'CONTRACT',
});
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: 'CONTRACT',
});
console.log('balResponse2: ', JSON.stringify(balResponse3, null, 2));
} catch (e) {
console.error('request failed: ', e);
}
})();
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "bybit-api",
"version": "3.9.8",
"version": "3.9.9",
"description": "Complete & robust Node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & strong end to end tests.",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
4 changes: 4 additions & 0 deletions src/rest-client-v5.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,10 @@ export class RestClientV5 extends BaseRestClient {
return this.get('/v3/public/time');
}

requestDemoTradingFunds(): Promise<{}> {
return this.postPrivate('/v5/account/demo-apply/money');
}

/**
*
****** Market APIs
Expand Down
8 changes: 7 additions & 1 deletion src/types/websockets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ export interface WSClientConfigurableOptions {
secret?: string;
testnet?: boolean;

/**
* Set to `true` to connect to Bybit's V5 demo trading: https://bybit-exchange.github.io/docs/v5/demo
*
* Only the "V5" "market" is supported here.
*/
demoTrading?: boolean;

/**
* The API group this client should connect to.
*
Expand All @@ -109,7 +116,6 @@ export interface WSClientConfigurableOptions {
}

export interface WebsocketClientOptions extends WSClientConfigurableOptions {
testnet?: boolean;
market: APIMarket;
pongTimeout: number;
pingInterval: number;
Expand Down
16 changes: 13 additions & 3 deletions src/util/requestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export interface RestClientOptions {
/** Set to `true` to connect to testnet. Uses the live environment by default. */
testnet?: boolean;

/**
* Set to `true` to use Bybit's V5 demo trading: https://bybit-exchange.github.io/docs/v5/demo
*/
demoTrading?: boolean;

/** Override the max size of the request window (in ms) */
recv_window?: number;

Expand Down Expand Up @@ -92,15 +97,20 @@ export function serializeParams(

export function getRestBaseUrl(
useTestnet: boolean,
restInverseOptions: RestClientOptions,
restClientOptions: RestClientOptions,
): string {
const exchangeBaseUrls = {
livenet: 'https://api.bybit.com',
testnet: 'https://api-testnet.bybit.com',
demoLivenet: 'https://api-demo.bybit.com',
};

if (restInverseOptions.baseUrl) {
return restInverseOptions.baseUrl;
if (restClientOptions.baseUrl) {
return restClientOptions.baseUrl;
}

if (restClientOptions.demoTrading) {
return exchangeBaseUrls.demoLivenet;
}

if (useTestnet) {
Expand Down
13 changes: 10 additions & 3 deletions src/util/websocket-util.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import WebSocket from 'isomorphic-ws';

import { APIMarket, CategoryV5, WsKey } from '../types';
import { APIMarket, CategoryV5, WebsocketClientOptions, WsKey } from '../types';
import { DefaultLogger } from './logger';

interface NetworkMapV3 {
Expand Down Expand Up @@ -398,14 +398,21 @@ export function getWsKeyForTopic(

export function getWsUrl(
wsKey: WsKey,
wsUrl: string | undefined,
isTestnet: boolean,
wsClientOptions: WebsocketClientOptions,
logger: typeof DefaultLogger,
): string {
const wsUrl = wsClientOptions.wsUrl;
if (wsUrl) {
return wsUrl;
}

// https://bybit-exchange.github.io/docs/v5/demo
const isDemoTrading = wsClientOptions.demoTrading;
if (isDemoTrading) {
return 'wss://stream-demo.bybit.com/v5/private';
}

const isTestnet = wsClientOptions.testnet;
const networkKey = isTestnet ? 'testnet' : 'livenet';

switch (wsKey) {
Expand Down
7 changes: 1 addition & 6 deletions src/websocket-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -623,12 +623,7 @@ export class WebsocketClient extends EventEmitter {
}

const authParams = await this.getAuthParams(wsKey);
const url = getWsUrl(
wsKey,
this.options.wsUrl,
this.isTestnet(),
this.logger,
);
const url = getWsUrl(wsKey, this.options, this.logger);
const ws = this.connectToWsUrl(url + authParams, wsKey);

return this.wsStore.setWs(wsKey, ws);
Expand Down

0 comments on commit cc362c4

Please sign in to comment.