Binance API

client module

class binance.client.Client(api_key, api_secret, requests_params=None)[ソース]

ベースクラス: object

API_URL = 'https://api.binance.com/api'
KLINE_INTERVAL_12HOUR = '12h'
KLINE_INTERVAL_15MINUTE = '15m'
KLINE_INTERVAL_1DAY = '1d'
KLINE_INTERVAL_1HOUR = '1h'
KLINE_INTERVAL_1MINUTE = '1m'
KLINE_INTERVAL_1MONTH = '1M'
KLINE_INTERVAL_1WEEK = '1w'
KLINE_INTERVAL_2HOUR = '2h'
KLINE_INTERVAL_30MINUTE = '30m'
KLINE_INTERVAL_3DAY = '3d'
KLINE_INTERVAL_3MINUTE = '3m'
KLINE_INTERVAL_4HOUR = '4h'
KLINE_INTERVAL_5MINUTE = '5m'
KLINE_INTERVAL_6HOUR = '6h'
KLINE_INTERVAL_8HOUR = '8h'
ORDER_RESP_TYPE_ACK = 'ACK'
ORDER_RESP_TYPE_FULL = 'FULL'
ORDER_RESP_TYPE_RESULT = 'RESULT'
ORDER_STATUS_CANCELED = 'CANCELED'
ORDER_STATUS_EXPIRED = 'EXPIRED'
ORDER_STATUS_FILLED = 'FILLED'
ORDER_STATUS_NEW = 'NEW'
ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED'
ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL'
ORDER_STATUS_REJECTED = 'REJECTED'
ORDER_TYPE_LIMIT = 'LIMIT'
ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER'
ORDER_TYPE_MARKET = 'MARKET'
ORDER_TYPE_STOP_LOSS = 'STOP_LOSS'
ORDER_TYPE_STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT'
ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT'
ORDER_TYPE_TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT'
PRIVATE_API_VERSION = 'v3'
PUBLIC_API_VERSION = 'v1'
SIDE_BUY = 'BUY'
SIDE_SELL = 'SELL'
SYMBOL_TYPE_SPOT = 'SPOT'
TIME_IN_FORCE_FOK = 'FOK'
TIME_IN_FORCE_GTC = 'GTC'
TIME_IN_FORCE_IOC = 'IOC'
WEBSITE_URL = 'https://www.binance.com'
WITHDRAW_API_URL = 'https://api.binance.com/wapi'
WITHDRAW_API_VERSION = 'v3'
__init__(api_key, api_secret, requests_params=None)[ソース]

Binance API Client constructor

パラメータ:
  • api_key (str.) – Api Key
  • api_secret (str.) – Api Secret
  • requests_params (dict.) – optional - Dictionary of requests params to use for all calls
cancel_order(**params)[ソース]

Cancel an active order. Either orderId or origClientOrderId must be sent.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#cancel-order-trade

パラメータ:
  • symbol (str) – required
  • orderId (int) – The unique order id
  • origClientOrderId (str) – optional
  • newClientOrderId (str) – Used to uniquely identify this cancel. Automatically generated by default.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

{
    "symbol": "LTCBTC",
    "origClientOrderId": "myOrder1",
    "orderId": 1,
    "clientOrderId": "cancelMyOrder1"
}
Raises:BinanceResponseException, BinanceAPIException
create_order(**params)[ソース]

Send in a new order

Any order with an icebergQty MUST have timeInForce set to GTC.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#new-order–trade

パラメータ:
  • symbol (str) – required
  • side (enum) – required
  • type (enum) – required
  • timeInForce (enum) – required if limit order
  • quantity (decimal) – required
  • price (str) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • icebergQty (decimal) – Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
  • newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

Response ACK:

{
    "symbol":"LTCBTC",
    "orderId": 1,
    "clientOrderId": "myOrder1" # Will be newClientOrderId
    "transactTime": 1499827319559
}

Response RESULT:

{
    "symbol": "BTCUSDT",
    "orderId": 28,
    "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
    "transactTime": 1507725176595,
    "price": "0.00000000",
    "origQty": "10.00000000",
    "executedQty": "10.00000000",
    "status": "FILLED",
    "timeInForce": "GTC",
    "type": "MARKET",
    "side": "SELL"
}

Response FULL:

