Giter Club home page Giter Club logo

python-binance's Introduction

Welcome to python-binance v1.0.19

Updated 11th Aug 2023

image

image

image

image

image

image

This is an unofficial Python wrapper for the Binance exchange REST API v3. I am in no way affiliated with Binance, use at your own risk.

If you came here looking for the Binance exchange to purchase cryptocurrencies, then go here. If you want to automate interactions with Binance stick around.

If you're interested in Binance's new DEX Binance Chain see my python-binance-chain library

Source code

https://github.com/sammchardy/python-binance

Documentation

https://python-binance.readthedocs.io/en/latest/

Binance API Telegram

https://t.me/binance_api_english

Blog with examples including async

https://sammchardy.github.io

Make sure you update often and check the Changelog for new features and bug fixes.

Features

  • Implementation of all General, Market Data and Account endpoints.
  • Asyncio implementation
  • Testnet support for Spot, Futures and Vanilla Options
  • Simple handling of authentication include RSA keys
  • No need to generate timestamps yourself, the wrapper does it for you
  • Response exception handling
  • Websocket handling with reconnection and multiplexed connections
  • Symbol Depth Cache
  • Historical Kline/Candle fetching function
  • Withdraw functionality
  • Deposit addresses
  • Margin Trading
  • Futures Trading
  • Vanilla Options
  • Support other domains (.us, .jp, etc)

Upgrading to v1.0.0+

The breaking changes include the migration from wapi to sapi endpoints which related to the wallet endpoints detailed in the Binance Docs

The other breaking change is for websocket streams and the Depth Cache Manager which have been converted to use Asynchronous Context Managers. See examples in the Async section below or view the websockets and depth cache docs.

Quick Start

Register an account with Binance.

Generate an API Key and assign relevant permissions.

If you are using an exchange from the US, Japan or other TLD then make sure pass tld='us' when creating the client.

To use the Spot or Vanilla Options Testnet, pass testnet=True when creating the client.

pip install python-binance
from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager
client = Client(api_key, api_secret)

# get market depth
depth = client.get_order_book(symbol='BNBBTC')

# place a test market buy order, to place an actual order use the create_order function
order = client.create_test_order(
    symbol='BNBBTC',
    side=Client.SIDE_BUY,
    type=Client.ORDER_TYPE_MARKET,
    quantity=100)

# get all symbol prices
prices = client.get_all_tickers()

# withdraw 100 ETH
# check docs for assumptions around withdrawals
from binance.exceptions import BinanceAPIException
try:
    result = client.withdraw(
        asset='ETH',
        address='<eth_address>',
        amount=100)
except BinanceAPIException as e:
    print(e)
else:
    print("Success")

# fetch list of withdrawals
withdraws = client.get_withdraw_history()

# fetch list of ETH withdrawals
eth_withdraws = client.get_withdraw_history(coin='ETH')

# get a deposit address for BTC
address = client.get_deposit_address(coin='BTC')

# get historical kline data from any date range

# fetch 1 minute klines for the last day up until now
klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")

# fetch 30 minute klines for the last month of 2017
klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018")

# fetch weekly klines since it listed
klines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan, 2017")

# socket manager using threads
twm = ThreadedWebsocketManager()
twm.start()

# depth cache manager using threads
dcm = ThreadedDepthCacheManager()
dcm.start()

def handle_socket_message(msg):
    print(f"message type: {msg['e']}")
    print(msg)

def handle_dcm_message(depth_cache):
    print(f"symbol {depth_cache.symbol}")
    print("top 5 bids")
    print(depth_cache.get_bids()[:5])
    print("top 5 asks")
    print(depth_cache.get_asks()[:5])
    print("last update time {}".format(depth_cache.update_time))

twm.start_kline_socket(callback=handle_socket_message, symbol='BNBBTC')

dcm.start_depth_cache(callback=handle_dcm_message, symbol='ETHBTC')

# replace with a current options symbol
options_symbol = 'BTC-210430-36000-C'
dcm.start_options_depth_cache(callback=handle_dcm_message, symbol=options_symbol)

# join the threaded managers to the main thread
twm.join()
dcm.join()

For more check out the documentation.

Async Example

Read Async basics for Binance for more information.

import asyncio
import json

from binance import AsyncClient, DepthCacheManager, BinanceSocketManager

async def main():

    # initialise the client
    client = await AsyncClient.create()

    # run some simple requests
    print(json.dumps(await client.get_exchange_info(), indent=2))

    print(json.dumps(await client.get_symbol_ticker(symbol="BTCUSDT"), indent=2))

    # initialise websocket factory manager
    bsm = BinanceSocketManager(client)

    # create listener using async with
    # this will exit and close the connection after 5 messages
    async with bsm.trade_socket('ETHBTC') as ts:
        for _ in range(5):
            res = await ts.recv()
            print(f'recv {res}')

    # get historical kline data from any date range

    # fetch 1 minute klines for the last day up until now
    klines = client.get_historical_klines("BNBBTC", AsyncClient.KLINE_INTERVAL_1MINUTE, "1 day ago UTC")

    # use generator to fetch 1 minute klines for the last day up until now
    async for kline in await client.get_historical_klines_generator("BNBBTC", AsyncClient.KLINE_INTERVAL_1MINUTE, "1 day ago UTC"):
        print(kline)

    # fetch 30 minute klines for the last month of 2017
    klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018")

    # fetch weekly klines since it listed
    klines = client.get_historical_klines("NEOBTC", Client.KLINE_INTERVAL_1WEEK, "1 Jan, 2017")

    # setup an async context the Depth Cache and exit after 5 messages
    async with DepthCacheManager(client, symbol='ETHBTC') as dcm_socket:
        for _ in range(5):
            depth_cache = await dcm_socket.recv()
            print(f"symbol {depth_cache.symbol} updated:{depth_cache.update_time}")
            print("Top 5 asks:")
            print(depth_cache.get_asks()[:5])
            print("Top 5 bids:")
            print(depth_cache.get_bids()[:5])

    # Vanilla options Depth Cache works the same, update the symbol to a current one
    options_symbol = 'BTC-210430-36000-C'
    async with OptionsDepthCacheManager(client, symbol=options_symbol) as dcm_socket:
        for _ in range(5):
            depth_cache = await dcm_socket.recv()
            count += 1
            print(f"symbol {depth_cache.symbol} updated:{depth_cache.update_time}")
            print("Top 5 asks:")
            print(depth_cache.get_asks()[:5])
            print("Top 5 bids:")
            print(depth_cache.get_bids()[:5])

    await client.close_connection()

