Monday, 6 June 2022

how to use a websocket connection in a main loop?

I want to close the websocket and return to a main loop under 2 conditions

condition 1: time in test_now reached

condition 2: threshold reached

I seem to be missing how I can break the connection of the websocket and return to the main loop, as if I call the on_close() function, and therefore the ws.close() function, the loop continues without the connection breaking.

how can I break the connection in my case?

would it be possible to run the websocket in the main loop as long as it only returns True values? (meaning that it would break the first time that I return False because of the reached time or threshold)

import websocket
import json
from db_connector_bot import db_bot_connect
import pandas as pd
import mysql.connector
import datetime
#from main import testnow


testnow = ('00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00')
cc = 'btcusdt'
interval = '1m'  # 5m 10m 30m 1h 2h 4h 6h 8h 12h 1d 3d 1w 1M (possibilities)
socket = f'wss://stream.binance.com:9443/ws/{cc}@kline_{interval}'


def check_time(): #checktime is 4 pm eastern time US (when the S&P normally closes, but BTC is still open)

    now = f"{datetime.datetime.now():%H%M}"

    if now in testnow:
        print(f'the time conditions was satisfied with {now}, as the condition is {testnow}')
        return True

    else:
        return False


def call_last_stored_values():

    mydb = db_bot_connect()

    c = mydb.cursor()

    query = "SELECT * FROM BOT1;"

    c.execute(query)

    result = c.fetchall()

    result = pd.DataFrame(result)

    result.rename(columns={1: 'portf_value', 2: 'value_btc_portf', 3: 'amount_btc', 4: 'price_btc', 5: 'cash_reserves',
                           6: 'perc_btc', 7: 'perc_cash', 8: 'pred_ml1', 9: 'pred_ml2'}, inplace=True)
    result = result.set_index([0])

    last_stored_price = result['price_btc'].tail(1).values
    pred_ml1 = result['pred_ml1'].tail(1).values
    pred_ml2 = result['pred_ml2'].tail(1).values

    return last_stored_price, pred_ml1, pred_ml2


def on_close(ws, *args):
    print('connection closed')
    for arg in args:
        print(arg)
    ws.close()


def on_message(ws, message):

    json_message = json.loads(message)
    candle = json_message['k']
    candle_closed = candle['x']
    close = candle['c']
    print(close, candle_closed)

    if candle_closed:

        if check_time():

            on_close('testnow reached')

        last_price = close

        print(f'Closed {interval} candle, closed at: {last_price}')

        last_stored_price, pred_ml1, pred_ml2 = call_last_stored_values()

        print(pred_ml1 + pred_ml2)

        threshold = last_stored_price * ((pred_ml1 + pred_ml2) ** -0.4)

        print(f'the threshthreshold amounts to {threshold}')

        if last_price < (last_stored_price - threshold):

            on_close(f'threshold reached with {threshold}')

ws = websocket.WebSocketApp(socket, on_message=on_message, on_close=on_close)

ws.run_forever()


from how to use a websocket connection in a main loop?

No comments:

Post a Comment