Trying to make a live PnL checker

I just started using Python, i created a simple strategy that buys when AAPL prices is lower than 150$ revolutionary!

I’m now trying to create an exit strategy that when my position PnL is lower or higher than 5% it closes.
with this formula: percentChange = ((old value - new value) / new value) x 100
but I’ve run into some problems I can’t access “the dictionary of my live positions”.


with the function b = api.get_position(‘AAPL’) it says Error has no attribute values.

if someone could help it would be appreciated!
here’s the sample code:
from config import *
import alpaca_trade_api as tradeapi
import requests
import pandas as pd

api = tradeapi.REST(api_key, secret_key, base_url)
account = api.get_account()
symbol = ‘AAPL’
r = requests.get(f’https://finnhub.io/api/v1/quote?symbol={symbol}&token=c0e6j5n48v6s9jus1ejg’)
a = list(r.json().values())
real_price = a[0]
balance_change = 0
b = api.get_position(‘AAPL’)
c = list(b.values())

print(balance_change)
if real_price <= 150:
qty = 1
#api.submit_order(‘AAPL’, side=‘buy’, qty=1, type=‘market’, time_in_force=‘gtc’)
print(f’Buying {qty} shares’)
if balance_change >= 3:
api.submit_order_close(symbol)
print(f’Take profit {qty} shares’)

To avoid that error, change the line:
b = api.get_position('AAPL')
to:
b = api.get_position('AAPL')._raw

**The get_position function returns an instance of the alpaca_trade_api.entity.Position class. Accessing the _raw member gives you a dict of the position elements.

Ok thx man, for the fix I was really stuck.
Have a great day!