<p>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:</p>
<pre><code>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(&quot;Sending Message:&quot;)
    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(&quot;Recieved Message: &quot;)
    pprint.pprint(msg_dict)
    if 'ping' in msg_dict:
        data = {
            &quot;pong&quot;: msg_dict['ping']
        }
        send_message(ws, data)


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


def on_close(ws):
    print(&quot;### closed ###&quot;)


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

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

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


if __name__ == &quot;__main__&quot;:
    # websocket.enableTrace(True)
    ws = websocket.WebSocketApp(
        &quot;wss://api.huobi.pro/ws&quot;,
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    ws.run_forever()
</code></pre>

CC BY-SA 4.0
2021-03-31T16:31:34.290Z
2021-03-31T16:31:34.290Z
Kalindro
<p>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](<a href="https://github.com/HuobiRDCenter/huobi_Python" rel="nofollow noreferrer">https://github.com/HuobiRDCenter/huobi_Python</a>. I managed to figure this out:</p>
<pre><code>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: &quot;CandlestickReq&quot;):
    Candles = candlestick_req.data

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

History_dataframe_new[&quot;Date&quot;] = [Candles[f].id for f in range(len(Candles))]
History_dataframe_new[&quot;Open&quot;] = [Candles[f].open for f in range(len(Candles))]
History_dataframe_new[&quot;High&quot;] = [Candles[f].high for f in range(len(Candles))]
History_dataframe_new[&quot;Low&quot;] = [Candles[f].low for f in range(len(Candles))]
History_dataframe_new[&quot;Close&quot;] = [Candles[f].close for f in range(len(Candles))]
History_dataframe_new[&quot;Volume&quot;] = [Candles[f].vol for f in range(len(Candles))]
</code></pre>
<p>The problem is, how can I get this <code>Candles</code> argument out of the callback to use below? I'm not calling callback directly, only in the <code>req_candlestick</code> 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?</p>

CC BY-SA 4.0
2021-03-30T02:16:01.670Z
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
CC BY-SA 4.0
2021-03-30T06:47:02.130Z
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
<api><python><historical-trade-data><websockets>
How can I pull the "Candles" argument from the Huobi websocket data?
Kalindro
# How can I pull the "Candles" argument from the Huobi websocket data?

(Asked by: username_0 on 2021-03-29)

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?

**Tags:** api, python, historical-trade-data, websockets

> **Comments:**
> **username_1**: 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.  
> **username_0**: 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!  

---

## 1 answers

### Answer by username_0 on 2021-03-31. Score: 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()

```


---

