Crypto Market News

Blockchain & Cryptocurrency News

node Binance api examples

Release time:2026-02-17 10:02:37

Recommend exchange platforms

Exploring Node Binance API Examples: A Comprehensive Guide


Binance, one of the world's leading cryptocurrency exchanges by trading volume, provides a comprehensive API (Application Programming Interface) that allows developers to interact with their platform programmatically. The Binance API is versatile and designed for both clients and developers, offering access to real-time market data, account information, order execution, and much more. This article delves into the world of Node.js programming and how it can be used to interact with the Binance API through various examples.


Setting Up Your Environment


Before diving into coding examples, ensure you have Node.js installed on your system. You can download it from the official website (https://nodejs.org/). Additionally, for this guide, we'll use Axios as a promise-based HTTP data client to simplify making requests to the Binance API. Install Axios by running `npm install axios` in your project directory.


Authentication: Signing Up and Getting Your API Key


To authenticate with the Binance API, you need an account on Binance. Once logged in, navigate to "API/Production" under the "Settings" tab and click "Exchange Endpoint" for private data access or "WebSocket Endpoint" for real-time updates. For this guide, we'll focus on making requests with your API key, which requires exchanging a temporary key pair for an API key that can be used in production.


Remember to keep your API key confidential; it is necessary for authenticating all Binance API requests.


Example 1: Getting Ticker Information


Tickers are real-time market statistics and they include the last trade price, volume over a specified time period, the highest price of the asset in that period, and more. Here's how to fetch this data using Node.js with Axios:


```javascript


const axios = require('axios');


async function getTicker() {


try {


const response = await axios.get("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT");


console.log(response.data);


} catch (error) {


console.error(error);


}


}


getTicker();


```


This script sends a GET request to the Binance API's `/api/v3/ticker/price` endpoint with the symbol `BTCUSDT`, which retrieves the price of Bitcoin in US dollars. The response includes various statistics such as the last trade price and volume.


Example 2: Order Book Data


The order book provides a list of bids (buy orders) and asks (sell orders) at any given time for a specific market pair, like `BTCUSDT`. Here's how to fetch this data:


```javascript


const axios = require('axios');


async function getOrderBook() {


try {


const response = await axios.get("https://api.binance.com/api/v3/depth?symbol=BTCUSDT&limit=10");


console.log(response.data);


} catch (error) {


console.error(error);


}


}


getOrderBook();


```


This script retrieves the top 10 bids and asks for Bitcoin trading against US dollars. The order book depth can influence trade execution price.


Example 3: Making a Trade Order


To place orders on Binance, you need to authenticate with your API key. Here's how to place a buy order for `BTCUSDT` pair:


```javascript


const axios = require('axios');


const apiKey = 'YOUR_API_KEY'; // Replace this with your actual API Key


const secretKey = 'YOUR_SECRET_KEY'; // Replace this with your actual Secret Key


const baseUrl = 'https://api.binance.com/api/v3/';


async function placeBuyOrder() {


try {


let timestamp = Date.now();


let stringToSign = apiKey + secretKey + timestamp.toString();


let signature = crypto.createHmac('sha256', secretKey).update(stringToSign).digest('hex');


const requestBody = {


'method': 'BUY',


'symbol': 'BTCUSDT',


'quantity': 0.1 // Trade amount


};


const config = {


headers: {


'X-MBINANCE-APIKEY': apiKey,


'Content-Type': 'application/json',


'X-MBINANCE-SIGNATURE': signature,


'Timestamp': timestamp.toString()


}


};


const response = await axios.post(baseUrl + "order", requestBody, config);


console.log(response.data);


} catch (error) {


console.error(error);


}


}


placeBuyOrder();


```


This script calculates a signature using your API key and secret key to authenticate the order placement request. It then sends a POST request to `/api/v3/order` with a body containing the trade details.


Example 4: Canceling an Order


To cancel a placed order, you need its ID, which was returned when it was created. Here's how to cancel an existing buy order for `BTCUSDT`:


```javascript


const axios = require('axios');


const apiKey = 'YOUR_API_KEY'; // Replace this with your actual API Key


const secretKey = 'YOUR_SECRET_KEY'; // Replace this with your actual Secret Key


const baseUrl = 'https://api.binance.com/api/v3/';


let orderId = "EXISTING_ORDER_ID"; // Replace this with the ID of an existing order


async function cancelOrder() {


try {


let timestamp = Date.now();


let stringToSign = apiKey + secretKey + timestamp.toString();


let signature = crypto.createHmac('sha256', secretKey).update(stringToSign).digest('hex');


const config = {


headers: {


'X-MBINANCE-APIKEY': apiKey,


'Content-Type': 'application/json',


'X-MBINANCE-SIGNATURE': signature,


'Timestamp': timestamp.toString()


}


};


const response = await axios.delete(baseUrl + "order/" + orderId, config);


console.log(response.data);


} catch (error) {


console.error(error);


}


}


cancelOrder();


```


This script calculates a signature and sends a DELETE request to `/api/v3/order/` with the ID of the order you wish to cancel.


Conclusion


The Binance API is powerful and versatile, offering a wide range of data and functionality for developers. Node.js provides an excellent platform for building these applications due to its asynchronous nature and vast ecosystem of third-party packages like Axios for handling HTTP requests. By following the examples outlined in this article, you should now have a solid understanding of how to interact with Binance's API using Node.js. Remember, it's crucial to follow best practices regarding security, such as not exposing your API key unnecessarily and keeping it confidential.

Recommended articles