0

I'm using Alpaca's API with websocket to get stock price data. I want to use the variable position outside the function on_message but message is not previously defined so I get an error when I run the code name message is not defined

def on_message(ws, message):
    global position
    json.loads(message)
    position = (message[0]['bp'])
import websocket, json

def on_open(ws):

    print("opened")
    auth_data = {
        "action": "auth", "key": <API_KEY>, "secret": <API_SECRET>
    }
    ws.send(json.dumps(auth_data))

    listen_message = {"action":"subscribe","quotes":["AAPL"]}

    ws.send(json.dumps(listen_message))

def on_message(ws, message):
    global position
    json.loads(message)
    position = (message[0]['bp'])

socket = "wss://stream.data.alpaca.markets/v2/iex"
             
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message)
ws.run_forever()

sorry if this is a badly worded question it's about 1 am and im tired.

Callum
  • 1
  • 3
  • There's more info needed here. `I want to use the variable positions` do you mean you want to use the variable called `position`? `one of the parameters is not previously defined` which parameter? `the code breaks when i call on the function` breaks how? What error do you get? – Random Davis Aug 03 '22 at 15:46
  • 3
    Also not sure you should post Alpaca key and secret in your question? – SanguineL Aug 03 '22 at 15:50
  • The variable is ```position``` not positions, the parameter that doesnt work for me is ```message```. I want to call the function just under where ws is defined ```on_message(ws, message)```. This is the error message I get when I try and call it ```name message is not defined```. Sorry for the confusion. – Callum Aug 03 '22 at 22:41
  • Can you post the full traceback? – tdelaney Aug 03 '22 at 22:49
  • `message` is defined in `on_message` - the traceback will help figure out where the error is. And btw `json.loads(message)` returns the decoded message but you don't assign to anything. – tdelaney Aug 03 '22 at 22:51
  • ```Traceback (most recent call last): File "C:/Users/****/Desktop/Stock.py", line 25, in on_message(ws, message) NameError: name 'message' is not defined``` – Callum Aug 03 '22 at 23:57
  • note that this was run with an updated version of the code so the line will not be accurate. – Callum Aug 03 '22 at 23:59
  • That exception suggests you're *calling* `on_message`, not defining it (no `def` at the start of the line). Can you [edit] the question to show the full traceback and the relevant lines of code? – Blckknght Aug 04 '22 at 00:29

0 Answers0