Not able to get real time data with Alpaca API

Question:

I’m trying to make a real time graph for plotting stock data but I can’t get .get_position to work. The error message I get is APIError: position does not exist and 404 Client Error: Not Found for url: https://paper-api.alpaca.markets/v2/positions/AAPL. If I follow the link directly I get a forbidden message.

import matplotlib.pyplot as plt
from itertools import count
from matplotlib.animation import FuncAnimation
import threading
import time

api_key = '<API_KEY>'
api_secret = '<SECRET_KEY>'
base_url = 'https://paper-api.alpaca.markets'

api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')

account = api.get_account()

def stock_grabber():
        global position
        SYMBOL = 'AAPL'
        try:
            position = api.get_position(symbol=SYMBOL)
        except Exception as exception:
            if exception.__str__() == 'position does not exist':
                position = 0
                print(position)
def threadz():
    while True:
        x = threading.Thread(target=stock_grabber)
        x.start()
        time.sleep(0.4)

t = threading.Thread(target=threadz)
t.start()

stock_grabber()

x = []
y = []

index = count()

def animate(i):
    x.append(next(index))
    y.append(position)
    plt.cla()
    plt.plot(x, y)
             
ani = FuncAnimation(plt.gcf(), animate, interval=400)

plt.tight_layout()
plt.show()```
Asked By: Callum

||

Answers:

I recently discovered that I am dumb. What I was trying to do was to get the real time price not the position.

instead of

position = api.get_position(symbol=SYMBOL)

use

position = (api.get_position('SYMBOL'))
realprice = position.current_price

Also the forbidden message was because I was on school wifi

Answered By: Callum
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.