binance / binance-futures-connector-python Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
i am unable to get data more then two day's
When I try and use the commands query_order and cancel_order, I keep getting the same error that the specified orders do not exist.
For example I would open a stop loss order on DOGEUSDT with a specified origClientOrderId and this order would appear as so when i print the order.
{'orderId': 123929928, 'symbol': 'DOGEUSDT', 'status': 'NEW', 'clientOrderId': '12345678', 'price': '0', 'avgPrice': '0', 'origQty': '150', 'executedQty': '0', 'cumQuote': '0', 'timeInForce': 'GTC', 'type': 'STOP_MARKET', 'reduceOnly': True, 'closePosition': False, 'side': 'SELL', 'positionSide': 'LONG', 'stopPrice': '0.160000', 'workingType': 'CONTRACT_PRICE', 'priceProtect': False, 'origType': 'STOP_MARKET', 'time': 1639763154202, 'updateTime': 1639763154202}
But if I use the single command with query_order and the specified id, I keep getting the error saying it does not exist. I have tried with using either orderId or origClientOrderId and by passing them as both a str and int and none seem to work
this is the command I am using:
futures_client.get_order(
symbol = 'DOGEUSDT',
origClientOrderId = '12345678'
)
Of course I have tried using OrderId also and even retrieving the specific ID's from get_orders and still I get the error that those don't exist. Also it seems this error is persistent with commands that seek a specific order, because I get the same error when I try the command cancel_order with a specified ID.
Steps to reproduce:
client.cancel_order(symbol = symbol, orderId = orderId, recvWindow = user.recvWindow)
Expectations: order is canceled
Reality: we are getting the error, that the order does not exist.
Actually, there is an error in the program code, so I am preparing a pull request right now
Hi, in the file https://github.com/Binance-docs/binance-futures-connector-python/blob/main/examples/websocket/futures/liquidation_order.py you write :
id= 13 callback = message_handler
I don't understand what these are and how to connect to testnet to my api.
Moreover, I try to autoclose an order when an order is close( ex : a Stop loss is closed but the take profit isn't canceled so i do i in code) and i don't know if that's the correct method to use.
No filter order open and cancel order.
I try to close an order just after i created it to test the method on the base_url="https://testnet.binancefuture.com"
but i have the following issue :
File "D:\Logiciels\Python\lib\site-packages\binance\futures\account.py", line 268, in cancel_order
return self.sign_request("DELETE", url_path, params)
File "D:\Logiciels\Python\lib\site-packages\binance\api.py", line 84, in sign_request
return self.send_request(http_method, url_path, payload, special)
File "D:\Logiciels\Python\lib\site-packages\binance\api.py", line 118, in send_request
self._handle_exception(response)
File "D:\Logiciels\Python\lib\site-packages\binance\api.py", line 171, in _handle_exception
raise ClientError(status_code, err["code"], err["msg"], response.headers)
binance.error.ClientError: (400, -2011, 'Unknown order sent.', {'Content-Type': 'application/json', 'Content-Length': '42', 'Connection': 'keep-alive', 'Date': 'Tue, 12 Apr 2022 16:28:13 GMT', 'Server': 'Bengine', 'X-MBX-USED-WEIGHT-1M': '2', 'x-response-time': '3ms', 'X-Frame-Options': 'SAMEORIGIN', 'X-Xss-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'origin-when-cross-origin', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains', 'X-Cache': 'Error from cloudfront', 'Via': '1.1 e832b62df62ac7dea0463212e63d91f6.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop': 'CDG50-P2', 'X-Amz-Cf-Id': 'HHB4Beib98-164R-Sp-TL_K8MBoDIk_bLYztkzbND6AF9mg2mmeX2w=='})
my cancel_order method call is here :
clientData.cancel_order(
symbol="BTCUSDT",
orderId = orderIdOpen)
where orderIdOpen is a var i get from the new_order method's result
run:
examples\websocket\um_futures\ticker.py'
INFO:root:Connection with URL: wss://fstream.binance.com/ws
INFO:root:Start to connect....
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: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。.
]. Retrying: 1
INFO:root:Start to connect....
while I was running the websocket example, there is all I got:
INFO:root:Connection with URL: wss://fstream.binance.com/ws
INFO:root:Start to connect....
DEBUG:root:closing ws connection
It seems I didn't connect the server, what was going wrong?
How to use a proxy with authorization? HTTPS/SOCKS?
IP from China got blocked. A connection error is returned when connect to binance, for example, https://fapi.binance.com/fapi/v1/time. The weblink is accessible through a VPN. But the python code does not work.
I tried to setup a proxy, using IP from Japan, Russia, India, Korea, Brazil. None of them works.
Could you please give a successful example of how to correctly use proxy settings?
You can use the free proxy resource from https://www.proxynova.com/proxy-server-list/
You can also use my VPN node,
ip:31.v2yd2.poronode.top
port:16857
encode:aes-256-cfb
protocal:auth_aes128_md5
protocal param:20810:n0FbrRQEFd1o
ofs:tls1.2_ticket_auth
ofs param:eefaa20810.microsoft.com
passwd: private msg. Discord: iAaron#6598
I ran the example WebSocket code:
import time
from binance.websocket.cm_futures.websocket_client import CMFuturesWebsocketClient
def message_handler(message):
print(message)
ws_client = CMFuturesWebsocketClient()
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,
)
and got some error:
WARNING:root:WebSocket connection closed: connection was closed uncleanly ("SSL error: unregistered scheme (in )"), code: 1006, clean: False, reason: connection was closed uncleanly ("SSL error: unregistered scheme (in )")
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
I tried it with different internet connections and different VPN servers and I have the same error.
Meanwhile, the REST API works fine.
Maybe have i to install some libraries?
import time
import logging
from binance.lib.utils import config_logging
from binance.websocket.um_futures.websocket_client import UMFuturesWebsocketClient
config_logging(logging, logging.DEBUG)
def message_handler(message):
print(message)
my_client = UMFuturesWebsocketClient()
my_client.start()
my_client.kline(
symbol="btcusdt",
id=12,
interval="1d",
callback=message_handler,
)
time.sleep(10)
logging.debug("closing ws connection")
my_client.stop()
this is oupuit:
INFO:root:Connection with URL: wss://fstream.binance.com/ws
INFO:root:Start to connect....
DEBUG:root:closing ws connection
Hello,
I am trying to use the cancel order func and just keep getting this error msg:
ERROR:root:Found error. status: 400, error code: -2011, error message: Unknown order sent.
I did everyting correctly,
the order just opened, not filled....
I looked all over the web and didn't found anything....
um_futures_client = UMFutures(base_url="https://testnet.binancefuture.com", key=key, secret=secret)
try:
response = um_futures_client.cancel_order(
symbol=symbol, orderId=orderId, recvWindow=recvWindow,
)
logging.info(response)
# print(response)
return response["status"]
except ClientError as error:
logging.error(
"Found error. status: {}, error code: {}, error message: {}".format(
error.status_code, error.error_code, error.error_message
)
)
I am using
my_client.agg_trade(
symbol="btcusdt",
id=1,
callback=message_handler,
)
Instead of fetching "btcusdt" only, is it possible to fetch more than one symbol at the same time, how should I do it?
in query_order()
from line 237~239 should be as below:
elif (origClientOrderId is None):
params = {"symbol": symbol, "orderId": orderId, **kwargs}
else:
params = {"symbol": symbol, "origClientOrderId": origClientOrderId, **kwargs}
When I try to establish a Websocket connection i get an SSL error
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.
The code i use is very simple
self.m_Client_Websocket = UMFuturesWebsocketClient()
self.m_Client_Websocket.start()
self.m_Client_Websocket.ticker(symbol='btcusdt',id=13,callback=self.message_handler)
time.sleep(10)
self.m_Client_Websocket.stop()
Revise:
def cancel_batch_order(self, symbol: str, orderIdList: list= None, origClientOrderIdList: list= None, **kwargs):
elif (orderIdList is not None):
run error:{"code":-1130,"msg":"Data sent for parameter 'orderIdList' is not valid."}
I am getting an issue with websocket. Any example I run from https://github.com/Binance-docs/binance-futures-connector-python/tree/main/examples/websocket/futures gives me the following error - "WARNING:root: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)".
Whenever I try to rerun the examples I get the error "error.ReactorNotRestartable() twisted.internet.error.ReactorNotRestartable".
I have found out that I can escape this error by uninstalling and then reinstalling the twisted library. But then I have to repeat the reinstallment every time I want to start the websocket. Since this isn't a feasible solution. Can someone here help me with how to resolve this issue? What would be the most appropriate way to close the websocket connection since ws_client = FuturesWebsocketClient(), ws_client.stop() is leading to this issue.
def open_interest(self, symbol: str):
"""Get present open interest of a specific symbol.
GET /fapi/v1/openInterest
https://binance-docs.github.io/apidocs/futures/en/#open-interest
Args:
symbol (str): the trading symbol
"""
check_required_parameter(symbol, "symbol")
params = {"symbol": symbol}
return self.query("/fapi/v1/ticker/bookTicker", params)
Hello .
How can i enable testnet ?
Unable to run any example in USD-M Websockets.
Error Message-
INFO:root:Connection with URL: wss://fstream.binance.com/stream?streams=btcusdt@bookTicker/ethusdt@bookTicker/eosusdt@bookTicker
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
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: 11
{'e': 'error', 'm': 'Max reconnect retries reached'}
I tried updating certifi from 2021.10.8
to certifi-2022.9.24
Solution- binance/binance-connector-python#57 (comment)
It would be very helpful if the team could add a warning for Windows or Anaconda users since there are many users with this same issue.
Hello thank you for making this library
I want to know if I can get multiple kline streams.
if self._single_stream(stream):
stream = [stream]
else:
combined = True
data = {"method": "SUBSCRIBE", "params": stream, "id": id}
this line shows that websocket_client can get stream data of multiple tickers
def kline(self, symbol: str, id: int, interval: str, callback, **kwargs):
"""Kline/Candlestick Streams
The Kline/Candlestick Stream push updates to the current klines/candlestick every 250 milliseconds (if existing)
Stream Name: <symbol>@kline_<interval>
https://binance-docs.github.io/apidocs/futures/en/#kline-candlestick-streams
interval:
m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
- 1m
- 3m
- 5m
- 15m
- 30m
- 1h
- 2h
- 4h
- 6h
- 8h
- 12h
- 1d
- 3d
- 1w
- 1M
Update Speed: 250ms
"""
self.live_subscribe(
"{}@kline_{}".format(symbol.lower(), interval), id, callback, **kwargs
)
but the actual kline method seems to get just single ticker as input
Is there any way to get multiple tickers' kline streams?
from binance.websocket.futures.websocket_client import FuturesWebsocketClient
ws_client = WebsocketClient()
ws_client.instant_subscribe(
stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],
callback=message_handler,
)
websocket接口怎么做掉线重连?在哪里指定onClose回调函数?
How can I set an onCLose() callback function for FuturesWebsocketClient?
I want to reconnect to the server when I loss the connect.
Though reported in #15 and closed as fixed, it is in fact still not encoding the query strings properly. I'm using 3.1.1 and the final query strings is still invalid:
[2022-06-02 08:44:58,565: DEBUG/ForkPoolWorker-8] https://testnet.binancefuture.com:443 "DELETE //fapi/v1/batchOrders?symbol=BTCUSDT&origClientOrderIdList=61cb41a6-a0b9-43d1-93d1-2a9050ae61cd&origClientOrderIdList=94e24acf-c3ba-4045-b359-1c9d3b7d75fd&origClientOrderIdList=dbd364ff-cf33-43a1-be48-1155c536e2f0×tamp=1654159497710&signature=beaf2c54f6e3f23befdbc5661f97ea90d0992fa0b7f91c103d5c035f364e2eec HTTP/1.1" 400 84
各位好,我使用币安的SDK 想尝试通过websocket获取价格数据,但没有返回任何数据。任何根据技术人员的指导,我尝试通过以下代码确认websocket连接是否好使。运行后10秒,得到closed connection,然后就停止了。
请问各位大佬,该如何解决,谢谢。
运行代码如下所示:
import websocket
import json
testnet = "wss://fstream.binance.com/ws/bnbusdt@bookTicker"
def on_open(ws):
print('opened connection')
#ws.send(payload)
def on_close(ws):
print('closed connection')
def on_message(ws, message):
json_message = json.loads(message)
print(json_message)
ws =websocket.WebSocketApp(testnet,on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever()
Does the library have a websocket function "Listing Subscriptions"?
Whenever I try to place a stop-limit order using:
_**client = Client(api_key="key", api_secret="secret")
client.futures_create_order(**dict(
symbol="BTCUSDT",
quantity=0.02,
stopPrice=50000, # As of writing this the price of BTC is ≈51000
price=40000,
side="BUY",
positionSide="LONG",
type="STOP",
timeInForce="GTC,
newOrderRespType="FULL"
))
**_
I get the following error:
Traceback (most recent call last):
File "/Users/yamansirajaldeen/Documents/Gismo_0/OrderPlacer.py", line 117, in
print(client.open_long_stop_limit("BTC", 0.02, stopPrice=50000, price=40000))
File "/Users/yamansirajaldeen/Documents/Gismo_0/OrderPlacer.py", line 98, in open_long_stop_limit
result: dict = self.futures_create_order(**dict(
File "/usr/local/lib/python3.9/site-packages/binance/client.py", line 5852, in futures_create_order
return self._request_futures_api('post', 'order', True, data=params)
File "/usr/local/lib/python3.9/site-packages/binance/client.py", line 339, in _request_futures_api
return self._request(method, uri, signed, True, **kwargs)
File "/usr/local/lib/python3.9/site-packages/binance/client.py", line 315, in _request
return self._handle_response(self.response)
File "/usr/local/lib/python3.9/site-packages/binance/client.py", line 324, in _handle_response
raise BinanceAPIException(response, response.status_code, response.text)
binance.exceptions.BinanceAPIException: APIError(code=-2021): Order would immediately trigger.
However, when I enter the same order on the application manually it works:
i can't cancel an open order
here is response from get_orders()
[{'orderId': 1896063477, 'symbol': 'HOTUSDT', 'status': 'NEW', 'clientOrderId': 'Tsar_TP', 'price': '0', 'avgPrice': '0', 'origQty': '0', 'executedQty': '0', 'cumQuote': '0', 'timeInForce': 'GTC', 'type': 'TAKE_PROFIT_MARKET', 'reduceOnly': True, 'closePosition': True, 'side': 'SELL', 'positionSide': 'BOTH', 'stopPrice': '0.006007', 'workingType': 'CONTRACT_PRICE', 'priceProtect': False, 'origType': 'TAKE_PROFIT_MARKET', 'time': 1641826768523, 'updateTime': 1641826768523}]
and here is my cancel order post data:
{'symbol': 'HOTUSDT', 'orderId': 1896063477}
the response is 400, -2011, 'Unknown order sent.'
i’ve been trying to use orderId and origClientOrderId but still have same response, trying to fill timestamp but still the same.
THE ORDER IS STILL OPEN AND NOT FILLED AT ALL
Hi there,
I've been trying to access the binance data for the long-short ratio using your python connector but despite having followed the different steps I still encounter a few struggles:
When doing it via 'binance/um_futures/market.py', I get the following error:
Fortunately you provided a second option in your examples, and although I can see the raw data, I am unable to access it:
Any luck you know what is going on for either of them?
Thank you for your time,
A
print(client.account())
binance.error.ClientError: (400, -1021, "Timestamp for this request was 1000ms ahead of the server's time.",
Collecting binance-futures-connector
Downloading binance_futures_connector-3.3.0-py3-none-any.whl (36 kB)
Collecting autobahn>=21.2.1
Using cached autobahn-22.12.1.tar.gz (479 kB)
ERROR: Error [WinError 225] Operation did not complete successfully because the file contains a virus or potentially unwanted software while executing command python setup.py egg_info
Preparing metadata (setup.py) ... error
ERROR: Could not install packages due to an OSError: [WinError 225] Operation did not complete successfully because the file contains a virus or potentially unwanted software
i logging to some log in my script
console_out = logging.StreamHandler()
log_format = logging.Formatter(fmt='%(asctime)s.%(msecs)03d : [%(levelname)s] : %(message)s',datefmt='%Y.%m.%d %H:%M:%S')
console_out.setFormatter(log_format)
client_wa = UMFutures()
papers = [ ["FUTURES", 'ETHUSDT',1] ]
in array of papers init logging (more string skip):
for cur_paper in papers:
paper = cur_paper[0]+"."+cur_paper[1]
ar_log[paper] = pd.DataFrame()
ar_log[paper].loc[paper,"log"] = logging.getLogger(paper)
ar_log[paper].loc[paper,"log"].addHandler(console_out)
ar_log[paper].loc[paper,"log"].setLevel(logging.INFO)
ar_log[paper].loc[paper,"log"].info(paper +" log script loading...")
i view true report:
2022.07.30 14:39:22.907 : [INFO] : FUTURES.ETHUSDT log script loading...
if before initializing the logs I call a any function, for example ping
client_wa.ping()
I get duplicate logs, with the second line without formatting.
the error manifests itself in Linux (CentOS, oraclelinux), under Windows there is no such error
2022.07.30 14:43:36.362 : [INFO] : MAIN log script loading...
INFO:MAIN:MAIN log script loading...
python ver 3.10.5 (same error in ver 3.6)
Take Profit Order is executed before "short limit" order is filled
i try to run the request but get_account_trades() without "symbol" - it gives an error
TypeError: get_account_trades() missing 1 required positional argument: 'symbol'
Indeed, in the documentation this parameter is mandatory.
But at the same time, postman gives out data.
I need to get trades on symbol, that has not been traded for more than 7 days.
Is there any other possibility to do this?
I created an order. Then I want to change the stop loss and write another value. how can I do it?
The get_open_orders() method in UMFutures requires either orderId or origClientOrderId must be passed.
The implementation is not inline with the spec: https://binance-docs.github.io/apidocs/futures/en/#current-all-open-orders-user_data
If orderId or origClientOrderId is not sent, then all the open orders for a given symbol should be returned.
the stream setup only a few minutes ,then the WS will be closed,what's the matter,help pls ,thanks.
DEBUG:root:closing ws connection
WARNING:root:WebSocket connection closed: connection was closed uncleanly ("SSL error: unexpected eof while reading (in )"), code: 1006, clean: False, reason: connection was closed uncleanly ("SSL error: unexpected eof while reading (in )")
root@bot-dev:/home/binance-futures-connector-python/examples/websocket/um_futures# python3 -V
Python 3.8.10
root@bot-dev:/home/binance-futures-connector-python/examples/websocket/um_futures# openssl version
OpenSSL 1.1.1f 31 Mar 2020 (Library: OpenSSL 1.1.1s 1 Nov 2022)
here is my code
params = {
"positionSide": "LONG",
"stop_price": stop_price
}
# s eq BTCUSDT
self.client.new_order(symbol=s, side="SELL", type="STOP_MARKET",
**params)
error is
1102, 'A mandatory parameter was not sent, was empty/null, or malformed.'
According to the API description, are not all the necessary parameters passed?
Futures websocket cannot accept api and secret key so cannot subscribe to private data as user info
greeting,
according to latest Binance Future Api Docs, premiumIndex endpoint:
GET /fapi/v1/premiumIndex
does not required symbol as mandatory argument, but in the current version its mandatory.
thanks
Hi,
When I tried to test websocket um_futures it appear the exception:
Exception has occurred: AttributeError
module 'OpenSSL.SSL' has no attribute 'TLS_METHOD'
Any idea to solve to exception? I follow the readme.md to test
I get error message even when dualSidePosition = True
from binance.um_futures import UMFutures
key = 'abcd'
secret = 'efgh'
base_url = "https://testnet.binancefuture.com"
um_futures_client = UMFutures(key=key, secret=secret, base_url=base_url)
dualSidePosition = True
positionSide = 'BOTH'
print(um_futures_client.get_position_mode())
#print(um_futures_client.account())
def futures_change_position_mode():
return um_futures_client(dualSidePosition= True)
response = um_futures_client.new_order(
symbol="BTCUSDT",
side="SELL",
type="MARKET",
quantity=0.001,
)
response = um_futures_client.new_order(
symbol="BTCUSDT",
side="BUY",
type="MARKET",
quantity=0.001,
)
Hi,
I'm quite new here.
I used to use "import binance.future"
I saw in the doc that it changed to 'binance.um_futures'.
I uninstalled package with 'pip uninstall binance-futures-connector'
Then i did a 'pip binance-futures-connector'
Since then i get the error ModuleNotFoundError: No module named 'binance.um_futures'
It works nice on my laptop, not at all on my second computer
Any ideas? thanks for help.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.