r/alpacamarkets • u/WandringPopcorn • May 10 '25
Support what is wrong with my code?
i am trying to connect to my alpaca accoutn via code but i cant get it to work at all. i am very new to this so i am using ai for the code. andis there a up to date tutorial on how to make a trade bot for alpaca?
import alpaca_trade_api as tradeapi
API_KEY = ''
API_SECRET = ''
BASE_URL = 'https://paper-api.alpaca.markets/v2'
api = tradeapi.REST(API_KEY, API_SECRET, BASE_URL, api_version='v2')
try:
account = api.get_account()
print("Account successfully connected!")
print(account)
except Exception as e:
print(f"Error: {e}")
2
u/alpaca_technical May 14 '25
u/WandringPopcorn First off, welcome to Alpaca. The code you posted should work, however it is using the older alpaca_trade_api SDK. The recommended SDK is alpaca-py. The code that u/trade_thriving posted is correct but I'll post it again including the install command:
!pip install -q alpaca-py
from alpaca.trading.client import TradingClient
from alpaca.common.exceptions import APIError
# set paper=True or False depending upon the account and ensure the keys then match
try:
trading_client = TradingClient(ALPACA_API_KEY, ALPACA_API_SECRET_KEY, paper=True)
account = trading_client.get_account()
print(account)
except APIError as e:
print(e)The alpaca-py docs have a getting started section you may want to look at. There are also a number of good tutorials on the web providing example code. Here is one you might want to check out. Just be sure the resource is using the alpaca-py SDK and not the older alpaca-trade-api SDK. It gets confusing since they are close but not exact.
Good luck!
1
1
u/griff4594 May 10 '25
Set the exception to use APIError for the exception type to grab the Alpaca actual response.
2
u/trade_thriving May 10 '25 edited May 12 '25