Getting Started with Trading API
This section outlines how to install Alpaca’s SDKs, create a free alpaca account, locate your API keys, and how to submit orders applicable for both stocks and crypto.
Installing Alpaca’s Python Client SDK
In this guide, we’ll be making use of the SDKs provided by Alpaca. Alpaca maintains SDKs in four languages: Python, JavaScript, C#, and Go. Follow the steps in the installation guide below to install the SDK of your choice before proceeding to the next section.
pip install alpaca-py
npm install --save @alpacahq/alpaca-trade-api
dotnet add package Alpaca.Markets
go get -u github.com/alpacahq/alpaca-trade-api-go/v2/alpaca
Creating an Alpaca Account and Locating API Keys
To request data from Alpaca you’ll need to include your API keys in your requests. This section outlines how one can create an account and generate the keys necessary to submit orders.
- Navigate to Alpaca’s website
- Sign up for a free account using the sign up button
- After confirming your account and logging in, navigate to your paper trading dashboard
- On the dashboard, click the button to view your API keys
- After expanding your API keys section, generate new keys
- After your keys have been generated, securely save them for future use
How to Place Orders Through the SDK
In this section, we’ll run through an example of placing a market buy for Bitcoin and view our open positions through the SDK. To see more involved examples of placing orders, visit Understand Orders or Order Type ABCs with Alpaca Trade API.
# Importing the API and instantiating the REST client according to our keys
from alpaca.trading.client import TradingClient
API_KEY = "<Your API Key>"
SECRET_KEY = "<Your Secret Key>"
trading_client = TradingClient(API_KEY, SECRET_KEY, paper=True)
# Getting account information and printing it
account = trading_client.get_account()
for property_name, value in account:
print(f"\"{property_name}\": {value}")
A typical response to the GET/account
request would look like this
"id": ee302827-4ced-4321-b5fb-71080392d828
"account_number": PA3717PJAYWN
"status": ACTIVE
"crypto_status": ACTIVE
"currency": USD
"buying_power": 1768290.404988
"regt_buying_power": 1768290.404988
"daytrading_buying_power": 0
"non_marginable_buying_power": 882145.2
"cash": 884145.202494
"accrued_fees": 0
"pending_transfer_out": None
"pending_transfer_in": 0
"portfolio_value": 910178.2209985875
"pattern_day_trader": False
"trading_blocked": False
"transfers_blocked": False
"account_blocked": False
"created_at": 2022-04-19 17:46:03.685850+00:00
"trade_suspended_by_user": False
"multiplier": 2
"shorting_enabled": True
"equity": 910178.2209985875
"last_equity": 907426.98
"long_market_value": 26033.0185045875
"short_market_value": 0
"initial_margin": 0
"maintenance_margin": 0
"last_maintenance_margin": 0
"sma": 868738.98
"daytrade_count": 0
Placing a Buy Order
Before placing an order, you need to import the corresponding request class. For a market order, the class is MarketOrderRequest. This class has four required parameters: symbol, quantity/notional, side, and time in force. Order side and time in force enums can be imported and used to instantiate your order request class easier.
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
# Setting parameters for our buy order
market_order_data = MarketOrderRequest(
symbol="BTC/USD",
qty=1,
side=OrderSide.BUY,
time_in_force=TimeInForce.GTC
)
Use the trading client’s method, submit_order
, to submit your order. This function call returns an Order
object that shows all the details of your order. Pass the object from the previous step into submit_order
and run your code to submit the order. Print the returning Order
object to see the details of the order.
# Submitting the order and then printing the returned object
market_order = trading_client.submit_order(market_order_data)
for property_name, value in market_order:
print(f"\"{property_name}\": {value}")
A response would look like this
"id": 403d15c4-9fd5-4fdf-a4be-1459717248ea
"client_order_id": 671cc18b-ea6b-46d9-9f0b-22b5af67a794
"created_at": 2022-09-09 11:51:04.778044+00:00
"updated_at": 2022-09-09 11:51:04.778092+00:00
"submitted_at": 2022-09-09 11:51:04.776737+00:00
"filled_at": None
"expired_at": None
"canceled_at": None
"failed_at": None
"replaced_at": None
"replaced_by": None
"replaces": None
"asset_id": 276e2673-764b-4ab6-a611-caf665ca6340
"symbol": BTC/USD
"asset_class": crypto
"notional": None
"qty": 1
"filled_qty": 0
"filled_avg_price": None
"order_class": simple
"order_type": market
"type": market
"side": buy
"time_in_force": gtc
"limit_price": None
"stop_price": None
"status": pending_new
"extended_hours": False
"legs": None
"trail_percent": None
"trail_price": None
"hwm": None
The order has now been submitted and your trading dashboard will update accordingly. The parameters available for submit_order
and the properties of its Order response can be found in the Trading API docs.
Updated about 1 month ago