Git Product home page Git Product logo

lucit-systems-and-development / unicorn-fy Goto Github PK

View Code? Open in Web Editor NEW
54.0 7.0 21.0 9.73 MB

A Python SDK by LUCIT to convert received raw data from crypto exchange API endpoints into well-formed python dictionaries.

Home Page: https://unicorn-fy.docs.lucit.tech

License: MIT License

Python 97.59% Shell 2.09% Makefile 0.15% Batchfile 0.18%
binance python cryptoexchange binance-us binance-futures binance-margin binance-isolated-margin binance-tr unicorn-fy binance-perpetual-coin-futures

unicorn-fy's People

Contributors

davivc avatar folktale42 avatar jorgejch avatar oliver-zehentleitner avatar tidone avatar uggel 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

unicorn-fy's Issues

Add '!userData@arr' + 'MARGIN/SPOT/FUTURES' to 'stream_type'

In the Binance websocket stream, 'outboundAccountInfo' websocket data is depreciated and will soon be removed.
In the Binance websocket stream, 'account_permissions': ['SPOT'] within 'outboundAccountInfo' is the only indicator of which account the user stream belongs.
In the unicorn-fy dictionary, user data streams are listed identically as: 'stream_type': '!userData@arr' whether the user streams are SPOT, MARGIN, ISOLATED or FUTURES

Can 'stream_type': '!userData@arr' be modified to include whether the stream is SPOT, MARGIN, ISOLATED or FUTURES?
for example: 'stream_type': '!userData@arrSpot', '!userData@arrMargin', '!userData@arrIsolated', '!userData@arrFutures

If there is a better way of labeling different types of user data streams please let me know!

Binance API Updates

Is your feature request related to a problem? Please describe.
https://binance-docs.github.io/apidocs/futures/en/#change-log

Describe the solution you'd like
Test the changes and make changes to the lib if needed:

2020-11-09

WEB SOCKET USER DATA STREAM

Please notice: new streamlined and optimized push rules on event ACCOUNT_UPDATE in USER-DATA-STREAM

When an asset of a user is changed:
    Only this asset and its balance information will be pushed
    Other assets and information will no longer be pushed even the balances may not be 0
    If none of the open positions change, the position "P" will only return an empty []

When a position or the margin type of a symbol is changed:
    "P" will push the details in the "BOTH" position of this symbol
    If the change happens in "LONG" or "SHORT" position, the changed "LONG" or "SHORT" position of this symbol will be pushed
    Initialized "LONG" or "SHORT" isolated position of this symbol will also be pushed
    Position information of other symbols will no longer be pushed, even their positions may not be 0

In short, the full information of assets and positions should be obtained via the related RESTful endpoints(GET /fapi/v2/account and GET /fapi/v2/positionRisk), and the locally cached asset or position data can be updated via the event ACCOUNT_UPDATE in Websocket USER-DATA-STREAM with the information of changed asset or position.

Please visit here to get examples for helping to understand the upgrade.

ModuleNotFoundError: No module named 'unicorn_fy.unicorn_fy'; 'unicorn_fy' is not a package

Check this or we will delete your issue. (fill in the checkbox with an X like so: [x])

  • [x ] I have searched for other issues with the same problem or similar feature requests.

Select one:

  • [ x] Bug
  • Feature Request
  • Technical Help
  • Other

Environment

  • Are you using the module on a VPS or other Cloud hosting?
  • If so, have you tried running the code on your local machine?
  • Are you using the module on a Raspberry Pi?

Operating System? (include version)

  • [x ] macOS
  • Windows
  • [x ] Linux (include flavour)

Exact Python Version?

Python 3.8.5

Pip Version?

pip 20.2.2

Description of your issue

ModuleNotFoundError: No module named 'unicorn_fy.unicorn_fy'; 'unicorn_fy' is not a package

I've fixed this for  unicorn-binance-websocket-api already. This is the same issue. The module is packaged as if it was a python script

Parse ACCOUNT_UPDATE for margin type change in Futures

Is your feature request related to a problem? Please describe.

When changing a margin mode in Futures a WebSocket event is created. Currently, the event is not fully parsed:
{'stream_type': 'ACCOUNT_UPDATE', 'event_type': 'ACCOUNT_UPDATE', 'event_time': 1657383734073, 'transaction': 1657383734071, 'update_data': {'B': [{'a': 'USDT', 'wb': '2561.04467225', 'cw': '2557.83387650', 'bc': '0'}], 'P': [{'s': 'BTCUSDT', 'pa': '0', 'ep': '0.00000', 'cr': '467.59971010', 'up': '0', 'mt': 'cross', 'iw': '0', 'ps': 'BOTH', 'ma': 'USDT'}], 'm': 'MARGIN_TYPE_CHANGE'}, 'unicorn_fied': ['binance.com-coin_futures', '0.11.0']}

Describe the solution you'd like.

Parse the whole event.

Describe alternatives you've considered

No response

Additional context

I am happy to solve this issue, just need the green light from the maintainer.

!userData Channel ?

Hi i've added userData stream.
binance_com_user_data_stream_id = binance_com_websocket_api_manager.create_stream('arr', '!userData')
Can UnicornFy work with this kind of stream?
userData stream don't have data in response and i got this:

Traceback (most recent call last):
  File "userdata_stream.py", line 34, in print_stream_data_from_stream_buffer
    unicorn = UnicornFy.binance_com_websocket(oldest_stream_data_from_stream_buffer)
  File "/home/dennis/py-projects/binance_ws/venv/lib/python3.7/site-packages/unicorn_fy/unicorn_fy.py", line 125, in binance_com_websocket
    return UnicornFy.binance_websocket(stream_data_json, exchange="binance.com", show_deprecated_warning=False)
  File "/home/dennis/py-projects/binance_ws/venv/lib/python3.7/site-packages/unicorn_fy/unicorn_fy.py", line 246, in binance_websocket
    if stream_data['data']['e'] == 'aggTrade':
