Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot create order using websocket #1526

Open
KissCoderr opened this issue Dec 24, 2024 · 4 comments
Open

Cannot create order using websocket #1526

KissCoderr opened this issue Dec 24, 2024 · 4 comments

Comments

@KissCoderr
Copy link

When attempting to use the ws_create_order method from the python-binance library to place an order via WebSocket, in asyncio.create_task(calculation_trade_loop()) it results in errors such as RuntimeError: This event loop is already running, timeouts, or connection closed issues. The behavior is inconsistent and does not allow successful order placement.

async def binance_balance_websocket():
client = await Binance_Client.create(api_key=api_key, api_secret=api_secret)
bm = BinanceSocketManager(client)
us = bm.user_socket()
async with us as uscm:
while True:
message2 = await uscm.recv()
asyncio.create_task(handle_binance_user(message2))
await client.close_connection()

async def binance_orderbook_websocket():
client = await Binance_Client.create(api_key=api_key, api_secret=api_secret)
bm = BinanceSocketManager(client)
lowercase_list = [item.lower() for item in listOfPairings]
modified_list = [item.lower() + '@bookTicker' for item in lowercase_list]
ts = bm.multiplex_socket(modified_list)

async with ts as tscm:
    while True:
        message = await tscm.recv()
        asyncio.create_task(handle_pair_data(message))

await client.close_connection()

async def main():
binancews1 = asyncio.create_task(binance_balance_websocket())
binancews2 = asyncio.create_task(binance_orderbook_websocket())
loop = asyncio.create_task(calculation_trade_loop())
await asyncio.gather(binancews1, binancews2, btcturkws1, btcturkws2, loop)

async def order_trade_binance_buy(pair1, quantity1):
binance_client.ws_create_order(symbol=pair1, side="BUY", type="MARKET", quantity=quantity1)

order_trade_binance_buy is in calculation_trade_loop().

The ws_create_order method should send an order through WebSocket without triggering event loop or connection issues. The expected result is a successful order response or a clear error message explaining why the order could not be processed.

Python version: 3.12
Virtual Env: venv
OS: Windows 10
python-binance version: 1.0.17

Logs
Traceback (most recent call last):
File "F:\pythonProject3\main_upgraded.py", line 1301, in
asyncio.run(main())
File "C:\Users\ersint\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 664, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "F:\pythonProject3\main_upgraded.py", line 754, in main
await asyncio.gather(binancews1, binancews2, btcturkws1, btcturkws2, loop1, loop2, loop3, loop4)
File "F:\pythonProject3\main_upgraded.py", line 765, in calculation_trade1_loop
await asyncio.gather(*tasks1)
File "F:\pythonProject3\main_upgraded.py", line 834, in calculation_trade1
await asyncio.gather(task1, task2, task3)
File "F:\pythonProject3\main_upgraded.py", line 1034, in order_trade_binance_buy
binance_client.ws_create_order(symbol=pair1, side="BUY", type="MARKET", quantity=quantity1)
File "C:\Users\ersint\AppData\Local\Programs\Python\Python312\Lib\site-packages\binance\client.py", line 10697, in ws_create_order
return self._ws_api_request_sync("order.place", True, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python312\Lib\site-packages\binance\base_client.py", line 399, in _ws_api_request_sync
return self.loop.run_until_complete(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 640, in run_until_complete
self._check_running()
File "C:\Users\ersint\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 599, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running

Additional context
The issue occurs when using ws_create_order in an asynchronous environment alongside other WebSocket tasks (e.g., listening to price updates). Switching to REST API methods (create_order) works without issues. There is no clear documentation in the library on how to use ws_create_order in such cases.

@pcriadoperez
Copy link
Collaborator

Hi @KissCoderr,

Thanks for reporting. Can you upgrade to the latest version and try again? This was an issue in previous versions but should working in the latest version

@KissCoderr
Copy link
Author

Yes, the version is 1.0.26. I'm sorry, I wrote wrong above without realizing it

@KissCoderr
Copy link
Author

Now, I am taking this error, I am using client to start user socket and orderbook websockets. In addition to that ı am trying to give ws order. What's wrong?

The error:

Traceback (most recent call last):
File "F:\pythonProject3\main_upgraded.py", line 1314, in
asyncio.run(main())
~~~~~~~~~~~^^^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python313\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
~~~~~~~~~~^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python313\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python313\Lib\asyncio\base_events.py", line 720, in run_until_complete
return future.result()
~~~~~~~~~~~~~^^
File "F:\pythonProject3\main_upgraded.py", line 755, in main
await asyncio.gather(binancews1, binancews2, btcturkws1, btcturkws2, loop1, loop2, loop3, loop4)
File "F:\pythonProject3\main_upgraded.py", line 766, in calculation_trade1_loop
await asyncio.gather(*tasks1)
File "F:\pythonProject3\main_upgraded.py", line 835, in calculation_trade1
await asyncio.gather(task1, task2, task3)
File "F:\pythonProject3\main_upgraded.py", line 1037, in order_trade_binance_buy
order = await client.ws_create_order(symbol="pair1", side="BUY", type="MARKET", quantity=quantity1,)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python313\Lib\site-packages\binance\async_client.py", line 3354, in ws_create_order
return await self._ws_api_request("order.place", True, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python313\Lib\site-packages\binance\base_client.py", line 394, in _ws_api_request
return await self.ws_api.request(id, payload)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\ersint\AppData\Local\Programs\Python\Python313\Lib\site-packages\binance\ws\websocket_api.py", line 116, in request
raise BinanceWebsocketUnableToConnect("Request timed out")
binance.exceptions.BinanceWebsocketUnableToConnect: Request timed out

Hi @KissCoderr,

Thanks for reporting. Can you upgrade to the latest version and try again? This was an issue in previous versions but should working in the latest version

@KissCoderr
Copy link
Author

async def binance_ws_order_websocket(order_data):
ws_client = await Binance_Client.create(api_key=api_key, api_secret=api_secret)
ws_bm = BinanceSocketManager(ws_client)
ws_us = ws_bm.user_socket()
async with ws_us:
# await ws_client.ws_create_order(symbol=order_data['symbol'], side=order_data['side'], type="MARKET",
# quantity=order_data['quantity'], )
await ws_client.close_connection()

async def handle_ws_binance(buy_trade, sell_trade, buy_arbit, sell_arbit, pair, quantity):
print(buy_trade, sell_trade, buy_arbit, sell_arbit, pair, quantity)
if buy_trade == 1:
buy_trade = 0
return {'symbol': pair, 'side': "BUY", 'quantity': quantity}
if sell_trade == 1:
sell_trade = 0
return {"symbol": pair, 'side': "SELL", 'quantity': quantity}
if buy_arbit == 1:
buy_arbit = 0
return {"symbol": pair, 'side': "BUY", 'quantity': quantity}
if sell_arbit == 1:
sell_arbit = 0
return {"symbol": pair, 'side': "SELL", 'quantity': quantity}

Now taking this error:

ConnectionClosedError (received 1003 (unsupported data) binary frames are not supported; then sent 1003 (unsupported data) binary frames are not supported)
BinanceWebsocketClosed (Connection closed. Reconnecting...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants