Skip to content

Commit d9a5ddb

Browse files
authored
Merge branch 'master' into bumpsfixesupdates
2 parents 9b5f14c + f11f5cf commit d9a5ddb

File tree

8 files changed

+292
-0
lines changed

8 files changed

+292
-0
lines changed

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebS
6565
- [Related Projects](#related-projects)
6666
- [Documentation Links](#documentation)
6767
- [Usage](#usage)
68+
- [Demo Trading vs Testnet](#demo-trading-vs-testnet)
6869
- [REST API Clients](#rest-api-clients)
6970
- [REST Main Client](#rest-main-client)
7071
- [REST USD-M Futures](#rest-usd-m-futures)
@@ -153,6 +154,16 @@ Create API credentials at Binance
153154
- [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO)
154155
- [Testnet](https://testnet.binance.vision/).
155156
- [Testnet Futures](testnet.binancefuture.com).
157+
- [Demo Trading](https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d) - Uses real market data with simulated trading.
158+
159+
### Demo Trading vs Testnet
160+
161+
Binance offers two testing environments:
162+
163+
- **Demo Trading**: Uses real market data but simulated trading. This is ideal for testing strategies since market conditions match production. Available for Spot, USD-M Futures, and COIN-M Futures.
164+
- **Testnet**: Separate environment with simulated market data. Market conditions are very different from real markets and not recommended for strategy testing.
165+
166+
To use demo trading, simply set `demoTrading: true` in the client options. See the [demo trading examples](./examples/REST/rest-spot-demo.ts) for more information.
156167

157168
## REST API Clients
158169

examples/REST/rest-spot-demo.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { MainClient } from '../../src/index';
2+
3+
// or
4+
// import { MainClient } from 'binance';
5+
6+
const key = process.env.API_KEY_COM || 'APIKEY';
7+
const secret = process.env.API_SECRET_COM || 'APISECRET';
8+
9+
const client = new MainClient({
10+
api_secret: secret,
11+
api_key: key,
12+
beautifyResponses: true,
13+
/**
14+
* Demo trading uses real market data with simulated trading.
15+
* Perfect for testing strategies without risk.
16+
*/
17+
demoTrading: true,
18+
});
19+
20+
async function start() {
21+
try {
22+
// Get account information on demo trading
23+
const accountInfo = await client.getAccountInformation();
24+
console.log('Demo account info: ', accountInfo);
25+
26+
// Place a test order on demo trading
27+
const result = await client.submitNewOrder({
28+
side: 'BUY',
29+
symbol: 'BTCUSDT',
30+
type: 'MARKET',
31+
quantity: 0.001,
32+
});
33+
34+
console.log('Demo market buy result: ', result);
35+
} catch (e) {
36+
console.error('Demo trading request failed: ', e);
37+
}
38+
}
39+
40+
start();

examples/REST/rest-usdm-demo.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { USDMClient } from '../../src/index';
2+
3+
// or
4+
// import { USDMClient } from 'binance';
5+
6+
const key = process.env.API_KEY_COM || 'APIKEY';
7+
const secret = process.env.API_SECRET_COM || 'APISECRET';
8+
9+
const client = new USDMClient({
10+
api_secret: secret,
11+
api_key: key,
12+
beautifyResponses: true,
13+
/**
14+
* Demo trading uses real market data with simulated trading.
15+
* Perfect for testing strategies without risk.
16+
*/
17+
demoTrading: true,
18+
});
19+
20+
async function start() {
21+
try {
22+
// Get account information on demo trading
23+
const accountInfo = await client.getAccountInformation();
24+
console.log('Demo account info: ', accountInfo);
25+
26+
// Place a test order on demo trading
27+
const result = await client.submitNewOrder({
28+
side: 'SELL',
29+
symbol: 'BTCUSDT',
30+
type: 'MARKET',
31+
quantity: 0.001,
32+
});
33+
34+
console.log('Demo market sell result: ', result);
35+
} catch (e) {
36+
console.error('Demo trading request failed: ', e);
37+
}
38+
}
39+
40+
start();
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { WebsocketClient } from '../../src';
2+
3+
// or
4+
// import { WebsocketClient } from 'binance';
5+
6+
const key = process.env.API_KEY_COM || 'APIKEY';
7+
const secret = process.env.API_SECRET_COM || 'APISECRET';
8+
9+
async function start() {
10+
const wsClient = new WebsocketClient({
11+
api_key: key,
12+
api_secret: secret,
13+
beautify: true,
14+
/**
15+
* Demo trading uses real market data with simulated trading.
16+
* Perfect for testing strategies without risk.
17+
*
18+
* For more information:
19+
* https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d
20+
*/
21+
demoTrading: true,
22+
});
23+
24+
wsClient.on('formattedMessage', (data) => {
25+
console.log('Demo WS data: ', JSON.stringify(data, null, 2));
26+
});
27+
28+
wsClient.on('open', (data) => {
29+
console.log('Demo WS connection opened:', data.wsKey);
30+
});
31+
32+
wsClient.on('response', (data) => {
33+
console.log('Demo WS response: ', JSON.stringify(data, null, 2));
34+
});
35+
36+
wsClient.on('reconnected', (data) => {
37+
console.log('Demo WS reconnected ', data?.wsKey);
38+
});
39+
40+
wsClient.on('exception', (data) => {
41+
console.error('Demo WS error', data);
42+
});
43+
44+
// Subscribe to spot market streams on demo trading
45+
wsClient.subscribeSpotTrades('BTCUSDT');
46+
wsClient.subscribeSpotKline('BTCUSDT', '1m');
47+
}
48+
49+
start();
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { WebsocketClient } from '../../src';
2+
3+
// or
4+
// import { WebsocketClient } from 'binance';
5+
6+
const key = process.env.API_KEY_COM || 'APIKEY';
7+
const secret = process.env.API_SECRET_COM || 'APISECRET';
8+
9+
async function start() {
10+
const wsClient = new WebsocketClient({
11+
api_key: key,
12+
api_secret: secret,
13+
beautify: true,
14+
/**
15+
* Demo trading uses real market data with simulated trading.
16+
* Perfect for testing strategies without risk.
17+
*/
18+
demoTrading: true,
19+
});
20+
21+
wsClient.on('formattedMessage', (data) => {
22+
console.log('Demo WS data: ', JSON.stringify(data, null, 2));
23+
});
24+
25+
wsClient.on('open', (data) => {
26+
console.log('Demo WS connection opened:', data.wsKey);
27+
});
28+
29+
wsClient.on('response', (data) => {
30+
console.log('Demo WS response: ', JSON.stringify(data, null, 2));
31+
});
32+
33+
wsClient.on('reconnected', (data) => {
34+
console.log('Demo WS reconnected ', data?.wsKey);
35+
});
36+
37+
wsClient.on('exception', (data) => {
38+
console.error('Demo WS error', data);
39+
});
40+
41+
// Subscribe to USDM futures market streams on demo trading
42+
wsClient.subscribeKlines('BTCUSDT', '1m', 'usdm');
43+
wsClient.subscribeUsdFuturesUserDataStream();
44+
}
45+
46+
start();

src/types/websockets/ws-general.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,17 @@ export interface WSClientConfigurableOptions {
139139
*/
140140
testnet?: boolean;
141141

142+
/**
143+
* Set to `true` to use Binance's demo trading WebSocket endpoints.
144+
* Demo trading uses real market data but simulated trading.
145+
* More info: https://demo.binance.com/
146+
*
147+
* Notes:
148+
* - If demo trading, `testnet` should be set to false!
149+
* - If testing a strategy, use demo trading instead. Testnet market data is very different from real market conditions.
150+
*/
151+
demoTrading?: boolean;
152+
142153
/**
143154
* Default: false. If true, use market maker endpoints when available.
144155
* Eligible for high-frequency trading users who have enrolled and qualified

src/util/requestUtils.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,13 @@ export interface RestClientOptions {
5353
*/
5454
testnet?: boolean;
5555

56+
/**
57+
* Set to `true` to use Binance's demo trading endpoints.
58+
* Demo trading uses real market data but simulated trading.
59+
* More info: https://demo.binance.com/
60+
*/
61+
demoTrading?: boolean;
62+
5663
/**
5764
* Default: false. If true, use market maker endpoints when available.
5865
* Eligible for high-frequency trading users who have enrolled and qualified
@@ -427,6 +434,35 @@ const BINANCE_BASE_URLS: Record<BinanceBaseUrlKey, string> = {
427434
www: 'https://www.binance.com',
428435
};
429436

437+
// Demo Trading URLs
438+
const BINANCE_DEMO_BASE_URLS: Record<BinanceBaseUrlKey, string | undefined> = {
439+
// Demo Trading - Spot
440+
spot: 'https://demo-api.binance.com',
441+
spot1: 'https://demo-api.binance.com',
442+
spot2: 'https://demo-api.binance.com',
443+
spot3: 'https://demo-api.binance.com',
444+
spot4: 'https://demo-api.binance.com',
445+
spottest: undefined, // No demo for testnet (testnet already is a demo)
446+
447+
// Demo Trading - UM Futures
448+
usdm: 'https://demo-fapi.binance.com',
449+
usdmtest: undefined, // No demo for testnet
450+
451+
// Demo Trading - CM Futures
452+
coinm: 'https://demo-dapi.binance.com',
453+
coinmtest: undefined, // No demo for testnet
454+
455+
// Vanilla Options - no demo endpoints
456+
voptions: undefined,
457+
voptionstest: undefined,
458+
459+
// Portfolio Margin - no demo endpoints
460+
papi: undefined,
461+
462+
// www - no demo endpoints
463+
www: undefined,
464+
};
465+
430466
const BINANCE_MM_BASE_URLS: Record<BinanceBaseUrlKey, string | undefined> = {
431467
// spot/margin/savings/mining - no MM endpoints
432468
spot: undefined,
@@ -517,6 +553,17 @@ export function getRestBaseUrl(
517553

518554
const urlKey = restClientOptions.baseUrlKey || clientType;
519555

556+
// Use demo trading endpoints if requested and available
557+
if (restClientOptions.demoTrading) {
558+
const demoUrl = BINANCE_DEMO_BASE_URLS[urlKey];
559+
if (demoUrl) {
560+
return demoUrl;
561+
}
562+
throw new Error(
563+
`Demo trading is currently not supported for the product group "${urlKey}". If demo trading should be available here, please open an issue on GitHub.`,
564+
);
565+
}
566+
520567
// Use MM endpoints if requested and available
521568
if (restClientOptions.useMMSubdomain) {
522569
const mmUrl = BINANCE_MM_BASE_URLS[urlKey];

src/util/websockets/websocket-util.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,42 @@ export const WS_KEY_MM_URL_MAP: Record<WsKey, string | undefined> = {
210210
portfolioMarginProUserData: undefined,
211211
};
212212

213+
// Demo Trading WebSocket URLs
214+
export const WS_KEY_DEMO_URL_MAP: Record<WsKey, string | undefined> = {
215+
// Demo Trading - Spot
216+
main: 'wss://demo-stream.binance.com:9443',
217+
main2: 'wss://demo-stream.binance.com:443',
218+
main3: 'wss://demo-stream-sbe.binance.com', // Alternative stream
219+
mainTestnetPublic: undefined, // No demo for testnet
220+
mainTestnetUserData: undefined, // No demo for testnet
221+
222+
// Demo Trading - Spot WebSocket API
223+
mainWSAPI: 'wss://demo-ws-api.binance.com:443',
224+
mainWSAPI2: 'wss://demo-ws-api.binance.com:9443',
225+
mainWSAPITestnet: undefined, // No demo for testnet
226+
227+
// Margin Risk - no demo endpoint
228+
marginRiskUserData: undefined,
229+
230+
// Demo Trading - USDM Futures
231+
usdm: 'wss://fstream.binancefuture.com',
232+
usdmTestnet: undefined, // No demo for testnet
233+
usdmWSAPI: 'wss://testnet.binancefuture.com',
234+
usdmWSAPITestnet: undefined, // No demo for testnet
235+
236+
// Demo Trading - COINM Futures
237+
coinm: 'wss://dstream.binancefuture.com',
238+
coinm2: undefined, // No demo for coinm2
239+
coinmTestnet: undefined, // No demo for testnet
240+
coinmWSAPI: 'wss://testnet.binancefuture.com',
241+
coinmWSAPITestnet: undefined, // No demo for testnet
242+
243+
// Other connections - no demo endpoints
244+
eoptions: undefined,
245+
portfolioMarginUserData: undefined,
246+
portfolioMarginProUserData: undefined,
247+
};
248+
213249
export function getWsURLSuffix(
214250
wsKey: WsKey,
215251
connectionType: 'market' | 'userData',
@@ -381,10 +417,22 @@ export function getWsUrl(
381417
}
382418

383419
const isTestnet = !!wsClientOptions.testnet;
420+
const isDemoTrading = !!wsClientOptions.demoTrading;
384421
const useMMSubdomain = !!wsClientOptions.useMMSubdomain;
385422

386423
const resolvedWsKey = isTestnet ? getTestnetWsKey(wsKey) : wsKey;
387424

425+
// Use demo trading endpoints if requested and available
426+
if (isDemoTrading && !isTestnet) {
427+
const demoUrl = WS_KEY_DEMO_URL_MAP[resolvedWsKey];
428+
if (demoUrl) {
429+
return demoUrl;
430+
}
431+
throw new Error(
432+
`Demo trading is currently not supported for the WebSocket key "${resolvedWsKey}". If demo trading should be available here, please open an issue on GitHub.`,
433+
);
434+
}
435+
388436
// Use MM endpoints if requested and available
389437
if (useMMSubdomain && !isTestnet) {
390438
const mmUrl = WS_KEY_MM_URL_MAP[resolvedWsKey];

0 commit comments

Comments
 (0)