Alpaca paper API: keys to first call
Make your first Alpaca Trading API call in Python, JavaScript or curl against the paper host: a paper account, its two key headers and GET /v2/account, with placeholder credentials only.
Risk warning: CFDs and spread bets are complex instruments and come with a high risk of losing money rapidly due to leverage. You can lose money on these products, and each provider publishes its own loss figure under FCA rules. You should consider whether you understand how they work and whether you can afford to take the high risk of losing your money. Automated and API trading can amplify losses through bugs, connectivity failures and runaway orders.
Demo accounts only. Credentials are read from environment variables on your own machine. No field on this site asks for a key, a username or a password.
Steps
Open a paper account
Alpaca is a US stock, ETF, options and crypto broker, not a CFD or FX provider. Its pages say anyone, anywhere, can open a Paper Only Account by signing up with an email address; it gives full API access, a dashboard and IEX market data, and it trades nothing real. Paper trading is a simulation: fills come from real time quotes against the NBBO, about one order in ten is partly filled at random, and market impact, slippage, fees and dividends are not modelled. Everything on this page uses the paper host.
docs.alpaca.marketschecked
Find your paper API keys
A paper account has its own API keys, separate from any live account, and the dashboard shows the paper base address beside them. Alpaca's pages as read on 30 Nov 2026 say to generate new keys for a newly created account and do not print the menu steps, so follow the dashboard. Keep the key id and the secret in environment variables on your own machine: the code below reads ALPACA_API_KEY_ID and ALPACA_API_SECRET_KEY and never holds a value.
docs.alpaca.marketschecked
Pick your host
Paper trading: https://paper-api.alpaca.markets. Live: https://api.alpaca.markets. Market data for both: https://data.alpaca.markets. The authentication page says live credentials do not work on the paper host, nor paper credentials on the live host.
docs.alpaca.marketschecked
Send the two key headers
Every request carries APCA-API-KEY-ID and APCA-API-SECRET-KEY, or the same pair as HTTP Basic with the key id as the user name. There is no login call and no session token to keep alive. OAuth client credentials are documented for the Broker API only and marked not yet available for the Trading API.
docs.alpaca.marketschecked
First call: your account
GET /v2/account is Alpaca's own first example on the getting started page, where the reply shown is a 403 because no credentials were sent. With the two headers it returns the account behind the keys. Every reply also carries an X-Request-ID header, which Alpaca asks for in a support request and which cannot be looked up later, so keep recent ones.
Python
# Set ALPACA_API_KEY_ID, ALPACA_API_SECRET_KEY as environment variables first. Never paste real values into code or into this site. import os import requests BASE_URL = "https://paper-api.alpaca.markets" # the paper host headers = { "APCA-API-KEY-ID": os.environ["ALPACA_API_KEY_ID"], "APCA-API-SECRET-KEY": os.environ["ALPACA_API_SECRET_KEY"], } resp = requests.get(BASE_URL + "/v2/account", headers=headers, timeout=10) resp.raise_for_status() print(resp.json())JavaScript
// Set ALPACA_API_KEY_ID, ALPACA_API_SECRET_KEY as environment variables first. Never paste real values into code or into this site. // Node 18 or later. Save as a .mjs file so top level await works. const BASE_URL = "https://paper-api.alpaca.markets"; // the paper host const res = await fetch(`${BASE_URL}/v2/account`, { method: "GET", headers: { "APCA-API-KEY-ID": process.env.ALPACA_API_KEY_ID, "APCA-API-SECRET-KEY": process.env.ALPACA_API_SECRET_KEY } }); if (!res.ok) throw new Error(`HTTP ${res.status}`); console.log(await res.json());curl
# Set ALPACA_API_KEY_ID, ALPACA_API_SECRET_KEY as environment variables first. Never paste real values into code or into this site. curl "https://paper-api.alpaca.markets/v2/account" \ -H "APCA-API-KEY-ID: $ALPACA_API_KEY_ID" \ -H "APCA-API-SECRET-KEY: $ALPACA_API_SECRET_KEY"
docs.alpaca.marketschecked
Read the reply
The fields to look at first: status (PAPER_ONLY and ACTIVE are among the AccountStatus values), cash, equity, buying_power and non_marginable_buying_power (what a crypto order is checked against), multiplier, and trading_blocked. Money fields are strings, not numbers, so convert before arithmetic. A new paper account starts with 100,000 US dollars by default.
docs.alpaca.marketschecked
Mind the limits
The Trading API OpenAPI document gives HTTP 429 above the rate limit and three headers on every reply, X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset, and no figure on the pages opened: read the headers rather than guessing a number. The market data pages do give figures: 200 historical calls a minute on the free Basic plan and 10,000 on Algo Trader Plus, 30 stream symbols on Basic, and one stream connection for many plans. The limits table below carries each with its source.
docs.alpaca.marketschecked
First errors
403 with no credentials, with the wrong host's credentials, or on an order that buying power cannot cover. 422 where an order field is not recognised, or the price has more decimals than allowed (the body carries code 42210000). 429 when the rate limit is hit. On the market data host, 403 where the plan does not include the feed asked for: a Paper Only Account asks for feed iex. Each has its own page under errors, linked below.
docs.alpaca.marketschecked
What next
Read the record of POST /v2/orders and the Placing Orders page before any order: type and time_in_force are the required fields, limit and stop prices depend on the type, and the reply is the order's state and not a fill. Open the trade_updates stream on wss://paper-api.alpaca.markets/stream to follow fills rather than polling. Stay on the paper host until every path, including rejection, has been seen.
docs.alpaca.marketschecked
From first call to first order
One Python file built from the Alpaca endpoint records on this site, as the last step of this quickstart. It reads ALPACA_API_KEY_ID and ALPACA_API_SECRET_KEY from the environment. GET /v2/positions (version v2) reads your open positions. POST /v2/orders (version v2) places one small demo order with every field the record marks required (type and time_in_force), plus symbol, qty and side for the reason the record gives. GET /v2/orders/{order_id} (version v2) reads the confirmation or status. It sends at most one request every second, which stays under each request limit in the Alpaca limits table below. It refuses to run against any host but https://paper-api.alpaca.markets, and it never prints a token. Dry run is the default: save it as alpaca_first_order.py, run python alpaca_first_order.py, and it prints each request it would send with every secret shown as the name of its variable, reading no credential at all. Run python alpaca_first_order.py send to send them to the demo host. The script has not been run against Alpaca.
Python
#!/usr/bin/env python3 """Alpaca demo API: from first call to first order. Unofficial example from Broker API Hub, not published by Alpaca. Written from the Alpaca endpoint records on openbrokerapi.com and not run against Alpaca: the quickstart page says so. Demo host only. What it does, in order: 1. proves the token with GET /v2/positions (version v2) 2. GET /v2/positions (version v2): reads your open positions 3. POST /v2/orders (version v2): places one small demo order with every field the record marks required 4. GET /v2/orders/{order_id} (version v2): reads the confirmation or status of that order Dry run is the default: nothing is sent, no credential is read, and each request is printed as it would go, with every secret shown as the name of the variable that holds it. Run it with the word send as the first argument (python alpaca_first_order.py send) to send the requests to the demo host. Before a real send, set these environment variables on your own machine: ALPACA_API_KEY_ID the API key id of the paper account, from the paper dashboard ALPACA_API_SECRET_KEY the secret key shown with that key id Never paste real values into this file or into any website. Needs Python 3.8 or later and requests (pip install requests). """ import json import os import sys import time import requests DEMO_HOST = "https://paper-api.alpaca.markets" BASE_URL = os.environ.get("ALPACA_BASE_URL", DEMO_HOST).rstrip("/") SEND = len(sys.argv) > 1 and sys.argv[1] == "send" # Pacing, from this site's limits register for Alpaca: # 200 requests per minute (Market Data API historical calls, Basic (free) plan; checked 30 Nov 2026) # 10000 requests per minute (Market Data API historical calls, Algo Trader Plus plan (99 US dollars a month); checked 30 Nov 2026) # One request every second stays under each of them. MIN_GAP = 1 if BASE_URL != DEMO_HOST: sys.exit("Refusing to run: this script only talks to the demo host " + DEMO_HOST) # The order. Every field the order record marks required is here, with the record's own words after it, # and so is every field the vendor's page marks neither required nor optional (tagged not marked by the vendor). # A value of "..." or 0 is a placeholder: set it before a real send, or the script refuses to send. ORDER = { "symbol": "...", # The asset to trade, by symbol or asset id. The document's words: required except for a multi leg (mleg) order. Crypto pairs take a slash, such as BTC/USD. (optional, sent because the record gives the document's words: required except for a multi leg order) "qty": "1", # How many shares, as a string. Fractional quantities only with a market order and time in force day. Required for a multi leg order. Send qty or notional, not both. (optional, sent because the record says to send qty or notional, not both, and a quantity of one share is the smallest whole order) "side": "buy", # buy or sell. (optional, sent because the record lists buy and sell, and a first order buys) "type": "market", # market, limit, stop, stop_limit or trailing_stop. (required) "time_in_force": "day", # day, gtc, opg, cls, ioc or fok. Crypto takes gtc and ioc only; trailing stops take day and gtc. (required) } def env(name): """A credential or setting. In a dry run the value is the variable's own name, so nothing secret is read or printed.""" if not SEND: return "<" + name + ">" value = os.environ.get(name) if not value: sys.exit("Set the " + name + " environment variable first.") return value # Session and credential headers live in this object's memory only: never printed, never saved. http = requests.Session() http.headers.update({ "APCA-API-KEY-ID": env("ALPACA_API_KEY_ID"), "APCA-API-SECRET-KEY": env("ALPACA_API_SECRET_KEY"), "Accept": "application/json", }) last_call = 0.0 def request(method, path, version=None, body=None, params=None): """One request: printed in a dry run, paced and sent otherwise. Exits on an error reply, without printing a token.""" global last_call headers = {} if version: headers["VERSION"] = version if not SEND: print("DRY RUN " + method + " " + BASE_URL + path) shown = dict(http.headers) shown.update(headers) print(" headers: " + json.dumps(shown, indent=4)) if params: print(" query: " + json.dumps(params)) if body is not None: print(" body: " + json.dumps(body, indent=4)) return None wait = MIN_GAP - (time.monotonic() - last_call) if wait > 0: time.sleep(wait) last_call = time.monotonic() resp = http.request(method, BASE_URL + path, headers=headers, json=body, params=params, timeout=15) if resp.status_code >= 400: sys.exit("HTTP " + str(resp.status_code) + " from " + method + " " + path + ": " + resp.text[:300]) print(method + " " + path + ": HTTP " + str(resp.status_code)) return resp def main(): # GET /v2/positions (version v2): Every open position on the account: symbol, quantity, side, average entry, market value and unrealised profit or loss. resp = request("GET", "/v2/positions") if resp is not None: print("Open positions: " + json.dumps(resp.json())[:600]) # POST /v2/orders (version v2): Places an order: market, limit, stop, stop limit or trailing stop, alone or as a bracket, OCO, OTO or multi leg order. The reply is the Order with its id. if SEND and any(v in ("...", 0) for v in walk(ORDER)): sys.exit("Set every placeholder in ORDER before a real send.") resp = request("POST", "/v2/orders", body=ORDER) ref = resp.json()["id"] if resp is not None else "<id from the order reply>" print("id: " + str(ref)) # GET /v2/orders/{order_id} (version v2): One order by its id, whatever its state: status, filled quantity and average fill price. resp = request("GET", "/v2/orders/" + str(ref)) if resp is not None: print("Confirmation: " + json.dumps(resp.json(), indent=2)) else: print("Dry run finished. Nothing was sent. Run again with the word send as the first argument to send these requests to the demo host.") def walk(value): """Every leaf value in a nested dict or list, for the placeholder check.""" if isinstance(value, dict): for v in value.values(): yield from walk(v) elif isinstance(value, list): for v in value: yield from walk(v) else: yield value if __name__ == "__main__": try: main() except requests.RequestException as err: sys.exit("Network error: " + str(err))docs.alpaca.marketschecked
Alpaca limits to pace against
| Limit | Value | Scope | Source |
|---|---|---|---|
| client_order_id length | 128 | POST /v2/orders and PATCH /v2/orders/{order_id} | docs.alpaca.marketschecked |
| Crypto order size | 200,000 | Crypto spot orders, buy or sell | docs.alpaca.marketschecked |
| Market data historical API, Basic plan | 200 | Market Data API historical calls, Basic (free) plan | docs.alpaca.marketschecked |
| Market data points per page | 10,000 | Market Data API historical bars, trades and quotes, counted across all symbols | docs.alpaca.marketschecked |
| Market data historical API, Algo Trader Plus | 10,000 | Market Data API historical calls, Algo Trader Plus plan (99 US dollars a month) | docs.alpaca.marketschecked |
| GTC order age | 90 | Orders with time in force gtc | docs.alpaca.marketschecked |
| Trading API request rate | HTTP 429 above the limit, with X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset headers on replies; no figure on the pages opened | Trading API, per account | docs.alpaca.marketschecked |
| Market data WebSocket authentication timeout | 10 | Market data WebSocket, from connecting to the auth message | docs.alpaca.marketschecked |
| Market data WebSocket connections | Depends on the subscription; 1 for many subscriptions and with none. A second connection is answered with error 406 connection limit exceeded | Market data WebSocket, per account | docs.alpaca.marketschecked |
| Market data WebSocket symbols, Basic plan | 30 | Market data WebSocket, US equities, Basic (free) plan; Algo Trader Plus is unlimited | docs.alpaca.marketschecked |
Sources
- docs.alpaca.marketschecked
- docs.alpaca.marketschecked
- docs.alpaca.marketschecked
- docs.alpaca.marketschecked
- docs.alpaca.marketschecked
- docs.alpaca.marketschecked
- docs.alpaca.marketschecked