KeyError: 'data'

info from response :

{"e":"ORDER_TRADE_UPDATE","T":1593708087377,"E":1593708087381,"o":{"s":"BTCUSDT","c":"u7AlA2t0ltH7fmyNOXon0j","S":"BUY","o":"MARKET","f":"GTC","q":"0.128","
p":"0","ap":"8958.98000","sp":"0","x":"TRADE","X":"FILLED","i":5520695062,"l":"0.016","z":"0.128","L":"8958.98","n":"0.05733747","N":"USDT","T":1593708087377
,"t":157239716,"b":"0","a":"0","m":false,"R":false,"wt":"CONTRACT_PRICE","ot":"MARKET","ps":"BOTH","cp":false,"rp":"0"}}

depth unittest shows asert error - why?

 File "unittest_unicorn_fy.py", line 211, in test_depth_futures
    self.assertEqual(str(self.unicorn_fy.binance_com_futures_websocket(data)), asserted_result)
AssertionError: "{'st[186 chars]77, 'asks': [['43900.54000000', '0.01080000'],[1446 chars]v']}" != "{'st[186 chars]77, 'bids': [['43903.04000000', '0.00000000'],[3496 chars]v']}"
Diff is 5429 characters long. Set self.maxDiff to None to see it.

https://github.com/LUCIT-Systems-and-Development/unicorn-fy/actions/runs/1935582006

json conversion function for outputting information to CSV files

Hi, first off, I want to say that the Unicorn Binance Websocket API is really great as it take the mess of the Binance API and structures it in to such a useful tool.

I am currently working on my own little bot and one of the things that became a little annoying was having to convert the raw data in to an exportable and usable CSV format where I can then load the CSV files as Pandas Dataframes for further calculation. The Unicorn_Fy module is awesome for taking the very raw json data and making it more readable but I think an executable function to convert that data further would be time-saving and very useful.

I am a novice Python coder but the following code is currently how I "clean" the raw data in to a usable CSV format:

``def process_message(msg):
if msg['e'] == 'error':
print("Error, malfunction")
time.sleep(3)
print("Terminating process")
time.sleep(3)
sys.exit()
else:
Data_Type = msg['e']

Datetimeindex = msg["E"] / 1000
Datetimeindex = datetime.fromtimestamp(Datetimeindex).strftime('%Y-%m-%d %H:%M:%S')

Symbol = msg['s']

Interval_Type = msg['k']['i']

Open_Price = msg['k']['o']

Close_Price = msg['k']['c']

High_Price = msg['k']['h']

Low_Price = msg['k']['l']

Volume = msg['k']['v']

Quantity = msg['k']['q']

