Node Binance API with TypeScript: A Deep Dive
In the world of cryptocurrency, APIs play a crucial role in enabling seamless interaction between developers and blockchain platforms such as Binance. This article explores how to set up an API application using the Binance Futures API with Node.js and TypeScript. We'll cover setting up the environment, connecting to the API, handling authentication, making requests, and processing responses.
Introduction
Binance is a global cryptocurrency exchange that has become one of the leading platforms in terms of trading volume and innovation. Binance's API platform offers extensive functionalities for both personal users and developers. The Binance Futures API allows developers to build applications around futures trading, including real-time order book data, trades history, and position management.
TypeScript is a superset of JavaScript that adds static typing capabilities, which helps catch errors before the code is run. It also offers better tooling for IDEs like Visual Studio Code, improving developer productivity and enabling safer development practices.
Setting Up the Environment
To get started, you'll need Node.js version 14 or above installed on your system. TypeScript can be installed globally by running `npm install -g typescript` in your terminal. To set up a new project, create a directory for your application and run `tsc --init` to generate a tsconfig.json file with default settings suitable for most projects.
Add the following packages to your package.json:
```json
{
"scripts": {
"start": "ts-node src/index.ts",
"build": "tsc",
"watch": "tsc --watch"
},
"dependencies": {
"@types/node": "^14.0.8"
}
}
```
This ensures that TypeScript compiles your code as Node.js modules.
Connecting to the Binance API
Binance requires authentication for all API requests. You need to sign up on the Binance website, navigate to "API/Premium," and generate a key pair. The public key is used for market data APIs like `GET /api/v3/ticker` and `GET /fapi/v1/ticker`, while the private key allows you to interact with trading-related endpoints.
Authentication in TypeScript
First, import the required modules:
```typescript
import * as fs from 'fs';
import { Socket } from 'net';
```
Next, load your API keys from a configuration file:
```typescript
const privateKey = fs.readFileSync('private_key.txt', 'utf8').trim();
const publicKey = fs.readFileSync('public_key.txt', 'utf8').trim();
```
Then, create an instance of the Binance WebSocket client:
```typescript
const ws = new Socket({
server: 'wss://fapi.binance.com/ws',
});
```
To authenticate with the API, use the `API Key Signature` method provided by Binance. This involves signing a SHA256 hash of the concatenation of your timestamp (current time in seconds), private key, and client ID:
```typescript
function getSignature(timestamp: number): string {
const message = `${timestamp}${process.env.BINANCE_CLIENT_ID}${privateKey}`;
const hash = crypto.createHash('sha256');
hash.update(message);
return hash.digest('hex');
}
```
With the signature, you can build your API request:
```typescript
const timestamp = Math.floor(Date.now() / 1000);
ws.write(`SIGNED ${getSignature(timestamp)}\n`);
ws.write(`api=fapi&method=ping×tamp=${timestamp}\n`);
```
Making Requests
To make a request to the Binance API, you can use the built-in `http` module or third-party libraries like `axios` for convenience:
```typescript
const axios = require('axios');
async function fetchTicker(symbol: string) {
try {
const response = await axios.get(`https://fapi.binance.com/fapi/v1/ticker/price?symbol=${symbol}`, {
headers: { 'X-MBX-APIKEY': publicKey },
});
console.log(response.data);
} catch (error) {
if (axios.isAxiosError(error)) {
switch (error.code) {
case 401:
console.error('Authentication error');
break;
default:
console.error('An unexpected error occurred', error);
}
} else {
console.error('An unknown error occurred', error);
}
}
}
```
Processing Responses
Binance API responses are JSON objects that can be parsed easily in TypeScript:
```typescript
interface BinanceTicker {
symbol: string;
price: number;
time_last_update_ms: number;
last_update_tick_count: number;
bidPrice: number;
bidQty: number;
askPrice: number;
askQty: number;
openPrice: number;
volume: number;
closePrice: number;
accumulatedSwapAmount: number;
priceChange: number;
priceChangePercentage: number;
baseAssetVolume: number;
numberOfTrades: number;
takerBaseAssetVol: number;
takerQuoteAssetVol: number;
}
```
This allows you to access specific fields of the response without risking runtime errors.
Conclusion
Building applications with the Binance Futures API and TypeScript provides a secure, efficient, and type-safe development experience. With this setup, developers can leverage the full range of Binance's functionalities for their projects, from simple market data queries to sophisticated trading algorithms. As cryptocurrency technology continues to evolve, integrating with platforms like Binance is crucial for innovation in the space.