|
| 1 | +/* eslint-disable @typescript-eslint/no-unused-vars */ |
| 2 | +import { |
| 3 | + PlaceOrderRequestV3, |
| 4 | + RestClientV3, |
| 5 | + WebsocketClientV3, |
| 6 | +} from '../../src'; |
| 7 | + |
| 8 | +// or |
| 9 | +// import { PlaceOrderRequestV3, RestClientV3, WebsocketClientV3 } from '../src'; |
| 10 | + |
| 11 | +// read from environmental variables |
| 12 | +const API_KEY = process.env.API_KEY_COM; |
| 13 | +const API_SECRET = process.env.API_SECRET_COM; |
| 14 | +const API_PASS = process.env.API_PASS_COM; |
| 15 | + |
| 16 | +// If running from CLI in unix, you can pass env vars as such: |
| 17 | +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-trade-futures.ts |
| 18 | + |
| 19 | +// note the single quotes, preventing special characters such as $ from being incorrectly passed |
| 20 | + |
| 21 | +const client = new RestClientV3({ |
| 22 | + apiKey: API_KEY, |
| 23 | + apiSecret: API_SECRET, |
| 24 | + apiPass: API_PASS, |
| 25 | + // apiKey: 'apiKeyHere', |
| 26 | + // apiSecret: 'apiSecretHere', |
| 27 | + // apiPass: 'apiPassHere', |
| 28 | +}); |
| 29 | + |
| 30 | +const wsClient = new WebsocketClientV3({ |
| 31 | + apiKey: API_KEY, |
| 32 | + apiSecret: API_SECRET, |
| 33 | + apiPass: API_PASS, |
| 34 | +}); |
| 35 | + |
| 36 | +function logWSEvent(type, data) { |
| 37 | + console.log(new Date(), `WS ${type} event: `, data); |
| 38 | +} |
| 39 | + |
| 40 | +// simple sleep function |
| 41 | +function promiseSleep(milliseconds) { |
| 42 | + return new Promise((resolve) => setTimeout(resolve, milliseconds)); |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). |
| 47 | + * |
| 48 | + * It is designed to: |
| 49 | + * - open a private websocket channel to log account events |
| 50 | + * - check for any available USDT balance in the account |
| 51 | + * - immediately open a minimum sized long position on BTCUSDT |
| 52 | + * - check active positions |
| 53 | + * - immediately send closing orders for any active futures positions |
| 54 | + * - check positions again |
| 55 | + * |
| 56 | + */ |
| 57 | +(async () => { |
| 58 | + try { |
| 59 | + // Add event listeners to log websocket events on account |
| 60 | + wsClient.on('update', (data) => logWSEvent('update', data)); |
| 61 | + |
| 62 | + wsClient.on('open', (data) => logWSEvent('open', data)); |
| 63 | + wsClient.on('response', (data) => logWSEvent('response', data)); |
| 64 | + wsClient.on('reconnect', (data) => logWSEvent('reconnect', data)); |
| 65 | + wsClient.on('reconnected', (data) => logWSEvent('reconnected', data)); |
| 66 | + wsClient.on('authenticated', (data) => logWSEvent('authenticated', data)); |
| 67 | + wsClient.on('exception', (data) => logWSEvent('exception', data)); |
| 68 | + |
| 69 | + // Subscribe to private topics for UTA account |
| 70 | + wsClient.subscribe( |
| 71 | + { |
| 72 | + topic: 'account', |
| 73 | + payload: { |
| 74 | + instType: 'UTA', |
| 75 | + }, |
| 76 | + }, |
| 77 | + 'v3Private', |
| 78 | + ); |
| 79 | + |
| 80 | + // Subscribe to position updates |
| 81 | + wsClient.subscribe( |
| 82 | + { |
| 83 | + topic: 'position', |
| 84 | + payload: { |
| 85 | + instType: 'UTA', |
| 86 | + }, |
| 87 | + }, |
| 88 | + 'v3Private', |
| 89 | + ); |
| 90 | + |
| 91 | + // Subscribe to order updates |
| 92 | + wsClient.subscribe( |
| 93 | + { |
| 94 | + topic: 'order', |
| 95 | + payload: { |
| 96 | + instType: 'UTA', |
| 97 | + }, |
| 98 | + }, |
| 99 | + 'v3Private', |
| 100 | + ); |
| 101 | + |
| 102 | + // wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) |
| 103 | + await promiseSleep(2.5 * 1000); |
| 104 | + |
| 105 | + const symbol = 'BTCUSDT'; |
| 106 | + |
| 107 | + const balanceResult = await client.getBalances(); |
| 108 | + const accountBalance = balanceResult.data; |
| 109 | + |
| 110 | + const usdtAsset = accountBalance.assets?.find( |
| 111 | + (asset) => asset.coin === 'USDT', |
| 112 | + ); |
| 113 | + const usdtAmount = usdtAsset ? Number(usdtAsset.available) : 0; |
| 114 | + |
| 115 | + console.log('USDT balance: ', usdtAmount); |
| 116 | + |
| 117 | + if (!usdtAmount) { |
| 118 | + console.error('No USDT to trade'); |
| 119 | + return; |
| 120 | + } |
| 121 | + |
| 122 | + const symbolRulesResult = await client.getInstruments({ |
| 123 | + category: 'USDT-FUTURES', |
| 124 | + symbol: symbol, |
| 125 | + }); |
| 126 | + const bitcoinUSDFuturesRule = symbolRulesResult.data.find( |
| 127 | + (row) => row.symbol === symbol, |
| 128 | + ); |
| 129 | + |
| 130 | + console.log('symbol rules: ', bitcoinUSDFuturesRule); |
| 131 | + if (!bitcoinUSDFuturesRule) { |
| 132 | + console.error('Failed to get trading rules for ' + symbol); |
| 133 | + return; |
| 134 | + } |
| 135 | + |
| 136 | + const order: PlaceOrderRequestV3 = { |
| 137 | + category: 'USDT-FUTURES', |
| 138 | + orderType: 'market', |
| 139 | + side: 'buy', |
| 140 | + qty: bitcoinUSDFuturesRule.minOrderQty, |
| 141 | + symbol: symbol, |
| 142 | + } as const; |
| 143 | + |
| 144 | + console.log('placing order: ', order); |
| 145 | + |
| 146 | + const result = await client.submitNewOrder(order); |
| 147 | + |
| 148 | + console.log('order result: ', result); |
| 149 | + |
| 150 | + const positionsResult = await client.getCurrentPosition({ |
| 151 | + category: 'USDT-FUTURES', |
| 152 | + }); |
| 153 | + const positionsToClose = positionsResult.data.list.filter( |
| 154 | + (pos) => pos.total !== '0', |
| 155 | + ); |
| 156 | + |
| 157 | + console.log('open positions to close: ', positionsToClose); |
| 158 | + |
| 159 | + // Loop through any active positions and send a closing market order on each position |
| 160 | + for (const position of positionsToClose) { |
| 161 | + const closingSide = position.posSide === 'long' ? 'sell' : 'buy'; |
| 162 | + const closingOrder: PlaceOrderRequestV3 = { |
| 163 | + category: 'USDT-FUTURES', |
| 164 | + orderType: 'market', |
| 165 | + side: closingSide, |
| 166 | + qty: position.total, |
| 167 | + symbol: position.symbol, |
| 168 | + }; |
| 169 | + |
| 170 | + console.log('closing position with market order: ', closingOrder); |
| 171 | + |
| 172 | + const result = await client.submitNewOrder(closingOrder); |
| 173 | + console.log('position closing order result: ', result); |
| 174 | + } |
| 175 | + |
| 176 | + console.log( |
| 177 | + 'positions after closing all: ', |
| 178 | + await client.getCurrentPosition({ |
| 179 | + category: 'USDT-FUTURES', |
| 180 | + }), |
| 181 | + ); |
| 182 | + } catch (e) { |
| 183 | + console.error('request failed: ', e); |
| 184 | + } |
| 185 | +})(); |
0 commit comments