feat(#186): add proxy & rate limits example. Misc doc updates.

This commit is contained in:
tiagosiebler
2023-12-22 11:47:54 +00:00
parent 923b1b02e0
commit 48eaa4785d
17 changed files with 216 additions and 68 deletions

View File

@@ -0,0 +1,5 @@
# Deprecated Examples
The examples in this folder use old/deprecated/obsolete APIs. They should all have a modern alternative.
As of December 2023, use the V5 APIs & WebSockets.

View File

@@ -0,0 +1,24 @@
import { ContractClient } from '../../src/index';
// or
// import { ContractClient } from 'bybit-api';
const key = process.env.API_KEY_COM;
const secret = process.env.API_SECRET_COM;
const client = new ContractClient({
key,
secret,
strict_param_validation: true,
});
(async () => {
try {
const getPositions = await client.getPositions({
settleCoin: 'USDT',
});
console.log('getPositions:', getPositions);
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,21 @@
/**
* This is the pure javascript version of the `rest-contract-public.ts` sample
*/
// To use a local build (testing with the repo directly), make sure to `npm run build` first from the repo root
// const { ContractClient } = require('../dist');
// or, use the version installed with npm
const { ContractClient } = require('bybit-api');
(async () => {
const client = new ContractClient();
try {
const orderbookResult = await client.getOrderBook('BTCUSDT', 'linear');
console.log('orderbook result: ', orderbookResult);
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,20 @@
/**
* This is the TypeScript version of the `rest-contract-public.js` sample.
*/
// For testing with the repo directly, import from the src folder
import { ContractClient } from '../../src';
// or, use the version installed with npm
// import { ContractClient } from 'bybit-api';
(async () => {
const client = new ContractClient();
try {
const orderbookResult = await client.getOrderBook('BTCUSDT', 'linear');
console.log('orderbook result: ', orderbookResult);
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,25 @@
import { CopyTradingClient } from '../../src/index';
// or
// import { CopyTradingClient } from 'bybit-api';
const key = process.env.API_KEY_COM;
const secret = process.env.API_SECRET_COM;
const client = new CopyTradingClient({
key,
secret,
strict_param_validation: true,
});
(async () => {
try {
const res = await client.closeOrder({
symbol: 'BTCUSDT',
parentOrderId: '419190fe-016c-469a-810e-936bef2f1234',
});
console.log('res:', res);
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,23 @@
import { LinearClient } from '../../src/index';
// or
// import { LinearClient } from 'bybit-api';
const client = new LinearClient();
(async () => {
try {
// console.log('getSymbols: ', await client.getSymbols());
// console.log('getOrderBook: ', await client.getOrderBook(symbol));
console.log(
'getKline: ',
await client.getKline({
symbol: 'ETHUSDT',
interval: 'D',
from: 1,
}),
);
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,33 @@
import { ContractClient } from '../../src/index';
// or
// import { ContractClient } from 'bybit-api';
const key = process.env.API_KEY_COM;
const secret = process.env.API_SECRET_COM;
const client = new ContractClient({
key,
secret,
strict_param_validation: true,
});
(async () => {
try {
/**
* You can make raw HTTP requests without the per-endpoint abstraction.
*
* The REST ContractClient uses bybit's v3 signature mechanism,
* so it can be used for raw calls to any v3-supporting endpoints (incl the V5 APIs).
* e.g. if an endpoint is missing and you desperately need it (but please raise an issue or PR if you're missing an endpoint)
*/
const rawCall = await client.getPrivate('/v5/order/realtime', {
category: 'linear',
symbol: 'BTCUSDT',
});
console.log('rawCall:', rawCall);
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,18 @@
import { SpotClientV3 } from '../../src/index';
// or
// import { SpotClientV3 } from 'bybit-api';
const client = new SpotClientV3();
const symbol = 'BTCUSDT';
(async () => {
try {
// console.log('getSymbols: ', await client.getSymbols());
// console.log('getOrderBook: ', await client.getOrderBook(symbol));
console.log('getOrderBook: ', await client.getOrderBook(symbol));
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,42 @@
import { SpotClientV3 } from '../../src/index';
// or
// import { SpotClientV3 } from 'bybit-api';
const symbol = 'BTCUSDT';
const key = process.env.API_KEY_COM;
const secret = process.env.API_SECRET_COM;
const client = new SpotClientV3({
key,
secret,
strict_param_validation: true,
});
(async () => {
try {
const orderId = undefined;
const ordersPerPage = undefined;
const orders = await client.getOpenOrders(symbol);
console.log('orders 1:', orders);
const normalOrders = await client.getOpenOrders(
symbol,
orderId,
ordersPerPage,
0,
);
console.log('normal orders:', normalOrders);
const tpSlOrders = await client.getOpenOrders(
symbol,
orderId,
ordersPerPage,
1,
);
console.log('tpSlOrders:', tpSlOrders);
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,44 @@
import { UnifiedMarginClient } from '../../src/index';
// or
// import { UnifiedMarginClient } from 'bybit-api';
const key = process.env.API_KEY_COM;
const secret = process.env.API_SECRET_COM;
const client = new UnifiedMarginClient({
key,
secret,
strict_param_validation: true,
});
(async () => {
try {
// page 1
const historicOrders1 = await client.getHistoricOrders({
category: 'linear',
limit: 1,
// cursor,
});
console.log('page 1:', JSON.stringify(historicOrders1, null, 2));
// page 2
const historicOrders2 = await client.getHistoricOrders({
category: 'linear',
limit: 1,
cursor: historicOrders1.result.nextPageCursor,
});
console.log('page 2:', JSON.stringify(historicOrders2, null, 2));
const historicOrdersBoth = await client.getHistoricOrders({
category: 'linear',
limit: 2,
});
console.log(
'both to compare:',
JSON.stringify(historicOrdersBoth, null, 2),
);
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,36 @@
import { UnifiedMarginClient } from '../../src/index';
// or
// import { UnifiedMarginClient } from 'bybit-api';
const client = new UnifiedMarginClient({
strict_param_validation: true,
});
(async () => {
try {
// page 1
const historicOrders1 = await client.getInstrumentInfo({
category: 'linear',
limit: '2',
});
console.log('page 1:', JSON.stringify(historicOrders1, null, 2));
// page 2
const historicOrders2 = await client.getInstrumentInfo({
category: 'linear',
limit: '2',
cursor: historicOrders1.result.nextPageCursor,
});
console.log('page 2:', JSON.stringify(historicOrders2, null, 2));
// page 1 & 2 in one request (for comparison)
const historicOrdersBoth = await client.getInstrumentInfo({
category: 'linear',
limit: '4',
});
console.log('both pages', JSON.stringify(historicOrdersBoth, null, 2));
} catch (e) {
console.error('request failed: ', e);
}
})();

View File

@@ -0,0 +1,61 @@
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-function */
import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from '../../src';
// or
// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api';
const logger = {
...DefaultLogger,
silly: (...params) => {
// console.log(params);
},
};
const key = process.env.API_KEY;
const secret = process.env.API_SECRET;
/**
* Copy trading api docs say that private topics should connect to: wss://stream.bybit.com/realtime_private
*
* Within this SDK, only the market `linear` uses this endpoint for private topics:
*/
const market = 'linear';
const wsClient = new WebsocketClient(
{
key: key,
secret: secret,
market: market,
},
logger,
);
wsClient.on('update', (data) => {
console.log('raw message received ', JSON.stringify(data, null, 2));
});
wsClient.on('open', (data) => {
console.log('connection opened open:', data.wsKey);
});
wsClient.on('response', (data) => {
console.log('ws response: ', JSON.stringify(data, null, 2));
});
wsClient.on('reconnect', ({ wsKey }) => {
console.log('ws automatically reconnecting.... ', wsKey);
});
wsClient.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});
wsClient.on('error', (data) => {
console.error('ws exception: ', data);
});
// copy trading topics from api docs: https://bybit-exchange.github.io/docs/copy-trade/ws-private/position
wsClient.subscribe([
'copyTradePosition',
'copyTradeOrder',
'copyTradeExecution',
'copyTradeWallet',
]);

View File

@@ -0,0 +1,69 @@
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-function */
import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from '../../src';
// or
// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api';
const logger = {
...DefaultLogger,
silly: () => {},
};
const key = process.env.API_KEY;
const secret = process.env.API_SECRET;
// USDT Perps:
// const market = 'linear';
// Inverse Perp
// const market = 'inverse';
// const market = 'spotv3';
// Contract v3
const market = 'contractUSDT';
// const market = 'contractInverse';
const wsClient = new WebsocketClient(
{
key: key,
secret: secret,
market: market,
// testnet: true,
restOptions: {
// enable_time_sync: true,
},
},
logger,
);
wsClient.on('update', (data) => {
console.log('raw message received ', JSON.stringify(data, null, 2));
});
wsClient.on('open', (data) => {
console.log('connection opened open:', data.wsKey);
});
wsClient.on('response', (data) => {
console.log('ws response: ', JSON.stringify(data, null, 2));
});
wsClient.on('reconnect', ({ wsKey }) => {
console.log('ws automatically reconnecting.... ', wsKey);
});
wsClient.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});
wsClient.on('error', (data) => {
console.error('ws exception: ', data);
});
// subscribe to private endpoints
// check the api docs in your api category to see the available topics
// wsClient.subscribe(['position', 'execution', 'order', 'wallet']);
// Contract v3
wsClient.subscribe([
'user.position.contractAccount',
'user.execution.contractAccount',
'user.order.contractAccount',
'user.wallet.contractAccount',
]);

View File

@@ -0,0 +1,172 @@
import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from '../../src';
// or
// import { DefaultLogger, WS_KEY_MAP, WebsocketClient } from 'bybit-api';
const logger = {
...DefaultLogger,
silly: (...params) => console.log('silly', ...params),
};
const wsClient = new WebsocketClient(
{
// key: key,
// secret: secret,
// market: 'linear',
// market: 'inverse',
// market: 'spot',
// market: 'spotv3',
// market: 'usdcOption',
// market: 'usdcPerp',
// market: 'unifiedPerp',
// market: 'unifiedOption',
market: 'contractUSDT',
},
logger,
);
wsClient.on('update', (data) => {
console.log('raw message received ', JSON.stringify(data));
// console.log('raw message received ', JSON.stringify(data, null, 2));
});
wsClient.on('open', (data) => {
console.log('connection opened open:', data.wsKey);
// if (data.wsKey === WS_KEY_MAP.spotPublic) {
// // Spot public, but not recommended - use spotv3 client instead
// // The old spot websockets dont automatically resubscribe if they disconnect
// // wsClient.subscribePublicSpotTrades('BTCUSDT');
// // wsClient.subscribePublicSpotTradingPair('BTCUSDT');
// // wsClient.subscribePublicSpotV1Kline('BTCUSDT', '1m');
// // wsClient.subscribePublicSpotOrderbook('BTCUSDT', 'full');
// }
});
wsClient.on('response', (data) => {
console.log('log response: ', JSON.stringify(data, null, 2));
});
wsClient.on('reconnect', ({ wsKey }) => {
console.log('ws automatically reconnecting.... ', wsKey);
});
wsClient.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});
// wsClient.on('error', (data) => {
// console.error('ws exception: ', data);
// });
// Inverse
// wsClient.subscribe('trade');
// Linear
// wsClient.subscribe('trade.BTCUSDT');
// Spot V3
// wsClient.subscribe('trade.BTCUSDT');
// Or an array of topics
// wsClient.subscribe([
// 'orderbook.40.BTCUSDT',
// 'orderbook.40.BTCUSDC',
// 'orderbook.40.USDCUSDT',
// 'orderbook.40.BTCDAI',
// 'orderbook.40.DAIUSDT',
// 'orderbook.40.ETHUSDT',
// 'orderbook.40.ETHUSDC',
// 'orderbook.40.ETHDAI',
// 'orderbook.40.XRPUSDT',
// 'orderbook.40.XRPUSDC',
// 'orderbook.40.EOSUSDT',
// 'orderbook.40.EOSUSDC',
// 'orderbook.40.DOTUSDT',
// 'orderbook.40.DOTUSDC',
// 'orderbook.40.XLMUSDT',
// 'orderbook.40.XLMUSDC',
// 'orderbook.40.LTCUSDT',
// 'orderbook.40.LTCUSDC',
// 'orderbook.40.DOGEUSDT',
// 'orderbook.40.DOGEUSDC',
// 'orderbook.40.BITUSDT',
// 'orderbook.40.BITUSDC',
// 'orderbook.40.BITDAI',
// 'orderbook.40.CHZUSDT',
// 'orderbook.40.CHZUSDC',
// 'orderbook.40.MANAUSDT',
// 'orderbook.40.MANAUSDC',
// 'orderbook.40.LINKUSDT',
// 'orderbook.40.LINKUSDC',
// 'orderbook.40.ICPUSDT',
// 'orderbook.40.ICPUSDC',
// 'orderbook.40.ADAUSDT',
// 'orderbook.40.ADAUSDC',
// 'orderbook.40.SOLUSDC',
// 'orderbook.40.SOLUSDT',
// 'orderbook.40.MATICUSDC',
// 'orderbook.40.MATICUSDT',
// 'orderbook.40.SANDUSDC',
// 'orderbook.40.SANDUSDT',
// 'orderbook.40.LUNCUSDC',
// 'orderbook.40.LUNCUSDT',
// 'orderbook.40.SLGUSDC',
// 'orderbook.40.SLGUSDT',
// 'orderbook.40.AVAXUSDC',
// 'orderbook.40.AVAXUSDT',
// 'orderbook.40.OPUSDC',
// 'orderbook.40.OPUSDT',
// 'orderbook.40.OKSEUSDC',
// 'orderbook.40.OKSEUSDT',
// 'orderbook.40.APEXUSDC',
// 'orderbook.40.APEXUSDT',
// 'orderbook.40.TRXUSDC',
// 'orderbook.40.TRXUSDT',
// 'orderbook.40.GMTUSDC',
// 'orderbook.40.GMTUSDT',
// 'orderbook.40.SHIBUSDC',
// 'orderbook.40.SHIBUSDT',
// 'orderbook.40.LDOUSDC',
// 'orderbook.40.LDOUSDT',
// 'orderbook.40.APEUSDC',
// 'orderbook.40.APEUSDT',
// 'orderbook.40.FILUSDC',
// 'orderbook.40.FILUSDT',
// ]);
// usdc options
// wsClient.subscribe([
// `recenttrades.BTC`,
// `recenttrades.ETH`,
// `recenttrades.SOL`,
// ]);
// usdc perps (note: the syntax is different for the unified perp market)
// (market: 'usdcPerp')
// wsClient.subscribe('trade.BTCUSDC');
// wsClient.subscribe('instrument_info.100ms.BTCPERP');
// unified perps
// wsClient.subscribe('publicTrade.BTCUSDT');
// wsClient.subscribe('publicTrade.BTCPERP');
// For spot v1 (the old, deprecated client), request public connection first then send required topics on 'open'
// Not necessary for spot v3
// wsClient.connectPublic();
// To unsubscribe from topics (after a 5 second delay, in this example):
// setTimeout(() => {
// console.log('unsubscribing');
// wsClient.unsubscribe('trade.BTCUSDT');
// }, 5 * 1000);
// Topics are tracked per websocket type
// Get a list of subscribed topics (e.g. for public v3 spot topics) (after a 5 second delay)
setTimeout(() => {
const publicSpotTopics = wsClient
.getWsStore()
.getTopics(WS_KEY_MAP.spotV3Public);
console.log('public spot topics: ', publicSpotTopics);
const privateSpotTopics = wsClient
.getWsStore()
.getTopics(WS_KEY_MAP.spotV3Private);
console.log('private spot topics: ', privateSpotTopics);
}, 5 * 1000);