Skip to content

Commit 6810397

Browse files
committed
demo latency
1 parent 6c3796a commit 6810397

File tree

1 file changed

+57
-19
lines changed

1 file changed

+57
-19
lines changed

demo/app.js

Lines changed: 57 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,24 @@
11
import 'dotenv/config';
22
import chalk from 'chalk';
3-
import { MexcClient } from '../src/nodejs/MexcClient.js';
3+
import { MexcClient } from './MexcClient.js';
44
import ora from 'ora';
55
import figlet from 'figlet';
66
import gradient from 'gradient-string';
77

8+
// Анимация ожидания
89
async function sleep(ms) {
910
return new Promise(resolve => setTimeout(resolve, ms));
1011
}
1112

13+
// Измерение времени выполнения запроса
14+
async function measureLatency(fn, ...args) {
15+
const start = Date.now();
16+
const result = await fn(...args);
17+
const latency = Date.now() - start;
18+
return { result, latency };
19+
}
20+
21+
// Красивый заголовок
1222
async function showBanner() {
1323
console.clear();
1424
console.log('\n');
@@ -44,19 +54,26 @@ async function main() {
4454
await sleep(1000);
4555
spinner.succeed(chalk.green('MEXC Client initialized successfully\n'));
4656

47-
// --- Step 1: Get account info ---
57+
// Получение баланса с замером latency
4858
const balanceSpinner = ora(chalk.yellow('Fetching account balance...')).start();
49-
const balance = await client.getAsset({ currency: 'USDT' });
50-
balanceSpinner.succeed(chalk.green('Balance data received\n'));
59+
const { result: balance, latency: balanceLatency } = await measureLatency(
60+
client.getAsset.bind(client),
61+
{ currency: 'USDT' }
62+
);
63+
balanceSpinner.succeed([
64+
chalk.green('Balance data received'),
65+
chalk.gray(`(${balanceLatency}ms)`)
66+
].join(' '));
5167

5268
console.log(chalk.gray('┌──────────────────────────────────────────────┐'));
5369
console.log(chalk.gray('│') + chalk.bold(' ACCOUNT SUMMARY ') + chalk.gray('│'));
5470
console.log(chalk.gray('├──────────────────────────────────────────────┤'));
5571
console.log(chalk.gray('│') + ` 💰 Available: ${chalk.greenBright(`${balance.data.availableBalance.toFixed(2)} USDT`)}${' '.repeat(12)}` + chalk.gray('│'));
5672
console.log(chalk.gray('│') + ` 📊 Unrealized PnL: ${balance.data.unrealized >= 0 ? chalk.greenBright(`${balance.data.unrealized.toFixed(2)}`) : chalk.redBright(`${balance.data.unrealized.toFixed(2)}`)} USDT` + ' '.repeat(5) + chalk.gray('│'));
73+
console.log(chalk.gray('│') + ` ⏱️ Last request latency: ${chalk.cyan(`${balanceLatency}ms`)}${' '.repeat(8)}` + chalk.gray('│'));
5774
console.log(chalk.gray('└──────────────────────────────────────────────┘\n'));
5875

59-
// --- Step 2: Open positions ---
76+
// --- Step 1: Open positions ---
6077
const openOrders = [
6178
{ symbol: 'BTC_USDT', side: 1, vol: 15, leverage: 25, emoji: '₿' },
6279
{ symbol: 'ETH_USDT', side: 3, vol: 1, leverage: 10, emoji: 'Ξ' },
@@ -66,6 +83,7 @@ async function main() {
6683
];
6784

6885
const openedOrderIds = [];
86+
const latencies = [];
6987

7088
console.log(chalk.blue.bold('🛫 OPENING POSITIONS'));
7189
console.log(chalk.gray('──────────────────────────────────────────────\n'));
@@ -87,12 +105,15 @@ async function main() {
87105
...(order.takeProfitPrice && { takeProfitPrice: order.takeProfitPrice }),
88106
};
89107

90-
const response = await client.createOrder(params);
108+
const { result: response, latency } = await measureLatency(
109+
client.createOrder.bind(client),
110+
params
111+
);
112+
latencies.push(latency);
113+
91114
const orderId = response?.data?.orderId;
92115
if (orderId) openedOrderIds.push(orderId);
93116

94-
await sleep(300);
95-
96117
const direction = order.side === 1 ?
97118
chalk.bgGreen.white(' LONG ') :
98119
chalk.bgRed.white(' SHORT ');
@@ -103,13 +124,18 @@ async function main() {
103124
`Volume: ${chalk.yellow(order.vol)}`,
104125
order.stopLossPrice ? `SL: ${chalk.red(order.stopLossPrice)}` : '',
105126
order.takeProfitPrice ? `TP: ${chalk.green(order.takeProfitPrice)}` : '',
106-
chalk.gray(`ID: ${orderId}`)
127+
chalk.gray(`ID: ${orderId}`),
128+
chalk.cyan(`${latency}ms`)
107129
].filter(Boolean).join(' | '));
108130

109131
await sleep(500);
110132
}
111133

112-
// --- Step 3: Cancel some orders ---
134+
// Вывод статистики latency
135+
const avgLatency = latencies.reduce((a, b) => a + b, 0) / latencies.length;
136+
console.log(chalk.gray(`\n📊 Average order latency: ${chalk.cyan(`${avgLatency.toFixed(0)}ms`)}`));
137+
138+
// --- Step 2: Cancel some orders ---
113139
console.log(`\n${chalk.magenta.bold('🛑 CANCELLING ORDERS')}`);
114140
console.log(chalk.gray('──────────────────────────────────────────────\n'));
115141

@@ -121,18 +147,21 @@ async function main() {
121147
color: 'magenta'
122148
}).start();
123149

