How do I return a character from a string in the Python function with Websockets and json library?

Asked

Viewed 83 times

2

I’m new to Python and I have a question I’ve been trying to figure out for a long time.

I’m creating a tick analysis program from an investment site, and I want to extract the value of a certain string. I even managed to get to the character I want to extract, but I cannot return it to the main.

Below is the main code for you to understand what I want to do:

import websocket
import json

def on_open(ws):
    json_data = json.dumps({'ticks':'R_100'})
    ws.send(json_data)

def on_message(ws, message):
    print('ticks update: %s' % message)

if __name__ == "__main__":
    apiUrl = "wss://ws.binaryws.com/websockets/v3?app_id=1089"
    ws = websocket.WebSocketApp(apiUrl, on_message = on_message, on_open = on_open)
    ws.run_forever()

I want to extract from the function the numbers highlighted in yellow, I took from IDLE:

IDLE do programa inicial

I even managed to extract the number I want, as image below, and I can print it in function:

import websocket
import json

def on_open(ws):
    json_data = json.dumps({'ticks': 'R_100'})
    ws.send(json_data)

def on_message(ws, message):
    a=""
    a=message[235]
    print(message)
    print('a = ', a)

if __name__ == "__main__":
    apiUrl = "wss://ws.binaryws.com/websockets/v3?app_id=1089"
    ws = websocket.WebSocketApp(apiUrl, on_message = on_message, on_open = on_open)
    ws.run_forever()

IDL2 - Imprimindo número desejado

But I can’t pull out the function because I want to work with this number on main, whereas in function it continues with the same number and not to use the if.

import websocket
import json

def on_open(ws):
    json_data = json.dumps({'ticks': 'R_100'})
    ws.send(json_data)

def on_message(ws, message):
    a=""
    a=message[235]
    return a

if __name__ == "__main__":
    apiUrl = "wss://ws.binaryws.com/websockets/v3?app_id=1089"
    ws = websocket.WebSocketApp(apiUrl, on_message = on_message, on_open = on_open)
    tick=""
    tick=on_message
    print(tick)
    ws.run_forever()

IDLE prints this instead of printing the desired number: <Function on_message at 0x00000195A1D4C310>

Can someone help me?

  • Someone can help?

  • Hi Luiz, there is no way you can return the value of a function, but there are other things you can do. I can help you with that, but what you intend to do with that character in the main?

1 answer

2


Before answering your question I will try to clarify a few things about what happens in this code that apparently you do not completely master. The first is what happens when you call the websocket.WebSocketApp(): At that point you create an instance of the Websocketapp class, but you still do not perform any action of sending or receiving data. For this reason trying to print a message now makes no sense, since no message has been received.

The second point is what on_message. There is the function on_message, which you have defined, which takes two parameters (an instance of Websocketapp and a message) and there is the parameter on_message websocketapp internal. This parameter defines which function will be executed every time the App receives data. You could change the name of your function, for example:

def a_cada_mensagem(ws, message):
    a=message[235]
    ...

and then create your app with ws = websocket.WebSocketApp(apiUrl, on_message = a_cada_mensagem). This means who will call the function specified in the parameter on_message is the websocket and not the user. Thus, the value that the function returns is not available to the user. You can change that by changing the "built-in" functions of the Websocketapp class, but go for me when I say you don’t want to do it. But calm that there is a solution.

The last thing you need to understand before the solution is what happens on ws.run_forever(). In this command yes your App will exchange data from the Websocket framework. But here it will go into an infinite loop and, until that loop is broken, no code that comes after that line will run. So at this point you can have the message, but it will change with each loop and you can’t follow in main. So if you want to do something with the messages only have two alternatives:

1: Operate messages within on_message(Ws, message): Since you can’t get back to main, you can do whatever you need within that function, including calling other functions. Here you have access to the variable you want, so why not use it here?

2: Break the loop: If you want to do something in main, but can’t because it’s stuck in the infinite loop then the alternative is to break the loop at some point. Let’s assume that you want to run the loop three times and then stop and analyze which answers you got. In this case you will need a global counter, to know how many times you have run, and a list to be able to store the variables you want. Being a list, you don’t have to worry about returning it. Just go to the main:

import websocket
import json

def on_open(ws):
    json_data = json.dumps({'ticks': 'R_100'})
    ws.send(json_data)

a_list = []
count = 0
def on_message(ws, message):
    global count
    if count == 3:
        ws.close()
    else:
        a=message[235]
        a_list.append(a)
        count += 1

if __name__ == "__main__":
    apiUrl = "wss://ws.binaryws.com/websockets/v3?app_id=1089"
    ws = websocket.WebSocketApp(apiUrl, on_message = on_message, on_open = on_open)
    ws.run_forever()
    print(a_list)

You can use the condition you want to interrupt the loop

  • I tried to work on the function itself, however, I wanted to define some conditions that would depend on another loop, and using the same loop, it would only consider a value for my conditions. What worked out, was your second suggestion when working with loop break and lists, it worked for my case. Thanks for the great reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.