1

I've a problem with Huobi Websocket, I know my ways in REST API but new to asyncio and websockets, and Huobi only gives resonable amount of history through websocket request so I'm stuck with it. I'm using their [sdk](https://github.com/HuobiRDCenter/huobi_Python. I managed to figure this out:

from huobi.client.market import MarketClient
from huobi.client.market import CandlestickInterval
import pandas as pd
from pandas import DataFrame as df

def callback(candlestick_req: "CandlestickReq"):
    Candles = candlestick_req.data

Market_client = MarketClient()
Market_client.req_candlestick("btcusdt", CandlestickInterval.MIN60, callback, from_ts_second = 1611788400, end_ts_second = 1614812400)

History_dataframe_new["Date"] = [Candles[f].id for f in range(len(Candles))]
History_dataframe_new["Open"] = [Candles[f].open for f in range(len(Candles))]
History_dataframe_new["High"] = [Candles[f].high for f in range(len(Candles))]
History_dataframe_new["Low"] = [Candles[f].low for f in range(len(Candles))]
History_dataframe_new["Close"] = [Candles[f].close for f in range(len(Candles))]
History_dataframe_new["Volume"] = [Candles[f].vol for f in range(len(Candles))]

The problem is, how can I get this Candles argument out of the callback to use below? I'm not calling callback directly, only in the req_candlestick so return won't work. And it's a callback so I propably have to wait for the response somehow. And tips how to do that? Or if what I'm trying here is the correct way?

2
  • Not familiar with this particular exchange but websocket requires you to subscribe to a data feed/channel after opening the websocket connection. I'm not seeing in your code where you are subscribing to anything. Once subscribed the message should start flowing in. After that it should just be simple JSON parsing the incoming messages.
    – m1xolyd1an
    Mar 30, 2021 at 2:16
  • This exchange is the only exchange I know that has history data pull from websockets, I guess there is no need to subscribe, if I go candlestick_req.print_object() there in the callback I receive the required data. I shall check how to parse with JSON, thanks!
    – Kalindro
    Mar 30, 2021 at 6:47

1 Answer 1

1

I will just throw it out here, there is a better way to do it, here above I was using Huobi SDK but I find using websocket without any external libraries better. A great template for websocket connection below:

import gzip
import json
import pprint
import threading

import time
import websocket


def send_message(ws, message_dict):
    data = json.dumps(message_dict).encode()
    print("Sending Message:")
    pprint.pprint(message_dict)
    ws.send(data)


def on_message(ws, message):
    unzipped_data = gzip.decompress(message).decode()
    msg_dict = json.loads(unzipped_data)
    print("Recieved Message: ")
    pprint.pprint(msg_dict)
    if 'ping' in msg_dict:
        data = {
            "pong": msg_dict['ping']
        }
        send_message(ws, data)


def on_error(ws, error):
    print("Error: " + str(error))
    error = gzip.decompress(error).decode()
    print(error)


def on_close(ws):
    print("### closed ###")


def on_open(ws):
    def run(*args):
        data = {
            "req": "market.btcusdt.kline.1min",
            "id": "id1"
            "from": int("fromtimestamp")
            "to": int("to timestamp")
        }

        for i in range(5):
            time.sleep(2)
            send_message(ws, data)
        ws.close()
        print("thread terminating...")

    t = threading.Thread(target=run, args=())
    t.start()


if __name__ == "__main__":
    # websocket.enableTrace(True)
    ws = websocket.WebSocketApp(
        "wss://api.huobi.pro/ws",
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    ws.run_forever()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.