OK and hello. First post, hopefully of many
I am after advice from a Newbie to python, so silly questions to follow…
i am reasonably advanced in php & SQL, but am learning python (read a few books and webpages, etc over the past few months)
At the confusion setting in stage, as to what is the best method (or a good one!) to do what i want. I am probably reading too much which is causing the confusion…
My code/application will have 3 main aspects
- get multiple stream data and insert into mySQL
- analyse the data from the database
- make trades
I should be OK with item 2 and 3. but item 1 needs to be RELIABLE!
So What i want:
Connect to the websocket kline stream.
Now i can do this easy enough (seen in lots of tutorials - basic code below), BUT… running it procedural does not seem to make for good coding (in php i would use methods within objects).
My main concern is: i need to check has the connection been closed, and if so re-open it OR take “emergency trading action”
So the very basic code below works fine but it does not sit easy with me. i need it to run separately
I have tried making it into a simple module or adding it as a class file (but when called this blocks the following code, as the stream never completes of course)
I have also been trying a few other methods, but below i am including the most basic, that i am sure you are all aware of…
I would like maybe pointing in the right direction (or any libraries) (as i am probably reading too much and getting confused what direction to be heading in)
i need to write it into an app/function/class/etc that will run indefinitely, be RELIABLE, reconnect if the connection is closed/lost (and message my other aspects if connection is not re-opened, so action can be taken) (i also read that the stream will be closed in 24 hours too…)
def on_message(ws, message):
closes = []
print('received message')
json_message = json.loads(message)
candle = json_message['k']
is_candle_closed = candle['x']
close = candle['c']
if is_candle_closed:
print("candle closed at {}".format(close))
closes.append(float(close))
print("closes")
print(closes)
insert_data(json_message)
def insert_data(json_message):
try:
Blah, Blah....
except Exception as e:
print("Something went wrong:", e)
def on_error(ws, error):
print(error)
def on_open(ws):
print(f"opened connection")
def on_close(ws):
print(‘connection closed’)
stream = “wss://stream.binance.com:9443/ws/ethusdt@kline_1m”
ws = websocket.WebSocketApp(stream, on_open=on_open, on_close=on_close, on_message=on_message, on_error=on_error)
ws.run_forever()
I hope this is not too confusing and you can see what it is i am badly asking
Thanks
Jon