{"id":13602211,"url":"https://github.com/binance/binance-connector-node","last_synced_at":"2025-03-22T19:01:37.261Z","repository":{"id":38351274,"uuid":"261664036","full_name":"binance/binance-connector-node","owner":"binance","description":"A simple connector to Binance Public API","archived":false,"fork":false,"pushed_at":"2025-02-21T08:48:41.000Z","size":1340,"stargazers_count":623,"open_issues_count":6,"forks_count":180,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-03-16T13:38:31.468Z","etag":null,"topics":["binance-api","connector","crypto","library","market-data","nodejs","real-time","trading"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/binance.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-05-06T05:49:08.000Z","updated_at":"2025-03-16T01:27:33.000Z","dependencies_parsed_at":"2024-06-10T08:47:05.687Z","dependency_job_id":"2d8f61ba-97bc-4f5c-bc22-a0aff42cd67e","html_url":"https://github.com/binance/binance-connector-node","commit_stats":{"total_commits":43,"total_committers":10,"mean_commits":4.3,"dds":0.6046511627906976,"last_synced_commit":"3da56843cd0d9fb508a69ce5d7e4372e55d83445"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-node","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-node/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-node/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binance%2Fbinance-connector-node/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/binance","download_url":"https://codeload.github.com/binance/binance-connector-node/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243920215,"owners_count":20369019,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["binance-api","connector","crypto","library","market-data","nodejs","real-time","trading"],"created_at":"2024-08-01T18:01:16.554Z","updated_at":"2025-03-22T19:01:37.152Z","avatar_url":"https://github.com/binance.png","language":"JavaScript","readme":"# Binance connector in Nodejs\n\n[![npm version](https://badge.fury.io/js/%40binance%2Fconnector.svg)](https://badge.fury.io/js/%40binance%2Fconnector)\n[![Node version](https://img.shields.io/node/v/%40binance%2Fconnector.svg?style=flat)](http://nodejs.org/download/)\n[![Standard-Js](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n\nThis is a lightweight library that works as a connector to [Binance public API](https://github.com/binance/binance-spot-api-docs). It’s designed to be simple, clean, and easy to use with minimal dependencies.\n\n- Supported APIs:\n    - `/api/*`\n    - `/sapi/*`\n    - Spot Websocket Market Stream\n    - Spot User Data Stream\n    - Spot Websocket API\n- Inclusion of test cases and examples\n- Customizable base URL\n- Support request timeout and HTTP proxy (since v2)\n- Response metadata can be displayed\n- Customizable Logger\n\n\n## Installation\n\n```bash\nnpm install @binance/connector\n```\n\n## Documentation\n\n[https://binance.github.io/binance-connector-node/](https://binance.github.io/binance-connector-node/)\n\n## RESTful APIs\n\n```javascript\nconst { Spot } = require('@binance/connector')\n\nconst apiKey = ''\nconst apiSecret = ''\nconst client = new Spot(apiKey, apiSecret)\n\n// Get account information\nclient.account().then(response =\u003e client.logger.log(response.data))\n\n// Place a new order\nclient.newOrder('BNBUSDT', 'BUY', 'LIMIT', {\n  price: '350',\n  quantity: 1,\n  timeInForce: 'GTC'\n}).then(response =\u003e client.logger.log(response.data))\n  .catch(error =\u003e client.logger.error(error))\n```\n\nPlease find `examples` folder to check for more endpoints.\n\n## Key Pair Based Authentication\n\n```javascript\nconst { Spot, PrivateKeyAlgo } = require('@binance/connector')\n\nconst apiKey = ''\nconst apiSecret = '' // has no effect when RSA private key is provided\n\n// load private key\nconst privateKey = fs.readFileSync('/Users/john/ssl/private_key_encrypted.pem')\nconst privateKeyPassphrase = 'password'\nconst privateKeyAlgo = PrivateKeyAlgo.RSA // for RSA key\nconst privateKeyAlgo = PrivateKeyAlgo.ED25519 // for Ed25519 key\n\nconst client = new Spot(apiKey, apiSecret, {\n  privateKey,\n  privateKeyPassphrase, // only used for encrypted key\n  privateKeyAlgo\n})\n\n// Get account information\nclient.account().then(response =\u003e client.logger.log(response.data))\n```\n\n### Testnet\n\nWhile `/sapi/*` endpoints don't have testnet environment yet, `/api/*` endpoints can be tested in\n[Spot Testnet](https://testnet.binance.vision/). You can use it by changing the base URL:\n\n```javascript\n// provide the testnet base url\nconst client = new Spot(apiKey, apiSecret, { baseURL: 'https://testnet.binance.vision'})\n```\n\n### Base URL\n\nIf `base_url` is not provided, it defaults to `api.binance.com`.\n\nIt's recommended to pass in the `base_url` parameter, even in production as Binance provides alternative URLs in case of performance issues:\n\n- `https://api1.binance.com`\n- `https://api2.binance.com`\n- `https://api3.binance.com`\n\n### Optional Parameters\n\nOptional parameters are encapsulated to a single object as the last function parameter.\n\n```javascript\nconst { Spot } = require('@binance/connector')\n\nconst apiKey = ''\nconst apiSecret = ''\nconst client = new Spot(apiKey, apiSecret)\n\nclient.account({ recvWindow: 2000 }).then(response =\u003e client.logger.log(response.data))\n```\n\n### Time Unit\n\nThe API supports different time units for timestamp values. By default, timestamp values are provided in milliseconds. You can specify the time unit in the request parameters:\n\n```javascript\nconst { Spot, TimeUnit } = require('@binance/connector')\n\nconst apiKey = ''\nconst apiSecret = ''\nconst client = new Spot(apiKey, apiSecret)\n\n// Using milliseconds (default)\nclient.exchangeInfo({ timeUnit: TimeUnit.MILLISECOND }).then(response =\u003e client.logger.log(response.data))\n\n// Using microseconds \nclient.exchangeInfo({ timeUnit: TimeUnit.MICROSECOND }).then(response =\u003e client.logger.log(response.data))\n```\n\n### Timeout\n\nIt's easy to set timeout in milliseconds in request. If the request take longer than timeout, the request will be aborted. If it's not set, there will be no timeout.\n\n```javascript\nconst { Spot } = require('@binance/connector')\n\nconst apiKey = ''\nconst apiSecret = ''\nconst client = new Spot(apiKey, apiSecret, { timeout: 1000 })\n\nclient.account()\n  .then(response =\u003e client.logger.log(response.data))\n  .catch(error =\u003e client.logger.error(error.message))\n```\n\n### Proxy\n\nThe `axios` package is used as the http client in this library. A proxy settings is passed into `axios` directly, the details can be found at [here](https://github.com/axios/axios#request-config):\n\n```javascript\nconst { Spot } = require('@binance/connector')\n\nconst apiKey = ''\nconst apiSecret = ''\nconst client = new Spot(apiKey, apiSecret,\n  {\n    proxy: {\n      protocol: 'https',\n      host: '127.0.0.1',\n      port: 9000,\n      auth: {\n        username: 'proxy_user',\n        password: 'password'\n      }\n    }\n  }\n)\n```\n\nYou may have a HTTP proxy, that can bring the problem that you need to make a HTTPS connection through the HTTP proxy.  You can do that by build a HTTPS-over-HTTP tunnel by npm package [tunnel](https://www.npmjs.com/package/tunnel), and then pass the turnnel agent to `httpsAgent` in `axios`.\n\n```javascript\nconst tunnel = require('tunnel')\n\nconst agent = tunnel.httpsOverHttp({\n  proxy: {\n    host: \"127.0.0.1\",\n    port: 3128\n  }\n})\n\nconst client = new Spot(null, null,\n  {\n    baseURL: \"https://api.binance.com\",\n    httpsAgent: agent\n  }\n)\n\nclient.time()\n  .then(response =\u003e client.logger.log(response.data))\n  .catch(error =\u003e client.logger.error(error))\n\n```\n[This comment](https://github.com/axios/axios/issues/925#issuecomment-359982190) provides more details.\n\n### Response Metadata\n\nThe Binance API server provides weight usages in the headers of each response. This information can be fetched from `headers` property. `x-mbx-used-weight` and `x-mbx-used-weight-1m` show the total weight consumed within 1 minute.\n\n```\n// client initialization is skipped\n\nclient.exchangeInfo().then(response =\u003e client.logger.log(response.headers['x-mbx-used-weight-1m']))\n\n```\n\n### Custom Logger Integration\n\n```javascript\nconst Spot = require('@binance/connector')\nconst fs = require('fs')\nconst { Console } = require('console')\n\n// make sure the logs/ folder is created beforehand\nconst output = fs.createWriteStream('./logs/stdout.log')\nconst errorOutput = fs.createWriteStream('./logs/stderr.log')\n\nconst logger = new Console({ stdout: output, stderr: errorOutput })\nconst client = new Spot('', '', {logger: logger})\n\nclient.exchangeInfo().then(response =\u003e client.logger.log(response.data))\n// check the output file\n\n```\n\nThe default logger defined in the package is [Node.js Console class](https://nodejs.org/api/console.html). Its output is sent to `process.stdout` and `process.stderr`, same as the global console.\n\n### Error\n\nThere are 2 types of error that may be returned from the API server and the user has to handle it properly:\n\n- `Client error`\n  - This is thrown when server returns `4XX`, it's an issue from client side.\n  - The following properties may be helpful to resolve the issue:\n    - Response header - Please refer to `Response Metadata` section for more details.\n    - HTTP status code\n    - Error code - Server's error code, e.g. `-1102`\n    - Error message - Server's error message, e.g. `Unknown order sent.`\n    - Request config - Configuration send to the server, which can include URL, request method and headers.\n\n  ```\n  // client initialization is skipped\n  client.exchangeInfo({ symbol: 'invalidSymbol' })\n    .then(response =\u003e client.logger.log(response.data))\n    .catch(err =\u003e {\n      client.logger.error(err.response.headers) // full response header\n      client.logger.error(err.response.status) // HTTP status code 400\n      client.logger.error(err.response.data) // includes both error code and message\n      client.logger.error(err.response.config) // includes request's config\n    })\n\n  ```\n\n- `Server error`\n  - This is thrown when server returns `5XX`, it's an issue from server side.\n\n\n## Websocket\n\n### Websocket Stream\n```javascript\nconst { WebsocketStream } = require('@binance/connector')\nconst logger = new Console({ stdout: process.stdout, stderr: process.stderr })\n\n// define callbacks for different events\nconst callbacks = {\n  open: () =\u003e logger.debug('Connected with Websocket server'),\n  close: () =\u003e logger.debug('Disconnected with Websocket server'),\n  message: data =\u003e logger.info(data)\n}\n\n// initialize websocket stream with microseconds as the preferred time unit\nconst websocketStreamClient = new WebsocketStream({ logger, callbacks, timeUnit: TimeUnit.MICROSECOND })\n// subscribe ticker stream\nwebsocketStreamClient.ticker('bnbusdt')\n// close websocket stream\nsetTimeout(() =\u003e websocketStreamClient.disconnect(), 6000)\n```\n\n### Unsubscribe Websocket Stream\n\n```javascript\n// unsubscribe websocket stream\nwebsocketStreamClient.unsubscribe('bnbusdt@kline_1m')\n```\n\n### WebSocket API\n\n```javascript\nconst { WebsocketAPI, TimeUnit } = require('@binance/connector')\nconst logger = new Console({ stdout: process.stdout, stderr: process.stderr })\n\n// callbacks for different events\nconst callbacks = {\n  open: (client) =\u003e {\n    logger.debug('Connected with Websocket server')\n    // send message to get orderbook info after connection open\n    client.orderbook('BTCUSDT')\n    client.orderbook('BNBUSDT', { limit: 10 })\n  },\n  close: () =\u003e logger.debug('Disconnected with Websocket server'),\n  message: data =\u003e logger.info(data)\n}\n\n// initialize WebsocketAPI client with microseconds as the preferred time unit\nconst websocketAPIClient = new WebsocketAPI(null, null, { logger, callbacks, timeUnit: TimeUnit.MICROSECOND })\n\n// disconnect the connection\nsetTimeout(() =\u003e websocketAPIClient.disconnect(), 20000)\n\n```\n\nMore websocket examples are available in the `examples` folder\n\n\n### Auto Reconnect\n\nIf there is a close event not initiated by the user, the reconnection mechanism will be triggered in 5 secs.\n\n### Ping Server\n\nIt is possible to ping server from client, and expect to receive a PONG message.\n\n```javascript\nwebsocketStreamClient.pingServer()\n```\n\n### Custom Logger Integration\n\nThe default logger defined in the package is [Node.js Console class](https://nodejs.org/api/console.html). Its output is sent to `process.stdout` and `process.stderr`, same as the global console.\n\nNote that when the connection is initialized, the console outputs a list of callbacks in the form of `listen to event: \u003cevent_name\u003e`.\n\n## Test\n\n```bash\nnpm install\n\nnpm run test\n\n```\n\n## Limitation\n\nFutures and Vanilla Options APIs are not supported:\n\n  - `/fapi/*`\n  - `/dapi/*`\n  - `/vapi/*`\n  -  Associated Websocket Market and User Data Streams\n\n## License\nMIT\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinance%2Fbinance-connector-node","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbinance%2Fbinance-connector-node","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinance%2Fbinance-connector-node/lists"}