This skill should be used when the user asks to "connect to Trading 212", "authenticate Trading 212 API", "place a trade", "buy stock", "sell shares", "place market order",, "place pending order", "place limit order", "cancel order", "check my balance", "view account summary", "get positions", "view portfolio", "check P&L", "find ticker symbol", "search instruments", "check trading hours", "view dividends", "get order history", "export transactions", "generate CSV report", or needs guidance on Trading 212 API authentication, order placement, position monitoring, account information, instrument lookup, or historical data retrieval.
Only Invest and Stocks ISA accounts are supported.
Instrument Identifiers
Trading 212 uses custom tickers as unique identifiers for instruments.
Always search for the Trading 212 ticker before making instrument requests.
Authentication
HTTP Basic Auth with API Key (username) and API Secret (password).
Check Existing Setup First
Before guiding the user through authentication setup, check if credentials are already configured:
Semantic rule: Credentials are configured when at least one complete set is present: a complete set is key + secret for the same account (e.g. T212_API_KEY + T212_API_SECRET, or T212_API_KEY_INVEST + T212_API_SECRET_INVEST, or T212_API_KEY_STOCKS_ISA + T212_API_SECRET_STOCKS_ISA). You do not need all four account-specific vars; having only the Invest pair or only the Stocks ISA pair is enough. Check for any combination that gives at least one usable key+secret pair.
bash
# Example: configured if any complete credential set exists
if [ -n "$T212_AUTH_HEADER" ] && [ -n "$T212_BASE_URL" ]; then
echo "Configured (derived vars)"
elif [ -n "$T212_API_KEY" ] && [ -n "$T212_API_SECRET" ]; then
echo "Configured (single account)"
elif [ -n "$T212_API_KEY_INVEST" ] && [ -n "$T212_API_SECRET_INVEST" ]; then
echo "Configured (Invest); Stocks ISA also if T212_API_KEY_STOCKS_ISA and T212_API_SECRET_STOCKS_ISA are set"
elif [ -n "$T212_API_KEY_STOCKS_ISA" ] && [ -n "$T212_API_SECRET_STOCKS_ISA" ]; then
echo "Configured (Stocks ISA); Invest also if T212_API_KEY_INVEST and T212_API_SECRET_INVEST are set"
else
echo "No complete credential set found"
fi
If any complete set is present, skip the full setup and proceed with API calls; when making requests, use the resolution order in "Making Requests" below (pick the pair that matches the user's account context when multiple sets exist). Do not ask the user to run derivation one-liners or merge keys into a header. Only guide users through the full setup process below when no complete credential set exists.
Important: Before making any API calls, always ask the user which environment they want to use: LIVE (real money) or DEMO (paper trading). Do not assume the environment.
API Keys Are Environment-Specific
API keys are tied to a specific environment and cannot be used across environments.
API Key Created In
Works With
Does NOT Work With
LIVE account
live.trading212.com
demo.trading212.com
DEMO account
demo.trading212.com
live.trading212.com
If you get a 401 error, verify that:
You're using the correct API key for the target environment
The API key was generated in the same environment (LIVE or DEMO) you're trying to access
Get Credentials
Decide which environment to use - LIVE (real money) or DEMO (paper trading)
Open Trading 212 app (mobile or web)
Switch to the correct account - Make sure you're in LIVE or DEMO mode matching your target environment
Navigate to Settings > API
Generate a new API key pair - you'll receive:
API Key (ID) (e.g., 35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF)
API Secret (e.g., 7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo)
Store the credentials separately for each environment if you use both
Building the Auth Header
Combine your API Key (ID) and Secret with a colon, base64 encode, and prefix with Basic for the Authorization header.
Optional: To precompute the header from key/secret, you can set:
When making API calls, use the first option that applies (semantically: pick the credential set that matches the user's account, or the only set present):
If T212_AUTH_HEADER and T212_BASE_URL are set: use them in requests.
Else if T212_API_KEY and T212_API_SECRET are set: use this pair (single account). Build header as Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64) and base URL as https://${T212_ENV:-live}.trading212.com. Do not guide the user to derive or merge; you do it.
Else if both account-specific pairs are set (T212_API_KEY_INVEST/T212_API_SECRET_INVEST and T212_API_KEY_STOCKS_ISA/T212_API_SECRET_STOCKS_ISA): the user must clearly specify which account to target (Invest or Stocks ISA), unless they ask for information for all accounts. Use the Invest pair when the user refers to Invest, and the Stocks ISA pair when the user refers to ISA/Stocks ISA. If the user wants information for all accounts, make multiple API calls—one per account (Invest and Stocks ISA)—and present or aggregate the results for both. If it is not clear from context which account to use (and they did not ask for all accounts), ask for confirmation before making API calls (e.g. "Which account should I use — Invest or Stocks ISA?"). Do not assume. Build the header from the chosen key/secret and base URL as https://${T212_ENV:-live}.trading212.com.
Else if only the Invest pair is set (T212_API_KEY_INVEST and T212_API_SECRET_INVEST): use this pair for requests; if the user asks about Stocks ISA, only the Invest account is configured.
Else if only the Stocks ISA pair is set (T212_API_KEY_STOCKS_ISA and T212_API_SECRET_STOCKS_ISA): use this pair for requests; if the user asks about Invest, only the Stocks ISA account is configured.
Use the T212_AUTH_HEADER value in the Authorization header when it is set:
bash
# When T212_AUTH_HEADER and T212_BASE_URL are set:
curl -H "Authorization: $T212_AUTH_HEADER" \
"${T212_BASE_URL}/api/v0/equity/account/summary"
When only primary vars are set, use the inline form in the curl:
bash
# When only T212_API_KEY, T212_API_SECRET, T212_ENV are set:
curl -H "Authorization: Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)" \
"https://${T212_ENV:-live}.trading212.com/api/v0/equity/account/summary"
Warning:T212_AUTH_HEADER must be the full header value including the Basic prefix.
bash
# WRONG - raw base64 without "Basic " prefix
curl -H "Authorization: <base64-only>" ... # This will NOT work!
# CORRECT - use T212_AUTH_HEADER (contains "Basic <base64>")
curl -H "Authorization: $T212_AUTH_HEADER" ... # This works
Environment Variables
Single account vs all accounts: API keys are for a single account. One key/secret pair (T212_API_KEY + T212_API_SECRET) = one account (Invest or Stocks ISA). To use all accounts (Invest and Stocks ISA), the user must set two sets of key/secret: T212_API_KEY_INVEST / T212_API_SECRET_INVEST and T212_API_KEY_STOCKS_ISA / T212_API_SECRET_STOCKS_ISA. When both pairs are set, the user must clearly specify which account to target; if it is not clear from context, ask for confirmation (Invest or Stocks ISA) before making API calls.
Primary (single account): Set these for consistent setup with the plugin README:
bash
export T212_API_KEY="your-api-key" # API Key (ID) from Trading 212
export T212_API_SECRET="your-api-secret"
export T212_ENV="demo" # or "live" (defaults to "live" if unset)
Account-specific (Invest and/or Stocks ISA): Set only the pair(s) you use. One complete set (key + secret for the same account) is enough. For example, only Invest:
bash
export T212_API_KEY_INVEST="your-invest-api-key"
export T212_API_SECRET_INVEST="your-invest-api-secret"
export T212_ENV="demo" # or "live"
For both accounts, set both pairs:
bash
export T212_API_KEY_INVEST="your-invest-api-key"
export T212_API_SECRET_INVEST="your-invest-api-secret"
export T212_API_KEY_STOCKS_ISA="your-stocks-isa-api-key"
export T212_API_SECRET_STOCKS_ISA="your-stocks-isa-api-secret"
export T212_ENV="demo" # or "live" (applies to both)
Optional – precomputed (for scripts or if the user prefers): The user can set the auth header and base URL from the primary vars, but they do not need to; when making API calls you (the agent) must build the header and base URL from primary vars if these are not set.
bash
# Build auth header and base URL from T212_API_KEY, T212_API_SECRET, T212_ENV
export T212_AUTH_HEADER="Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)"
export T212_BASE_URL="https://${T212_ENV:-live}.trading212.com"
Alternative (manual): If you prefer not to store key/secret in env, set derived vars directly. Remember: API keys only work with their matching environment.
bash
# For DEMO (paper trading)
export T212_AUTH_HEADER="Basic $(echo -n "<DEMO_API_KEY_ID>:<DEMO_API_SECRET>" | base64)"
export T212_BASE_URL="https://demo.trading212.com"
# For LIVE (real money) - generate separate credentials in LIVE account
# export T212_AUTH_HEADER="Basic $(echo -n "<LIVE_API_KEY_ID>:<LIVE_API_SECRET>" | base64)"
# export T212_BASE_URL="https://live.trading212.com"
Tip: If you use both environments, use separate variable names:
Important: Always check quantityAvailableForTrading before placing sell orders.
Instruments
Ticker Lookup Workflow
When users reference instruments by common names (e.g., "SAP", "Apple", "AAPL"), you must look up the exact Trading 212 ticker before making any order, position, or historical data queries. Never construct ticker formats manually.
CACHE FIRST: Always check /tmp/t212_instruments.json before calling the API. The instruments endpoint has a 50-second rate limit and returns ~5MB. Only call the API if cache is missing or older than 1 hour.
Generic search: Match the user's search term in the three meaningful fields: ticker, name, or shortName. Use one variable (e.g. SEARCH_TERM) with test($q; "i") on each field so "TSLA", "Tesla", "TL0", etc. match efficiently. For regional filtering (e.g. "US stocks", "European SAP"), use the ISIN prefix (first 2 characters) for country code or currencyCode after the grep.
IMPORTANT: Never auto-select instruments. If multiple options exist, you are required to ask the user for their preference.
All historical endpoints use cursor-based pagination with nextPagePath.
Pagination Parameters
Parameter
Type
Default
Max
Description
limit
integer
20
50
Items per page
cursor
string/number
-
-
Pagination cursor (used in nextPagePath)
ticker
string
-
-
Filter by ticker (orders, dividends)
time
datetime
-
-
Pagination time (used in nextPagePath for transactions)
Pagination Example
bash
#!/bin/bash
# Fetch all historical orders with pagination
NEXT_PATH="/api/v0/equity/history/orders?limit=50"
while [ -n "$NEXT_PATH" ]; do
echo "Fetching: $NEXT_PATH"
RESPONSE=$(curl -s -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL$NEXT_PATH")
# Process items (e.g., save to file)
echo "$RESPONSE" | jq '.items[]' >> orders.json
# Get next page path (null if no more pages)
NEXT_PATH=$(echo "$RESPONSE" | jq -r '.nextPagePath // empty')
# Wait 1 second between requests (50 req/min limit)
if [ -n "$NEXT_PATH" ]; then
sleep 1
fi
done
echo "Done fetching all orders"
# Get the download link from the response
DOWNLOAD_URL=$(curl -s -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/exports" | jq -r '.[0].downloadLink')
# Download the CSV file
curl -o trading212_report.csv "$DOWNLOAD_URL"
Report Status Values
Status
Description
Queued
Report request received
Processing
Report generation started
Running
Report actively generating
Finished
Complete - downloadLink available
Canceled
Report cancelled
Failed
Generation failed
Pre-Order Validation
Before BUY - Check Available Funds
bash
#!/bin/bash
# Validate funds before placing a buy order
TICKER="AAPL_US_EQ"
QUANTITY=10
ESTIMATED_PRICE=185.00
ESTIMATED_COST=$(echo "$QUANTITY * $ESTIMATED_PRICE" | bc)
# Get available funds
AVAILABLE=$(curl -s -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/account/summary" | jq '.cash.availableToTrade')
echo "Estimated cost: $ESTIMATED_COST"
echo "Available funds: $AVAILABLE"
if (( $(echo "$ESTIMATED_COST > $AVAILABLE" | bc -l) )); then
echo "ERROR: Insufficient funds"
exit 1
fi
echo "OK: Funds available, proceeding with order"
Before SELL - Check Available Shares
bash
#!/bin/bash
# Validate position before placing a sell order
TICKER="AAPL_US_EQ"
SELL_QUANTITY=5
# Get position for the ticker
POSITION=$(curl -s -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/positions?ticker=$TICKER")
AVAILABLE_QTY=$(echo "$POSITION" | jq '.[0].quantityAvailableForTrading // 0')
echo "Sell quantity: $SELL_QUANTITY"
echo "Available to sell: $AVAILABLE_QTY"
if (( $(echo "$SELL_QUANTITY > $AVAILABLE_QTY" | bc -l) )); then
echo "ERROR: Insufficient shares (some may be in pies)"
exit 1
fi
echo "OK: Shares available, proceeding with order"
Rate Limit Handling
Understanding Rate Limits
Rate limits are per-account, not per API key or IP address. If you have multiple applications using the same Trading 212 account, they share the same rate limit pool.
Response Headers
Every API response includes rate limit headers:
Header
Description
x-ratelimit-limit
Total requests allowed in period
x-ratelimit-period
Time period in seconds
x-ratelimit-remaining
Requests remaining
x-ratelimit-reset
Unix timestamp when limit resets
x-ratelimit-used
Requests already made
Avoid Burst Requests to avoid Rate Limiting
Do not send requests in bursts. Even if an endpoint allows 50 requests per minute, sending them all at once can trigger rate limiting and degrade performance.
Pace your requests evenly, for example, by making one call every 1.2 seconds, ensuring you always stay within the limit.
Bad approach (bursting):
bash
# DON'T DO THIS - sends all requests at once
for ticker in AAPL_US_EQ MSFT_US_EQ GOOGL_US_EQ; do
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/positions?ticker=$ticker" &
done
wait
Good approach (paced):
bash
# DO THIS - space requests evenly
for ticker in AAPL_US_EQ MSFT_US_EQ GOOGL_US_EQ; do
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/positions?ticker=$ticker"
sleep 1.2 # 1.2 second between requests for 50 req/m limit
done
Caching Strategy
For data that doesn't change frequently, cache locally to reduce API calls:
bash
#!/bin/bash
# Cache instruments list (changes rarely)
CACHE_FILE="/tmp/t212_instruments.json"
CACHE_MAX_AGE=3600 # 1 hour
if [ -f "$CACHE_FILE" ]; then
CACHE_AGE=$(($(date +%s) - $(stat -f %m "$CACHE_FILE")))
if [ "$CACHE_AGE" -lt "$CACHE_MAX_AGE" ]; then
cat "$CACHE_FILE"
exit 0
fi
fi
# Cache expired or doesn't exist - fetch fresh data
curl -s -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/instruments" > "$CACHE_FILE"
cat "$CACHE_FILE"
Safety Guidelines
Test in demo first - Always validate workflows before live trading
Validate before ordering - Check funds (cash.availableToTrade) before buy, positions (quantityAvailableForTrading) before sell
Confirm destructive actions - Order placement and cancellation are irreversible
API is not idempotent - Duplicate requests may create duplicate orders
Never log credentials - Use environment variables
Respect rate limits - Space requests evenly, never burst
Max 50 pending orders - Per ticker, per account
Cache metadata - Instruments and exchanges change rarely