{
    "symbol": "BTCUSDT",
    "orderId": 28,
    "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP",
    "transactTime": 1507725176595,
    "price": "0.00000000",
    "origQty": "10.00000000",
    "executedQty": "10.00000000",
    "status": "FILLED",
    "timeInForce": "GTC",
    "type": "MARKET",
    "side": "SELL",
    "fills": [
        {
            "price": "4000.00000000",
            "qty": "1.00000000",
            "commission": "4.00000000",
            "commissionAsset": "USDT"
        },
        {
            "price": "3999.00000000",
            "qty": "5.00000000",
            "commission": "19.99500000",
            "commissionAsset": "USDT"
        },
        {
            "price": "3998.00000000",
            "qty": "2.00000000",
            "commission": "7.99600000",
            "commissionAsset": "USDT"
        },
        {
            "price": "3997.00000000",
            "qty": "1.00000000",
            "commission": "3.99700000",
            "commissionAsset": "USDT"
        },
        {
            "price": "3995.00000000",
            "qty": "1.00000000",
            "commission": "3.99500000",
            "commissionAsset": "USDT"
        }
    ]
}
Raises:BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
create_test_order(**params)[ソース]

Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#test-new-order-trade

パラメータ:
  • symbol (str) – required
  • side (enum) – required
  • type (enum) – required
  • timeInForce (enum) – required if limit order
  • quantity (decimal) – required
  • price (str) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • icebergQty (decimal) – Used with iceberg orders
  • newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – The number of milliseconds the request is valid for
戻り値:

API response

{}
Raises:BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
get_account(**params)[ソース]

Get current account information.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data

パラメータ:recvWindow (int) – the number of milliseconds the request is valid for
戻り値:API response
{
    "makerCommission": 15,
    "takerCommission": 15,
    "buyerCommission": 0,
    "sellerCommission": 0,
    "canTrade": true,
    "canWithdraw": true,
    "canDeposit": true,
    "balances": [
        {
            "asset": "BTC",
            "free": "4723846.89208129",
            "locked": "0.00000000"
        },
        {
            "asset": "LTC",
            "free": "4763368.68006011",
            "locked": "0.00000000"
        }
    ]
}
Raises:BinanceResponseException, BinanceAPIException
get_account_status(**params)[ソース]

Get account status detail.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#account-status-user_data

パラメータ:recvWindow (int) – the number of milliseconds the request is valid for
戻り値:API response
{
    "msg": "Order failed:Low Order fill rate! Will be reactivated after 5 minutes.",
    "success": true,
    "objs": [
        "5"
    ]
}
Raises:BinanceWithdrawException
get_aggregate_trades(**params)[ソース]

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

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list

パラメータ:
  • symbol (str) – required
  • fromId (str) – ID to get aggregate trades from INCLUSIVE.
  • startTime (int) – Timestamp in ms to get aggregate trades from INCLUSIVE.
  • endTime (int) – Timestamp in ms to get aggregate trades until INCLUSIVE.
  • limit (int) – Default 500; max 500.
戻り値:

API response