if __name__ == "__main__":

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Donate

If this library helped you out feel free to donate.

  • ETH: 0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70
  • LTC: LPC5vw9ajR1YndE1hYVeo3kJ9LdHjcRCUZ
  • NEO: AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBo
  • BTC: 1Dknp6L6oRZrHDECRedihPzx2sSfmvEBys

Other Exchanges

If you use Binance Chain check out my python-binance-chain library.

If you use Kucoin check out my python-kucoin library.

If you use IDEX check out my python-idex library.

image

python-binance's People

Contributors

alexnik avatar anson-vandoren avatar byronformwalt avatar cmollen avatar flashnuke avatar g00dnight avatar gbozee avatar guillemap avatar hughsw avatar indrasweb avatar jolium avatar junghoon-vans avatar kimchirichie avatar knaperek avatar lancechua avatar mennovdijk avatar mfiro avatar mishaker avatar ollie-hooper avatar piyushdixit96 avatar pprados avatar r41d avatar rezaya92 avatar samjosephmark avatar sammchardy avatar sapph1re avatar sinafa avatar t2o2 avatar ttamg avatar wobuup avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-binance's Issues

Getting Symbol Price

Whenever I try and get the ticker price for 1 specific symbol it throws an error saying "TypeError: get_symbol_ticker() takes 1 positional argument but 2 were given",
I'm only sending in 1 argument
price = client.get_symbol_ticker({"BTCUSDT"})
I've tried in braces and without braces. Do you know about this issue or is it something on my end?

Returning variables from websocket functions

I'm running a symbol_ticker socket in order to buy, sell and cancel orders based on realtime orderbook info, but I can't figure out how to return a variable from the websocket process function. Since the process function acts as parameters in the socket function, I am not sure where or how to request output. Can someone fill me in? Thanks.

enums WEBSOCKET_DEPTH_20 was wrong