124-
await client.cancelOrders({ ids: idsToCancel });
125-
await sleep(800);
150+
const { latency: cancelLatency } = await measureLatency(
151+
client.cancelOrders.bind(client),
152+
{ ids: idsToCancel }
153+
);
126154

127155
cancelSpinner.succeed([
128156
chalk.gray('Cancelled orders:'),
129-
chalk.yellow(idsToCancel.join(', '))
157+
chalk.yellow(idsToCancel.join(', ')),
158+
chalk.cyan(`${cancelLatency}ms`)
130159
].join(' '));
131160
} else {
132161
console.log(chalk.yellow('⚠️ No orders available for cancellation'));
133162
}
134163

135-
// --- Step 4: Close positions ---
164+
// --- Step 3: Close positions ---
136165
const closingOrders = [
137166
{ symbol: 'BTC_USDT', side: 4, vol: 15, leverage: 25, emoji: '₿' },
138167
{ symbol: 'ETH_USDT', side: 2, vol: 1, leverage: 10, emoji: 'Ξ' },
@@ -156,14 +185,17 @@ async function main() {
156185
leverage: order.leverage,
157186
};
158187

159-
const response = await client.createOrder(params);
188+
const { result: response, latency: closeLatency } = await measureLatency(
189+
client.createOrder.bind(client),
190+
params
191+
);
160192
const orderId = response?.data?.orderId;
161193

162-
await sleep(500);
163194
closeSpinner.succeed([
164195
`${chalk.bgBlue.white(' CLOSE ')} ${order.emoji} ${chalk.bold(order.symbol)}`,
165196
`Volume: ${chalk.yellow(order.vol)}`,
166-
chalk.gray(`ID: ${orderId}`)
197+
chalk.gray(`ID: ${orderId}`),
198+
chalk.cyan(`${closeLatency}ms`)
167199
].join(' | '));
168200
}
169201

@@ -177,9 +209,15 @@ async function main() {
177209
}).start();
178210

179211
await sleep(2000);
180-
await client.closeAllPositions();
212+
const { latency: cleanupLatency } = await measureLatency(
213+
client.closeAllPositions.bind(client)
214+
);
215+
216+
cleanupSpinner.succeed([
217+
chalk.green('All positions have been force-closed'),
218+
chalk.cyan(`${cleanupLatency}ms`)
219+
].join(' '));
181220

182-
cleanupSpinner.succeed(chalk.green('All positions have been force-closed'));
183221
console.log(`\n${chalk.bold.green('✅ All operations completed successfully!')}\n`);
184222

185223
} catch (error) {

0 commit comments

Comments
 (0)