Save Received Candle Stick Message from KuCoin Websocket to variable and then to database

1.3k Views Asked by At

I have this Code to connect to the KuCoin web socket and receive the candle stick data. My question is: How can I save the message to a variable (maybe in a another script)? I want to use this data afterwards and save it to a database and then use it for calculations and ploting.

import asyncio
from kucoin.client import WsToken
from kucoin.ws_client import KucoinWsClient


async def kline_msg(msg):
    if msg["topic"] == "/market/candles:SLP-USDT_30min":
        print(msg["data"])


async def wsocket():
    client = WsToken()
    ws_client = await KucoinWsClient.create(None, client, kline_msg, private=False)
    await ws_client.subscribe("/market/candles:SLP-USDT_30min")
    while True:
        print("Sleep until message")
        await asyncio.sleep(60)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(wsocket())
2

There are 2 best solutions below

0
On

well, first of all you don't need to save candle sticks to database, you can get candles data from web service, you just have to tell from when to when and web service will give you candle sticks from that period. to get this data, you don't need web socket, you can get it with a simple REST API. this is the endpoint : /api/v1/market/candles

how to save this data to a variable? since the result of your api call is in JSON format, you can convert it to model class easly

0
On

The message is already in a variable called msg. Print it out and you'll see a JSON format. Grab the data you want from that JSON and reformat it to how you like it and save to CSV or json file in the naming format that works for you. Then read that file back and dump the data to the DB later.

An alternative is to use pandas to get part the JSON msg you want and turn it into a dataframe. From the dataframe, you can use pandas methods to save it to DB or other formats, i.e.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html