Search code examples
python-3.xbinance-api-client

The script works for sometime and the crashes


This script runs for like may be 10 seconds(It varies) and then suddenly stops with an error saying

IndexError: index 0 is out of bounds for axis 0 with size 0

from binance.client import Client
client = Client()

coin = "PYRBUSD"
ST = 20
LT = 60

def gethistoricals(symbol, LT):
    df = pd.DataFrame(client.get_historical_klines(symbol, '1m', str(LT) + 'minutes ago UTC'))
    closes = pd.DataFrame(df[4])
    closes.columns = ['Close']    
    closes['ST'] = closes.Close.rolling(ST).sum() 
    closes.dropna(inplace=True)
    return closes

def check(coin): 
    ma1 = round((float(historicals['ST'].values[0]) / ST), 4)
    
    print(ma1)
    print(type(ma1))
    return True

while True:
    historicals = gethistoricals(coin, 20) 
    print(historicals)

    if check(coin): 
        print("Check Pass")

My output looks like this. Please note the Index: [] at the end

.
.
.

Close     ST
19  4.43000000  88.72
4.436
<class 'float'>
Check Pass
         Close     ST
19  4.43000000  88.72
4.436
<class 'float'>
Check Pass
         Close     ST
19  4.43000000  88.72
4.436
<class 'float'>
Check Pass
         Close     ST
19  4.43000000  88.72
4.436
<class 'float'>
Check Pass
Empty DataFrame
Columns: [Close, ST]
Index: []

I am getting this error

IndexError                                Traceback (most recent call last)
Input In [7], in <cell line: 23>()
     24 historicals = gethistoricals(coin, 20) 
     25 print(historicals)
---> 27 if check(coin): 
     28     print("Check Pass")

Input In [7], in check(coin)
     16 def check(coin): 
---> 17     ma1 = round((float(historicals['ST'].values[0]) / ST), 4)
     19     print(ma1)
     20     print(type(ma1))

IndexError: index 0 is out of bounds for axis 0 with size 0

Solution

  • Check before you access a value:

    def check(coin): 
        if historicals.empty:
            return False
    
        ma1 = round((float(historicals['ST'].values[0]) / ST), 4)    
        print(ma1)
        print(type(ma1))
        return True