in enums file, the WEBSOCKET_DEPTH_20 is 5 not 20. and can i config it by myself? when i use bm.start_depth_socket(symbol='BTCUSDT', depth='20, callback=depth_tick) it cannot work

I met a crash, and only get such a piece of log. Hope it may help.

File "/usr/local/lib64/python2.7/site-packages/twisted/python/context.py", line 85, in callWithContext
    return func(*args,**kw)
  File "/usr/local/lib64/python2.7/site-packages/twisted/internet/posixbase.py", line 627, in _doReadOrWrite
    self._disconnectSelectable(selectable, why, inRead)
  File "/usr/local/lib64/python2.7/site-packages/twisted/internet/posixbase.py", line 258, in _disconnectSelectable
    selectable.connectionLost(failure.Failure(why))
  File "/usr/local/lib64/python2.7/site-packages/twisted/internet/tcp.py", line 475, in connectionLost
    self._commonConnection.connectionLost(self, reason)
  File "/usr/local/lib64/python2.7/site-packages/twisted/internet/tcp.py", line 289, in connectionLost
    protocol.connectionLost(reason)
  File "/usr/local/lib64/python2.7/site-packages/twisted/protocols/tls.py", line 398, in connectionLost
    self._flushReceiveBIO()
  File "/usr/local/lib64/python2.7/site-packages/twisted/protocols/tls.py", line 295, in _flushReceiveBIO
    ProtocolWrapper.dataReceived(self, bytes)
  File "/usr/local/lib64/python2.7/site-packages/twisted/protocols/policies.py", line 120, in dataReceived
    self.wrappedProtocol.dataReceived(data)
  File "/usr/local/lib/python2.7/site-packages/autobahn/twisted/websocket.py", line 131, in dataReceived
    self._dataReceived(data)
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 1175, in _dataReceived
    self.consumeData()
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 1187, in consumeData
    while self.processData() and self.state != WebSocketProtocol.STATE_CLOSED:
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 1545, in processData
    fr = self.onFrameData(payload)
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 1639, in onFrameData
    self._onMessageFrameData(payload)
  File "/usr/local/lib/python2.7/site-packages/autobahn/twisted/websocket.py", line 150, in _onMessageFrameData
    self.onMessageFrameData(payload)
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 601, in onMessageFrameData
    self.frame_data.append(payload)
exceptions.AttributeError: 'NoneType' object has no attribute 'append'

Not all sent parameters were not read issue

Thanks for the great project.

Running into a bit of an issue when trying to place a buy/sell, particularly when attempting to specify order ID's. When trying to do so the following exception is raised:

binance.exceptions.BinanceAPIException: APIError(code=-1104): Not all sent parameters were not read; read '8' parameter(s) but was sent '9'.

Here's an example of my sell/buy function:

def sell(price, asset, quantity, orderid):
    client.create_order(
        symbol=asset,
        side=SIDE_SELL,
        type=ORDER_TYPE_LIMIT,
        timeInForce=TIME_IN_FORCE_GTC,
        quantity=quantity,
        price=price,
        newClientOrderID=orderid)
def buy(price, asset, quantity, orderid):
    client.create_order(
        symbol=asset,
        side=SIDE_BUY,
        type=ORDER_TYPE_LIMIT,
        timeInForce=TIME_IN_FORCE_GTC,
        quantity=quantity,
        price=price,
        newClientOrderID=orderid)

And here's an example of calling those functions which is resulting in the above exception:

buy("{0:.6f}".format(round((priceYVal[tradePair]), 6)), tradePair, int(float(amountPurchased * 0.95)), str(orderInt))

Note: I have orderInt (the desired order ID) formatted as string on account of Binance specifying that in the API.

Any ideas?

getDepositAddress

Does Binance support the getDepositAddress function? I get "api not exist" when trying to use it.

Thanks

Withdrawal Exception raised

Hi,

Thank you for sharing this great project!

I'm trying to automate the withdrawal process but am getting this error:

binance.exceptions.BinanceWithdrawException: BinanceWithdrawException: Name is empty.

result = client.withdraw(asset = currency, address = addr, amount = 10)

I thought the name field is optional?

Thank you,
Michael

'exchangeInfo' not working anymore since of today

info = client.get_exchange_info() returns following error message from the JSON decoder:

File "c:\python36-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This issue is consistent for me since this morning, where Binance did a planned maintenance

Invalid Timestamp Issue

Hi, Sorry, to generate the same issue. But i have tried all solutions mentioned but no luck. I have one doubt. my account is unverified on binance, can that be the reason for this issue?

local1: 1507741266414 server:1507741240901 local2: 1507741266522 diff1:-25513 diff2:25621
local1: 1507741268524 server:1507741243017 local2: 1507741268639 diff1:-25507 diff2:25622
local1: 1507741270641 server:1507741245133 local2: 1507741270755 diff1:-25508 diff2:25622
local1: 1507741272758 server:1507741247245 local2: 1507741272865 diff1:-25513 diff2:25620
local1: 1507741274867 server:1507741249355 local2: 1507741274975 diff1:-25512 diff2:25620
local1: 1507741276977 server:1507741251469 local2: 1507741277091 diff1:-25508 diff2:25622
local1: 1507741279094 server:1507741253585 local2: 1507741279208 diff1:-25509 diff2:25623
local1: 1507741281210 server:1507741255701 local2: 1507741281324 diff1:-25509 diff2:25623
local1: 1507741283326 server:1507741257818 local2: 1507741283440 diff1:-25508 diff2:25622

Precision for "price" float value when placing orders

What is the max precision for the "price" variable when placing an order, such as a limit order? I'm getting:

BinanceAPIException: APIError(code=-1111): Precision is over the maximum defined for this asset.

For the following float:
0.000614250470875

Is the trimming not handled by the API?

Expecting value: line 1 column 1 (char 0)

I started getting this error randomly but constantly today, sometimes combined with:
APIError(code=-1001): Internal error; unable to process your request. Please try again.
This wasn't an issue up until yesterday and I didn't mess with the code in any way. What is going on?

Get indicators

Hi!
Thanks for this tool.
I cannot find the method to get the indicators such as DMI, OBV, etc. that are available on Exchange -> Advanced. Is this possible to get these values with binance api?
If not do you recommend other python library to get these values?
Thanks again!
João

Enhancement - Example of how to maintain the correct state of the order book using the feeds

Either creating an example in this repo or referencing another would be awesome.

For example, GDAX has documentation on how to get order book snapshots and then sync the "full" channel websocket feed data with the snapshot.

Ideally Binance would have explained how to do this, but they don't. The depth channel contains order book deltas, but it's unclear how you'd tell if those deltas are order book fills or cancellations, and how these deltas would reflect a partial fill. Also it looks like it's only possible to get 100 order book entries, so that's an interesting challenge of how to match up those 100 order book entries in the snapshot with the order book entries in the channel.

new to trading bot

i would like to start using the trading bot but dont know how to start , if anyone can give a step by step of to start . Thanx

Threads: binance.exceptions.BinanceAPIException: APIError(code=-1003): Way too many requests; IP banned

I got class with 3 api methods that i call into it:
Common code

"""
client = Client(api_key, api_secret) # CALL ONCE
while True:
   sleep(random.randint(5,10)
   ticker = client.get_ticker(symbol='{}{}'.format(markets[0],markets[1]))
   sleep(1)
   orderbook = client.get_order_book(symbol='{}{}'.format(markets[0],markets[1]),limit=1000)
   sleep(1)
   history = client.get_historical_trades(symbol='{}{}'.format(markets[0],markets[1]),limit=500)
"""

When i use threads(threading.Thread), untill it's less than 3 - all OK. But when it's 3 and more i got
binance.exceptions.BinanceAPIException: APIError(code=-1003): Way too many requests; IP banned until TimeStamp

From documentation:
At the current time Binance rate limits are:
1200 requests per minute
10 orders per second (what mean orders in my case?)
100,000 orders per 24hrs

Is it actual information?
Cause, as i thought, i made 9 requests total (max - 3 methods in 3 threads) at one second(if all random-time sets at one value), and i still got that error. Or it counts not like that? In what moment i get over 1200?

Also i read here https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#limits
and here - https://github.com/binance-exchange/binance-official-api-docs/blob/master/errors.md#-1003-too_many_requests in official documentation.

Still don't understand where i get over limits for my 3 calls (get_ticker, get_order_book, get_historical_trades)? And what max. possible limits for that methods?

fixed

I run client.get_account()
get error
ibinance.exceptions.BinanceAPIException: APIError(code=-2015): Invalid API-key, IP, or permissions for action.

maybe not PUBLIC_API_VERSION?

Websocket - start/stop behaviour

On v0.4.1: Websockets in API overall work fine - edge case behaviour starting/stopping is unexpected for me. (I'm unfamiliar with websocket usage, possibly I'm using it wrongly?)

For orderbook depth sockets:

  • existing sockets don't stop with bm.stop_socket(conn_key) , only with bm.close() [which stops all sockets]
  • after calling bm.close() websockets can't be re-started with bm.start()
  • the update speed on the 'default' setting is irregular, providing parameter update_time=WEBSOCKET_UPDATE_1SECOND makes it regular and approx. to 1000ms, maybe the default is different from 1sec? (Using WEBSOCKET_UPDATE_0SECOND myself)
  • in basic example provided: should it read 'e' instead of e (to allow copy and pasting)?

start trade websocket

def process_message(msg):
print("message type:" + msg[e])
print(msg)
# do something

After a long run, websocket may encounter "listen-key does not exist"

Binance technician replies that I should put for another listen-key.
I think this exception should be handled automatically.

Exception in thread Thread-18:
Traceback (most recent call last):
  File "/usr/lib64/python2.7/threading.py", line 804, in __bootstrap_inner
    self.run()
  File "/usr/lib64/python2.7/threading.py", line 1076, in run
    self.function(*self.args, **self.kwargs)
  File "/usr/local/lib/python2.7/site-packages/binance/websockets.py", line 295, in _keepalive_user_socket
    self._client.stream_keepalive(listenKey=self._user_listen_key)
  File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 1113, in stream_keepalive
    return self._put('userDataStream', False, data=params)
  File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 140, in _put
    return self._request_api('put', path, signed, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 108, in _request_api
    return self._request(method, uri, signed, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 103, in _request
    return self._handle_response(response)
  File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 127, in _handle_response
    raise BinanceAPIException(response)
BinanceAPIException: APIError(code=-1125): This listenKey does not exist.

The websocket is autoclose and not restart

I try to proccess all info using:
bm = BinanceSocketManager(client)
conn_key = bm.start_multiplex_socket(['bnbbtc@aggTrade'], process_m_message)
bm.start

But after appx 1h the socket is closed and the script stop receive the data i need do manual restarting the script to get the data. I try too using that with the same issue:
conn_key = bm.start_aggtrade_socket('BNBBTC', process_message)

After 1h +/- the socket is closed. How i can do an auto restart?

Thx!

TypeError: start_aggtrade_socket() missing 1 required positional argument: 'callback'

Hi

I tried to run example code but I received error:

from binance.websockets import BinanceSocketManager' 'bm = BinanceSocketManager(client)' 'bm.start_aggtrade_socket(symbol='BTCUSD')' 'bm.start()

Traceback (most recent call last):
File "C:/Users/JM/Documents/GitHub/python-binance/main.py", line 20, in
bm.start_aggtrade_socket(symbol='BTCUSD')
TypeError: start_aggtrade_socket() missing 1 required positional argument: 'callback'

Process finished with exit code 1

Can you help fix the issue?

Unrelated

Sorry to leave this here, not sure how to message people on github. I am a big python guy and can understand your code here. However, is the same thing possible in Javascript? I have been trying for two days now and I cannot get the binance api to work with javascript. I use a function like so:

function httpGetAsync(theUrl, callback) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous
    xmlHttp.send(null);
  }

and attempt to get the server time with

url = 'https://www.binance.com/api/v1/time'
console.log(httpGetAsync(url))

but I get an error in the console of my server:

XMLHttpRequest cannot load https://www.binance.com/api/v1/time. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myserver.com' is therefore not allowed access.

where myserver.com is my website. I see that you also use Javascript, perhaps you could provide some insight? Again sorry for placing this here.

When I stop a socket and close the manager, exceptions here

Unhandled Error
Traceback (most recent call last):
  File "/usr/local/lib64/python2.7/site-packages/twisted/python/log.py", line 103, in callWithLogger
    return callWithContext({"system": lp}, func, *args, **kw)
  File "/usr/local/lib64/python2.7/site-packages/twisted/python/log.py", line 86, in callWithContext
    return context.call({ILogContext: newCtx}, func, *args, **kw)
  File "/usr/local/lib64/python2.7/site-packages/twisted/python/context.py", line 122, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
  File "/usr/local/lib64/python2.7/site-packages/twisted/python/context.py", line 85, in callWithContext
    return func(*args,**kw)
--- <exception caught here> ---
  File "/usr/local/lib64/python2.7/site-packages/twisted/internet/posixbase.py", line 614, in _doReadOrWrite
    why = selectable.doRead()
  File "/usr/local/lib64/python2.7/site-packages/twisted/internet/tcp.py", line 205, in doRead
    return self._dataReceived(data)
  File "/usr/local/lib64/python2.7/site-packages/twisted/internet/tcp.py", line 211, in _dataReceived
    rval = self.protocol.dataReceived(data)
  File "/usr/local/lib64/python2.7/site-packages/twisted/protocols/tls.py", line 330, in dataReceived
    self._flushReceiveBIO()
  File "/usr/local/lib64/python2.7/site-packages/twisted/protocols/tls.py", line 295, in _flushReceiveBIO
    ProtocolWrapper.dataReceived(self, bytes)
  File "/usr/local/lib64/python2.7/site-packages/twisted/protocols/policies.py", line 120, in dataReceived
    self.wrappedProtocol.dataReceived(data)
  File "/usr/local/lib/python2.7/site-packages/autobahn/twisted/websocket.py", line 131, in dataReceived
    self._dataReceived(data)
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 1175, in _dataReceived
    self.consumeData()
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 1187, in consumeData
    while self.processData() and self.state != WebSocketProtocol.STATE_CLOSED:
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 1553, in processData
    fr = self.onFrameEnd()
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 1674, in onFrameEnd
    self._onMessageEnd()
  File "/usr/local/lib/python2.7/site-packages/autobahn/twisted/websocket.py", line 159, in _onMessageEnd
    self.onMessageEnd()
  File "/usr/local/lib/python2.7/site-packages/autobahn/websocket/protocol.py", line 627, in onMessageEnd
    self._onMessage(payload, self.message_is_binary)
  File "/usr/local/lib/python2.7/site-packages/autobahn/twisted/websocket.py", line 162, in _onMessage
    self.onMessage(payload, isBinary)
  File "/usr/local/lib/python2.7/site-packages/binance/websockets.py", line 27, in onMessage
    payload_obj = json.loads(payload.decode('utf8'))
  File "/usr/lib64/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
exceptions.ValueError: No JSON object could be decoded

Websocket unresponsive

Starting up and receiving data from a ticker_socket is successful, but after some time the callback function simply stops calling back.
I thought perhaps to start and stop the socket, but every combination of stops/starts or closing/starting the manager yielded an exception.
So I would like to know how/why the ticket websocket stops responding,
Or if it’s simply random, I would like to know how to properly restart it.
Thank you.
(Also, I am sleeping the thread inside the callback function, I’ll test it without that when I get the chance.)

Amazon EC2 Server [SSL: CERTIFICATE_VERIFY_FAILED]

Hello,

I'm currently attempting to setup my script to run from Amazon EC2 and am running into an issue where the SSL certificate is failing to verify. Code is pretty simple to this point:

from binance.client import Client client = Client(x,y)

Wherein x,y are my API key pair. This key pair has been confirmed working on several other machines, however all of these have been using older versions of python-binance, and after this issue I'm afraid to update and potentially run into the same issue. The full error message supplied is as follows:

client = Client('x,y')
File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 86, in init
self.ping()
File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 332, in ping
return self._get('ping')
File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 176, in _get
return self._request_api('get', path, signed, version, **kwargs)
File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 150, in _request_api
return self._request(method, uri, signed, **kwargs)
File "/usr/local/lib/python2.7/site-packages/binance/client.py", line 144, in _request
response = getattr(self.session, method)(uri, **kwargs)
File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 477, in get
return self.request('GET', url, **kwargs)
File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 465, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python2.7/site-packages/requests/adapters.py", line 431, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

I've tried allowing all connections to/from the EC2 server to no avail. Does anyone have any further ideas here? I realize the problem may be less with this project and more with Amazon/Binance.

Any help is appreciated!

Starting Kline Data websocket and callback???

What would be the best websocket to get the volume data for the last 1m in time?
Would it be the Kline Data websocket?

If so, I am trying to implement this way:


bm = BinanceSocketManager(self.binanceClient)
conn_key = self.socketManager.start_kline_socket(symbol, self.websocket_callback, interval='1m')
bm.start

with a callback :

	def websocket_callback(self, message):
		print("invoked websock_handler:", message)

but no message is printing, can you point me in the right direction?

Thanks!

Unable to start two depthcache for pairs

I created client and did this:

bnbbtc_dcm = DepthCacheManager(client, 'BNBBTC', display_any_msg)
bnbeth_dcm = DepthCacheManager(client, 'BNBETH', display_any_msg)

And I got error like this. It seems that simultaneously creating multiple depthcachemanager is not possible?

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\site-packages\binance\websockets.py", line 305, in run
    reactor.run(installSignalHandlers=False)
  File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 1242, in run
    self.startRunning(installSignalHandlers=installSignalHandlers)
  File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 1222, in startRunning
    ReactorBase.startRunning(self)
  File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 728, in startRunning
    raise error.ReactorAlreadyRunning()
ReactorAlreadyRunning

'Timestamp for this request is not valid'

Using Python 3.6.1 |Anaconda 4.4.0 (64-bit)

from binance.client import Client
api_key = '...'
api_secret = '...'
client = Client(api_key, api_secret)
time_res = client.get_server_time()
orders = client.get_all_orders(symbol='HSRBTC', limit=10)
Traceback (most recent call last):
  File "E:/PyCharm_Project/Binance/main", line 6, in <module>
    orders = client.get_all_orders(symbol='HSRBTC', limit=10)
  File "D:\Anaconda3\lib\site-packages\binance\client.py", line 222, in get_all_orders
    return self._get('allOrders', True, data=params)
  File "D:\Anaconda3\lib\site-packages\binance\client.py", line 75, in _get
    return self._request('get', path, signed, **kwargs)
  File "D:\Anaconda3\lib\site-packages\binance\client.py", line 63, in _request
    return self._handle_response(response)
  File "D:\Anaconda3\lib\site-packages\binance\client.py", line 71, in _handle_response
    raise BinanceAPIException(response)
binance.exceptions.BinanceAPIException: APIError(code=-1021): Timestamp for this request is not valid.

ImportError: No module named 'binance'

kint@ubuntu:/block$ git clone https://github.com/binance-exchange/python-binance.git
Cloning into 'python-binance'...
remote: Counting objects: 939, done.
remote: Total 939 (delta 0), reused 0 (delta 0), pack-reused 939
Receiving objects: 100% (939/939), 154.13 KiB | 68.00 KiB/s, done.
Resolving deltas: 100% (613/613), done.
Checking connectivity... done.
kint@ubuntu:
/block$ pip install python-binance
Collecting python-binance
Downloading python_binance-0.5.6-py2.py3-none-any.whl
Collecting requests (from python-binance)
Downloading requests-2.18.4-py2.py3-none-any.whl (88kB)
100% |████████████████████████████████| 92kB 117kB/s
Collecting six (from python-binance)
Using cached six-1.11.0-py2.py3-none-any.whl
Collecting autobahn (from python-binance)
Downloading autobahn-17.10.1-py2.py3-none-any.whl (283kB)
100% |████████████████████████████████| 286kB 35kB/s
Collecting pyOpenSSL (from python-binance)
Downloading pyOpenSSL-17.5.0-py2.py3-none-any.whl (53kB)
100% |████████████████████████████████| 61kB 41kB/s
Collecting Twisted (from python-binance)
Downloading Twisted-17.9.0.tar.bz2 (3.0MB)
100% |████████████████████████████████| 3.0MB 51kB/s
Collecting service-identity (from python-binance)
Downloading service_identity-17.0.0-py2.py3-none-any.whl
Collecting urllib3<1.23,>=1.21.1 (from requests->python-binance)
Downloading urllib3-1.22-py2.py3-none-any.whl (132kB)
100% |████████████████████████████████| 133kB 75kB/s
Collecting idna<2.7,>=2.5 (from requests->python-binance)
Downloading idna-2.6-py2.py3-none-any.whl (56kB)
100% |████████████████████████████████| 61kB 91kB/s
Collecting chardet<3.1.0,>=3.0.2 (from requests->python-binance)
Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB)
100% |████████████████████████████████| 143kB 48kB/s
Collecting certifi>=2017.4.17 (from requests->python-binance)
Downloading certifi-2017.11.5-py2.py3-none-any.whl (330kB)
100% |████████████████████████████████| 337kB 80kB/s
Collecting txaio>=2.7.0 (from autobahn->python-binance)
Downloading txaio-2.8.2-py2.py3-none-any.whl
Collecting cryptography>=2.1.4 (from pyOpenSSL->python-binance)
Downloading cryptography-2.1.4-cp27-cp27mu-manylinux1_x86_64.whl (2.2MB)
100% |████████████████████████████████| 2.2MB 45kB/s
Collecting zope.interface>=3.6.0 (from Twisted->python-binance)
Downloading zope.interface-4.4.3-cp27-cp27mu-manylinux1_x86_64.whl (170kB)
100% |████████████████████████████████| 174kB 91kB/s
Collecting constantly>=15.1 (from Twisted->python-binance)
Downloading constantly-15.1.0-py2.py3-none-any.whl
Collecting incremental>=16.10.1 (from Twisted->python-binance)
Downloading incremental-17.5.0-py2.py3-none-any.whl
Collecting Automat>=0.3.0 (from Twisted->python-binance)
Downloading Automat-0.6.0-py2.py3-none-any.whl
Collecting hyperlink>=17.1.1 (from Twisted->python-binance)
Downloading hyperlink-17.3.1-py2.py3-none-any.whl (73kB)
100% |████████████████████████████████| 81kB 91kB/s
Collecting pyasn1 (from service-identity->python-binance)
Downloading pyasn1-0.4.2-py2.py3-none-any.whl (71kB)
100% |████████████████████████████████| 71kB 87kB/s
Collecting attrs (from service-identity->python-binance)
Downloading attrs-17.3.0-py2.py3-none-any.whl
Collecting pyasn1-modules (from service-identity->python-binance)
Downloading pyasn1_modules-0.2.1-py2.py3-none-any.whl (60kB)
100% |████████████████████████████████| 61kB 66kB/s
Collecting cffi>=1.7; platform_python_implementation != "PyPy" (from cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading cffi-1.11.2-cp27-cp27mu-manylinux1_x86_64.whl (405kB)
100% |████████████████████████████████| 409kB 72kB/s
Collecting enum34; python_version < "3" (from cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading enum34-1.1.6-py2-none-any.whl
Collecting asn1crypto>=0.21.0 (from cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading asn1crypto-0.24.0-py2.py3-none-any.whl (101kB)
100% |████████████████████████████████| 102kB 41kB/s
Collecting ipaddress; python_version < "3" (from cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading ipaddress-1.0.19.tar.gz
Collecting setuptools (from zope.interface>=3.6.0->Twisted->python-binance)
Downloading setuptools-38.2.4-py2.py3-none-any.whl (489kB)
100% |████████████████████████████████| 491kB 48kB/s
Collecting pycparser (from cffi>=1.7; platform_python_implementation != "PyPy"->cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading pycparser-2.18.tar.gz (245kB)
100% |████████████████████████████████| 256kB 50kB/s
Building wheels for collected packages: Twisted, ipaddress, pycparser
Running setup.py bdist_wheel for Twisted ... done
Stored in directory: /home/kint/.cache/pip/wheels/91/c7/95/0bb4d45bc4ed91375013e9b5f211ac3ebf4138d8858f84abbc
Running setup.py bdist_wheel for ipaddress ... done
Stored in directory: /home/kint/.cache/pip/wheels/d7/6b/69/666188e8101897abb2e115d408d139a372bdf6bfa7abb5aef5
Running setup.py bdist_wheel for pycparser ... done
Stored in directory: /home/kint/.cache/pip/wheels/95/14/9a/5e7b9024459d2a6600aaa64e0ba485325aff7a9ac7489db1b6
Successfully built Twisted ipaddress pycparser
Installing collected packages: urllib3, idna, chardet, certifi, requests, six, txaio, autobahn, pycparser, cffi, enum34, asn1crypto, ipaddress, cryptography, pyOpenSSL, setuptools, zope.interface, constantly, incremental, attrs, Automat, hyperlink, Twisted, pyasn1, pyasn1-modules, service-identity, python-binance
Successfully installed Automat-0.6.0 Twisted-17.9.0 asn1crypto-0.24.0 attrs-17.3.0 autobahn-17.10.1 certifi-2017.11.5 cffi-1.11.2 chardet-3.0.4 constantly-15.1.0 cryptography-2.1.4 enum34-1.1.6 hyperlink-17.3.1 idna-2.6 incremental-17.5.0 ipaddress-1.0.19 pyOpenSSL-17.5.0 pyasn1-0.4.2 pyasn1-modules-0.2.1 pycparser-2.18 python-binance-0.5.6 requests-2.18.4 service-identity-17.0.0 setuptools-38.2.4 six-1.11.0 txaio-2.8.2 urllib3-1.22 zope.interface-4.4.3
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
kint@ubuntu:/block$ cd python-binance/
kint@ubuntu:
/block/python-binance$ ls
binance docs LICENSE PYPIREADME.rst README.rst requirements.txt setup.cfg setup.py test-requirements.txt tests tox.ini
kint@ubuntu:/block/python-binance$ cd tests/
kint@ubuntu:
/block/python-binance/tests$ python test
test_api_request.py test.py

kint@ubuntu:~/block/python-binance/tests$ python test.py
Traceback (most recent call last):
File "test.py", line 1, in
from binance.client import Client
ImportError: No module named 'binance'

ImportError: No module named 'binance'

kint@ubuntu:/block$ git clone https://github.com/binance-exchange/python-binance.git
Cloning into 'python-binance'...
remote: Counting objects: 939, done.
remote: Total 939 (delta 0), reused 0 (delta 0), pack-reused 939
Receiving objects: 100% (939/939), 154.13 KiB | 68.00 KiB/s, done.
Resolving deltas: 100% (613/613), done.
Checking connectivity... done.
kint@ubuntu:
/block$ pip install python-binance
Collecting python-binance
Downloading python_binance-0.5.6-py2.py3-none-any.whl
Collecting requests (from python-binance)
Downloading requests-2.18.4-py2.py3-none-any.whl (88kB)
100% |████████████████████████████████| 92kB 117kB/s
Collecting six (from python-binance)
Using cached six-1.11.0-py2.py3-none-any.whl
Collecting autobahn (from python-binance)
Downloading autobahn-17.10.1-py2.py3-none-any.whl (283kB)
100% |████████████████████████████████| 286kB 35kB/s
Collecting pyOpenSSL (from python-binance)
Downloading pyOpenSSL-17.5.0-py2.py3-none-any.whl (53kB)
100% |████████████████████████████████| 61kB 41kB/s
Collecting Twisted (from python-binance)
Downloading Twisted-17.9.0.tar.bz2 (3.0MB)
100% |████████████████████████████████| 3.0MB 51kB/s
Collecting service-identity (from python-binance)
Downloading service_identity-17.0.0-py2.py3-none-any.whl
Collecting urllib3<1.23,>=1.21.1 (from requests->python-binance)
Downloading urllib3-1.22-py2.py3-none-any.whl (132kB)
100% |████████████████████████████████| 133kB 75kB/s
Collecting idna<2.7,>=2.5 (from requests->python-binance)
Downloading idna-2.6-py2.py3-none-any.whl (56kB)
100% |████████████████████████████████| 61kB 91kB/s
Collecting chardet<3.1.0,>=3.0.2 (from requests->python-binance)
Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB)
100% |████████████████████████████████| 143kB 48kB/s
Collecting certifi>=2017.4.17 (from requests->python-binance)
Downloading certifi-2017.11.5-py2.py3-none-any.whl (330kB)
100% |████████████████████████████████| 337kB 80kB/s
Collecting txaio>=2.7.0 (from autobahn->python-binance)
Downloading txaio-2.8.2-py2.py3-none-any.whl
Collecting cryptography>=2.1.4 (from pyOpenSSL->python-binance)
Downloading cryptography-2.1.4-cp27-cp27mu-manylinux1_x86_64.whl (2.2MB)
100% |████████████████████████████████| 2.2MB 45kB/s
Collecting zope.interface>=3.6.0 (from Twisted->python-binance)
Downloading zope.interface-4.4.3-cp27-cp27mu-manylinux1_x86_64.whl (170kB)
100% |████████████████████████████████| 174kB 91kB/s
Collecting constantly>=15.1 (from Twisted->python-binance)
Downloading constantly-15.1.0-py2.py3-none-any.whl
Collecting incremental>=16.10.1 (from Twisted->python-binance)
Downloading incremental-17.5.0-py2.py3-none-any.whl
Collecting Automat>=0.3.0 (from Twisted->python-binance)
Downloading Automat-0.6.0-py2.py3-none-any.whl
Collecting hyperlink>=17.1.1 (from Twisted->python-binance)
Downloading hyperlink-17.3.1-py2.py3-none-any.whl (73kB)
100% |████████████████████████████████| 81kB 91kB/s
Collecting pyasn1 (from service-identity->python-binance)
Downloading pyasn1-0.4.2-py2.py3-none-any.whl (71kB)
100% |████████████████████████████████| 71kB 87kB/s
Collecting attrs (from service-identity->python-binance)
Downloading attrs-17.3.0-py2.py3-none-any.whl
Collecting pyasn1-modules (from service-identity->python-binance)
Downloading pyasn1_modules-0.2.1-py2.py3-none-any.whl (60kB)
100% |████████████████████████████████| 61kB 66kB/s
Collecting cffi>=1.7; platform_python_implementation != "PyPy" (from cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading cffi-1.11.2-cp27-cp27mu-manylinux1_x86_64.whl (405kB)
100% |████████████████████████████████| 409kB 72kB/s
Collecting enum34; python_version < "3" (from cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading enum34-1.1.6-py2-none-any.whl
Collecting asn1crypto>=0.21.0 (from cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading asn1crypto-0.24.0-py2.py3-none-any.whl (101kB)
100% |████████████████████████████████| 102kB 41kB/s
Collecting ipaddress; python_version < "3" (from cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading ipaddress-1.0.19.tar.gz
Collecting setuptools (from zope.interface>=3.6.0->Twisted->python-binance)
Downloading setuptools-38.2.4-py2.py3-none-any.whl (489kB)
100% |████████████████████████████████| 491kB 48kB/s
Collecting pycparser (from cffi>=1.7; platform_python_implementation != "PyPy"->cryptography>=2.1.4->pyOpenSSL->python-binance)
Downloading pycparser-2.18.tar.gz (245kB)
100% |████████████████████████████████| 256kB 50kB/s
Building wheels for collected packages: Twisted, ipaddress, pycparser
Running setup.py bdist_wheel for Twisted ... done
Stored in directory: /home/kint/.cache/pip/wheels/91/c7/95/0bb4d45bc4ed91375013e9b5f211ac3ebf4138d8858f84abbc
Running setup.py bdist_wheel for ipaddress ... done
Stored in directory: /home/kint/.cache/pip/wheels/d7/6b/69/666188e8101897abb2e115d408d139a372bdf6bfa7abb5aef5
Running setup.py bdist_wheel for pycparser ... done
Stored in directory: /home/kint/.cache/pip/wheels/95/14/9a/5e7b9024459d2a6600aaa64e0ba485325aff7a9ac7489db1b6
Successfully built Twisted ipaddress pycparser
Installing collected packages: urllib3, idna, chardet, certifi, requests, six, txaio, autobahn, pycparser, cffi, enum34, asn1crypto, ipaddress, cryptography, pyOpenSSL, setuptools, zope.interface, constantly, incremental, attrs, Automat, hyperlink, Twisted, pyasn1, pyasn1-modules, service-identity, python-binance
Successfully installed Automat-0.6.0 Twisted-17.9.0 asn1crypto-0.24.0 attrs-17.3.0 autobahn-17.10.1 certifi-2017.11.5 cffi-1.11.2 chardet-3.0.4 constantly-15.1.0 cryptography-2.1.4 enum34-1.1.6 hyperlink-17.3.1 idna-2.6 incremental-17.5.0 ipaddress-1.0.19 pyOpenSSL-17.5.0 pyasn1-0.4.2 pyasn1-modules-0.2.1 pycparser-2.18 python-binance-0.5.6 requests-2.18.4 service-identity-17.0.0 setuptools-38.2.4 six-1.11.0 txaio-2.8.2 urllib3-1.22 zope.interface-4.4.3
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
kint@ubuntu:/block$ cd python-binance/
kint@ubuntu:
/block/python-binance$ ls
binance docs LICENSE PYPIREADME.rst README.rst requirements.txt setup.cfg setup.py test-requirements.txt tests tox.ini
kint@ubuntu:/block/python-binance$ cd tests/
kint@ubuntu:
/block/python-binance/tests$ python test
test_api_request.py test.py

kint@ubuntu:~/block/python-binance/tests$ python test.py
Traceback (most recent call last):
File "test.py", line 1, in
from binance.client import Client
ImportError: No module named 'binance'

market_order can not pass validation

client = Client(config.account['key'], config.account['secret'])
order = client.order_market_buy(
    symbol='BCPTBNB',
    quantity=1,
    #newOrderRespType='FULL'
    )

and I got following, but market order just has no 'price' parameter

Traceback (most recent call last):
  File "test.py", line 18, in <module>
    quantity=1,
  File "C:\Python27\lib\site-packages\binance\client.py", line 650, in order_market_buy
    return self.order_market(disable_validation=disable_validation, **params)
  File "C:\Python27\lib\site-packages\binance\client.py", line 619, in order_market
    return self.create_order(disable_validation=disable_validation, **params)
  File "C:\Python27\lib\site-packages\binance\client.py", line 465, in create_order
    validate_order(params, self._products)
  File "C:\Python27\lib\site-packages\binance\validation.py", line 40, in validate_order
    price = float(params['price'])
KeyError: 'price'

how do i exit BinanceSocketManager?

bm = BinanceSocketManager(client)
conn_key = bm.start_depth_socket(symbol, process_book, depth=BinanceSocketManager.WEBSOCKET_DEPTH_5)
bm.start()
bm.close()

after bm.close(), still receive message

binance.exceptions.BinanceAPIException: APIError(code=-1022): Signature for this request is not valid.

Hi!

First of all, thank you for the implementation!

However I run into a problem and hoping for your help.
I am using this code.

from binance import client

APIKEY_BINANCE ='XXXXXX'
SECRETKEY_BINANCE = 'XXXXXX'

client = client.Client(APIKEY_BINANCE, SECRETKEY_BINANCE)

print(client.get_account()`

For some reason, a lot of my requests do not go through due to the signature, resulting in this error:

{"code":-1022,"msg":"Signature for this request is not valid."}
Traceback (most recent call last):
  File "/home/huynh/PycharmProjects/gdax_rl/binance_test.py", line 13, in <module>
    print(client.get_account())
  File "/home/huynh/PycharmProjects/gdax_rl/binance/client.py", line 311, in get_account
    return self._get('account', True, data=params)
  File "/home/huynh/PycharmProjects/gdax_rl/binance/client.py", line 101, in _get
    return self._request('get', path, signed, **kwargs)
  File "/home/huynh/PycharmProjects/gdax_rl/binance/client.py", line 73, in _request
    return self._handle_response(response)
  File "/home/huynh/PycharmProjects/gdax_rl/binance/client.py", line 97, in _handle_response
    raise BinanceAPIException(response)
binance.exceptions.BinanceAPIException: APIError(code=-1022): Signature for this request is not valid.

Process finished with exit code 1

However, some requests work without a problem.

Do you know how I can fix that?

Best regards,

Install issue....

3.4\twisted\words\im
    copying src\twisted\words\xish\xpathparser.g -> build\lib.win-amd64-3.4\twis
ted\words\xish
    running build_ext
    building 'twisted.test.raiser' extension
    error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows
 SDK 7.1": www.microsoft.com/download/details.aspx?id=8279

    ----------------------------------------
Command "c:\python34\python.exe -u -c "import setuptools, tokenize;__file__='C:\
\Users\\Alex\\AppData\\Local\\Temp\\pip-build-3scyxu0w\\Twisted\\setup.py';f=get
attr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.clo
se();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Alex\AppDa
ta\Local\Temp\pip-aeidjyp5-record\install-record.txt --single-version-externally
-managed --compile" failed with error code 1 in C:\Users\Alex\AppData\Local\Temp
\pip-build-3scyxu0w\Twisted\

I have tried setting my location of my env var as described here, still doesn't fix the issue.
Proposed solutions here

Installation error against Python 2.7.6

Python Version: 2.7.6
OS: Ubuntu 14 LTS
PIP: 1.5.4

The following error is seen when installing via pip install.

Downloading/unpacking cryptography>=1.9 (from pyOpenSSL->python-binance)
Downloading cryptography-2.1.2.tar.gz (441kB): 441kB downloaded
Running setup.py (path:/home/caof/.virtual_envs/biance_ve/build/cryptography/setup.py) egg_info for package cryptography
error in cryptography setup command: Invalid environment marker: python_version < '3'
Complete output from command python setup.py egg_info:
error in cryptography setup command: Invalid environment marker: python_version < '3'


Cleaning up...

It seems like the dependent library cryptography doesn't support python 2.x

Invalid LOT size

2017-12-20 03:00:01 buying 0.00572925 at: 7.394e-05 (VENBTC)

gives me APIError(code=-1013): Filter failure: LOT_SIZE

I used client.order_market_buy()

Flaky Validation Test

if quantity / min_trade - int(quantity / min_trade) > 0.0:

quantity = 2.24
min_trade = 0.01

quantity / min_trade  
# 224.00000000000003
print quantity / min_trade  
# 224.0
print quantity / min_trade - int(quantity / min_trade) > 0.0  
# True
print 224.0 - int(quantity / min_trade) > 0.0  
# False

I think that the float division is causing a weird rounding error typical of python. I don't have a nice fix for this yet, but wanted to let you know at least.

Websockets is not working

After the binance update, websockets do not work. I try to use the code of bm.start_trade_socket and cant get the values of last trades

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.