sammchardy / python-binance

Binance Exchange API python implementation for automated trading
https://python-binance.readthedocs.io/en/latest/
MIT License
6.02k stars 2.2k forks source link

RuntimeError: dictionary changed size during iteration #178

Closed so1tsuda closed 2 years ago

so1tsuda commented 6 years ago

Hi, I've got this error below when using websocket for streaming market depth.

Traceback (most recent call last):
  File "inago-simulation-BTCUSD-realtime-linux.py", line 118, in <module>
    if len(depth_cache.get_bids()[:5]) > 0:
  File "/home/soichiro_tsuda/miniconda3/lib/python3.6/site-packages/binance/depthcache.py", line 75, in get_bids
    return DepthCache.sort_depth(self._bids, reverse=True)
  File "/home/soichiro_tsuda/miniconda3/lib/python3.6/site-packages/binance/depthcache.py", line 114, in sort_de
pth
    lst = [[float(price), quantity] for price, quantity in vals.items()]
  File "/home/soichiro_tsuda/miniconda3/lib/python3.6/site-packages/binance/depthcache.py", line 114, in <listco
mp>
    lst = [[float(price), quantity] for price, quantity in vals.items()]
RuntimeError: dictionary changed size during iteration

My code was pretty simple --- read depth_cache every 1s

dcm = DepthCacheManager(client, 'BTCUSDT', refresh_interval=0) # disable refresh
depth_cache = dcm.get_depth_cache()

while True:
    if len(depth_cache.get_bids()[:5]) > 0:
        curr_bids = depth_cache.get_bids()[:5]
    else:
        curr_bids = ""
    if len(depth_cache.get_asks()[:5]) > 0:
        curr_asks = depth_cache.get_asks()[:5]
    else:
        curr_asks = ""    
    time.sleep(0.6)

I've got the above error on Windows (7 or 10) as well as on Linux (GCP), both with Anaconda Python 3.6. python-binance was installed via pip (ver 0.6.4).

As a workaround, I changed vals.items() to list(vals.items()) in depthcache.py as follows:

lst = [[float(price), quantity] for price, quantity in list(vals.items())]

I don't have the above error message any more after this modification, although I'm not 100% sure if it's the right way as I'm still a noob.

so1tsuda commented 6 years ago

a little update: I still got the error even after the modification in the code... although it was significantly less to see the error.