print("{}, {}, {}, {}, {}, {}, {}, {}, {}, {}".format(Data_Type, Datetimeindex, 
                                                      Symbol, Interval_Type, Open_Price, 
                                                      Close_Price, High_Price, Low_Price, Volume, 
                                                      Quantity), file = "insert file name variable here, flush=True)``

I was wondering if this function could be inserted in to handling the kline streams or at least offer an "enable/disbale" function on a per stream basis via a boolean value which would allow each user to add the json conversion function if they wanted it.

On two side notes to this, the variable tags would need to be amended to offer users the full data-set, I am only interested in nine data points for further analysis.

The second side note is that you have to convert the UNIX timestamp to a proper datetime format as aggregation and resampling of kline data is "buggy" without a correctly formatted datetime to use as an index.

Hopefully this makes sense, I know I am "green" in terms of Python coding but I think the json conversion function would be something that would be really useful.

Either way, thanks for taking the time to think about this and consider it.

Cheers

James

Fix "bool object does not support item assignment" error hint.

Is your feature request related to a problem? Please describe.

Every time I tried to stop manager with stop_manager_with_all_streams, it hints an error which could be described like function_name -> error: bool object does not support item assignment. And I found out others mentioned this phenomenon with relatively lower frequency, see at: #30.

Describe the solution you'd like.

Change = False to = {} everywhere in Unicornfy can solve this directly without currently known side effects locally.

Describe alternatives you've considered

No response

Additional context

No response

new event "listStatus"

Hello,
Sorry for reopening the issue. I have the same error today when listening on UserData Stream.
I have verified the version of unicorn-fy, it's 0.6.0.

  File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/jean/myriad/projects/pyenv/crypto/lib/python3.7/site-packages/unicorn_binance_websocket_api/unicorn_binance_websocket_api_manager.py", line 415, in _create_stream_thread
    loop.run_until_complete(socket.start_socket())
  File "/usr/lib/python3.7/asyncio/base_events.py", line 579, in run_until_complete
    return future.result()
  File "/home/jean/myriad/projects/pyenv/crypto/lib/python3.7/site-packages/unicorn_binance_websocket_api/unicorn_binance_websocket_api_socket.py", line 114, in start_socket
    received_stream_data = self.unicorn_fy.binance_com_websocket(received_stream_data_json)
  File "/home/jean/myriad/projects/pyenv/crypto/lib/python3.7/site-packages/unicorn_fy/unicorn_fy.py", line 85, in binance_com_websocket
    return UnicornFy.binance_websocket(stream_data_json, exchange="binance.com", show_deprecated_warning=False)
  File "/home/jean/myriad/projects/pyenv/crypto/lib/python3.7/site-packages/unicorn_fy/unicorn_fy.py", line 249, in binance_websocket
    if stream_data['data']['e'] == 'aggTrade':
KeyError: 'data'

[Update]
I have identified the response that causes the error.

{
    "e": "listStatus",
    "E": 1606754342870,
    "s": "BTCUSDT",
    "g": 10610159,
    "c": "OCO",
    "l": "EXEC_STARTED",
    "L": "EXECUTING",
    "r": "NONE",
    "C": "VR0br4b4QJEFkbMqCsDUBJ",
    "T": 1606754342869,
    "O": [{
        "s": "BTCUSDT",
        "i": xxx,
        "c": "xxx"
    }, {
        "s": "BTCUSDT",
        "i": xxx,
        "c": "xxx"
    }]
}

Can you add support for this ? Thanks in advance for your help!

Originally posted by @giahung24 in #6 (comment)

key_error from the json output

I'm consistently getting key_error when I try to get data from the json output.
For example print(unicorn_fied_stream_data) works
But when I try to get the data part such as print(unicorn_fied_stream_data["data"]) it crashes with KeyError: 'data'
This is my code below. Code works on version 4.0.0 in my mac and ubuntu vps. The latest version gives the error

binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")
	binance_websocket_api_manager.create_stream(['ticker'], symbols_to_look )

	while True:
		oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
		if oldest_stream_data_from_stream_buffer:
			unicorn_fied_stream_data = UnicornFy.binance_com_websocket(oldest_stream_data_from_stream_buffer)
			symbol = unicorn_fied_stream_data['data'][0]['symbol']
			fields=[symbol,
					unicorn_fied_stream_data['data'][0]['event_time'],
					unicorn_fied_stream_data['data'][0]['price_change'],
					unicorn_fied_stream_data['data'][0]['price_change_percent'],
					unicorn_fied_stream_data['data'][0]['last_price'],
					unicorn_fied_stream_data['data'][0]['best_bid_price'],
					unicorn_fied_stream_data['data'][0]['best_ask_price'],
					unicorn_fied_stream_data['data'][0]['total_traded_base_asset_volume'],
					unicorn_fied_stream_data['data'][0]['total_traded_quote_asset_volume']]

			path = data_path + symbol + '.csv'
			with open(path, 'a') as f:
				writer = csv.writer(f)
				writer.writerow(fields)

Running for a few hours with this error

Version of this library.

Please post this to your github issue:
unicorn_fy: 0.12.2
unicorn_binance_local_depth_cache: not found
unicorn_binance_rest_api: not found
unicorn_binance_trailing_stop_loss: not found
unicorn_binance_websocket_api: 1.41.0

Solution to Issue cannot be found in the documentation or other Issues and also occurs in the latest version of this library.

  • I checked the documentation and other Issues. I am using the latest version of this library.

Hardware?

VPS or other cloud hosting

Operating System?

Linux

Python version?

Python3.8

Installed packages

Package                       Version
----------------------------- -------------------
aioamqp                       0.14.0
aiodns                        2.0.0
aiohttp                       3.7.4.post0
aioquant                      1.0.7
aioredis                      2.0.1
akshare                       1.3.38
aniso8601                     9.0.1
anyio                         3.5.0
asgiref                       3.5.0
async-timeout                 3.0.1
attrs                         21.2.0
bcrypt                        3.2.0
beautifulsoup4                4.10.0
Brotli                        1.0.9
ccxt                          1.54.58
certifi                       2021.5.30
cffi                          1.14.6
chardet                       4.0.0
charset-normalizer            2.0.4
cheroot                       8.5.2
click                         8.0.1
colorama                      0.4.4
cryptography                  3.4.7
cycler                        0.10.0
dateparser                    1.0.0
decorator                     5.1.1
demjson                       2.2.4
et-xmlfile                    1.1.0
fastapi                       0.73.0
Flask                         2.0.1
Flask-Compress                1.10.1
Flask-RESTful                 0.3.9
gunicorn                      20.1.0
h11                           0.13.0
hiredis                       2.0.0
html5lib                      1.1
httptools                     0.3.0
idna                          3.2
itsdangerous                  2.0.1
jaraco.functools              3.3.0
Jinja2                        3.0.1
jsonpath                      0.82
kiwisolver                    1.3.2
lxml                          4.7.1
MarkupSafe                    2.0.1
matplotlib                    3.4.3
more-itertools                8.8.0
motor                         2.0.0
multidict                     5.1.0
numpy                         1.21.1
openpyxl                      3.0.9
pamqp                         2.3.0
pandas                        1.3.1
paramiko                      2.10.3
pathlib                       1.0.1
patsy                         0.5.1
pika                          1.2.0
Pillow                        8.3.2
pip                           21.2.2
psutil                        5.8.0
py                            1.11.0
py-mini-racer                 0.6.0
pycares                       4.0.0
pycparser                     2.20
pydantic                      1.9.0
pymongo                       3.12.0
PyNaCl                        1.5.0
pyparsing                     2.4.7
pypinyin                      0.44.0
python-binance                1.0.12
python-dateutil               2.8.2
python-dotenv                 0.19.2
pytz                          2021.1
PyYAML                        6.0
regex                         2021.8.3
rel                           0.4.7
requests                      2.26.0
retry                         0.9.2
scipy                         1.7.1
setuptools                    52.0.0.post20210125
six                           1.16.0
sniffio                       1.2.0
soupsieve                     2.3.1
starlette                     0.17.1
unicorn-fy                    0.12.2
urllib3                       1.26.6
uvicorn                       0.17.4
uvloop                        0.16.0
watchgod                      0.7
webencodings                  0.5.1
websocket-client              1.1.1
websockets                    10.3
Werkzeug                      2.0.1
wheel                         0.36.2
xlrd                          2.0.1
yarl                          1.6.3

Logging output

Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-88-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Mon 18 Jul 2022 04:19:29 PM CST

  System load:  0.12               Processes:              182
  Usage of /:   86.6% of 19.62GB   Users logged in:        0
  Memory usage: 35%                IPv4 address for ens17: 10.0.4.2
  Swap usage:   0%

  => / is using 86.6% of 19.62GB
  => There is 1 zombie process.

 * Super-optimized for small spaces - read how we shrank the memory
Traceback (most recent call last):
  File "/root/anaconda3/envs/binancebot/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/root/anaconda3/envs/binancebot/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/root/anaconda3/envs/binancebot/lib/python3.8/site-packages/unicorn_binance_websocket_api/manager.py", line 529, in _create_stream_thread
    loop.run_until_complete(socket.start_socket())
  File "/root/anaconda3/envs/binancebot/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/root/anaconda3/envs/binancebot/lib/python3.8/site-packages/unicorn_binance_websocket_api/sockets.py", line 139, in start_socket
    received_stream_data = self.unicorn_fy.binance_com_futures_websocket(received_stream_data_json)
  File "/root/anaconda3/envs/binancebot/lib/python3.8/site-packages/unicorn_fy/unicorn_fy.py", line 129, in binance_com_futures_websocket
    return UnicornFy.binance_futures_websocket(stream_data_json,
  File "/root/anaconda3/envs/binancebot/lib/python3.8/site-packages/unicorn_fy/unicorn_fy.py", line 647, in binance_futures_websocket  
    if stream_data['data']['e'] == 'aggTrade':
KeyError: 'data'

Used endpoint?

binance.com-futures

Issue

Running for a few hours with this error

from unicorn_binance_websocket_api.manager import BinanceWebSocketApiManager
import logging
import time
import threading
import os
from unicorn_fy.unicorn_fy import UnicornFy
from termcolor import colored, cprint
import traceback
from pydantic import BaseModel
import time
from functools import wraps


# create instances of BinanceWebSocketApiManager
binance_com_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com-futures", output_default="UnicornFy",throw_exception_if_unrepairable=True)

# configure api key and secret for binance.com for Alice
alice_api_key = ""
alice_api_secret = ""
# create the userData streams
alice_stream_id = binance_com_websocket_api_manager.create_stream('arr', '!userData', stream_label="Alice",
                                                                  stream_buffer_name=True,
                                                                  api_key=alice_api_key, api_secret=alice_api_secret)


info_stream = binance_com_websocket_api_manager.get_stream_list()

print(alice_stream_id)
print('status',info_stream[alice_stream_id]['status'])
print('stop_request',info_stream[alice_stream_id]['stop_request'])#停止请求
print('crash_request',info_stream[alice_stream_id]['crash_request'])#崩溃请求
print('kill_request',info_stream[alice_stream_id]['kill_request'])#杀死请求
print('reconnects',info_stream[alice_stream_id]['reconnects'])#重连次数


# print(binance_com_websocket_api_manager.get_stream_statistic(alice_stream_id))

# 结果转成JSON


def str2json(result):
    return UnicornFy.binance_com_futures_websocket(result)

def getdate2(t):
    '''时间戳转换为时间'''
    t1 = float(t)/1000
    # print(timeStamp)
    t2 = time.localtime(t1)
    # print(timeArray)
    t3 = time.strftime("%Y-%m-%d %H:%M:%S", t2)
    # print(otherStyleTime)
    return t3

# # https://docs.python.org/3/library/logging.html#logging-levels
logging.basicConfig(level=logging.DEBUG,
                    filename=os.path.basename(__file__) + '.log',
                    format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
                    style="{")




# Python线程退出条件有以下几种:
# 1、线程内的函数语句执行完毕,线程自动结束
# 2、线程内的函数抛出未处理的异常

def print_stream_buffer_data(binance_websocket_api_manager, stream_id):
    while True:
        #有停止请求,则返回True ,否则返回 'False'。
        try :
            if binance_websocket_api_manager.is_manager_stopping():
                print("遇到错误了,正常运行程序并退出程序")
                exit(0)
            oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer(stream_id)
            if oldest_stream_data_from_stream_buffer is False:
                time.sleep(0.01)
                
            else:
                # print(oldest_stream_data_from_stream_buffer)
                #信号状态
                data = UnicornFy.binance_com_futures_websocket(oldest_stream_data_from_stream_buffer)
                event_type = data["event_type"]
                if event_type == "ORDER_TRADE_UPDATE":
                    #币种
                    symbol = data['symbol']
                    #方向
                    side = data['side']
                    #持仓方向
                    position_side = data['position_side']
                    #挂单价格
                    order_price = data['order_price']
                    #实际成交价格
                    order_avg_price = data['order_avg_price']
                    #挂单数量
                    order_quantity = data['order_quantity']
                    current_order_status = data['current_order_status']
                    current_execution_type =  data['current_execution_type']
                    transaction_time = getdate2( data['transaction_time'])
                    
                    last_executed_price = data['last_executed_price']
                    #交易编号 ex android_mJlmVJJhRdpoL2fnSAhB
                    client_order_id =  data['client_order_id']
                    #交易ID  ex 60952023909
                    order_id =  data['order_id']
                    #这个目前没用
                    trade_id = data['trade_id']
                    #下单为 LIMIT  挂单止盈为TAKE_PROFIT
                    order_type = data['order_type']
                    
                    trad_type = None 
                    if order_type == "LIMIT":
                        trad_type = "限价单"
                    elif order_type == "TAKE_PROFIT":
                        trad_type = "止盈止损单"
                    elif order_type == "MARKET":
                        trad_type = "市价单" 

                    
                    temp ={ 
                        "BUYLONG":"买入开多",
                        "BUYSHORT":"买入平空",
                        "SELLSHORT":"卖出开空",
                        "SELLLONG":"卖出平多",
                        'NEWNEW':"挂单未成交",
                        'CANCELEDCANCELED':"撤单",
                        'TRADEFILLED':"挂单已成交",
                        'EXPIREDEXPIRED':"订单已过期",
                        'TRADEPARTIALLY_FILLED':'部分成交'
                    }
                
                    side_away = temp[side+position_side]
                    acction = temp[current_execution_type + current_order_status]
                    cprint(f"订单状态:{acction}  信号状态:{event_type} 币种:{symbol} 下单动作:{side_away} 挂单价格:{order_price} 成交价格:{order_avg_price} 平仓价格:{last_executed_price} 挂单数量:{order_quantity} 时间:{transaction_time}",
                        'green', 'on_red')
                    
        except BaseException as e :
            print(e)
            
                    



# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading.Thread(target=print_stream_buffer_data, args=(binance_com_websocket_api_manager,
                                                                        alice_stream_id))


