# @binance/connector 中文文档

规范地址：https://npmcn.com/package/%40binance/connector/

版本：3\.6\.1
npm 元数据更新时间：2025-01-08T10:01:24.948Z
中文译文更新时间：2026-11-08T02:56:31.946Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40binance/connector
原文对照：https://npmcn.com/package/%40binance/connector/?lang=original
项目主页：https://github.com/binance/binance-connector-node#readme
源码仓库：https://github.com/binance/binance-connector-node

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：213 kB，42 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- Node.js 要求：\>=12\.22\.3
- 运行依赖：2 个
- 首次发布：2021-07-27T04:17:35.419Z
- 最新版本发布：2025-01-08T10:01:24.755Z
- 近 30 天下载量：31638（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：33（近 12 个月 0 个）

## 中文简介

这是一个轻量级的图书馆,作为比能斯公共API的连接器.

## 安装

```sh
npm install @binance/connector
```

也可以使用：`pnpm add @binance/connector`、`yarn add @binance/connector`、`bun add @binance/connector`

## README

# 节点连接符

[![npm version](https://badge.fury.io/js/%40binance%2Fconnector.svg)](https://badge.fury.io/js/%40binance%2Fconnector) [![Node version](https://img.shields.io/node/v/%40binance%2Fconnector.svg?style=flat)](http://nodejs.org/download/) [![Standard-Js](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

这是一个轻量级的库 ,作为连接器 [二进制公共 API](https://github.com/binance/binance-spot-api-docs)它设计得简单、干净、易于使用,而且依赖性极小.

-   支持的 API :
    -   `/api/*`
    -   `/sapi/*`
    -   Spot Websocket 市场流
    -   Spot 用户数据流
    -   点点 Websocket API
-   包括测试案例和实例
-   自定义基址
-   支持请求超时和 HTTP 代理( 自 v2)
-   可显示响应元数据
-   可自定义的 Logger

## 安装

```bash
npm install @binance/connector
```

## 文档

[https://binance.github.io/binance-connectionor-node/ 互联网档案馆的存檔,存档日期2014-12-21](https://binance.github.io/binance-connector-node/)

## 剩余 APIs

```javascript
const { Spot } = require('@binance/connector')

const apiKey = ''
const apiSecret = ''
const client = new Spot(apiKey, apiSecret)

// Get account information
client.account().then(response => client.logger.log(response.data))

// Place a new order
client.newOrder('BNBUSDT', 'BUY', 'LIMIT', {
  price: '350',
  quantity: 1,
  timeInForce: 'GTC'
}).then(response => client.logger.log(response.data))
  .catch(error => client.logger.error(error))
```

请找到 `examples` 要检查更多终点的文件夹.

## 基于密钥对等认证

```javascript
const { Spot, PrivateKeyAlgo } = require('@binance/connector')

const apiKey = ''
const apiSecret = '' // has no effect when RSA private key is provided

// load private key
const privateKey = fs.readFileSync('/Users/john/ssl/private_key_encrypted.pem')
const privateKeyPassphrase = 'password'
const privateKeyAlgo = PrivateKeyAlgo.RSA // for RSA key
const privateKeyAlgo = PrivateKeyAlgo.ED25519 // for Ed25519 key

const client = new Spot(apiKey, apiSecret, {
  privateKey,
  privateKeyPassphrase, // only used for encrypted key
  privateKeyAlgo
})

// Get account information
client.account().then(response => client.logger.log(response.data))
```

### 测试网

虽然 `/sapi/*` 端点还没有测试网环境, `/api/*` 结束点可以在 [点点测试网](https://testnet.binance.vision/)。您可以通过更改基址来使用它 :

```javascript
// provide the testnet base url
const client = new Spot(apiKey, apiSecret, { baseURL: 'https://testnet.binance.vision'})
```

### 基础 URL

若为 `base_url` 未提供,默认为 `api.binance.com`。 。 。 .

建议通过 `base_url` 参数,即使在生产中,因为Binance在出现性能问题时提供替代的URL:

-   `https://api1.binance.com`
-   `https://api2.binance.com`
-   `https://api3.binance.com`

### 可选参数

可选参数被封装到单个对象上,作为最后一个函数参数.

```javascript
const { Spot } = require('@binance/connector')

const apiKey = ''
const apiSecret = ''
const client = new Spot(apiKey, apiSecret)

client.account({ recvWindow: 2000 }).then(response => client.logger.log(response.data))
```

### 时间单位

API支持时间戳值的不同时间单位. 默认情况下,时间戳值以毫秒提供. 您可以在请求参数中指定时间单位 :

```javascript
const { Spot, TimeUnit } = require('@binance/connector')

const apiKey = ''
const apiSecret = ''
const client = new Spot(apiKey, apiSecret)

// Using milliseconds (default)
client.exchangeInfo({ timeUnit: TimeUnit.MILLISECOND }).then(response => client.logger.log(response.data))

// Using microseconds 
client.exchangeInfo({ timeUnit: TimeUnit.MICROSECOND }).then(response => client.logger.log(response.data))
```

### 超时

在请求中以毫秒的速度设置超时是很容易的. 如果请求需要超过超时,则请求将被中止. 如未定出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出入出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出出.

```javascript
const { Spot } = require('@binance/connector')

const apiKey = ''
const apiSecret = ''
const client = new Spot(apiKey, apiSecret, { timeout: 1000 })

client.account()
  .then(response => client.logger.log(response.data))
  .catch(error => client.logger.error(error.message))
```

### 代理服务器

这个 `axios` 软件包被用作此库中的 http 客户端 。 一个代理设置被传递到 `axios` 详情可在 [这里](https://github.com/axios/axios#request-config)数字 :

```javascript
const { Spot } = require('@binance/connector')

const apiKey = ''
const apiSecret = ''
const client = new Spot(apiKey, apiSecret,
  {
    proxy: {
      protocol: 'https',
      host: '127.0.0.1',
      port: 9000,
      auth: {
        username: 'proxy_user',
        password: 'password'
      }
    }
  }
)
```

您可能拥有一个 HTTP 代理, 它可以带来您需要通过 HTTP 代理实现 HTTP 连接的问题 。 您可以通过 npm 包建造 HTTPS- over- HTTP 隧道来做到这一点 [隧道](https://www.npmjs.com/package/tunnel),然后将转子代理传递给 `httpsAgent` 内 `axios`。 。 。 .

```javascript
const tunnel = require('tunnel')

const agent = tunnel.httpsOverHttp({
  proxy: {
    host: "127.0.0.1",
    port: 3128
  }
})

const client = new Spot(null, null,
  {
    baseURL: "https://api.binance.com",
    httpsAgent: agent
  }
)

client.time()
  .then(response => client.logger.log(response.data))
  .catch(error => client.logger.error(error))

```

[本评论](https://github.com/axios/axios/issues/925#issuecomment-359982190) 提供更详细的情况.

### 响应元数据

Binance API 服务器在每个响应头提供重用. 此信息可以从 `headers` 属性. `x-mbx-used-weight` 财务报告和审定财务报表 `x-mbx-used-weight-1m` 显示1分钟内消耗的总重量.

```
// client initialization is skipped

client.exchangeInfo().then(response => client.logger.log(response.headers['x-mbx-used-weight-1m']))

```

### 自定义 Logger 集成

```javascript
const Spot = require('@binance/connector')
const fs = require('fs')
const { Console } = require('console')

// make sure the logs/ folder is created beforehand
const output = fs.createWriteStream('./logs/stdout.log')
const errorOutput = fs.createWriteStream('./logs/stderr.log')

const logger = new Console({ stdout: output, stderr: errorOutput })
const client = new Spot('', '', {logger: logger})

client.exchangeInfo().then(response => client.logger.log(response.data))
// check the output file

```

软件包中定义的默认日志是 [节点控制台类](https://nodejs.org/api/console.html)。其输出发送给 `process.stdout` 财务报告和审定财务报表 `process.stderr`,与全球控制台相同.

### 错误

API服务器可能还原出两种出错类型,用户必须妥善处理:

-   `Client error`
    
    -   当服务器返回时, 将丢弃此选项 `4XX`这是客户端的问题.
    -   下列财产可能有助于解决问题:
        -   回复信头 - 请参见 `Response Metadata` 详细情况.
        -   HTTP 状态代码
        -   错误代码 - 服务器错误代码, 例如 . `-1102`
        -   错误消息 - 服务器的错误消息, 例如 . `Unknown order sent.`
        -   请求配置 - 配置发送到服务器,可以包括URL,请求方法和信头.
    
    ```
    // client initialization is skipped
    client.exchangeInfo({ symbol: 'invalidSymbol' })
      .then(response => client.logger.log(response.data))
      .catch(err => {
        client.logger.error(err.response.headers) // full response header
        client.logger.error(err.response.status) // HTTP status code 400
        client.logger.error(err.response.data) // includes both error code and message
        client.logger.error(err.response.config) // includes request's config
      })
    
    ```
    
-   `Server error`
    
    -   当服务器返回时, 将丢弃此选项 `5XX`服务器那边的问题.

## 网页

### 网页串流

```javascript
const { WebsocketStream } = require('@binance/connector')
const logger = new Console({ stdout: process.stdout, stderr: process.stderr })

// define callbacks for different events
const callbacks = {
  open: () => logger.debug('Connected with Websocket server'),
  close: () => logger.debug('Disconnected with Websocket server'),
  message: data => logger.info(data)
}

// initialize websocket stream with microseconds as the preferred time unit
const websocketStreamClient = new WebsocketStream({ logger, callbacks, timeUnit: TimeUnit.MICROSECOND })
// subscribe ticker stream
websocketStreamClient.ticker('bnbusdt')
// close websocket stream
setTimeout(() => websocketStreamClient.disconnect(), 6000)
```

### 取消订阅 Websocket 流

```javascript
// unsubscribe websocket stream
websocketStreamClient.unsubscribe('bnbusdt@kline_1m')
```

### WebSocket API 服务器

```javascript
const { WebsocketAPI, TimeUnit } = require('@binance/connector')
const logger = new Console({ stdout: process.stdout, stderr: process.stderr })

// callbacks for different events
const callbacks = {
  open: (client) => {
    logger.debug('Connected with Websocket server')
    // send message to get orderbook info after connection open
    client.orderbook('BTCUSDT')
    client.orderbook('BNBUSDT', { limit: 10 })
  },
  close: () => logger.debug('Disconnected with Websocket server'),
  message: data => logger.info(data)
}

// initialize WebsocketAPI client with microseconds as the preferred time unit
const websocketAPIClient = new WebsocketAPI(null, null, { logger, callbacks, timeUnit: TimeUnit.MICROSECOND })

// disconnect the connection
setTimeout(() => websocketAPIClient.disconnect(), 20000)

```

网页上有更多的网页实例 `examples` 文件夹

### 自动重接

如果有用户未启动的相近事件,则重联机制将在5秒后被触发.

### Ping 服务器

可以从客户端调取服务器, 并期望收到 PONG 消息 .

```javascript
websocketStreamClient.pingServer()
```

### 自定义 Logger 集成

软件包中定义的默认日志是 [节点控制台类](https://nodejs.org/api/console.html)。其输出发送给 `process.stdout` 财务报告和审定财务报表 `process.stderr`,与全球控制台相同.

请注意,当连接被初始化时,控制台会以下列形式输出一个召回列表: `listen to event: <event_name>`。 。 。 .

## 测试

```bash
npm install

npm run test

```

## 限制

未来和香草选项 API 不支持:

-   `/fapi/*`
-   `/dapi/*`
-   `/vapi/*`
-   相关 Websocket 市场和用户数据流

## 许可证

麻省理工学院

## 常见问题

### @binance/connector 是什么？

这是一个轻量级的图书馆,作为比能斯公共API的连接器\.

### 如何安装 @binance/connector？

在项目目录运行 npm install @binance/connector，或使用 pnpm add / yarn add / bun add。

### @binance/connector 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/binance\_\_connector 是否存在。

### @binance/connector 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @binance/connector 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=12\.22\.3。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @binance/connector 可以商用吗？

@binance/connector 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @binance/connector 的下载量有多少？

根据 npm 官方下载统计，@binance/connector 在 2026/10/08 – 2026/11/06 这 30 天内被下载 31,638 次，日均约 1,055 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @binance/connector 还在维护吗？

最新版本 3\.6\.1 发布于 2025/01/08（1\.8 年前）；至今共发布 33 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/07/27。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

