Search code examples
pythonta-libbinance-api-client

Why is the ATR Indicator of TA-Lib not working?


I'm having some problems using the ATR-Indicator in the TA-Lib library. Every other indicator seems to work just fine.

Here's the code in python:

import json
import numpy
import talib
import websocket


# *******PARAMETERS
# Name of Socket for BTC in USDT 1min Candle
SOCKET = "wss://stream.binance.com:9443/ws/btcusdt@kline_1m"
# Arrays
closes = []
highs = []
lows = []

# ***Websocket definition***
def on_open_ws(ws):
    print('opened connection')


def on_close_ws(ws):
    print('closed connection')


def on_message_ws(ws, message):
    json_message = json.loads(message)

    # only watching the candle infos in received message
    candle = json_message['k']

    # getting close, high and low values
    is_candle_closed = candle['x']
    close = float(candle['c'])
    high = float(candle['h'])
    low = float(candle['l'])


    if is_candle_closed:  
        closes.append(close)  # add close price to closes-array
        np_closes = numpy.array(closes)  # convert closes-array in numpy
        c_close = np_closes[-1]  # current close
        p_close = np_closes[-2]  # previous close
        print(len(closes))

        highs.append(high)
        np_highs = numpy.array(highs)
        last_high = np_highs[-1]

        lows.append(low)
        np_lows = numpy.array(lows)
        last_low = np_lows[-1]

        # Set ATR
        atr = talib.ATR(np_highs, np_lows, np_closes, timeperiod=14)
        last_atr = atr[-1]
        print('last atr')
        print(last_atr)

ws = websocket.WebSocketApp(SOCKET, on_open=on_open_ws, on_close=on_close_ws, on_message=on_message_ws)

# Run websocket app
ws.run_forever()

The last commands "print('last atr') and print(last_atr) do not print, suggesting that the atr isnt working.

Does somehow have any idea what could be the problem?

I tried using just the last values of high, low and close as well as the non-numpied values, but this doesn't change anything. I'm not even getting the "nan" answer for the first few values...


Solution

  • Your first call of on_message_ws() with is_candle_closed == true crashes at line p_close = np_closes[-2] # previous close as there is only 1 element in closes yet.

    After this crash the next call of on_message_ws() with is_candle_closed == true will continue with len(closes) == 2 and len(lows) == len(highs) == 1 and then crash at talib.ATR() with Exception: input array lengths are different.

    And so on.

    P.S. I would also suggest to use numpy.array(closes, dtype='double') instead of numpy.array(closes) as talib.ATR() is able to crash with Exception: input array type is not double. That's not happening with current data received from binance, but just to be safe I would ensure the arrays are converted to double.