How to use websocket-client and Thread as a claass?

Question:

I need to call my class >> CotarMoedas another python file.
But I need to get return of cons live stream as result.

#https://www.youtube.com/watch?v=pxyaENuoZUM&list=PL9ATnizYJ7f8_opOpLnekEZNsNVUVbCZN&index=47
import websocket
import json 
import pandas as pd 
from sqlalchemy import create_engine
from threading import Thread


engine = create_engine('sqlite:///COINS.db')

class CotarMoedas:

    def __init__(self):
        self.endpoint = 'wss://stream.binance.com:9443/ws/!miniTicker@arr'
        tr = Thread(target=self.call_ws)
        tr.start()


    def df_import(self, data):
        #Pegar os valores dos pares casados com USDT
        df_ = pd.DataFrame(data)
        df_ = df_[df_['s'].str.endswith('USDT')]
        df_.c = df_.c.astype(float)
        final = df_[['s','E','c']]
        for i in range(len(final)):
            row_ = final[i:i+1]
            #print(row_)
            row_[['E','c']].to_sql(row_.s.values[0], engine, index=False, if_exists='append')


    def best_conin(self):
        engine = create_engine('sqlite:///COINS.db')
        dfs = pd.read_sql("""SELECT name FROM sqlite_master WHERE type='table'""", engine)
        tables = dfs.name.to_list()
        reutrns = []

        for table in tables:
            df__ = pd.read_sql(table,engine)
            # ret_ = (df__.tail(20).c.pct_change() + 1).prod() - 1 # Os 20 mais recentes
            ret_ = (df__.c.pct_change() + 1).prod() - 1
            reutrns.append(ret_)

        rst = pd.Series(reutrns).nlargest(10)
        rst.sort_values()
        bv = rst.to_dict()
        ls = []
        for k, v in bv.items():
            ls.append([tables[k],v])
            tt = print(tables[k],v)
        
        return tt


    def on_close(self,ws):
        print('Conexão encerrada!')


    def on_message(self, ws, message):
        out = json.loads(message)
        #print(out)
        df_import(out)
        print('============')
        best_conin()


    def call_ws(self):
        ws = websocket.WebSocketApp(self.endpoint, on_message=self.on_message, on_close=self.on_close)
        ws.run_forever()

But I traying call it like this

from videos_algovibes.cotacao import CotarMoedas

rst = CotarMoedas()
vai = rst.best_conin()
if __name__ == "__main__":
    print(vai)
Asked By: marreco

||

Answers:

I’m simplifying the code :

#https://www.youtube.com/watch?v=pxyaENuoZUM&list=PL9ATnizYJ7f8_opOpLnekEZNsNVUVbCZN&index=47
import websocket
import json 
import pandas as pd 
from sqlalchemy import create_engine
from threading import Thread
import threading

class CotarMoedas:

    def __init__(self):
        self.endpoint = 'wss://stream.binance.com:9443/ws/!miniTicker@arr'
        #tr = Thread(target=self.call_ws)
        #tr.start()
        self.call_ws()


    def best_conin(self):
        print("Best coin")


    def on_close(self,ws):
        print('Conexão encerrada!')


    def on_message(self, ws, message):
        def run(*args):
            print(message)
            print("Message received...")

        threading.Thread(target=run).start()


    def call_ws(self):
        def _call_ws():
            ws = websocket.WebSocketApp(self.endpoint, on_message=self.on_message, on_close=self.on_close)
            ws.run_forever()

        threading.Thread(target=_call_ws).start()
    

https://youtu.be/pDslZbvO7Hs
As you can see in the video.
Threading could be handled this way.
Good luck with SQLAlchemy, Sessions, etc.

Answered By: firatto
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.