Python Tutorial
Connect to a Trading API with Python
Learn how to connect to broker APIs (Alpaca, IBKR, Trading212) to fetch market data and place orders programmatically.
Install Alpaca SDK
pip install alpaca-trade-api pandasConnect & Fetch Data
import alpaca_trade_api as tradeapi
# Connect to Alpaca paper trading
api = tradeapi.REST(
key_id="YOUR_KEY",
secret_key="YOUR_SECRET",
base_url="https://paper-api.alpaca.markets"
)
# Get account info
account = api.get_account()
print(f"Portfolio Value: ${float(account.portfolio_value):,.2f}")
print(f"Buying Power: ${float(account.buying_power):,.2f}")
print(f"Cash: ${float(account.cash):,.2f}")Get Market Data
# Fetch historical bars
bars = api.get_bars("AAPL", "1Day", limit=30).df
print(bars[["close", "volume"]].tail(10))
# Get current price
quote = api.get_latest_quote("AAPL")
print(f"AAPL: ${quote.ap:.2f}")Place an Order
# Place a market buy order (paper trading)
order = api.submit_order(
symbol="AAPL",
qty=1,
side="buy",
type="market",
time_in_force="day"
)
print(f"Order placed: {order.id}")
print(f"Status: {order.status}")N
Recommended
Protect Your API Keys with NordVPN
Encrypt your connection when working with trading APIs and financial data. Essential for developers handling sensitive credentials.
Get NordVPN →We may earn a commission at no extra cost to you