# get info about the new stream
# second_multi_stream_info = binance_com_websocket_api_manager.get_stream_info(alice_stream_id)
# print(second_multi_stream_info)
worker_thread.start()






KeyError: 'symbol'

Hello,

When I try to print a formatted unicorn dict to console i get Keyerror.

This is my code:


def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
    while True:
        if binance_websocket_api_manager.is_manager_stopping():
            exit(0)
        oldest_stream_data_from_stream_buffer = \
            binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
        if oldest_stream_data_from_stream_buffer is not False:
            unicorn_fied_data = UnicornFy.binance_com_websocket(
                    oldest_stream_data_from_stream_buffer)
            print('Time: {} Symbol: {} Side: {} Price: {} Quantity: {} '
                'Status: {}'.format(unicorn_fied_data['event_time'],
                                    unicorn_fied_data['symbol'],
                                    unicorn_fied_data['side'],
                                    unicorn_fied_data['order_price'],
                                    unicorn_fied_data['order_quantity'],
                                    unicorn_fied_data['current_order_status']))
        else:
            time.sleep(0.01)

This is the error:

Time: 1600220588187 Symbol: ETHBTC Side: BUY Price: 0.03000000 Quantity: 0.02300000 Status: NEW
Exception in thread Thread-16:
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\asus\Documents\Personal\Corporate\Python\red_robin\websockettest.py", line 23, in print_stream_data_from_stream_buffer
    unicorn_fied_data['symbol'],
