1

我在使用 TA-Lib 库中的 ATR-Indicator 时遇到了一些问题。其他所有指标似乎都运行良好。

这是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()

最后一个命令 "print('last atr') 和 print(last_atr) 不打印,表明 atr 不工作。

不知何故知道可能是什么问题?

我尝试只使用高、低和关闭的最后一个值以及非 numpied 值,但这并没有改变任何东西。我什至没有得到前几个值的“nan”答案......

4

2 回答 2

0

所以我通过编写自己的 ATR 来解决我的问题,这比我想象的要容易得多。如果它可以帮助任何人继承代码

def true_range(high, low, p_close):
    high_low = high - low
    high_close = numpy.abs(high - p_close)
    low_close = numpy.abs(low - p_close)

trange = max(high_low, high_close, low_close)
return trange

# Set TR
    
    last_tr = true_range(last_high, last_low, p_close)
    tr.append(last_tr)
    if len(tr) > ATR_PERIOD:
        del tr[0]

    # Set ATR (SMA smoothing but need RMA)
    atr = sum(tr) / ATR_PERIOD
    print('atr ', atr)

ATR_PERIOD 是您要设置的时间段。对于 ATR_PERIOD 的长度,你显然会得到错误的数字,但之后你应该没问题

于 2021-09-09T14:07:27.123 回答
0

您第一次调用on_message_ws()with is_candle_closed == truecrashs at linep_close = np_closes[-2] # previous close因为目前只有 1 个元素closes

在此崩溃之后,下一次调用on_message_ws()withis_candle_closed == true将继续,len(closes) == 2然后len(lows) == len(highs) == 1talib.ATR()with崩溃Exception: input array lengths are different

等等。

PS 我还建议使用numpy.array(closes, dtype='double')而不是numpy.array(closes)astalib.ATR()能够与Exception: input array type is not double. 从币安收到的当前数据不会发生这种情况,但为了安全起见,我会确保将数组转换为双精度。

于 2021-09-09T14:13:08.493 回答