Deno quickstart
Run a public BTC REST request and a WebSocket subscription with binance. No API key is needed. Prices are BTCUSDT last traded prices.
Create the project
Install Deno first. The runtime compatibility report records the versions exercised with this SDK.
Download the complete Deno starter, or create an empty directory and copy the files below. The archive contains the same files shown on this page.
mkdir binance-deno-quickstart
cd binance-deno-quickstartCopy the files below, or extract the downloaded archive into this directory (adjust the download path if needed):
tar -xzf ~/Downloads/deno.tar.gzInstall the dependencies after saving or extracting the files:
deno installThe SDK dependency uses latest, so a new installation selects the current npm release.
Project files
package.json
{
"name": "binance-deno-quickstart",
"private": true,
"type": "module",
"scripts": {},
"dependencies": {
"binance": "latest"
}
}market.js
export const endpoints = {"rest": "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT", "websocket": "wss://stream.binance.com:9443"};
export function client(sdk) { return new sdk.MainClient({}, {timeout:15000}); }
export async function read(client) {
const response = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' });
if (Array.isArray(response)) throw new Error('Expected one ticker');
return response.price;
}
export function stream(sdk, logger) { return new sdk.WebsocketClient({}, logger); }
export const event = 'message';
export function value(message) { return message.e === '24hrTicker' ? message.c : undefined; }
export async function subscribe(ws) { await ws.subscribeSpotSymbol24hrTicker('btcusdt'); }price.js
import * as sdk from 'binance';
import * as market from './market.js';
function positivePrice(value) {
if (!Number.isFinite(Number(value)) || Number(value) <= 0) {
throw new Error('The exchange did not return a positive BTC price.');
}
return String(value);
}
export async function readPrice() {
return positivePrice(await market.read(market.client(sdk)));
}
// Returns cleanup without waiting for subscription acknowledgement.
export function watchPrice(onPrice, onError) {
const ws = market.stream(sdk);
let stopped = false;
const receive = message => {
const value = market.value(message);
if (!stopped && value !== undefined) {
clearTimeout(deadline);
try { onPrice(positivePrice(value)); } catch (error) { fail(error); }
}
};
const fail = error => { if (!stopped) onError(error); };
const deadline = setTimeout(() => fail(new Error('No BTC update within 30 seconds. Check network access.')), 30000);
ws.on(market.event, receive);
ws.on('exception', fail);
// React may clean up an effect before its queued subscription starts.
Promise.resolve().then(async () => {
if (stopped) return;
try {
await market.subscribe(ws);
} finally {
// A connection may finish opening after cleanup was requested.
if (stopped) ws.closeAll();
}
}).catch(fail);
return () => {
if (stopped) return;
stopped = true;
clearTimeout(deadline);
ws.closeAll();
ws.removeListener(market.event, receive);
ws.removeListener('exception', fail);
};
}prices.js
import process from 'node:process';
import { readPrice, watchPrice } from './price.js';
async function main() {
console.log('BTC REST price:', await readPrice());
let stop;
try {
const price = await new Promise((resolve, reject) => {
stop = watchPrice(resolve, reject);
});
console.log('BTC WebSocket price:', price);
} finally {
stop?.();
console.log('WebSocket closed.');
}
}
main().catch(error => {
console.error(error.message || String(error));
process.exitCode = 1;
});deno.json
{
"nodeModulesDir": "auto",
"tasks": {
"start": "deno run --allow-net --allow-env --allow-read prices.js"
}
}Run
deno task startAlongside SDK connection logs, the script prints one REST price and the first valid WebSocket price, closes the WebSocket client in finally, and exits. Prices change continuously; the two values may differ.
BTC REST price: 65000.5
BTC WebSocket price: 65001.2
WebSocket closed.Troubleshooting
Use
deno task startto retain the documented permissions. A permission prompt or denial can mean you randeno run prices.jsdirectly. Network access is needed for the public exchange; environment and read access support npm dependencies.Keep
nodeModulesDir: "auto"indeno.jsonand rundeno installif npm dependencies cannot be resolved.A rejected HTTP request or no WebSocket update within 30 seconds usually needs a network check. Allow outbound HTTPS and WSS to the exchange endpoints in
market.js. An exchange may restrict access from your region.For API errors, see Troubleshooting. For continuous subscriptions and shutdown, see WebSocket subscriptions.