KeyError: 'symbol'

As you can see the correct formatting is printing to console but there still a keyerror, how can I fix this?

Mini Ticker cannot be converted

Hello,

I am using unicorn_fy in combination with the unicorn_binance_websocket_api and am trying to get data via mini ticker subscriptions (https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-mini-ticker-stream).

However, when subscribing to a mini ticker, unicorn_fy is not able to process the stream output and throws an exception:

ERROR:root:Detected unknown data stream format (type2) in module `unicorn_fy`: please report to https://github.com/oliver-zehentleitner/unicorn_fy/issues {'stream': '!miniTicker@arr', 'data': [{'e': '24hrMiniTicker', 'E': 1588516002804, 's': 'BTCUSDT', 'c': '8900.00000000', 'o': '8898.33000000', 'h': '9200.00000000', 'l': '8811.00000000', 'v': '88800.22015400', 'q': '798918007.17006880'}, ... ]} - list indices must be integers or slices, not str

Here is the code I used:

from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager
from unicorn_fy.unicorn_fy import UnicornFy

binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")
binance_websocket_api_manager.create_stream(['!miniTicker'], [])

while True:
    oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
    if oldest_stream_data_from_stream_buffer:
        unicorn_fied_stream_data = UnicornFy.binance_com_websocket(oldest_stream_data_from_stream_buffer)
        print(unicorn_fied_stream_data)

It would be great, if support for mini tickers could be added.

Thanks in advance and best regards,
Stefan

Edit: Corrected shown error and used code (they were not complete / reflecting the correct version used)

userdata

def binance_futures_websocket

->>

line 577

        elif stream_data['e'] == 'ORDER_TRADE_UPDATE':
            stream_data = {'data': stream_data}
        elif stream_data['e'] == 'ACCOUNT_UPDATE':
            stream_data = {'data': stream_data}

line elif stream_data['data']['e'] == 'executionReport': #next

       elif stream_data['data']['e'] == 'ORDER_TRADE_UPDATE':
            print('这里是发现了订单推送')
            unicorn_fied_data = {'stream_type': 'ORDER_TRADE_UPDATE',
                                 'event_type': stream_data['data']['e'],
                                 'event_time': stream_data['data']['E'],
                                 'symbol': stream_data['data']['o']['s'], # 交易对
                                 'client_order_id': stream_data['data']['o']['c'], # 订单编号
                                 'side': stream_data['data']['o']['S'], # 有用,订单方向
                                 'order_type': stream_data['data']['o']['o'], # 订单类型
                                 'time_in_force': stream_data['data']['o']['f'], # 有效方式
                                 'order_quantity': stream_data['data']['o']['q'], # 订单原始数量
                                 'order_price': stream_data['data']['o']['p'],# 原始价格
                                 'order_avg_price': stream_data['data']['o']['ap'],# 平均价格
                                 'order_tj_price': stream_data['data']['o']['sp'],# 条件订单触发价格,对追踪止损单无效
                                 'current_execution_type': stream_data['data']['o']['x'],# 本次事件的具体执行类型
                                 'current_order_status': stream_data['data']['o']['X'], # 订单的当前状态
                                 'order_id': stream_data['data']['o']['i'],# 订单ID
                                 'last_executed_quantity': stream_data['data']['o']['l'],# 订单末次成交量
                                 'cumulative_filled_quantity': stream_data['data']['o']['z'],# 订单累计已成交量
                                 'last_executed_price': stream_data['data']['o']['L'],# 订单末次成交价格
                                 # 'commission_amount': stream_data['data']['o']['n'],# 手续费数量
                                 # 'commission_asset': stream_data['data']['o']['N'],# 手续费资产类型
                                 'transaction_time': stream_data['data']['o']['T'],# 成交时间
                                 'trade_id': stream_data['data']['o']['t'], # 成交ID
                                 'net_pay': stream_data['data']['o']['b'], # 买单净值
                                 'net_selling_order_value': stream_data['data']['o']['a'],# 卖单净值
                                 'is_trade_maker_side': stream_data['data']['o']['m'], # 该成交是作为挂单成交吗
                                 'reduceOnly': stream_data['data']['o']['R'],# 是否是只减仓单
                                 'trigger_price_type': stream_data['data']['o']['wt'], # 触发价类型
                                 'order_price_type': stream_data['data']['o']['ot'],# 原始定单类型
                                 'positionSide': stream_data['data']['o']['ps'],
                                 # 'cumulative_quote_asset_transacted_quantity': stream_data['data']['cp'],
                                 # 'cumulative_quote_asset_transacted_quantity': stream_data['data']['AP'],
                                 # 'cumulative_quote_asset_transacted_quantity': stream_data['data']['cr'],
                                 'order_profit_loss': stream_data['data']['o']['rp']} #该交易实现盈亏