[
    {
        "a": 26129,         # Aggregate tradeId
        "p": "0.01633102",  # Price
        "q": "4.70443515",  # Quantity
        "f": 27781,         # First tradeId
        "l": 27781,         # Last tradeId
        "T": 1498793709153, # Timestamp
        "m": true,          # Was the buyer the maker?
        "M": true           # Was the trade the best price match?
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_all_orders(**params)[ソース]

Get all account orders; active, canceled, or filled.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#all-orders-user_data

パラメータ:
  • symbol (str) – required
  • orderId (int) – The unique order id
  • limit (int) – Default 500; max 500.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

[
    {
        "symbol": "LTCBTC",
        "orderId": 1,
        "clientOrderId": "myOrder1",
        "price": "0.1",
        "origQty": "1.0",
        "executedQty": "0.0",
        "status": "NEW",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "BUY",
        "stopPrice": "0.0",
        "icebergQty": "0.0",
        "time": 1499827319559
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_all_tickers()[ソース]

Latest price for all symbols.

https://www.binance.com/restapipub.html#symbols-price-ticker

戻り値:List of market tickers
[
    {
        "symbol": "LTCBTC",
        "price": "4.00000200"
    },
    {
        "symbol": "ETHBTC",
        "price": "0.07946600"
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_asset_balance(asset, **params)[ソース]

Get current asset balance.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data

パラメータ:
  • asset (str) – required
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

dictionary or None if not found

{
    "asset": "BTC",
    "free": "4723846.89208129",
    "locked": "0.00000000"
}
Raises:BinanceResponseException, BinanceAPIException
get_deposit_address(**params)[ソース]

Fetch a deposit address for a symbol

https://www.binance.com/restapipub.html

パラメータ:
  • asset (str) – required
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

{
    "address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
    "success": true,
    "addressTag": "1231212",
    "asset": "BNB"
}
Raises:BinanceResponseException, BinanceAPIException
get_deposit_history(**params)[ソース]

Fetch deposit history.

https://www.binance.com/restapipub.html

パラメータ:
  • asset (str) – optional
  • startTime (long) – optional
  • endTime (long) – optional
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

{
    "depositList": [
        {
            "insertTime": 1508198532000,
            "amount": 0.04670582,
            "asset": "ETH",
            "status": 1
        }
    ],
    "success": true
}
Raises:BinanceResponseException, BinanceAPIException
get_exchange_info()[ソース]

Return rate limits and list of symbols

戻り値:list - List of product dictionaries
{
    "timezone": "UTC",
    "serverTime": 1508631584636,
    "rateLimits": [
        {
            "rateLimitType": "REQUESTS",
            "interval": "MINUTE",
            "limit": 1200
        },
        {
            "rateLimitType": "ORDERS",
            "interval": "SECOND",
            "limit": 10
        },
        {
            "rateLimitType": "ORDERS",
            "interval": "DAY",
            "limit": 100000
        }
    ],
    "exchangeFilters": [],
    "symbols": [
        {
            "symbol": "ETHBTC",
            "status": "TRADING",
            "baseAsset": "ETH",
            "baseAssetPrecision": 8,
            "quoteAsset": "BTC",
            "quotePrecision": 8,
            "orderTypes": ["LIMIT", "MARKET"],
            "icebergAllowed": false,
            "filters": [
                {
                    "filterType": "PRICE_FILTER",
                    "minPrice": "0.00000100",
                    "maxPrice": "100000.00000000",
                    "tickSize": "0.00000100"
                }, {
                    "filterType": "LOT_SIZE",
                    "minQty": "0.00100000",
                    "maxQty": "100000.00000000",
                    "stepSize": "0.00100000"
                }, {
                    "filterType": "MIN_NOTIONAL",
                    "minNotional": "0.00100000"
                }
            ]
        }
    ]
}
Raises:BinanceResponseException, BinanceAPIException
get_historical_klines(symbol, interval, start_str, end_str=None)[ソース]

Get Historical Klines from Binance

See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/

If using offset strings for dates add 「UTC」 to date string e.g. 「now UTC」, 「11 hours ago UTC」

パラメータ:
  • symbol (str) – Name of symbol pair e.g BNBBTC
  • interval (str) – Biannce Kline interval
  • start_str (str) – Start date string in UTC format
  • end_str (str) – optional - end date string in UTC format
戻り値:

list of OHLCV values

get_historical_trades(**params)[ソース]

Get older trades.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#recent-trades-list

パラメータ:
  • symbol (str) – required
  • limit (int) – Default 500; max 500.
  • fromId (str) – TradeId to fetch from. Default gets most recent trades.
戻り値:

API response

[
    {
        "id": 28457,
        "price": "4.00000100",
        "qty": "12.00000000",
        "time": 1499865549590,
        "isBuyerMaker": true,
        "isBestMatch": true
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_klines(**params)[ソース]

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

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#klinecandlestick-data

パラメータ:
  • symbol (str) – required
  • interval (enum) –
  • limit (int) –
    • Default 500; max 500.
  • startTime (int) –
  • endTime (int) –
戻り値:

API response

[
    [
        1499040000000,      # Open time
        "0.01634790",       # Open
        "0.80000000",       # High
        "0.01575800",       # Low
        "0.01577100",       # Close
        "148976.11427815",  # Volume
        1499644799999,      # Close time
        "2434.19055334",    # Quote asset volume
        308,                # Number of trades
        "1756.87402397",    # Taker buy base asset volume
        "28.46694368",      # Taker buy quote asset volume
        "17928899.62484339" # Can be ignored
    ]
]
Raises:BinanceResponseException, BinanceAPIException
get_my_trades(**params)[ソース]

Get trades for a specific symbol.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-trade-list-user_data

パラメータ:
  • symbol (str) – required
  • limit (int) – Default 500; max 500.
  • fromId (int) – TradeId to fetch from. Default gets most recent trades.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

[
    {
        "id": 28457,
        "price": "4.00000100",
        "qty": "12.00000000",
        "commission": "10.10000000",
        "commissionAsset": "BNB",
        "time": 1499865549590,
        "isBuyer": true,
        "isMaker": false,
        "isBestMatch": true
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_open_orders(**params)[ソース]

Get all open orders on a symbol.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#current-open-orders-user_data

パラメータ:
  • symbol (str) – optional
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

[
    {
        "symbol": "LTCBTC",
        "orderId": 1,
        "clientOrderId": "myOrder1",
        "price": "0.1",
        "origQty": "1.0",
        "executedQty": "0.0",
        "status": "NEW",
        "timeInForce": "GTC",
        "type": "LIMIT",
        "side": "BUY",
        "stopPrice": "0.0",
        "icebergQty": "0.0",
        "time": 1499827319559
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_order(**params)[ソース]

Check an order’s status. Either orderId or origClientOrderId must be sent.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#query-order-user_data

パラメータ:
  • symbol (str) – required
  • orderId (int) – The unique order id
  • origClientOrderId (str) – optional
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

{
    "symbol": "LTCBTC",
    "orderId": 1,
    "clientOrderId": "myOrder1",
    "price": "0.1",
    "origQty": "1.0",
    "executedQty": "0.0",
    "status": "NEW",
    "timeInForce": "GTC",
    "type": "LIMIT",
    "side": "BUY",
    "stopPrice": "0.0",
    "icebergQty": "0.0",
    "time": 1499827319559
}
Raises:BinanceResponseException, BinanceAPIException
get_order_book(**params)[ソース]

Get the Order Book for the market

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#order-book

パラメータ:
  • symbol (str) – required
  • limit (int) – Default 100; max 100
戻り値:

API response

{
    "lastUpdateId": 1027024,
    "bids": [
        [
            "4.00000000",     # PRICE
            "431.00000000",   # QTY
            []                # Can be ignored
        ]
    ],
    "asks": [
        [
            "4.00000200",
            "12.00000000",
            []
        ]
    ]
}
Raises:BinanceResponseException, BinanceAPIException
get_orderbook_ticker(**params)[ソース]

Latest price for a symbol or symbols.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker

パラメータ:symbol (str) –
戻り値:API response
{
    "symbol": "LTCBTC",
    "bidPrice": "4.00000000",
    "bidQty": "431.00000000",
    "askPrice": "4.00000200",
    "askQty": "9.00000000"
}

OR

[
    {
        "symbol": "LTCBTC",
        "bidPrice": "4.00000000",
        "bidQty": "431.00000000",
        "askPrice": "4.00000200",
        "askQty": "9.00000000"
    },
    {
        "symbol": "ETHBTC",
        "bidPrice": "0.07946700",
        "bidQty": "9.00000000",
        "askPrice": "100000.00000000",
        "askQty": "1000.00000000"
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_orderbook_tickers()[ソース]

Best price/qty on the order book for all symbols.

https://www.binance.com/restapipub.html#symbols-order-book-ticker

戻り値:List of order book market entries
[
    {
        "symbol": "LTCBTC",
        "bidPrice": "4.00000000",
        "bidQty": "431.00000000",
        "askPrice": "4.00000200",
        "askQty": "9.00000000"
    },
    {
        "symbol": "ETHBTC",
        "bidPrice": "0.07946700",
        "bidQty": "9.00000000",
        "askPrice": "100000.00000000",
        "askQty": "1000.00000000"
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_products()[ソース]

Return list of products currently listed on Binance

Use get_exchange_info() call instead

戻り値:list - List of product dictionaries
Raises:BinanceResponseException, BinanceAPIException
get_recent_trades(**params)[ソース]

Get recent trades (up to last 500).

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#recent-trades-list

パラメータ:
  • symbol (str) – required
  • limit (int) – Default 500; max 500.
戻り値:

API response

[
    {
        "id": 28457,
        "price": "4.00000100",
        "qty": "12.00000000",
        "time": 1499865549590,
        "isBuyerMaker": true,
        "isBestMatch": true
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_server_time()[ソース]

Test connectivity to the Rest API and get the current server time.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#check-server-time

戻り値:Current server time
{
    "serverTime": 1499827319559
}
Raises:BinanceResponseException, BinanceAPIException
get_symbol_info(symbol)[ソース]

Return information about a symbol

パラメータ:symbol (str) – required e.g BNBBTC
戻り値:Dict if found, None if not
{
    "symbol": "ETHBTC",
    "status": "TRADING",
    "baseAsset": "ETH",
    "baseAssetPrecision": 8,
    "quoteAsset": "BTC",
    "quotePrecision": 8,
    "orderTypes": ["LIMIT", "MARKET"],
    "icebergAllowed": false,
    "filters": [
        {
            "filterType": "PRICE_FILTER",
            "minPrice": "0.00000100",
            "maxPrice": "100000.00000000",
            "tickSize": "0.00000100"
        }, {
            "filterType": "LOT_SIZE",
            "minQty": "0.00100000",
            "maxQty": "100000.00000000",
            "stepSize": "0.00100000"
        }, {
            "filterType": "MIN_NOTIONAL",
            "minNotional": "0.00100000"
        }
    ]
}
Raises:BinanceResponseException, BinanceAPIException
get_symbol_ticker(**params)[ソース]

Latest price for a symbol or symbols.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics

パラメータ:symbol (str) –
戻り値:API response
{
    "symbol": "LTCBTC",
    "price": "4.00000200"
}

OR

[
    {
        "symbol": "LTCBTC",
        "price": "4.00000200"
    },
    {
        "symbol": "ETHBTC",
        "price": "0.07946600"
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_ticker(**params)[ソース]

24 hour price change statistics.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics

パラメータ:symbol (str) –
戻り値:API response
{
    "priceChange": "-94.99999800",
    "priceChangePercent": "-95.960",
    "weightedAvgPrice": "0.29628482",
    "prevClosePrice": "0.10002000",
    "lastPrice": "4.00000200",
    "bidPrice": "4.00000000",
    "askPrice": "4.00000200",
    "openPrice": "99.00000000",
    "highPrice": "100.00000000",
    "lowPrice": "0.10000000",
    "volume": "8913.30000000",
    "openTime": 1499783499040,
    "closeTime": 1499869899040,
    "fristId": 28385,   # First tradeId
    "lastId": 28460,    # Last tradeId
    "count": 76         # Trade count
}

OR

[
    {
        "priceChange": "-94.99999800",
        "priceChangePercent": "-95.960",
        "weightedAvgPrice": "0.29628482",
        "prevClosePrice": "0.10002000",
        "lastPrice": "4.00000200",
        "bidPrice": "4.00000000",
        "askPrice": "4.00000200",
        "openPrice": "99.00000000",
        "highPrice": "100.00000000",
        "lowPrice": "0.10000000",
        "volume": "8913.30000000",
        "openTime": 1499783499040,
        "closeTime": 1499869899040,
        "fristId": 28385,   # First tradeId
        "lastId": 28460,    # Last tradeId
        "count": 76         # Trade count
    }
]
Raises:BinanceResponseException, BinanceAPIException
get_withdraw_history(**params)[ソース]

Fetch withdraw history.

https://www.binance.com/restapipub.html

パラメータ:
  • asset (str) – optional
  • startTime (long) – optional
  • endTime (long) – optional
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

{
    "withdrawList": [
        {
            "amount": 1,
            "address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
            "asset": "ETH",
            "applyTime": 1508198532000
            "status": 4
        },
        {
            "amount": 0.005,
            "address": "0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b",
            "txId": "0x80aaabed54bdab3f6de5868f89929a2371ad21d666f20f7393d1a3389fad95a1",
            "asset": "ETH",
            "applyTime": 1508198532000,
            "status": 4
        }
    ],
    "success": true
}
Raises:BinanceResponseException, BinanceAPIException
order_limit(timeInForce='GTC', **params)[ソース]

Send in a new limit order

Any order with an icebergQty MUST have timeInForce set to GTC.

パラメータ:
  • symbol (str) – required
  • side (enum) – required
  • quantity (decimal) – required
  • price (str) – required
  • timeInForce (enum) – default Good till cancelled
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • icebergQty (decimal) – Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.
  • newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

See order endpoint for full response options

Raises:BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_limit_buy(timeInForce='GTC', **params)[ソース]

Send in a new limit buy order

Any order with an icebergQty MUST have timeInForce set to GTC.

パラメータ:
  • symbol (str) – required
  • quantity (decimal) – required
  • price (str) – required
  • timeInForce (enum) – default Good till cancelled
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • stopPrice (decimal) – Used with stop orders
  • icebergQty (decimal) – Used with iceberg orders
  • newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

See order endpoint for full response options

Raises:BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_limit_sell(timeInForce='GTC', **params)[ソース]

Send in a new limit sell order

パラメータ:
  • symbol (str) – required
  • quantity (decimal) – required
  • price (str) – required
  • timeInForce (enum) – default Good till cancelled
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • stopPrice (decimal) – Used with stop orders
  • icebergQty (decimal) – Used with iceberg orders
  • newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

See order endpoint for full response options

Raises:BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_market(**params)[ソース]

Send in a new market order

パラメータ:
  • symbol (str) – required
  • side (enum) – required
  • quantity (decimal) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

See order endpoint for full response options

Raises:BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_market_buy(**params)[ソース]

Send in a new market buy order

パラメータ:
  • symbol (str) – required
  • quantity (decimal) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

See order endpoint for full response options

Raises:BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
order_market_sell(**params)[ソース]

Send in a new market sell order

パラメータ:
  • symbol (str) – required
  • quantity (decimal) – required
  • newClientOrderId (str) – A unique id for the order. Automatically generated if not sent.
  • newOrderRespType (enum) – Set the response JSON. ACK, RESULT, or FULL; default: RESULT.
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

See order endpoint for full response options

Raises:BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
ping()[ソース]

Test connectivity to the Rest API.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#test-connectivity

戻り値:Empty array
{}
Raises:BinanceResponseException, BinanceAPIException
stream_close(listenKey)[ソース]

Close out a user data stream.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#close-user-data-stream-user_stream

パラメータ:listenKey (str) – required
戻り値:API response
{}
Raises:BinanceResponseException, BinanceAPIException
stream_get_listen_key()[ソース]

Start a new user data stream and return the listen key If a stream already exists it should return the same key. If the stream becomes invalid a new key is returned.

Can be used to keep the user stream alive.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#start-user-data-stream-user_stream

戻り値:API response
{
    "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"
}
Raises:BinanceResponseException, BinanceAPIException
stream_keepalive(listenKey)[ソース]

PING a user data stream to prevent a time out.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#keepalive-user-data-stream-user_stream

パラメータ:listenKey (str) – required
戻り値:API response
{}
Raises:BinanceResponseException, BinanceAPIException
withdraw(**params)[ソース]

Submit a withdraw request.

https://www.binance.com/restapipub.html

Assumptions:

  • You must have Withdraw permissions enabled on your API key
  • You must have withdrawn to the address specified through the website and approved the transaction via email
パラメータ:
  • asset (str) – required
  • amount (decimal) – required
  • name (str) – optional - Description of the address, default asset value passed will be used
  • recvWindow (int) – the number of milliseconds the request is valid for
戻り値:

API response

{
    "msg": "success",
    "success": true,
    "id":"7213fea8e94b4a5593d507237e5a555b"
}
Raises:BinanceResponseException, BinanceAPIException, BinanceWithdrawException

depthcache module

class binance.depthcache.DepthCache(symbol)[ソース]

ベースクラス: object

__init__(symbol)[ソース]

Intialise the DepthCache

パラメータ:symbol (string) – Symbol to create depth cache for
add_ask(ask)[ソース]

Add an ask to the cache

パラメータ:ask
戻り値:
add_bid(bid)[ソース]

Add a bid to the cache

パラメータ:bid
戻り値:
get_asks()[ソース]

Get the current asks

戻り値:list of asks with price and quantity as floats
[
    [
        0.0001955,  # Price
        57.0'       # Quantity
    ],
    [
        0.00019699,
        778.0
    ],
    [
        0.000197,
        64.0
    ],
    [
        0.00019709,
        1130.0
    ],
    [
        0.0001971,
        385.0
    ]
]
get_bids()[ソース]

Get the current bids

戻り値:list of bids with price and quantity as floats
[
    [
        0.0001946,  # Price
        45.0        # Quantity
    ],
    [
        0.00019459,
        2384.0
    ],
    [
        0.00019158,
        5219.0
    ],
    [
        0.00019157,
        1180.0
    ],
    [
        0.00019082,
        287.0
    ]
]
static sort_depth(vals, reverse=False)[ソース]

Sort bids or asks by price

class binance.depthcache.DepthCacheManager(client, symbol, callback=None, refresh_interval=1800)[ソース]

ベースクラス: object

__init__(client, symbol, callback=None, refresh_interval=1800)[ソース]

Initialise the DepthCacheManager

パラメータ:
  • client (binance.Client) – Binance API client
  • symbol (string) – Symbol to create depth cache for
  • callback (function) – Optional function to receive depth cache updates
  • refresh_interval (int) – Optional number of seconds between cache refresh, use 0 or None to disable
close()[ソース]

Close the open socket for this manager

戻り値:
get_depth_cache()[ソース]

Get the current depth cache

戻り値:DepthCache object

exceptions module

exception binance.exceptions.BinanceAPIException(response)[ソース]

ベースクラス: exceptions.Exception

LISTENKEY_NOT_EXIST = '-1125'
__init__(response)[ソース]
exception binance.exceptions.BinanceOrderException(code, message)[ソース]

ベースクラス: exceptions.Exception

__init__(code, message)[ソース]
exception binance.exceptions.BinanceOrderInactiveSymbolException(value)[ソース]

ベースクラス: binance.exceptions.BinanceOrderException

__init__(value)[ソース]
exception binance.exceptions.BinanceOrderMinAmountException(value)[ソース]

ベースクラス: binance.exceptions.BinanceOrderException

__init__(value)[ソース]
exception binance.exceptions.BinanceOrderMinPriceException(value)[ソース]

ベースクラス: binance.exceptions.BinanceOrderException

__init__(value)[ソース]
exception binance.exceptions.BinanceOrderMinTotalException(value)[ソース]

ベースクラス: binance.exceptions.BinanceOrderException

__init__(value)[ソース]
exception binance.exceptions.BinanceOrderUnknownSymbolException(value)[ソース]

ベースクラス: binance.exceptions.BinanceOrderException

__init__(value)[ソース]
exception binance.exceptions.BinanceRequestException(message)[ソース]

ベースクラス: exceptions.Exception

__init__(message)[ソース]
exception binance.exceptions.BinanceWithdrawException(message)[ソース]

ベースクラス: exceptions.Exception

__init__(message)[ソース]

helpers module

binance.helpers.date_to_milliseconds(date_str)[ソース]

Convert UTC date to milliseconds

If using offset strings add 「UTC」 to date string e.g. 「now UTC」, 「11 hours ago UTC」

See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/

パラメータ:date_str (str) – date in readable format, i.e. 「January 01, 2018」, 「11 hours ago UTC」, 「now UTC」
binance.helpers.interval_to_milliseconds(interval)[ソース]

Convert a Binance interval string to milliseconds

パラメータ:interval (str) – Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
戻り値:None if unit not one of m, h, d or w None if string not in correct format int value of interval in milliseconds

websockets module

class binance.websockets.BinanceClientFactory(*args, **kwargs)[ソース]

ベースクラス: autobahn.twisted.websocket.WebSocketClientFactory, binance.websockets.BinanceReconnectingClientFactory

clientConnectionFailed(connector, reason)[ソース]
clientConnectionLost(connector, reason)[ソース]
protocol

BinanceClientProtocol のエイリアス

class binance.websockets.BinanceClientProtocol[ソース]

ベースクラス: autobahn.twisted.websocket.WebSocketClientProtocol

onConnect(response)[ソース]
onMessage(payload, isBinary)[ソース]
class binance.websockets.BinanceReconnectingClientFactory[ソース]

ベースクラス: twisted.internet.protocol.ReconnectingClientFactory

initialDelay = 0.1
maxDelay = 10
maxRetries = 5
class binance.websockets.BinanceSocketManager(client)[ソース]

ベースクラス: threading.Thread

STREAM_URL = 'wss://stream.binance.com:9443/'
WEBSOCKET_DEPTH_10 = '10'
WEBSOCKET_DEPTH_20 = '20'
WEBSOCKET_DEPTH_5 = '5'
__init__(client)[ソース]

Initialise the BinanceSocketManager

パラメータ:client (binance.Client) – Binance API client
close()[ソース]

Close all connections

run()[ソース]
start_aggtrade_socket(symbol, callback)[ソース]

Start a websocket for symbol trade data

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#aggregate-trade-streams

パラメータ:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
戻り値:

connection key string if successful, False otherwise

Message Format

{
    "e": "aggTrade",                # event type
    "E": 1499405254326,             # event time
    "s": "ETHBTC",                  # symbol
    "a": 70232,                             # aggregated tradeid
    "p": "0.10281118",              # price
    "q": "8.15632997",              # quantity
    "f": 77489,                             # first breakdown trade id
    "l": 77489,                             # last breakdown trade id
    "T": 1499405254324,             # trade time
    "m": false,                             # whether buyer is a maker
    "M": true                               # can be ignored
}
start_depth_socket(symbol, callback, depth=None)[ソース]

Start a websocket for symbol market depth returning either a diff or a partial book

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams

パラメータ:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
  • depth (enum) – optional Number of depth entries to return, default None. If passed returns a partial book instead of a diff
戻り値:

connection key string if successful, False otherwise

Partial Message Format

{
    "lastUpdateId": 160,  # Last update ID
    "bids": [             # Bids to be updated
        [
            "0.0024",     # price level to be updated
            "10",         # quantity
            []            # ignore
        ]
    ],
    "asks": [             # Asks to be updated
        [
            "0.0026",     # price level to be updated
            "100",        # quantity
            []            # ignore
        ]
    ]
}

Diff Message Format

{
    "e": "depthUpdate", # Event type
    "E": 123456789,     # Event time
    "s": "BNBBTC",      # Symbol
    "U": 157,           # First update ID in event
    "u": 160,           # Final update ID in event
    "b": [              # Bids to be updated
        [
            "0.0024",   # price level to be updated
            "10",       # quantity
            []          # ignore
        ]
    ],
    "a": [              # Asks to be updated
        [
            "0.0026",   # price level to be updated
            "100",      # quantity
            []          # ignore
        ]
    ]
}
start_kline_socket(symbol, callback, interval='1m')[ソース]

Start a websocket for symbol kline data

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams

パラメータ:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
  • interval (enum) – Kline interval, default KLINE_INTERVAL_1MINUTE
戻り値:

connection key string if successful, False otherwise

Message Format

{
    "e": "kline",                                   # event type
    "E": 1499404907056,                             # event time
    "s": "ETHBTC",                                  # symbol
    "k": {
        "t": 1499404860000,                 # start time of this bar
        "T": 1499404919999,                 # end time of this bar
        "s": "ETHBTC",                              # symbol
        "i": "1m",                                  # interval
        "f": 77462,                                 # first trade id
        "L": 77465,                                 # last trade id
        "o": "0.10278577",                  # open
        "c": "0.10278645",                  # close
        "h": "0.10278712",                  # high
        "l": "0.10278518",                  # low
        "v": "17.47929838",                 # volume
        "n": 4,                                             # number of trades
        "x": false,                                 # whether this bar is final
        "q": "1.79662878",                  # quote volume
        "V": "2.34879839",                  # volume of active buy
        "Q": "0.24142166",                  # quote volume of active buy
        "B": "13279784.01349473"    # can be ignored
        }
}
start_multiplex_socket(streams, callback)[ソース]

Start a multiplexed socket using a list of socket names. User stream sockets can not be included.

Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker

Combined stream events are wrapped as follows: {「stream」:」<streamName>」,」data」:<rawPayload>}

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md

パラメータ:
  • streams (list) – list of stream names in lower case
  • callback (function) – callback function to handle messages
戻り値:

connection key string if successful, False otherwise

Message Format - see Binance API docs for all types

start_symbol_ticker_socket(symbol, callback)[ソース]

Start a websocket for a symbol’s ticker data

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#individual-symbol-ticker-streams

パラメータ:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
戻り値:

connection key string if successful, False otherwise

Message Format

{
    "e": "24hrTicker",  # Event type
    "E": 123456789,     # Event time
    "s": "BNBBTC",      # Symbol
    "p": "0.0015",      # Price change
    "P": "250.00",      # Price change percent
    "w": "0.0018",      # Weighted average price
    "x": "0.0009",      # Previous day's close price
    "c": "0.0025",      # Current day's close price
    "Q": "10",          # Close trade's quantity
    "b": "0.0024",      # Best bid price
    "B": "10",          # Bid bid quantity
    "a": "0.0026",      # Best ask price
    "A": "100",         # Best ask quantity
    "o": "0.0010",      # Open price
    "h": "0.0025",      # High price
    "l": "0.0010",      # Low price
    "v": "10000",       # Total traded base asset volume
    "q": "18",          # Total traded quote asset volume
    "O": 0,             # Statistics open time
    "C": 86400000,      # Statistics close time
    "F": 0,             # First trade ID
    "L": 18150,         # Last trade Id
    "n": 18151          # Total number of trades
}
start_ticker_socket(callback)[ソース]

Start a websocket for all ticker data

By default all markets are included in an array.

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#all-market-tickers-stream

パラメータ:callback (function) – callback function to handle messages
戻り値:connection key string if successful, False otherwise

Message Format

[
    {
        'F': 278610,
        'o': '0.07393000',
        's': 'BCCBTC',
        'C': 1509622420916,
        'b': '0.07800800',
        'l': '0.07160300',
        'h': '0.08199900',
        'L': 287722,
        'P': '6.694',
        'Q': '0.10000000',
        'q': '1202.67106335',
        'p': '0.00494900',
        'O': 1509536020916,
        'a': '0.07887800',
        'n': 9113,
        'B': '1.00000000',
        'c': '0.07887900',
        'x': '0.07399600',
        'w': '0.07639068',
        'A': '2.41900000',
        'v': '15743.68900000'
    }
]
start_trade_socket(symbol, callback)[ソース]

Start a websocket for symbol trade data

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#trade-streams

パラメータ:
  • symbol (str) – required
  • callback (function) – callback function to handle messages
戻り値:

connection key string if successful, False otherwise

Message Format

{
    "e": "trade",     # Event type
    "E": 123456789,   # Event time
    "s": "BNBBTC",    # Symbol
    "t": 12345,       # Trade ID
    "p": "0.001",     # Price
    "q": "100",       # Quantity
    "b": 88,          # Buyer order Id
    "a": 50,          # Seller order Id
    "T": 123456785,   # Trade time
    "m": true,        # Is the buyer the market maker?
    "M": true         # Ignore.
}
start_user_socket(callback)[ソース]

Start a websocket for user data

https://www.binance.com/restapipub.html#user-wss-endpoint

パラメータ:callback (function) – callback function to handle messages
戻り値:connection key string if successful, False otherwise

Message Format - see Binance API docs for all types

stop_socket(conn_key)[ソース]

Stop a websocket given the connection key

パラメータ:conn_key (string) – Socket connection key
戻り値:connection key string if successful, False otherwise