# Binance US Client (WIP)

[![TypeScript](https://img.shields.io/badge/Code-TypeScript-blue.svg)](https://www.typescriptlang.org/)
[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://choosealicense.com/licenses/isc/)
[![Node Version](https://img.shields.io/badge/Node->=8-blue.svg)](https://nodejs.org)

[![pipeline status](https://gitlab.com/cluttered-code/open-source/binance-us/badges/master/pipeline.svg)](https://gitlab.com/cluttered-code/open-source/binance-us/commits/master)
[![coverage report](https://gitlab.com/cluttered-code/open-source/binance-us/badges/master/coverage.svg)](https://gitlab.com/cluttered-code/open-source/binance-us/commits/master)
[![codecov](https://codecov.io/gl/cluttered-code:open-source/binance-us/branch/master/graph/badge.svg)](https://codecov.io/gl/cluttered-code:open-source/binance-us)

[![NPM](https://nodei.co/npm/binance-us.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/binance-us/)

## Install

```bash
# NPM
npm i binance-us

# Yarn
yarn add binance-us
```

## Getting Started

### Importing

#### modules
```js
import { BinanceClient, PublicBinanceClient } from 'bianace-us'

// Authenticated
const key = 'xV7WDC9IbREgZ...'
const secret = 'KvBlbigseoZcv...'
const client = new BinanceClient({ key, secret })

// Public
const client = new PublicBinanceClient()
```

#### commonjs
```js
const BinanceUS = require('binance-us')

// Authenticated
const key = 'xV7WDC9IbREgZ...'
const secret = 'KvBlbigseoZcv...'
const client = BinanceUS({ key, secret })


// Public
const client = BinanceUS()
```

### Usage

#### async/await

```js
const response = await client.time()
console.log(response)
```

#### callback

```js
client.time().then(response => console.log(response))
```

## Table of Contents

- Public REST Endpoints
  - General
    - [ping](#ping)
    - [time](#time)
    - [exchange information](#exchangeinfo)
  - Market Data
    - [order book](#book)
    - [recent trades](#trades)
    - [compressed/aggregate trades](#aggtrades)
    - [candlesticks/klines](#candles)
    - [average price](#avgprice)
    - [24hr ticker](#ticker24hour)
    - [price ticker](#tickerprice)
    - [order book ticker](#tickerbook)
- Protected REST Endpoints
  - Market Data
    - [historical trades](#historicaltrades)
  - Order
    - new order
    - test new order
    - lookup order
    - cancel order
    - open orders
    - all orders
  - OCO
    - new OCO
    - cancel OCO
    - lookup OCO
    - all OCOs
    - open OCOs
  - Account
    - account information
    - account trades
- WebSocket...

## ping

Test connectivity to the API.

**Weight:** 1

```js
console.log(await client.ping())
```

<details>
<summary><b>Response</b></summary>

```js
{}
```

</details>

## time

Current server time.

**Weight:** 1

```js
console.log(await client.time())
```

<details>
<summary><b>Response</b></summary>

```js
{
  serverTime: 1578369719229
}
```

</details>

## exchangeInfo

Current exchange trading rules and symbol information.

**Weight:** 1

```js
console.log(await client.exchangeInfo())
```

<details>
<summary><b>Response</b></summary>

```js
{
  timezone: "UTC",
  serverTime: 1578375682742,
  rateLimits: [
    {
      rateLimitType: "REQUEST_WEIGHT",
      interval: "MINUTE",
      intervalNum: 1,
      limit: 1200
    },
    {
      rateLimitType: "ORDERS",
      interval: "SECOND",
      intervalNum: 10,
      limit: 100
    },
    {
      rateLimitType: "ORDERS",
      interval: "DAY",
      intervalNum: 1,
      limit: 200000
    }
  ],
  exchangeFilters: [],
  symbols: [
    {
      symbol: "BTCUSD",
      status: "TRADING",
      baseAsset: "BTC",
      baseAssetPrecision: 8,
      quoteAsset: "USD",
      quotePrecision: 4,
      baseCommissionPrecision: 8,
      quoteCommissionPrecision: 2,
      orderTypes: ["LIMIT", "LIMIT_MAKER", "MARKET", "STOP_LOSS_LIMIT", "TAKE_PROFIT_LIMIT"],
      icebergAllowed: true,
      ocoAllowed: true,
      isSpotTradingAllowed: true,
      isMarginTradingAllowed: false,
      filters: [
        {
          filterType: "PRICE_FILTER",
          minPrice: "0.0100",
          maxPrice: "100000.0000",
          tickSize: "0.0100"
        },
        {
          filterType: "PERCENT_PRICE",
          multiplierUp: "5",
          multiplierDown: "0.2",
          avgPriceMins: 5
        },
        {
          filterType: "LOT_SIZE",
          minQty: "0.00000100",
          maxQty: "9000.00000000",
          stepSize: "0.00000100"
        }
      ]
    }
  ]
}
```

</details>

## book

Order book.

**Weight:**

| Limit          | Weight |
| -------------- | :----: |
| 5,10,20,50,100 |   1    |
| 500            |   5    |
| 1000           |   10   |
| 5000           |   50   |

**Parameters**

| Name   | Type   | Mandatory | Default | Description                          |
| ------ | ------ | :-------: | :-----: | ------------------------------------ |
| symbol | string |    YES    |   N/A   |                                      |
| limit  | number |    NO     |   100   | valid:[5,10,20,50,100,500,1000,5000] |

```js
const symbol = 'BTCUSD'
const limit = 500

console.log(await client.book({ symbol }))
console.log(await client.book({ symbol, limit }))
```

<details>
<summary><b>Response</b></summary>

```js
{
  lastUpdateId: 1027024,
  bids: [
    {
      price: "4.00000000",
      quantity: "431.00000000"
    }
  ],
  asks: [
    {
      price: "4.00000200",
      quantity: "12.00000000"
    }
  ]
}
```

</details>

## trades

Recent trades.

**Weight:** 1

**Parameters**

| Name   | Type   | Mandatory | Default | Description |
| ------ | ------ | :-------: | :-----: | ----------- |
| symbol | string |    YES    |   N/A   |             |
| limit  | number |    NO     |   500   | max: 1000   |

```js
const symbol = 'BTCUSD'
const limit = 850

console.log(await client.trades({ symbol }))
console.log(await client.trades({ symbol, limit }))
```

<details>
<summary><b>Response</b></summary>

```js
;[
  {
    id: 28457,
    price: '4.00000100',
    quantity: '12.00000000',
    quoteQuantity: '48.000012',
    time: 1499865549590,
    isBuyerMaker: true,
    isBestMatch: true
  }
]
```

</details>

## aggTrades

Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.

**Weight:** 1

**Parameters**

| Name      | Type   | Mandatory | Default | Description                                             |
| --------- | ------ | :-------: | :-----: | ------------------------------------------------------- |
| symbol    | string |    YES    |   N/A   |                                                         |
| limit     | number |    NO     |   500   | max: 1000                                               |
| fromId    | number |    NO     |   N/A   | ID to get aggregate trades from INCLUSIVE               |
| startTime | number |    NO     |   N/A   | Timestamp in ms to get aggregate trades from INCLUSIVE  |
| endTime   | number |    NO     |   N/A   | Timestamp in ms to get aggregate trades until INCLUSIVE |

- If both `startTime` and `endTime` are sent, time between `startTime` and `endTime` must be less than 1 hour.
- If `fromId`, `startTime`, and `endTime` are not sent, the most recent aggregate trades will be returned.

```js
const symbol = 'BTCUSD'
const limit = 625

console.log(await client.aggTrades({ symbol }))
console.log(await client.aggTrades({ symbol, limit }))
```

<details>
<summary><b>Response</b></summary>

```js
;[
  {
    id: 26129,
    price: '0.01633102',
    quantity: '4.70443515',
    firstId: 27781,
    lastId: 27781,
    time: 1498793709153,
    isBuyerMaker: true,
    isBestMatch: true
  }
]
```

</details>

## candles

Kline/candlestick bars for a symbol. Candlesticks are uniquely identified by their open time.

**Weight:** 1

**Parameters**

| Name      | Type   | Mandatory | Default | Description                                     |
| --------- | ------ | :-------: | :-----: | ----------------------------------------------- |
| symbol    | string |    YES    |   N/A   |                                                 |
| interval  | enum   |    YES    |   N/A   | 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M |
| startTime | number |    NO     |   N/A   |                                                 |
| endTime   | number |    NO     |   N/A   |                                                 |
| limit     | number |    NO     |   500   | max: 1000                                       |

- If `startTime` and `endTime` are not sent, the most recent candlesticks are returned.

```js
import { CandlestickInterval } from 'binance-us'

const symbol = 'BTCUSD'
const interval = CandlestickInterval.FIFTEEN_MINUTES
const limit = 920

console.log(await client.candles({ symbol, interval }))
console.log(await client.candles({ symbol, interval, limit }))
```

<details>
<summary><b>Response</b></summary>

```js
;[
  {
    openTime: 1499040000000,
    open: '0.01634790',
    high: '0.80000000',
    low: '0.01575800',
    close: '0.01577100',
    volume: '148976.11427815',
    closeTime: 1499644799999,
    quoteVolume: '2434.19055334',
    trades: 308,
    takerBuyVolume: '1756.87402397',
    tackerBuyQuoteVolume: '28.46694368'
  }
]
```

</details>

## avgPrice

Current average price for a symbol.

**Weight:** 1

**Parameters**

| Name   | Type   | Mandatory | Default | Description |
| ------ | ------ | :-------: | :-----: | ----------- |
| symbol | string |    YES    |   N/A   |             |

```js
const symbol = 'BTCUSD'

console.log(await client.avgPrice({ symbol }))
```

<details>
<summary><b>Response</b></summary>

```js
{
  minutes: 5,
  price: "9.35751834"
}
```

</details>

## ticker24Hour

24 hour rolling window price change statistics. **Careful** when accessing this with no symbol.

**Weight:** 1 for a single symbol; **40** when the symbol parameter is omitted

**Parameters**

| Name   | Type   | Mandatory | Default | Description |
| ------ | ------ | :-------: | :-----: | ----------- |
| symbol | string |    NO     |   N/A   |             |

```js
const symbol = 'BTCUSD'

console.log(await client.ticker24Hour()) // weight: 40
console.log(await client.ticker24Hour({ symbol })) // weight: 1
```

<details>
<summary><b>Response</b></summary>

```js
;[
  {
    symbol: 'BNBBTC',
    priceChange: '-94.99999800',
    priceChangePercent: '-95.960',
    weightedAvgPrice: '0.29628482',
    prevClosePrice: '0.10002000',
    lastPrice: '4.00000200',
    lastQuantity: '200.00000000',
    bidPrice: '4.00000000',
    askPrice: '4.00000200',
    openPrice: '99.00000000',
    highPrice: '100.00000000',
    lowPrice: '0.10000000',
    volume: '8913.30000000',
    quoteVolume: '15.30000000',
    openTime: 1499783499040,
    closeTime: 1499869899040,
    firstId: 28385,
    lastId: 28460,
    trades: 76
  }
]
```

</details>

## tickerPrice

Latest price for a symbol or symbols.

**Weight:** 1 for a single symbol; **2** when the symbol parameter is omitted

**Parameters**

| Name   | Type   | Mandatory | Default | Description |
| ------ | ------ | :-------: | :-----: | ----------- |
| symbol | string |    NO     |   N/A   |             |

```js
const symbol = 'BTCUSD'

console.log(await client.tickerPrice()) // weight: 2
console.log(await client.tickerPrice({ symbol })) // weight: 1
```

<details>
<summary><b>Response</b></summary>

```js
;[
  {
    symbol: 'LTCBTC',
    price: '4.00000200'
  }
]
```

</details>

## tickerBook

Best price/quantity on the order book for a symbol or symbols.

**Weight:** 1 for a single symbol; **2** when the symbol parameter is omitted

**Parameters**

| Name   | Type   | Mandatory | Default | Description |
| ------ | ------ | :-------: | :-----: | ----------- |
| symbol | string |    NO     |   N/A   |             |

```js
const symbol = 'BTCUSD'

console.log(await client.tickerBook()) // weight: 2
console.log(await client.tickerBook({ symbol })) // weight: 1
```

<details>
<summary><b>Response</b></summary>

```js
;[
  {
    symbol: 'LTCBTC',
    bidPrice: '4.00000000',
    bidQuantity: '431.00000000',
    askPrice: '4.00000200',
    askQuantity: '9.00000000'
  }
]
```

</details>

## historicalTrades

Get older trades.

**Key Required**

**Weight:** 5

**Parameters**

| Name   | Type   | Mandatory | Default | Description                                             |
| ------ | ------ | :-------: | :-----: | ------------------------------------------------------- |
| symbol | string |    NO     |   N/A   |                                                         |
| limit  | number |    NO     |   500   | max: 1000                                               |
| fromId | number |    NO     |   N/A   | TradeId to fetch from. Default gets most recent trades. |

```js
const symbol = 'BTCUSD'
const limit = 100

console.log(await client.historicalTrades({ symbol }))
console.log(await client.historicalTrades({ symbol, limit }))
```

<details>
<summary><b>Response</b></summary>

```js
[
  {
    id: 28457,
    price: '4.00000100',
    quantity: '12.00000000',
    quoteQuantity: '48.000012',
    time: 1499865549590,
    isBuyerMaker: true,
    isBestMatch: true
  }
]
```

</details>

## License

This project is licensed under the ISC License - see the [LICENSE](https://gitlab.com/cluttered-code/open-source/binance-us/blob/master/LICENSE) file for details