Unhandled exception with UnicornFy

Version of this library.

Using v1.41.0 of unicorn websocket and 0.12.2 of unicorn-fy.

Solution to Issue cannot be found in the documentation or other Issues and also occurs in the latest version of this library.

  • I checked the documentation and other Issues. I am using the latest version of this library.

Hardware?

VPS or other cloud hosting

Operating System?

Linux

Python version?

Python3.8

Installed packages

aiohttp                       3.8.1
aiosignal                     1.2.0
aniso8601                     9.0.1
async-timeout                 4.0.2
attrs                         22.1.0
autobahn                      22.6.1
Automat                       20.2.0
backports.zoneinfo            0.2.1
Backtesting                   0.3.2
binance-futures-connector     3.1.1
bokeh                         2.4.3
certifi                       2022.5.18.1
cffi                          1.15.1
charset-normalizer            2.0.12
cheroot                       8.6.0
click                         8.1.3
colorama                      0.4.5
constantly                    15.1.0
cryptography                  37.0.4
cycler                        0.11.0
dateparser                    1.1.1
et-xmlfile                    1.1.0
Flask                         2.1.2
Flask-RESTful                 0.3.9
fonttools                     4.34.3
frozenlist                    1.3.0
hyperlink                     21.0.0
idna                          3.3
importlib-metadata            4.12.0
incremental                   21.3.0
itsdangerous                  2.1.2
jaraco.functools              3.5.1
Jinja2                        3.1.2
kiwisolver                    1.4.3
MarketProfile                 0.2.0
MarkupSafe                    2.1.1
matplotlib                    3.5.2
more-itertools                8.14.0
multidict                     6.0.2
numpy                         1.22.4
openpyxl                      3.0.10
packaging                     21.3
pandas                        1.4.2
pandas-ta                     0.3.14b0
patsy                         0.5.2
Pillow                        9.2.0
pip                           22.1.2
plotly                        5.9.0
plotly-express                0.4.1
psutil                        5.9.1
pyasn1                        0.4.8
pyasn1-modules                0.2.8
pybit                         2.4.0
pycparser                     2.21
pyOpenSSL                     22.0.0
pyparsing                     3.0.9
python-binance                1.0.16
python-dateutil               2.8.2
pytz                          2022.1
pytz-deprecation-shim         0.1.0.post0
PyYAML                        6.0
regex                         2022.3.2
requests                      2.28.0
scipy                         1.9.0
seaborn                       0.11.2
service-identity              21.1.0
setuptools                    61.2.0
six                           1.16.0
statsmodels                   0.13.2
tenacity                      8.0.1
tornado                       6.1
Twisted                       22.4.0
twisted-iocpsupport           1.0.2
txaio                         22.2.1
typing_extensions             4.3.0
tzdata                        2022.1
tzlocal                       4.2
ujson                         5.4.0
unicorn-binance-websocket-api 1.41.0
unicorn-fy                    0.12.2
urllib3                       1.26.9
websocket-client              1.3.2
websockets                    10.3
Werkzeug                      2.1.2
wheel                         0.37.1
wincertstore                  0.2
yarl                          1.7.2
zipp                          3.8.1
zope.interface                5.4.0

Logging output

No response

Processing method?

stream_buffer

Used endpoint?

binance.com-futures-testnet

Issue

This problem happens specifically with .pop_stream_signal_from_stream_signal_buffer(). The issue appears after I open an order with a take profit and stop loss where one of them is filled and the other is canceled.

My question is; how do we handle this error since it cannot be caught as an exception in my handler/thread?

Stacktrace:

