Git Product home page Git Product logo

binance-connector-python's Introduction

Binance Public API Connector Python

PyPI version Python version Documentation Code Style License: MIT

This is a lightweight library that works as a connector to Binance public API

  • Supported APIs:
    • /api/*
    • /sapi/*
    • Spot Websocket Market Stream
    • Spot User Data Stream
    • Spot WebSocket API
  • Inclusion of test cases and examples
  • Customizable base URL, request timeout and HTTP proxy
  • Response metadata can be displayed

Installation

pip install binance-connector

Documentation

https://binance-connector.readthedocs.io

RESTful APIs

Usage examples:

from binance.spot import Spot

client = Spot()

# Get server timestamp
print(client.time())
# Get klines of BTCUSDT at 1m interval
print(client.klines("BTCUSDT", "1m"))
# Get last 10 klines of BNBUSDT at 1h interval
print(client.klines("BNBUSDT", "1h", limit=10))

# API key/secret are required for user data endpoints
client = Spot(api_key='<api_key>', api_secret='<api_secret>')

# Get account and balance information
print(client.account())

# Post a new order
params = {
    'symbol': 'BTCUSDT',
    'side': 'SELL',
    'type': 'LIMIT',
    'timeInForce': 'GTC',
    'quantity': 0.002,
    'price': 9500
}

response = client.new_order(**params)
print(response)

Please find examples folder to check for more endpoints.

  • In order to set your API and Secret Key for use of the examples, create a file examples/config.ini with your keys.
  • Eg:
    # examples/config.ini
    [keys]
    api_key=abc123456
    api_secret=cba654321

Authentication

Binance supports HMAC, RSA and ED25519 API authentication.

# HMAC: pass API key and secret
client = Client(api_key, api_secret)
print(client.account())

# RSA Keys
client = Client(api_key=api_key, private_key=private_key)
print(client.account())

# ED25519 Keys
api_key = ""
private_key = "./private_key.pem"
private_key_pass = "<password_if_applicable>"

with open(private_key, 'rb') as f:
    private_key = f.read()

spot_client = Client(api_key=api_key, private_key=private_key, private_key_pass=private_key_pass)

# Encrypted RSA Key
client = Client(api_key=api_key, private_key=private_key, private_key_pass='password')
print(client.account())

Please find examples/spot/wallet/account_snapshot.py for more details on ED25519. Please find examples/spot/trade/get_account.py for more details on RSA.

Testnet

Spot Testnet is available, it can be used to test /api/* endpoints.

To use testnet:

from binance.spot import Spot as Client

client = Client(base_url='https://testnet.binance.vision')
print(client.time())

Base URL

If base_url is not provided, it defaults to api.binance.com.
It's recommended to pass in the base_url parameter, even in production as Binance provides alternative URLs in case of performance issues:

  • https://api1.binance.com
  • https://api2.binance.com
  • https://api3.binance.com

Optional parameters

PEP8 suggests lowercase with words separated by underscores, but for this connector, the methods' optional parameters should follow their exact naming as in the API documentation.

# Recognised parameter name
response = client.cancel_oco_order('BTCUSDT', orderListId=1)

# Unrecognised parameter name
response = client.cancel_oco_order('BTCUSDT', order_list_id=1)

RecvWindow parameter

Additional parameter recvWindow is available for endpoints requiring signature.
It defaults to 5000 (milliseconds) and can be any value lower than 60000(milliseconds). Anything beyond the limit will result in an error response from Binance server.

from binance.spot import Spot as Client

client = Client(api_key, api_secret)
response = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)

Timeout

timeout is available to be assigned with the number of seconds you find most appropriate to wait for a server response.
Please remember the value as it won't be shown in error message no bytes have been received on the underlying socket for timeout seconds.
By default, timeout is None. Hence, requests do not time out.

from binance.spot import Spot as Client

client= Client(timeout=1)

Proxy

Proxy is supported.

from binance.spot import Spot as Client

proxies = { 'https': 'http://1.2.3.4:8080' }

client= Client(proxies=proxies)

Response Metadata

The Binance API server provides weight usages in the headers of each response. You can display them by initializing the client with show_limit_usage=True:

from binance.spot import Spot as Client

client = Client(show_limit_usage=True)
print(client.time())

returns:

{'data': {'serverTime': 1587990847650}, 'limit_usage': {'x-mbx-used-weight': '31', 'x-mbx-used-weight-1m': '31'}}

You can also display full response metadata to help in debugging:

client = Client(show_header=True)
print(client.time())

returns:

{'data': {'serverTime': 1587990847650}, 'header': {'Context-Type': 'application/json;charset=utf-8', ...}}

If ClientError is received, it'll display full response meta information.

Display logs

Setting the log level to DEBUG will log the request URL, payload and response text.

Error

There are 2 types of error returned from the library:

  • binance.error.ClientError
    • This is thrown when server returns 4XX, it's an issue from client side.
    • It has 5 properties:
      • status_code - HTTP status code
      • error_code - Server's error code, e.g. -1102
      • error_message - Server's error message, e.g. Unknown order sent.
      • header - Full response header.
      • error_data* - Additional detailed data which supplements the error_message.
        • *Only applicable on select endpoints, eg. cancelReplace
  • binance.error.ServerError
    • This is thrown when server returns 5XX, it's an issue from server side.

Websocket

Connector v3

WebSocket can be established through either of the following types of connections:

  • WebSocket API (https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md)
  • WebSocket Stream (https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md)
# WebSocket API Client
from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient

def message_handler(_, message):
    logging.info(message)

my_client = SpotWebsocketAPIClient(on_message=message_handler)

my_client.ticker(symbol="BNBBUSD", type="FULL")

time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
# WebSocket Stream Client
from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient

def message_handler(_, message):
    logging.info(message)

my_client = SpotWebsocketStreamClient(on_message=message_handler)

# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()

Proxy

Proxy is supported for both WebSocket API and WebSocket Stream.

To use it, pass in the proxies parameter when initializing the client.

The format of the proxies parameter is the same as the one used in the Spot RESTful API.

It consists on a dictionary with the following format, where the key is the type of the proxy and the value is the proxy URL:

For websockets, the proxy type is http.

proxies = { 'http': 'http://1.2.3.4:8080' }

You can also use authentication for the proxy by adding the username and password parameters to the proxy URL:

proxies = { 'http': 'http://username:password@host:port' }
# WebSocket API Client
from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient

def message_handler(_, message):
    logging.info(message)

proxies = { 'http': 'http://1.2.3.4:8080' }

my_client = SpotWebsocketAPIClient(on_message=message_handler, proxies=proxies, timeout=10)

my_client.ticker(symbol="BNBBUSD", type="FULL")

time.sleep(5)
logging.info("closing ws connection")
my_client.stop()
# WebSocket Stream Client
from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient

def message_handler(_, message):
    logging.info(message)

proxies = { 'http': 'http://1.2.3.4:8080' }

my_client = SpotWebsocketStreamClient(on_message=message_handler, proxies=proxies, timeout=10)

# Subscribe to a single symbol stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
logging.info("closing ws connection")
my_client.stop()

Request Id

Client can assign a request id to each request. The request id will be returned in the response message. Not mandatory in the library, it generates a uuid format string if not provided.

# id provided by client
my_client.ping_connectivity(id="my_request_id")

# library will generate a random uuid string
my_client.ping_connectivity()

Combined Streams

  • If you set is_combined to True, "/stream/" will be appended to the baseURL to allow for Combining streams.
  • is_combined defaults to False and "/ws/" (raw streams) will be appended to the baseURL.

More websocket examples are available in the examples folder.

Example file "examples/websocket_api/app_demo.py" demonstrates how Websocket API and Websocket Stream can be used together.

Connector v1 and v2

from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient

def message_handler(message):
    print(message)

ws_client = WebsocketClient()
ws_client.start()

ws_client.mini_ticker(
    symbol='bnbusdt',
    id=1,
    callback=message_handler,
)

# Combine selected streams
ws_client.instant_subscribe(
    stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],
    callback=message_handler,
)

ws_client.stop()

Heartbeat

Once connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within a 10 minutes period. This package handles the pong responses automatically.

Testnet

from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient

ws_client = WebsocketClient(stream_url='wss://testnet.binance.vision')

Test Case

# In case packages are not installed yet
pip install -r requirements/requirements-test.txt

python -m pytest tests/

Limitation

Futures and Vanilla Options APIs are not supported:

  • /fapi/*
  • /dapi/*
  • /vapi/*
  • Associated Websocket Market and User Data Streams

Contributing

Contributions are welcome.
If you've found a bug within this project, please open an issue to discuss what you would like to change.
If it's an issue with the API, please open a topic at Binance Developer Community

binance-connector-python's People

Contributors

2pd avatar aisling-2 avatar aisling11 avatar alplabin avatar byildiz avatar chairz avatar chairz-2 avatar crmoratelli avatar eliaonceagain avatar jonte-z avatar tantialex avatar trkzmn avatar urbanogt 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

binance-connector-python's Issues

Trade websocket doesn't receive data (SSL error: certificate verify failed)

When trying to run the trade websocket example, I always get the following message:

INFO:root:Connection with URL: wss://stream.binance.com:9443/ws
INFO:root:Start to connect....
WARNING:root:WebSocket connection closed: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate)), code: 1006, clean: False, reason: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate))
ERROR:root:Lost connection to Server. Reason: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.
]. Retrying: 1

After that it tries again for four times and doesn't print any messages. All dependencies are installed. On the testnet it doesn't work neither.

Do you have any ideas how to solve it?

Timestamp out of recvWindow when pinging test api.

issue subject

Running the example code on the test api leads to a Timestamp for this request is outside of the recvWindow error.

repro

from binance.spot import Spot 

client = Spot()
print(client.time())

client = Spot(base_url='https://testnet.binance.vision', key='<api_key>', secret='<api_secret>')

# Get account information
print(client.account()) # error here

I have also tried passing a timestamp (sourced from client.time()['serverTime']) and setting recvWindow=60000, to no avail.

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python - binance-connector==1.8.0
  • Python version - Python 3.9.9
  • Operating system - x86_64 GNU/Linux, (5.10.83-1-MANJARO )

websocket如何获取合并精度的市场深度?

例如想获取精度分别为0.1 / 1 / 10的有限档市场深度,应该怎么做?
现有的api似乎无法指定精度,比如订阅btcusdt@depth20,只能拿到20档,精确到0.01的深度,似乎不能取精确到10的深度。

binance.error.ClientError: (400, -1104, "Not all sent parameters were read; read '2' parameter(s) but was sent '3'.",

Before submitting a new issue, please check if a similar issue has already been filed.

Issue subject

I'm getting the error:
E binance.error.ClientError: (400, -1104, "Not all sent parameters were read; read '2' parameter(s) but was sent '3'.", {'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '97', 'Connection': 'keep-alive', 'Date': 'Wed, 18 Aug 2021 03:49:05 GMT', 'Server': 'nginx', 'x-mbx-uuid': 'b2481ad6-f0c5-4184-a2d5-43668f05b317', 'x-mbx-used-weight': '1', 'x-mbx-used-weight-1m': '1', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'self'", 'X-Content-Security-Policy': "default-src 'self'", 'X-WebKit-CSP': "default-src 'self'", 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 ce6cbaba4ae4791f264842567fcc912a.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'ORD52-C1', 'X-Amz-Cf-Id': 'fPUJC6XOwaTJjZVrShUCvNDu9nss5fAQ6v8ENWt1nqivAr5an0BbAA=='})
when passing start_time as an argument to Spot().klines()

Expected behaviour

I should get a list of klines data delimited by start_time just like when I send a request directly to the api like: /api/v3/klines?symbol=BNBUSDT&interval=1d&startTime=1619845200000&endTime=1627794000000

Actual behaviour

Throws the abovementioned error

Steps to reproduce

  1. Create a Spot instance
    client = Spot(base_url="https://testnet.binance.vision", key=bnb_client_key, secret=bnb_client_secret)
  2. Call the klinesmethod passing a value to start_time
    client.klines(symbol='BNBUSDT', interval=1d, start_time=1619845200000)

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python
    1.4.0
  • Python version
    3.7
  • Operating system
    Mac Big Sur 11.5.1

Async support

Before submitting a new issue, please check if a similar issue has already been filed.

Issue subject

Can you create async classes, based on httpx or aiohttp client.

Expected behaviour

Async support for api

Actual behaviour

Only sync connector supported

TimeoutError: [WinError 10060]

Issue subject

This code would raise the error.

from binance.spot import Spot
client2 = Spot(key='...', secret='...')
print(client2.ticker_price())

but use testnet is OK.

client2 = Spot(base_url='https://testnet.binance.vision',
               key='...',
               secret='...')
print(client2.ticker_price())

and I can get all price using Chrome -> https://api.binance.com/api/v3/ticker/price
but not Spot in Pycharm

Expected behaviour

D:\Anaconda\python.exe E:/PythonProjects/BinanceArbitrage/main.py
Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
conn = connection.create_connection(
File "D:\Anaconda\lib\site-packages\urllib3\util\connection.py", line 84, in create_connection
raise err
File "D:\Anaconda\lib\site-packages\urllib3\util\connection.py", line 74, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
httplib_response = self._make_request(
File "D:\Anaconda\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
self._validate_conn(conn)
File "D:\Anaconda\lib\site-packages\urllib3\connectionpool.py", line 976, in _validate_conn
conn.connect()
File "D:\Anaconda\lib\site-packages\urllib3\connection.py", line 308, in connect
conn = self._new_conn()
File "D:\Anaconda\lib\site-packages\urllib3\connection.py", line 171, in _new_conn
raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x000001C47AA92070>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\requests\adapters.py", line 439, in send
resp = conn.urlopen(
File "D:\Anaconda\lib\site-packages\urllib3\connectionpool.py", line 724, in urlopen
retries = retries.increment(
File "D:\Anaconda\lib\site-packages\urllib3\util\retry.py", line 439, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.binance.com', port=443): Max retries exceeded with url: /api/v3/ticker/price (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000001C47AA92070>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "E:/PythonProjects/BinanceArbitrage/main.py", line 11, in
print(client2.ticker_price())
File "D:\Anaconda\lib\site-packages\binance\spot\market.py", line 205, in ticker_price
return self.query("/api/v3/ticker/price", params)
File "D:\Anaconda\lib\site-packages\binance\api.py", line 68, in query
return self.send_request("GET", url_path, payload=payload)
File "D:\Anaconda\lib\site-packages\binance\api.py", line 115, in send_request
response = self._dispatch_request(http_method)(**params)
File "D:\Anaconda\lib\site-packages\requests\sessions.py", line 555, in get
return self.request('GET', url, **kwargs)
File "D:\Anaconda\lib\site-packages\requests\sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "D:\Anaconda\lib\site-packages\requests\sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "D:\Anaconda\lib\site-packages\requests\adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.binance.com', port=443): Max retries exceeded with url: /api/v3/ticker/price (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000001C47AA92070>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'))

Process finished with exit code 1

Environment

Provide any relevant information about your setup, such as:
Version of binance-connector-python lastest
Python version 3.8
Operating system win10
IDE Pycharm

SSL: WRONG_VERSION_NUMBER

Hi,
I use a proxy to access the api and it crashes with SSL: WRONG_VERSION_NUMBER.
How can I fix it?

code:

import logging
from binance.spot import Spot as Client

proxies = { 'https': 'http://192.168.50.60:3213' }

spot_client = Client(base_url='https://api2.binance.com', proxies=proxies)
print(spot_client.ping())

output:

Traceback (most recent call last):
  File "/home/panzhida/miniconda3/lib/python3.8/site-packages/urllib3/connectionpool.py", line 667, in urlopen
    self._prepare_proxy(conn)
  File "/home/panzhida/miniconda3/lib/python3.8/site-packages/urllib3/connectionpool.py", line 932, in _prepare_proxy
    conn.connect()
  File "/home/panzhida/miniconda3/lib/python3.8/site-packages/urllib3/connection.py", line 362, in connect
    self.sock = ssl_wrap_socket(
  File "/home/panzhida/miniconda3/lib/python3.8/site-packages/urllib3/util/ssl_.py", line 386, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "/home/panzhida/miniconda3/lib/python3.8/ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "/home/panzhida/miniconda3/lib/python3.8/ssl.py", line 1040, in _create
    self.do_handshake()
  File "/home/panzhida/miniconda3/lib/python3.8/ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1123)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/panzhida/miniconda3/lib/python3.8/site-packages/requests/adapters.py", line 439, in send
    resp = conn.urlopen(
  File "/home/panzhida/miniconda3/lib/python3.8/site-packages/urllib3/connectionpool.py", line 726, in urlopen
    retries = retries.increment(
  File "/home/panzhida/miniconda3/lib/python3.8/site-packages/urllib3/util/retry.py", line 446, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api2.binance.com', port=443): Max retries exceeded with url: /api/v3/ping (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1123)')))

Avoid pinning specific dependency versions

Issue subject

Dependencies are specified in requirements/*.txt with == versioning (example), against Python's best-practice guidance here.

This can cause conflicts in projects which have incompatible version requirements

Expected behaviour

Module dependencies should be as unrestrictive as possible.
If no known incompatibilities exist, then simply specify the package name, or if certain versions are known to be incompatible then use A>=1,<2 style versioning.

Actual behaviour

Dependencies are pinned to specific versions.

Steps to reproduce

N/A

Environment

N/A

Futures consult dont match with wallet balance

I'm trying to use Spot with Futures module to consult USER_DATA, but the data I get from the API (almost all NULL results), dont match with the wallet balances that I see in Binance.

I'm using the following code:

from binance.spot import Spot as Client

client.futures_loan_liquidation_history(collateralCoin="BTC")
client.futures_loan_repay_history(coin="USDTPERP")
client.futures_loan_configs(collateralCoin="BTC")
client.futures_loan_adjust_collateral_history(collateralCoin="BTC")
client.futures_loan_borrow_history(coin="USDTPERP")
client.futures_loan_interest_history()

And the output:

{'total': 0, 'rows': []}
{'total': 0, 'rows': []}
[{'collateralCoin': 'BTC', 'rate': '0.65', 'marginCallCollateralRate': '0.8', 'liquidationCollateralRate': '0.9', 'currentCollateralRate': '0', 'interestRate': '0.0024', 'interestGracePeriod': '2', 'loanCoin': 'USDT'}, {'collateralCoin': 'BTC', 'rate': '0.65', 'marginCallCollateralRate': '0.8', 'liquidationCollateralRate': '0.9', 'currentCollateralRate': '0', 'interestRate': '0.0024', 'interestGracePeriod': '2', 'loanCoin': 'BUSD'}]
{'total': 0, 'rows': []}
{'total': 0, 'rows': []}
{'total': 0, 'rows': []}

  • Version of binance-connector-python: 1.5.0
  • Python version: 3.6.9
  • Operating system: Ubuntu 18.04

Error to install with Docker Python3.9.6 Alpine 3.1.4

Hi have tried to install it in a container with Python 3.9.6 and Alpine 3.14 and I got the following error message:

ERROR: Command errored out with exit status 1:
command: /usr/local/bin/python /tmp/pip-standalone-pip-mtf2xy07/env_pip.zip/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-80k39b7z/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.6.0' wheel 'cffi>=1.8,!=1.11.3; platform_python_implementation != '"'"'PyPy'"'"''
cwd: None
Complete output (118 lines):
Collecting setuptools>=40.6.0
Using cached setuptools-58.0.4-py3-none-any.whl (816 kB)
Collecting wheel
Using cached wheel-0.37.0-py2.py3-none-any.whl (35 kB)
Collecting cffi!=1.11.3,>=1.8
Using cached cffi-1.14.6.tar.gz (475 kB)
Collecting pycparser
Using cached pycparser-2.20-py2.py3-none-any.whl (112 kB)
Building wheels for collected packages: cffi
Building wheel for cffi (setup.py): started
Building wheel for cffi (setup.py): finished with status 'error'
ERROR: Command errored out with exit status 1:
command: /usr/local/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-411s5dew/cffi_f8429fcf63d14a70bac556ec50d26d87/setup.py'"'"'; file='"'"'/tmp/pip-install-411s5dew/cffi_f8429fcf63d14a70bac556ec50d26d87/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-i3fqerf1
cwd: /tmp/pip-install-411s5dew/cffi_f8429fcf63d14a70bac556ec50d26d87/
Complete output (45 lines):

    No working compiler found, or bogus compiler options passed to
    the compiler from Python's standard "distutils" module.  See
    the error messages above.  Likely, the problem is not related
    to CFFI but generic to the setup.py of any Python package that
    tries to compile C code.  (Hints: on OS/X 10.8, for errors about
    -mno-fused-madd see http://stackoverflow.com/questions/22313407/
    Otherwise, see https://wiki.python.org/moin/CompLangPython or
    the IRC channel #python on irc.libera.chat.)

    Trying to continue anyway.  If you are trying to install CFFI from
    a build done in a different context, you can ignore this warning.

running bdist_wheel
running build
running build_py
creating build
creating build/lib.linux-x86_64-3.9
creating build/lib.linux-x86_64-3.9/cffi
copying cffi/__init__.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/backend_ctypes.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/cffi_opcode.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/lock.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/vengine_cpy.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/setuptools_ext.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/ffiplatform.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/model.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/error.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/cparser.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/recompiler.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/verifier.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/api.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/commontypes.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/vengine_gen.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/pkgconfig.py -> build/lib.linux-x86_64-3.9/cffi
copying cffi/_cffi_include.h -> build/lib.linux-x86_64-3.9/cffi
copying cffi/parse_c_type.h -> build/lib.linux-x86_64-3.9/cffi
copying cffi/_embedding.h -> build/lib.linux-x86_64-3.9/cffi
copying cffi/_cffi_errors.h -> build/lib.linux-x86_64-3.9/cffi
running build_ext
building '_cffi_backend' extension
creating build/temp.linux-x86_64-3.9
creating build/temp.linux-x86_64-3.9/c

SSL error: certificate verify failed

I tried to run examples/websocket/spot/symbol_kline.py
but got SSl error

the error msg i got:
(SSL error: certificate verify failed (in tls_process_server_certificate)), code: 1006, clean: False, reason: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate))

full error:
2022-04-10 09:59:07.921 UTC INFO binance.websocket.binance_socket_manager: Connection with URL: wss://stream.binance.com:9443/ws
2022-04-10 09:59:07.925 UTC INFO binance.websocket.binance_client_factory: Start to connect....
2022-04-10 09:59:08.747 UTC WARNING binance.websocket.binance_client_protocol: WebSocket connection closed: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate)), code: 1006, clean: False, reason: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate))
2022-04-10 09:59:08.754 UTC ERROR binance.websocket.binance_client_factory: Lost connection to Server. Reason: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.

Environment

  • Version of binance-connector-python 1.11.0
  • Python version = 3.10.04
  • Operating system = windows 11

Can't run any websocket example

Normal spot examples run fine but when I run any websocket example I get this error:

INFO:root:Start to connect....
WARNING:root:WebSocket connection closed: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate)), code: 1006, clean: False, reason: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate))
ERROR:root:Lost connection to Server. Reason: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.
]. Retrying: 2

Could you help me fix this issue ?

Error APIError(code=-1013): Filter failure: LOT_SIZE

Before submitting a new issue, please check if a similar issue has already been filed.

Issue subject

Keep getting LOT_SIZE error while trying to SELL, calling create_order .

Expected behavior

Sell of the currency.

Actual behavior

I receive the error APIError(code=-1013): Filter failure: LOT_SIZE.

Steps to reproduce

Call create_order with params:

BC.create_order(symbol=symbol, side=side, type=ORDER_TYPE_MARKET, quoteOrderQty=quantity)

Where:
symbol = SIDE_SELL
quoteOrderQty = 229.37062937

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python
    • python-binance==1.0.15
  • Python version
    • Python 3.8.10
  • Operating system
    • Ubuntu 20.04.1

Trivial test program hangs

Before submitting a new issue, please check if a similar issue has already been filed.

Trivial websocket program hangs

If only a websocket instance is created and start()ed, it will hang if stop() is called without executing a subscription (for instance).

Expected behaviour

A websocket program should terminate gracefully and immediately after calling stop()

Actual behaviour

Program does not terminate.

Steps to reproduce

from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient

ws_client = WebsocketClient()
ws_client.start()
ws_client.stop()

Environment

Default system and setup

Connection reset by peer

Hi all, I regularly encountered this error while querying tick_price. How can I fix this problem?

E0713 15:17:06.131145 4108157 binance_handler.py:414] Failed when querying ticker_price! ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

mypy support

Hello everyone 👋

It should be great if this library could pass the mypy (--strict) static typing checker ✅

Thanks

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.binance.com', port=443): Max retries exceeded with url: /api/v3/ping (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x000000306BFA9340>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

hi how are you

i have a error to request to binance but i request with colab google have not error and ok .
thank you very much for reply me about error

i search very much in multiple website

good luck
god willing

limit order

我有一个限价单, 部分成交, 那么撤销该限价单, 那么成交的部分会撤销吗? 那位表弟给解释一下

Exchange Information - Add symbol as optional parameter

New simple feature

It would be helpfull to add optional symbol parameter for this:
https://binance-connector.readthedocs.io/en/latest/binance.spot.market.html#binance.spot.market.exchange_info

Original Binance API supports it so it only needs to pass it inside.
https://binance-docs.github.io/apidocs/spot/en/#exchange-information

Now default exchange_info() returns so much useless informations and you need filter it by symbol you looking for.
Its same situation like ticker_price() you can get prices of all symbols by ommiting parametr or simple one by providing it.

How to config proxy in websocket in the example

Before submitting a new issue, please check if a similar issue has already been filed.

Issue subject

Briefly describe the issue here.
Currently,I can access https://api.binance.com succssfully, while unfortunately it fails when I intend to connect wss://stream.binance.com:9443

Expected behaviour

Describe what should happen.
connect successfully

Actual behaviour

Describe what happens instead. Please include the complete failure message.
ERROR:root:Can't connect to server. Reason: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.TCPTimedOutError'>: TCP connection timed out: 10060:

Steps to reproduce

Provide steps to let us know how we can reproduce this issue.
run examples in websocket spot

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python
  • Python version
  • Operating system
    Python 3.7.8
    Windows10

Unhandled Error

Unhandled Error
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/twisted/python/log.py", line 96, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/usr/local/lib/python3.6/site-packages/twisted/python/log.py", line 80, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/usr/local/lib/python3.6/site-packages/twisted/python/context.py", line 117, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/local/lib/python3.6/site-packages/twisted/python/context.py", line 82, in callWithContext
return func(*args, **kw)
--- ---
File "/usr/local/lib/python3.6/site-packages/twisted/internet/posixbase.py", line 683, in _doReadOrWrite
why = selectable.doRead()
File "/usr/local/lib/python3.6/site-packages/twisted/internet/tcp.py", line 248, in doRead
return self._dataReceived(data)
File "/usr/local/lib/python3.6/site-packages/twisted/internet/tcp.py", line 253, in _dataReceived
rval = self.protocol.dataReceived(data)
File "/usr/local/lib/python3.6/site-packages/twisted/protocols/tls.py", line 330, in dataReceived
self._flushReceiveBIO()
File "/usr/local/lib/python3.6/site-packages/twisted/protocols/tls.py", line 296, in _flushReceiveBIO
ProtocolWrapper.dataReceived(self, bytes)
File "/usr/local/lib/python3.6/site-packages/twisted/protocols/policies.py", line 110, in dataReceived
self.wrappedProtocol.dataReceived(data)
File "/usr/local/lib/python3.6/site-packages/autobahn/twisted/websocket.py", line 290, in dataReceived
self._dataReceived(data)
File "/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py", line 1207, in _dataReceived
self.consumeData()
File "/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py", line 1219, in consumeData
while self.processData() and self.state != WebSocketProtocol.STATE_CLOSED:
File "/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py", line 1579, in processData
fr = self.onFrameEnd()
File "/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py", line 1704, in onFrameEnd
self._onMessageEnd()
File "/usr/local/lib/python3.6/site-packages/autobahn/twisted/websocket.py", line 318, in _onMessageEnd
self.onMessageEnd()
File "/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py", line 628, in onMessageEnd
self._onMessage(payload, self.message_is_binary)
File "/usr/local/lib/python3.6/site-packages/autobahn/twisted/websocket.py", line 321, in _onMessage
self.onMessage(payload, isBinary)
File "/usr/local/lib/python3.6/site-packages/binance/websocket/binance_client_protocol.py", line 31, in onMessage
self.factory.callback(payload_obj)
File "/root/download/work/coin/trade_strg_03.py", line 218, in message_handler
track.dataSubscribe(message.get('k')['s'],closeP,track.trade,highP)
File "/root/download/work/coin/trade_strg_03.py", line 190, in dataSubscribe
self.strategy.strategy(price,self,trade,highPrice)
File "/root/download/work/coin/trade_strg_03.py", line 75, in strategy
response = trade.tradeClient.new_order(**params)
File "/usr/local/lib/python3.6/site-packages/binance/spot/account.py", line 66, in new_order
return self.sign_request("POST", url_path, params)
File "/usr/local/lib/python3.6/site-packages/binance/api.py", line 83, in sign_request
return self.send_request(http_method, url_path, payload)
File "/usr/local/lib/python3.6/site-packages/binance/api.py", line 117, in send_request
self._handle_exception(response)
File "/usr/local/lib/python3.6/site-packages/binance/api.py", line 170, in _handle_exception
raise ClientError(status_code, err["code"], err["msg"], response.headers)
binance.error.ClientError: (400, -1013, 'Filter failure: LOT_SIZE', {'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '47', 'Connection': 'keep-alive', 'Date': 'Sun, 27 Mar 2022 02:27:44 GMT', 'Server': 'nginx', 'x-mbx-uuid': 'e7b3bf5d-c3f0-4466-8ddf-448206cf16b5', 'x-mbx-used-weight': '57', 'x-mbx-used-weight-1m': '57', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'self'", 'X-Content-Security-Policy': "default-src 'self'", 'X-WebKit-CSP': "default-src 'self'", 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 6806abb26fb4ce0aa6ebca12d6a79246.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'YTO50-C2', 'X-Amz-Cf-Id': 'oCnC15UMcODtHicYpNDobBbxntmqWb1qI37zDusM03H8GcuDW36APA=='})

WebSocket connection closed: connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake), code: 1006, clean: False, reason: connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)
Lost connection to Server. Reason: [Failure instance: Traceback: <class 'binance.error.ClientError'>: (400, -1013, 'Filter failure: LOT_SIZE', {'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '47', 'Connection': 'keep-alive', 'Date': 'Sun, 27 Mar 2022 02:27:44 GMT', 'Server': 'nginx', 'x-mbx-uuid': 'e7b3bf5d-c3f0-4466-8ddf-448206cf16b5', 'x-mbx-used-weight': '57', 'x-mbx-used-weight-1m': '57', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'self'", 'X-Content-Security-Policy': "default-src 'self'", 'X-WebKit-CSP': "default-src 'self'", 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 6806abb26fb4ce0aa6ebca12d6a79246.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'YTO50-C2', 'X-Amz-Cf-Id': 'oCnC15UMcODtHicYpNDobBbxntmqWb1qI37zDusM03H8GcuDW36APA=='})
/usr/local/lib/python3.6/site-packages/twisted/python/log.py:80:callWithContext
/usr/local/lib/python3.6/site-packages/twisted/python/context.py:117:callWithContext
/usr/local/lib/python3.6/site-packages/twisted/python/context.py:82:callWithContext
/usr/local/lib/python3.6/site-packages/twisted/internet/posixbase.py:696:_doReadOrWrite
--- ---
/usr/local/lib/python3.6/site-packages/twisted/internet/posixbase.py:683:_doReadOrWrite
/usr/local/lib/python3.6/site-packages/twisted/internet/tcp.py:248:doRead
/usr/local/lib/python3.6/site-packages/twisted/internet/tcp.py:253:_dataReceived
/usr/local/lib/python3.6/site-packages/twisted/protocols/tls.py:330:dataReceived
/usr/local/lib/python3.6/site-packages/twisted/protocols/tls.py:296:_flushReceiveBIO
/usr/local/lib/python3.6/site-packages/twisted/protocols/policies.py:110:dataReceived
/usr/local/lib/python3.6/site-packages/autobahn/twisted/websocket.py:290:dataReceived
/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py:1207:_dataReceived
/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py:1219:consumeData
/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py:1579:processData
/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py:1704:onFrameEnd
/usr/local/lib/python3.6/site-packages/autobahn/twisted/websocket.py:318:_onMessageEnd
/usr/local/lib/python3.6/site-packages/autobahn/websocket/protocol.py:628:onMessageEnd
/usr/local/lib/python3.6/site-packages/autobahn/twisted/websocket.py:321:_onMessage
/usr/local/lib/python3.6/site-packages/binance/websocket/binance_client_protocol.py:31:onMessage
/root/download/work/coin/trade_strg_03.py:218:message_handler
/root/download/work/coin/trade_strg_03.py:190:dataSubscribe
/root/download/work/coin/trade_strg_03.py:75:strategy
/usr/local/lib/python3.6/site-packages/binance/spot/account.py:66:new_order
/usr/local/lib/python3.6/site-packages/binance/api.py:83:sign_request
/usr/local/lib/python3.6/site-packages/binance/api.py:117:send_request
/usr/local/lib/python3.6/site-packages/binance/api.py:170:_handle_exception
]. Retrying: 1

get User_data demo cannot get respose..

Before submitting a new issue, please check if a similar issue has already been filed.
I tried the testnet version and the product version... I still cannot get response from user data socket.

Issue subject

Briefly describe the issue here.

`
api_key =API_KEY
client = Client(api_key, base_url="https://api.binance.com")
response = client.new_listen_key()

logging.info("Receving listen key : {}".format(response["listenKey"]))

ws_client = SpotWebsocketClient(stream_url="wss://stream.binance.com:9443")
ws_client.start()

ws_client.user_data(
listen_key=response["listenKey"],
id=1,
callback=message_handler,
)
`

DEBUG:root:url: https://api.binance.com/api/v3/userDataStream
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.binance.com
DEBUG:urllib3.connectionpool:https://api.binance.com:443 "POST /api/v3/userDataStream HTTP/1.1" 200 76
DEBUG:root:raw response from server:{"listenKey":"KfDQG5T7wKEjxqlaOlgnCIDLLSaUbbFAlnAyD5ES85cEmlYowDdRKuJ9bCNE"}
INFO:root:Receving listen key : KfDQG5T7wKEjG332aOlgnCIDLLSaUbbFAlnAyD5ES85cEmlYowDdRKuJ9bCNE
INFO:root:Connection with URL: wss://stream.binance.com:9443/ws
INFO:root:Start to connect....
INFO:root:Server connected
INFO:root:Sending message to Server: b'{"method": "SUBSCRIBE", "params": ["KfDQG5T7wKEjxqlaOlgnCIDLLSaUbbFAlnAyD53G85cEmlYowDdRKuJ9bCNE"], "id": 1}'
{'result': None, 'id': 1}

Cannot find reference 'callFromThread' in 'reactor.py'

Before submitting a new issue, please check if a similar issue has already been filed.

Issue subject

Briefly describe the issue here.
刚下的websocket sdk, binance_socket_manager模块下的reactor.callFromThread方法读不到 Cannot find reference 'callFromThread' in 'reactor.py'
还有导入库也报错Package containing module 'twisted' is not listed in the project requirements
已经pip install -r requirements/requirements.txt

Expected behaviour

Describe what should happen.

Actual behaviour

Describe what happens instead. Please include the complete failure message.

Steps to reproduce

Provide steps to let us know how we can reproduce this issue.

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python
  • Python version 3.9
  • Operating system windows11

Use own logger for module

Hi,

can you please use a own logger for your module and not write to the default logger?
Like it is described here: https://stackoverflow.com/a/15735146

Expected behaviour

import logging
...
logger = logging.getLogger(__name__)
...
logger.debug("raw response from server:" + response.text)

Actual behaviour

import logging
......
logging.debug("raw response from server:" + response.text)

Binance added staking endpoint, it's not too difficult to add it in binance-connector

Issue subject

I've tried to enhance Binance-connector with a Spot method :

    """
    https://binance-docs.github.io/apidocs/spot/en/#get-staking-product-position-user_data
    GET /sapi/v1/staking/position (HMAC SHA256)

    Name         Type    Mandatory    Description
    ========================================
    product      ENUM    YES        "STAKING" for Locked Staking,
                                    "F_DEFI" for flexible DeFi Staking,
                                    "L_DEFI" for locked DeFi Staking
    productId    STRING  NO
    asset        STRING  NO
    current      LONG    NO    Currently querying the page. Start from 1. Default:1
    size         LONG    NO    Default:10, Max:100
    recvWindow   LONG    NO
    timestamp    LONG    YES
    """
def staking_product_position(self, **kwargs) :
    return self.sign_request("GET", "/sapi/v1/staking/position", kwargs)

then add this method in spot.__init__.py like this :

    from binance.spot.bstaking import staking_product_position

and finally call it :

>>> spot = Spot(key=kkk, secret=sss)
>>>  spot.staking_product_position(product="STAKING", timestamp=datetime.datetime.utcnow().timestamp()*1000)
...  [{'accrualDays': 8,
  'amount': xxx,
  'apy': '0.0469',
  'asset': 'EOS',
  'canRedeemEarly': True,
  'deliverDate': 1653904800000,
  'duration': 30,
  'interestEndDate': 1653782400000,
  'nextInterestPay':yy,
  'payInterestPeriod': 1,
  'positionId': 63721224,
  'productId': 'EOS*30',
  'purchaseTime': 1651138664000,
  'redeemAmountEarly': ...,
  'redeemPeriod': 1,
  'renewable': False,
  'rewardAmt': '...',
  'rewardAsset': 'EOS',
  'status': 'HOLDING',
  'type': 'NORMAL'},...]

Expected behaviour

display my account staking position.

Actual behaviour

my account staking position is displayed, all is right.
Un fortunatly, i have no time, just now, to implement it in binance-connector.
If someone is in a hurry to have it, just do it.

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python : 1.11.0
  • Python version : 3.9
  • Operating system : macOS 12.3.1

Callback funciton doesn't work while use websocket client

I'm trying to run example code in examples/websocket/spot/all_book_ticker.py

Issue subject

No response print to console, it seems that function message_handler doesn't work.

Expected behaviour

Response should be printed to console.

Actual behaviour

No response print to console and No error occurred.

image

Steps to reproduce

run all_book_ticker.py

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python: v1.7.0
  • Python version: Python 3.9.6
  • Operating system: Macos big sure 11.6

Wrong logging.basicConfig params for Windows platform

Issue subject

If user tries to build first example from readme git file on windows platform then it fails due to strftime is not maintain %s format. https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
I've fixed this with changing file binance\lib\utils.py line 79: changed to datefmt="%Y-%m-%d %H:%M:%S.".(remove %s)

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python: latest on 2021-11-07
  • Python version: 3.10
  • Operating system: Windows 10

ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1091)

Before submitting a new issue, please check if a similar issue has already been filed.

Issue subject

ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1091)

Expected behaviour

Describe what should happen.

Actual behaviour

Describe what happens instead. Please include the complete failure message.

Steps to reproduce

Provide steps to let us know how we can reproduce this issue.

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python 1.6.0
  • Python version Python 3.7.9
  • Operating system window 10 X64 familly

certificate verify failed

报错:WARNING:root:WebSocket connection closed: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate)), code: 1006, clean: False, reason: connection was closed uncleanly (SSL error: certificate verify failed (in tls_process_server_certificate))
ERROR:root:Lost connection to Server. Reason: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.
]. Retrying: 1

代码如下:

#!/usr/bin/env python

import time
from binance.websocket.spot.websocket_client import SpotWebsocketClient as Client

def message_handler(message):
print(message)

my_client = Client()
my_client.start()

my_client.book_ticker(
symbol="btcusdt",
id=2,
callback=message_handler,
)

time.sleep(30)

my_client.stop()

Delay Binance

Hello @2pd @aisling11

The problem is in the 5 minute delay.
I need to make a scraper that can find the currency fixed, without delaying the listing on the website by 5 minutes, is it possible somehow?

https://stackoverflow.com/questions/67736951/beautiful-soup-web-scraper-on-binance-announcement-page-lags-behind-by-5-minutes

Other coin listed recently with delay 5 minutes:

chesstime
Screenshot-7-1024x576

Coin Chess the announcement has been announced on 3:36. But 5 minutes before it started buying massively on other platforms.

websocket

websocket可以挂代理吗,现在不挂代理访问不了

import failure with undefined symbol: OPENSSL_sk_num

Before submitting a new issue, please check if a similar issue has already been filed.

Issue subject

Briefly describe the issue here.

Expected behaviour

Describe what should happen.

pi@raspberrypi:~ $ cat wsTest.py 
from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient

def message_handler(message):
    print(message)

ws_client = WebsocketClient()
ws_client.start()

ws_client.mini_ticker(
    symbol='bnbusdt',
    id=1,
    callback=message_handler,
)

# Combine selected streams
ws_client.instant_subscribe(
    stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],
    callback=message_handler,
)
Traceback (most recent call last):
  File "wsTest.py", line 1, in <module>
    from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient
  File "/home/pi/.local/lib/python3.6/site-packages/binance/websocket/spot/websocket_client.py", line 1, in <module>
    from binance.websocket.websocket_client import BinanceWebsocketClient
  File "/home/pi/.local/lib/python3.6/site-packages/binance/websocket/websocket_client.py", line 3, in <module>
    from binance.websocket.binance_socket_manager import BinanceSocketManager
  File "/home/pi/.local/lib/python3.6/site-packages/binance/websocket/binance_socket_manager.py", line 5, in <module>
    from twisted.internet import reactor, ssl
  File "/home/pi/.local/lib/python3.6/site-packages/twisted/internet/ssl.py", line 58, in <module>
    from OpenSSL import SSL
  File "/opt/miniconda3/lib/python3.6/site-packages/OpenSSL/__init__.py", line 8, in <module>
    from OpenSSL import crypto, SSL
  File "/opt/miniconda3/lib/python3.6/site-packages/OpenSSL/crypto.py", line 16, in <module>
    from OpenSSL._util import (
  File "/opt/miniconda3/lib/python3.6/site-packages/OpenSSL/_util.py", line 6, in <module>
    from cryptography.hazmat.bindings.openssl.binding import Binding
  File "/home/pi/.local/lib/python3.6/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 14, in <module>
    from cryptography.hazmat.bindings._openssl import ffi, lib
ImportError: /home/pi/.local/lib/python3.6/site-packages/cryptography/hazmat/bindings/_openssl.abi3.so: undefined symbol: OPENSSL_sk_num

Actual behaviour

Describe what happens instead. Please include the complete failure message.

Steps to reproduce

Provide steps to let us know how we can reproduce this issue.
I install pip install binance-connector
and found some warning message

 WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/pycparser
  sysconfig: /home/pi/.local/include/python3.6/pycparser
  WARNING: Additional context:
  user = True
  home = None
  root = None
  prefix = None
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/pyasn1
  sysconfig: /home/pi/.local/include/python3.6/pyasn1
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/cffi
  sysconfig: /home/pi/.local/include/python3.6/cffi
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/attrs
  sysconfig: /home/pi/.local/include/python3.6/attrs
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/zope.interface
  sysconfig: /home/pi/.local/include/python3.6/zope.interface
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/txaio
  sysconfig: /home/pi/.local/include/python3.6/txaio
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/pyasn1-modules
  sysconfig: /home/pi/.local/include/python3.6/pyasn1-modules
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/incremental
  sysconfig: /home/pi/.local/include/python3.6/incremental
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/hyperlink
  sysconfig: /home/pi/.local/include/python3.6/hyperlink
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/cryptography
  sysconfig: /home/pi/.local/include/python3.6/cryptography
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/constantly
  sysconfig: /home/pi/.local/include/python3.6/constantly
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/Automat
  sysconfig: /home/pi/.local/include/python3.6/Automat
  WARNING: The script automat-visualize is installed in '/home/pi/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/Twisted
  sysconfig: /home/pi/.local/include/python3.6/Twisted
  WARNING: The scripts cftp, ckeygen, conch, mailmail, pyhtmlizer, tkconch, trial, twist and twistd are installed in '/home/pi/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/service-identity
  sysconfig: /home/pi/.local/include/python3.6/service-identity
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/autobahn
  sysconfig: /home/pi/.local/include/python3.6/autobahn
  WARNING: The scripts wamp and xbrnetwork are installed in '/home/pi/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
  distutils: /home/pi/.local/include/python3.6m/binance-connector
  sysconfig: /home/pi/.local/include/python3.6/binance-connector
WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/10151>
distutils: /home/pi/.local/include/python3.6m/UNKNOWN
sysconfig: /home/pi/.local/include/python3.6/UNKNOWN

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python
    binance-connector 1.3.0
  • Python version
    Python 3.6.6
  • Operating system
    Raspberry Pi OS
    Linux raspberrypi 5.10.17-v7+ #1421 SMP Thu May 27 13:59:01 BST 2021 armv7l GNU/Linux

c2c live price

hi one every
someoce can add live price of the c2c
thank you

400, -1022, 'Signature for this request is not valid.',

Hello,

I am trying to run the basic example from the API doc:

from binance.spot import Spot


client = Spot()
print(client.time())

client = Spot(key='<api_key>', secret='<api_secret>')

# Get account information
print(client.account())

# Post a new order
params = {
    'symbol': 'BTCUSDT',
    'side': 'SELL',
    'type': 'LIMIT',
    'timeInForce': 'GTC',
    'quantity': 0.002,
    'price': 9500
}

response = client.new_order(**params)
print(response)

But I get this error:


    raise ClientError(status_code, err["code"], err["msg"], response.headers)
binance.error.ClientError: (400, -1022, 'Signature for this request is not valid.', {'Content-Type': 'application/json;charset=UTF-8', 'Content-Length': '63', 'Connection': 'keep-alive', 'Date': 'Thu, 11 Nov 2021 13:39:07 GMT', 'Server': 'nginx', 'x-mbx-uuid': '0e8ac82f-f491-485b-9689-7d6fe4f1f4ae', 'x-mbx-used-weight': '11', 'x-mbx-used-weight-1m': '11', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'self'", 'X-Content-Security-Policy': "default-src 'self'", 'X-WebKit-CSP': "default-src 'self'", 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 c9eda0567a1d169784ebe65d259cdee9.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'CDG50-P2', 'X-Amz-Cf-Id': 'GLaWL5bqMO6e7FCFZq5ilu9TjwwNSkaUmIfH2pxx5M1MYU9AwkW13g=='})

I though it was relating to a wring UTC (because my computer has UTC+1), so I changed the time of my computer (to be UTC+0) but still the same error.

I am on Windows 10, Python 3.8

Any idea ?

Thank you

Websocket for margin accounts

Feature request

Websocket features for Margin (Cross and Isolated) accounts seem to not be implemented

Expected behaviour

Listen to events from margin accounts like orders state update, etc. It can be classify as a

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python
  • Python version
  • ALL

Margin TAKE_PROFIT Order - Unknown Error

Hi there, I would appreciate your help with an issue that I have been trying to solve for a bit but can't get my head around, and I have not seen any other Issue about this in this project.

Issue subject

I managed to open a margin order using for example side = 'BUY', type='MARKET' and sideEffectType='MARGIN_BUY'.

client.new_margin_order(symbol = coin,
                        side = 'BUY',
                        type = 'MARKET',
                        sideEffectType='MARGIN_BUY',
                        newOrderRespType='FULL',
                        quantity=qty_order
                        )

The issue comes when I try to close and repay that order. I am using side = 'SELL', type='TAKE_PROFIT', sideEffectType = 'AUTO_REPAY'

client.new_margin_order(symbol = coin,
                       side = 'SELL',
                       type =  'TAKE_PROFIT,
                       stopPrice = stopPrice,
                       quantity=qty_order,
                       sideEffectType = 'AUTO_REPAY',
                       newOrderRespType = 'FULL'
                       )

stopPrice, in this example, will be higher than the price I entered the first order.
The quantity in both order is the same.

Expected behaviour

I am expecting to create an open position which will sell the same quantity I bought in the first order, when a certain price has been reached (in this case at a take profit level). At the same time it repays any money 'borrowed' (using 'Auto_repay') when the first order was placed.

Actual behaviour

Instead I am getting a 'Unknown Error':

ServerError: (500, '{"code":-1000,"msg":"An unknown error occurred while processing the request."}')

I will paste the Traceback:

ServerError                               Traceback (most recent call last)
Input In [12], in <cell line: 1>()
----> 1 client.new_margin_order(
      2                             symbol = coin,
      3                             side = 'SELL',
      4                             type =  'TAKE_PROFIT',
      5                             stopPrice = stopPrice,
      6                             quantity=qty_order,
      7                              sideEffectType = 'AUTO_REPAY',
      8                              newOrderRespType = 'FULL'
      9                                      )

File /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/binance/spot/margin.py:187, in new_margin_order(self, symbol, side, type, **kwargs)
    178 check_required_parameters(
    179     [
    180         [symbol, "symbol"],
   (...)
    183     ]
    184 )
    186 payload = {"symbol": symbol, "side": side, "type": type, **kwargs}
--> 187 return self.sign_request("POST", "/sapi/v1/margin/order", payload)

File /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/binance/api.py:83, in API.sign_request(self, http_method, url_path, payload)
     81 signature = self._get_sign(query_string)
     82 payload["signature"] = signature
---> 83 return self.send_request(http_method, url_path, payload)

File /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/binance/api.py:117, in API.send_request(self, http_method, url_path, payload)
    115 response = self._dispatch_request(http_method)(**params)
    116 self._logger.debug("raw response from server:" + response.text)
--> 117 self._handle_exception(response)
    119 try:
    120     data = response.json()

File /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/binance/api.py:171, in API._handle_exception(self, response)
    169         raise ClientError(status_code, None, response.text, response.headers)
    170     raise ClientError(status_code, err["code"], err["msg"], response.headers)
--> 171 raise ServerError(status_code, response.text)

ServerError: (500, '{"code":-1000,"msg":"An unknown error occurred while processing the request."}')

Steps to reproduce

Create a margin market order using sideEffectType='MARGIN_BUY' and create a TAKE_PROFIT order, in the opposite direction, using sideEffectType = 'AUTO_REPAY'

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python == 1.12 (I am using binance-connector not binance-connector-python, I believe is the same?)
  • Python version == 3.9.12
  • Operating system == MacOS Catalina

Futures trade history fee

Hi,

I have tried multiple endpoints to get my futures trade history fees but no luck.
Can anyone suggest how I could achieve this?

Thanks

ReactorNotRestartable

Issue subject

When I run the example websocket code twice, I get an error.

Code to run

from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient

def message_handler(message):
    print(message)

ws_client = WebsocketClient()
ws_client.start()

# Combine selected streams
ws_client.instant_subscribe(
    stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],
    callback=message_handler,
)

ws_client.stop()

ws_client = WebsocketClient()
ws_client.start()

Error Message

Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Program Files\Python39\lib\threading.py", line 954, in _bootstrap_inner
>>>     self.run()
  File "C:\Program Files\Python39\lib\site-packages\binance\websocket\binance_socket_manager.py", line 74, in run
    reactor.run(installSignalHandlers=False)
  File "C:\Program Files\Python39\lib\site-packages\twisted\internet\base.py", line 1422, in run
    self.startRunning(installSignalHandlers=installSignalHandlers)
  File "C:\Program Files\Python39\lib\site-packages\twisted\internet\base.py", line 1404, in startRunning
    ReactorBase.startRunning(cast(ReactorBase, self))
  File "C:\Program Files\Python39\lib\site-packages\twisted\internet\base.py", line 843, in startRunning
    raise error.ReactorNotRestartable()
twisted.internet.error.ReactorNotRestartable

Environment

Provide any relevant information about your setup, such as:

  • Version of binance-connector-python: binance-connector==1.7.0
  • Python version: Python 3.9.2
  • Operating system: Windows 10

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.