3

I am trying to develop a short script that connects to a real-time stock data provider through a websocket API, gets some data, makes some calculations, stores the results in a database and stops.

EDIT: I need to keep the connection alive for a few seconds until I get all required data. Thus, breaking the connection after the first message is not an option.

The problem I am facing is how to stop the run_forever() connection.

This is what I have so far:

import websocket
import json

def on_open(ws):
    channel_data = {
        "action": "subscribe",
        "symbols": "ETH-USD,BTC-USD"
    }
    ws.send(json.dumps(channel_data))
    
def on_message(ws, message):
    # Do some stuff (store messages for a few seconds)
    print(message)
    
def on_close(ws):
    print("Close connection")
    
socket = "wss://ws.url"
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message)
ws.run_forever()
ws.close()

# Once the connection is closed, continue with the program

I do not want to stay connected after the "Do some stuff" is executed, how can I force the connection close?

Your help is much appreciated.

4
  • 1
    "how can I force the connection close?" ... by calling ws.close() when "the "Do some stuff" is executed", perhaps? Am I missing something? Commented Feb 26, 2022 at 18:13
  • Sorry, I was not too clear. The API provides several messages (actually, stock prices) but I need to keep the connection alive until all requested stocks are provided. Thus, I can´t close the connection in the first message received. Is there any way to set a counter? or a timer? Commented Feb 26, 2022 at 18:21
  • Instantiate a global variable that keeps track of the messages you've received and bump it up each time against the symbols you requested. Once the lists match, invoke close(). Commented Feb 26, 2022 at 18:26
  • I have tried something similar. I declared global n n=0 at the beginning of on_open() function and n+=1 inside the on_message() function. But if I try to print(n) inside this function, it does not seem to do anything Commented Feb 26, 2022 at 18:35

1 Answer 1

8

I managed how to solve this. I leave my solution in case it is useful to someone.

I just added some attributes to the ws object that allows me to track the number of messages received and store them into a list to work with once the connection is closed.

import websocket
import json

def on_open(ws):
    channel_data = {
        "action": "subscribe",
        "symbols": "ETH-USD,BTC-USD"
    }
    ws.send(json.dumps(channel_data))
    
def on_message(ws, message):
    
    ws.messages_count+=1
    ws.messages_storage.append(message)
    
    if ws.messages_count>50:
        ws.close()
    
def on_close(ws):
    print("Close connection")
    
socket = "wss://ws.url"
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message)

# Create a counter and an empty list to store messages
ws.messages_count = 0
ws.messages_storage = []

# Run connection
ws.run_forever()

# Close connection
ws.close()

# Continue with the program
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.