Exception in thread _create_stream_thread:  stream_id=708e339568d4-4c94-8349-c19f-2bb85a1e, time=1662466313.6806593:
Traceback (most recent call last):
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\site-packages\unicorn_binance_websocket_api\manager.py", line 529, in _create_stream_thread
    loop.run_until_complete(socket.start_socket())
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\site-packages\unicorn_binance_websocket_api\sockets.py", line 141, in start_socket
    received_stream_data = self.unicorn_fy.binance_com_futures_websocket(received_stream_data_json)
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\site-packages\unicorn_fy\unicorn_fy.py", line 129, in binance_com_futures_websocket
    return UnicornFy.binance_futures_websocket(stream_data_json,
  File "C:\Users\caspe\miniconda3\envs\tradingbot\lib\site-packages\unicorn_fy\unicorn_fy.py", line 647, in binance_futures_websocket
    if stream_data['data']['e'] == 'aggTrade':
KeyError: 'data'

Complete ACCOUNT_UPDATE event for binance futures

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

The account data is not being parsed on the ACCOUNT_UPDATE event of binance futures.

Describe the solution you'd like
A clear and concise description of what you want to happen.

Implement the missing sections.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Exception in thread _create_stream_thread

Version of this library.

unicorn-binance-websocket-api==1.41.0
unicorn-fy==0.12.2

Solution to Issue cannot be found in the documentation or other Issues and also occurs in the latest version of this library.

  • I checked the documentation and other Issues. I am using the latest version of this library.

Hardware?

VPS or other cloud hosting

Operating System?

Windows

Python version?

Python3.10

Installed packages

pip install unicorn-binance-websocket-api --upgrade

Logging output

Exception in thread _create_stream_thread:  stream_id=, time=1661778274.3499045:
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "C:\Program Files\Python310\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "\venv\lib\site-packages\unicorn_binance_websocket_api\manager.py", line 529, in _create_stream_thread
    loop.run_until_complete(socket.start_socket())
  File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "\venv\lib\site-packages\unicorn_binance_websocket_api\sockets.py", line 139, in start_socket
    received_stream_data = self.unicorn_fy.binance_com_futures_websocket(received_stream_data_json)
  File "\venv\lib\site-packages\unicorn_fy\unicorn_fy.py", line 129, in binance_com_futures_websocket
    return UnicornFy.binance_futures_websocket(stream_data_json,
  File "\venv\lib\site-packages\unicorn_fy\unicorn_fy.py", line 647, in binance_futures_websocket
    if stream_data['data']['e'] == 'aggTrade':
KeyError: 'data'

Processing method?

process_stream_data

Used endpoint?

binance.com-futures

Issue

Hello,
I got this error :
Exception in thread _create_stream_thread: stream_id=, time=1661778274.3499045:Exception in thread _create_stream_thread: stream_id=, time=1661778274.3499045:
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\threading.py", line 1016, in _bootstrap_inner
self.run()
File "C:\Program Files\Python310\lib\threading.py", line 953, in run
self._target(*self._args, **self._kwargs)
File "\venv\lib\site-packages\unicorn_binance_websocket_api\manager.py", line 529, in _create_stream_thread
loop.run_until_complete(socket.start_socket())
File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "\venv\lib\site-packages\unicorn_binance_websocket_api\sockets.py", line 139, in start_socket
received_stream_data = self.unicorn_fy.binance_com_futures_websocket(received_stream_data_json)
File "\venv\lib\site-packages\unicorn_fy\unicorn_fy.py", line 129, in binance_com_futures_websocket
return UnicornFy.binance_futures_websocket(stream_data_json,
File "\venv\lib\site-packages\unicorn_fy\unicorn_fy.py", line 647, in binance_futures_websocket
if stream_data['data']['e'] == 'aggTrade':
KeyError: 'data'

Update "outboundAccountPosition" not supported

Check this or we will delete your issue. (fill in the checkbox with an X like so: [x])

  • I have searched for other issues with the same problem or similar feature requests.

Select one:

  • Bug
  • Feature Request
  • Technical Help
  • Other

Environment

  • Are you using the module on a VPS or other Cloud hosting?
  • If so, have you tried running the code on your local machine?
  • Are you using the module on a Raspberry Pi?

Operating System? (include version)

  • macOS
  • Windows
  • Linux (include flavour)

Exact Python Version?

Python 3.8.5

Pip Version?

pip 20.1.1

Description of your issue

I found that unicorn_fy does not support the outboundAccountPosition socket update. The fix is pretty straightforward and I can create a PR or just use what I put in the comments here

Traceback (most recent call last):
  File "/Users/bschwartz/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/Users/bschwartz/.pyenv/versions/3.8.5/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "./project/exchange_account.py", line 23, in print_stream_data_from_stream_buffer
    stream_data = UnicornFy.binance_com_websocket(received_stream_data_json)
  File "/.../venv/lib/python3.8/site-packages/unicorn_fy/unicorn_fy.py", line 125, in binance_com_websocket
    return UnicornFy.binance_websocket(stream_data_json, exchange="binance.com", show_deprecated_warning=False)
  File "/.../venv/lib/python3.8/site-packages/unicorn_fy/unicorn_fy.py", line 246, in binance_websocket
    if stream_data['data']['e'] == 'aggTrade':
KeyError: 'data'

Fix

In unicorn_fy/unicorn_fy.py

On line 204 beneath the executionReport block

elif stream_data['e'] == 'outboundAccountPosition':
    stream_data = {'data': stream_data}

On line 441 beneath the outboundAccountInfo block:

elif stream_data['data']['e'] == 'outboundAccountPosition':
    unicorn_fied_data = {'stream_type': '!userData@arr',
                            'event_type': stream_data['data']['e'],
                            'event_time': stream_data['data']['E'],
                            'last_update_time': stream_data['data']['u'],
                            'balances': []}
    for item in stream_data['data']['B']:
        new_item = {'asset': item['a'],
                    'free': item['f'],
                    'locked': item['l']}
        unicorn_fied_data['balances'] += [new_item]

Unicorn Websocket crashes because of key 'data' error when the event type is balanceUpdate

Check this or we will delete your issue. (fill in the checkbox with an X like so: [x])

  • I have searched for other issues with the same problem or similar feature requests.

Select one:

  • Bug
  • Feature Request
  • Technical Help
  • Other

Environment

  • Are you using the module on a VPS or other Cloud hosting?
  • If so, have you tried running the code on your local machine?
  • Are you using the module on a Raspberry Pi?

Operating System? (include version)

  • macOS
  • Windows
  • Linux (include flavour) Docker Image python:3.8

Exact Python Version?

Python 3.8.7

Pip Version?

pip 21.0.1

Description of your issue

unicorn-binance-websocket-api crashes when I use the output=UnicornFy on my user stream and I make a manual trade on my Binance account. My guess is that the key 'balanceUpdate' does not exist in UnicornFy.

This error occurs both in margin (cross and isolated) and spot account stream data.

I've created the isolated margin stream with the output=UnicornFy

ubwa_com_im.create_stream(
                "arr",
                "!userData",
                symbols="BTCUSDT",
                output="UnicornFy",
                api_key=binance_api_key,
                api_secret=binance_api_secret,
                stream_label="im BTCUSDT"
)

This is part of the DEBUG output after I've sent 1USDT to my BTCUSDT Isolated-Margin (this error also happens in the spot account when I trade manually.

unicorn_stream                | 2021-03-16 20:21:58,309 - DEBUG |client - received solicited pong: 60806399
unicorn_stream                | 2021-03-16 20:22:10,470 - DEBUG |client - event = data_received(<72 bytes>)
unicorn_stream                | 2021-03-16 20:22:10,470 - DEBUG |client - event = data_received(<97 bytes>)
unicorn_stream                | 2021-03-16 20:22:10,481 - DEBUG |client < Frame(fin=True, opcode=1, data=b'{"e":"balanceUpdate","E":1615926131286,"a":"USDT","d":"1.00000000","T":1615926131285}', rsv1=False, rsv2=False, rsv3=False)
unicorn_stream                | 2021-03-16 20:22:10,491 - DEBUG |client < Frame(fin=True, opcode=1, data=b'{"e":"outboundAccountPosition","E":1615926131286,"u":1615926131285,"B":[{"a":"USDT","f":"1.00000000","l":"0.00000000"}]}', rsv1=False, rsv2=False, rsv3=False)
unicorn_stream                | 2021-03-16 20:22:10,622 - DEBUG |UnicornFy->binance_websocket({"e":"balanceUpdate","E":1615926131286,"a":"USDT","d":"1.00000000","T":1615926131285})
unicorn_stream                | 2021-03-16 20:22:10,627 - ERROR |BinanceWebSocketApiSocket.start_socket(d4b1ac8c-f4c3-4f4a-b6a7-e67bb04ad856, ['arr'], ['!userData']) - Exception General Exception - error_msg: 'data'
unicorn_stream                | 2021-03-16 20:22:10,632 - CRITICAL |BinanceWebSocketApiManager.stream_is_crashing(d4b1ac8c-f4c3-4f4a-b6a7-e67bb04ad856)
unicorn_stream                | 2021-03-16 20:22:10,638 - DEBUG |client - state = CLOSING
unicorn_stream                | 2021-03-16 20:22:10,643 - DEBUG |client > Frame(fin=True, opcode=8, data=b'\x03\xe8', rsv1=False, rsv2=False, rsv3=False)
unicorn_stream                | 2021-03-16 20:22:10,721 - INFO |BinanceWebSocketApiManager.kill_stream(d4b1ac8c-f4c3-4f4a-b6a7-e67bb04ad856)
unicorn_stream                | 2021-03-16 20:22:10,726 - INFO |BinanceWebSocketApiManager._restart_stream(d4b1ac8c-f4c3-4f4a-b6a7-e67bb04ad856, ['arr'], ['!userData'])
unicorn_stream                | 2021-03-16 20:22:10,737 - DEBUG |Using selector: EpollSelector

I think this is the part of the UnicornFy code that misses the balanceUpdate key and throws the error down in the code:

        try:
            if stream_data['e'] == 'outboundAccountInfo':
                stream_data = {'data': stream_data}
            elif stream_data['e'] == 'executionReport':
                stream_data = {'data': stream_data}
            elif stream_data['e'] == 'outboundAccountPosition':
                stream_data = {'data': stream_data}
            elif stream_data['e'] == 'listStatus':
                stream_data = {'data': stream_data}
        except KeyError:
            pass

Since the 'balanceUpdate' is not on this if-else chain the stream_data follows as it is, the code down below can't find the key 'data' and raises the error killing the WebSocket.

I did a local test tinkering with this and worked, however, I did by processing the JSON after the buffer output and not using the output param in create_stream. I'll fork the code, fix this and will do a pull request.

Logo for this project

Hello!
Is there someone who would make a logo for this project?
Thank you!
Oliver

Add unittests

Is your feature request related to a problem? Please describe.
Quality management...

Describe the solution you'd like
Unittests for every kind of receive.

Describe alternatives you've considered

Additional context

Slight differences between Binance.com and Binance-futures

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
The response message from a aggTrade stream is slightly different than than that from Binance.com. The resonse I get is:
{"stream":"btcusdt@aggTrade","data":{"e":"aggTrade","E":1573576417345,"a":6292316,"s":"BTCUSDT","p":"8718.19","q":"0.792","f":8414086,"l":8414086,"T":1573576417240,"m":true}}

This key doen't exist for futures:
stream_data['data']['M']

Describe the solution you'd like
A clear and concise description of what you want to happen.

Remove this part in method 'binance_websocket':
'ignore': stream_data['data']['M']

in:
if stream_data['data']['e'] == 'aggTrade':
unicorn_fied_data = {'stream_type': stream_data['stream'],
'event_type': stream_data['data']['e'],
'event_time': stream_data['data']['E'],
'symbol': stream_data['data']['s'],
'aggregate_trade_id': stream_data['data']['a'],
'price': stream_data['data']['p'],
'quantity': stream_data['data']['q'],
'first_trade_id': stream_data['data']['f'],
'last_trade_id': stream_data['data']['l'],
'trade_time': stream_data['data']['T'],
'is_market_maker': stream_data['data']['m'],
--> 'ignore': stream_data['data']['M'] <-- }

since it's not used anyway.

Thanks.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

CRITICAL:root:UnicornFy

Check this or we will delete your issue. (fill in the checkbox with an X like so: [x])

  • I have searched for other issues with the same problem or similar feature requests.

Select one:

  • Bug
  • Feature Request
  • Technical Help
  • Other

Environment

  • Are you using the module on a VPS or other Cloud hosting?
  • If so, have you tried running the code on your local machine?
  • Are you using the module on a Raspberry Pi?

Operating System? (include version)

  • macOS
  • Windows
  • Linux (include flavour)

Exact Python Version?

Include here the response of 'python --version' or 'python3 --version'
Python 3.9.7

Pip Version?

Include here the response of 'pip --version' or 'pip3 --version'
pip 21.2.4

Description of your issue

I just got this error while looking at logs, it seems that a Boolean has been passed instead of json data

CRITICAL:root:UnicornFy->binance_futures_websocket(False) - error: 'bool' object does not support item assignment

def print_stream_buffer_data(binance_websocket_api_manager, stream_id):
    while True:
        if binance_websocket_api_manager.is_manager_stopping():
            exit(0)
        oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer(
            stream_id)
        if oldest_stream_data_from_stream_buffer is False:
            time.sleep(0.01)
        else:
            order = UnicornFy.binance_com_futures_websocket(oldest_stream_data_from_stream_buffer) # <--- ERROR HERE
            if order.get('stream_type') == "ACCOUNT_CONFIG_UPDATE":
                # PROCESS DATA
            if order.get("stream_type") == "ORDER_TRADE_UPDATE":
                # PROCESS DATA

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.