trading212-api by trading212-labs/agent-skills
npx skills add https://github.com/trading212-labs/agent-skills --skill trading212-api注意: Trading 212 API 目前处于 测试版 并正在积极开发中。某些端点或行为可能会发生变化。
| 环境 | 基础 URL | 用途 |
|---|---|---|
| 演示 | https://demo.trading212.com/api/v0 | 模拟交易 - 无需真实资金进行测试 |
| 实盘 | https://live.trading212.com/api/v0 | 真实资金交易 |
10 买入 10 股)-10 卖出 10 股)广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
仅支持 投资 和 股票 ISA 账户。
Trading 212 使用自定义代码作为交易品种的唯一标识符。在进行交易品种请求之前,请务必搜索 Trading 212 代码。
使用 API 密钥(用户名)和 API 密钥(密码)进行 HTTP 基本认证。
在引导用户完成认证设置之前,请检查凭据是否已配置:
语义规则: 当至少存在一组完整的凭据时,即视为已配置:一组完整的凭据是指同一账户的密钥 + 密钥(例如 T212_API_KEY + T212_API_SECRET,或 T212_API_KEY_INVEST + T212_API_SECRET_INVEST,或 T212_API_KEY_STOCKS_ISA + T212_API_SECRET_STOCKS_ISA)。您不需要所有四个账户特定变量;仅拥有投资账户对或仅拥有股票 ISA 账户对就足够了。检查是否存在任何能提供至少一组可用密钥+密钥对的组合。
# 示例:如果存在任何完整的凭据集,则视为已配置
if [ -n "$T212_AUTH_HEADER" ] && [ -n "$T212_BASE_URL" ]; then
echo "已配置(派生变量)"
elif [ -n "$T212_API_KEY" ] && [ -n "$T212_API_SECRET" ]; then
echo "已配置(单一账户)"
elif [ -n "$T212_API_KEY_INVEST" ] && [ -n "$T212_API_SECRET_INVEST" ]; then
echo "已配置(投资);如果设置了 T212_API_KEY_STOCKS_ISA 和 T212_API_SECRET_STOCKS_ISA,则股票 ISA 也已配置"
elif [ -n "$T212_API_KEY_STOCKS_ISA" ] && [ -n "$T212_API_SECRET_STOCKS_ISA" ]; then
echo "已配置(股票 ISA);如果设置了 T212_API_KEY_INVEST 和 T212_API_SECRET_INVEST,则投资账户也已配置"
else
echo "未找到完整的凭据集"
fi
如果存在任何完整的凭据集,请跳过完整设置并继续进行 API 调用;发出请求时,请使用下文“发出请求”中的解析顺序(当存在多组凭据时,选择与用户账户上下文匹配的那一组)。不要要求用户运行派生单行命令或将密钥合并到头信息中。仅当不存在完整的凭据集时,才引导用户完成下面的完整设置过程。
重要提示: 在进行任何 API 调用之前,务必询问用户他们想要使用哪个环境:实盘(真实资金)还是演示(模拟交易)。不要假设环境。
API 密钥绑定到特定环境,不能跨环境使用。
| API 密钥创建于 | 适用于 | 不适用于 |
|---|---|---|
| 实盘账户 | live.trading212.com | demo.trading212.com |
| 演示账户 | demo.trading212.com | live.trading212.com |
如果您收到 401 错误,请验证:
35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF)7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo)将您的 API 密钥(ID)和密钥用冒号连接,进行 base64 编码,并加上 Basic 前缀,作为 Authorization 头信息。
可选: 要从密钥/密钥预计算头信息,您可以设置:
export T212_AUTH_HEADER="Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)"
否则,代理在发出请求时会从 T212_API_KEY 和 T212_API_SECRET 构建头信息。
手动(占位符):
# 格式:T212_AUTH_HEADER = "Basic " + base64(API_KEY_ID:API_SECRET)
export T212_AUTH_HEADER="Basic $(echo -n "<YOUR_API_KEY_ID>:<YOUR_API_SECRET>" | base64)"
# 使用示例凭据:
export T212_AUTH_HEADER="Basic $(echo -n "35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF:7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo" | base64)"
进行 API 调用时,使用第一个适用的选项(语义上:选择与用户账户匹配的凭据集,或唯一存在的凭据集):
T212_AUTH_HEADER 和 T212_BASE_URL: 在请求中使用它们。T212_API_KEY 和 T212_API_SECRET: 使用这对凭据(单一账户)。构建头信息为 Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64),基础 URL 为 https://${T212_ENV:-live}.trading212.com。不要引导用户进行派生或合并;由您来完成。T212_API_KEY_INVEST/T212_API_SECRET_INVEST 和 T212_API_KEY_STOCKS_ISA/T212_API_SECRET_STOCKS_ISA):用户必须明确指定要操作哪个账户(投资或股票 ISA),除非他们要求获取所有账户的信息。当用户提及投资账户时使用投资账户对,当用户提及 ISA/股票 ISA 时使用股票 ISA 对。如果用户想要所有账户的信息,请进行多次 API 调用——每个账户(投资和股票 ISA)一次——并为两者呈现或汇总结果。如果从上下文不清楚要使用哪个账户(并且他们没有要求所有账户),请在发出 API 调用之前请求确认(例如,“我应该使用哪个账户——投资账户还是股票 ISA 账户?”)。不要假设。根据选择的密钥/密钥构建头信息,基础 URL 为 https://${T212_ENV:-live}.trading212.com。T212_API_KEY_INVEST 和 T212_API_SECRET_INVEST):使用这对凭据进行请求;如果用户询问股票 ISA,则仅配置了投资账户。T212_API_KEY_STOCKS_ISA 和 T212_API_SECRET_STOCKS_ISA):使用这对凭据进行请求;如果用户询问投资账户,则仅配置了股票 ISA 账户。当设置了 T212_AUTH_HEADER 值时,在 Authorization 头信息中使用它:
# 当设置了 T212_AUTH_HEADER 和 T212_BASE_URL 时:
curl -H "Authorization: $T212_AUTH_HEADER" \
"${T212_BASE_URL}/api/v0/equity/account/summary"
当仅设置了主变量时,在 curl 中使用内联形式:
# 当仅设置了 T212_API_KEY, T212_API_SECRET, T212_ENV 时:
curl -H "Authorization: Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)" \
"https://${T212_ENV:-live}.trading212.com/api/v0/equity/account/summary"
警告:
T212_AUTH_HEADER必须是完整的头信息值,包括Basic前缀。# 错误 - 只有原始 base64,没有 "Basic " 前缀 curl -H "Authorization: <base64-only>" ... # 这将无法工作! # 正确 - 使用 T212_AUTH_HEADER(包含 "Basic <base64>") curl -H "Authorization: $T212_AUTH_HEADER" ... # 这可以工作
单一账户 vs 所有账户: API 密钥用于单一账户。一组密钥/密钥对 (T212_API_KEY + T212_API_SECRET) = 一个账户(投资或股票 ISA)。要使用所有账户(投资和股票 ISA),用户必须设置两组密钥/密钥:T212_API_KEY_INVEST / T212_API_SECRET_INVEST 和 T212_API_KEY_STOCKS_ISA / T212_API_SECRET_STOCKS_ISA。当两组都已设置时,用户必须明确指定要操作哪个账户;如果从上下文不清楚,请在发出 API 调用之前请求确认(投资或股票 ISA)。
主变量(单一账户): 为与插件 README 保持一致的设置,请设置这些变量:
export T212_API_KEY="your-api-key" # 来自 Trading 212 的 API 密钥(ID)
export T212_API_SECRET="your-api-secret"
export T212_ENV="demo" # 或 "live"(如果未设置,默认为 "live")
账户特定变量(投资和/或股票 ISA): 仅设置您使用的凭据对。一组完整的凭据(同一账户的密钥 + 密钥)就足够了。例如,仅投资账户:
export T212_API_KEY_INVEST="your-invest-api-key"
export T212_API_SECRET_INVEST="your-invest-api-secret"
export T212_ENV="demo" # 或 "live"
对于两个账户,设置两组凭据:
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" # 或 "live"(适用于两者)
可选 – 预计算(用于脚本或如果用户偏好): 用户可以从主变量设置认证头信息和基础 URL,但他们不需要这样做;在进行 API 调用时,您(代理)必须从主变量构建头信息和基础 URL(如果这些变量未设置)。
# 从 T212_API_KEY, T212_API_SECRET, T212_ENV 构建认证头信息和基础 URL
export T212_AUTH_HEADER="Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)"
export T212_BASE_URL="https://${T212_ENV:-live}.trading212.com"
替代方案(手动): 如果您不希望将密钥/密钥存储在环境变量中,可以直接设置派生变量。请记住:API 密钥仅适用于其匹配的环境。
# 对于演示环境(模拟交易)
export T212_AUTH_HEADER="Basic $(echo -n "<DEMO_API_KEY_ID>:<DEMO_API_SECRET>" | base64)"
export T212_BASE_URL="https://demo.trading212.com"
# 对于实盘环境(真实资金)- 在实盘账户中生成单独的凭据
# export T212_AUTH_HEADER="Basic $(echo -n "<LIVE_API_KEY_ID>:<LIVE_API_SECRET>" | base64)"
# export T212_BASE_URL="https://live.trading212.com"
提示: 如果您同时使用两个环境,请使用单独的变量名:
# 演示环境凭据
export T212_DEMO_AUTH_HEADER="Basic $(echo -n "<DEMO_KEY_ID>:<DEMO_SECRET>" | base64)"
# 实盘环境凭据
export T212_LIVE_AUTH_HEADER="Basic $(echo -n "<LIVE_KEY_ID>:<LIVE_SECRET>" | base64)"
| 代码 | 原因 | 解决方案 |
|---|---|---|
| 401 | 无效凭据 | 检查 API 密钥/密钥,确保没有多余的空格 |
| 401 | 环境不匹配 | 实盘 API 密钥不适用于演示环境,反之亦然 - 验证密钥是否与目标环境匹配 |
| 403 | 缺少权限 | 检查 Trading 212 设置中的 API 权限 |
| 408 | 请求超时 | 重试请求 |
| 429 | 超出速率限制 | 等待 x-ratelimit-reset 时间戳 |
GET /api/v0/equity/account/summary (1 次请求/5秒)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/account/summary"
响应模式:
{
"id": 12345678,
"currency": "GBP",
"totalValue": 15250.75,
"cash": {
"availableToTrade": 2500.5,
"reservedForOrders": 150.0,
"inPies": 500.0
},
"investments": {
"currentValue": 12100.25,
"totalCost": 10500.0,
"realizedProfitLoss": 850.5,
"unrealizedProfitLoss": 1600.25
}
}
| 字段 | 类型 | 描述 |
|---|---|---|
id | 整数 | 主要交易账户号码 |
currency | 字符串 | 主要账户货币(ISO 4217) |
totalValue | 数字 | 以主要货币计的总账户价值 |
cash.availableToTrade | 数字 | 可用于投资的资金 |
cash.reservedForOrders | 数字 | 为待处理订单预留的现金 |
cash.inPies | 数字 | 投资组合内的未投资现金 |
investments.currentValue | 数字 | 所有投资的当前价值 |
investments.totalCost | 数字 | 当前投资的成本基础 |
investments.realizedProfitLoss | 数字 | 所有已实现盈亏 |
investments.unrealizedProfitLoss | 数字 | 如果现在卖出,潜在的盈亏 |
| 类型 | 端点 | 可用性 | 描述 |
|---|---|---|---|
| 市价 | /api/v0/equity/orders/market | 演示 + 实盘 | 以最佳价格立即执行 |
| 限价 | /api/v0/equity/orders/limit | 演示 + 实盘 | 以限价或更优价格执行 |
| 止损 | /api/v0/equity/orders/stop | 演示 + 实盘 | 当达到止损价时触发市价单 |
| 止损限价 | /api/v0/equity/orders/stop_limit | 演示 + 实盘 | 当达到止损价时触发限价单 |
| 状态 | 描述 |
|---|---|
LOCAL | 订单在本地创建,尚未发送 |
UNCONFIRMED | 已发送至交易所,等待确认 |
CONFIRMED | 已由交易所确认 |
NEW | 活跃并等待执行 |
CANCELLING | 取消请求进行中 |
CANCELLED | 已成功取消 |
PARTIALLY_FILLED | 部分股票已执行 |
FILLED | 完全执行 |
REJECTED | 被交易所拒绝 |
REPLACING | 修改进行中 |
REPLACED | 已成功修改 |
| 值 | 描述 |
|---|---|
DAY | 在交易所时区的午夜到期 |
GOOD_TILL_CANCEL | 在成交或取消前保持活跃(默认) |
| 值 | 描述 |
|---|---|
QUANTITY | 按股票数量下单(API 支持) |
VALUE | 按货币价值下单(API 不支持) |
| 值 | 描述 |
|---|---|
API | 通过此 API 下单 |
IOS | iOS 应用程序 |
ANDROID | Android 应用程序 |
WEB | 网页平台 |
SYSTEM | 系统生成 |
AUTOINVEST | 自动投资功能 |
POST /api/v0/equity/orders/market (50 次请求/分钟)
# 买入 5 股
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/market" \
-d '{"ticker": "AAPL_US_EQ", "quantity": 5}'
# 卖出 3 股(负数数量)
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/market" \
-d '{"ticker": "AAPL_US_EQ", "quantity": -3}'
# 启用盘前盘后交易买入
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/market" \
-d '{"ticker": "AAPL_US_EQ", "quantity": 5, "extendedHours": true}'
请求字段:
| 字段 | 类型 | 必填 | 描述 |
|---|---|---|---|
ticker | 字符串 | 是 | 交易品种代码(例如,AAPL_US_EQ) |
quantity | 数字 | 是 | 正数表示买入,负数表示卖出 |
extendedHours | 布尔值 | 否 | 设置为 true 以允许在盘前(东部时间 4:00-9:30)和盘后(东部时间 16:00-20:00)时段执行。默认:false |
响应:
{
"id": 123456789,
"type": "MARKET",
"ticker": "AAPL_US_EQ",
"instrument": {
"ticker": "AAPL_US_EQ",
"name": "Apple Inc",
"isin": "US0378331005",
"currency": "USD"
},
"quantity": 5,
"filledQuantity": 0,
"status": "NEW",
"side": "BUY",
"strategy": "QUANTITY",
"initiatedFrom": "API",
"extendedHours": false,
"createdAt": "2024-01-15T10:30:00Z"
}
POST /api/v0/equity/orders/limit (1 次请求/2秒)
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/limit" \
-d '{"ticker": "AAPL_US_EQ", "quantity": 5, "limitPrice": 150.00, "timeValidity": "DAY"}'
请求字段:
| 字段 | 类型 | 必填 | 描述 |
|---|---|---|---|
ticker | 字符串 | 是 | 交易品种代码 |
quantity | 数字 | 是 | 正数表示买入,负数表示卖出 |
limitPrice | 数字 | 是 | 买入的最高价格,卖出的最低价格 |
timeValidity | 字符串 | 否 | DAY(默认)或 GOOD_TILL_CANCEL |
POST /api/v0/equity/orders/stop (1 次请求/2秒)
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/stop" \
-d '{"ticker": "AAPL_US_EQ", "quantity": -5, "stopPrice": 140.00, "timeValidity": "GOOD_TILL_CANCEL"}'
请求字段:
| 字段 | 类型 | 必填 | 描述 |
|---|---|---|---|
ticker | 字符串 | 是 | 交易品种代码 |
quantity | 数字 | 是 | 正数表示买入,负数表示卖出 |
stopPrice | 数字 | 是 | 触发价格(基于最后成交价) |
timeValidity | 字符串 | 否 | DAY(默认)或 GOOD_TILL_CANCEL |
POST /api/v0/equity/orders/stop_limit (1 次请求/2秒)
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/stop_limit" \
-d '{"ticker": "AAPL_US_EQ", "quantity": -5, "stopPrice": 145.00, "limitPrice": 140.00, "timeValidity": "DAY"}'
请求字段:
| 字段 | 类型 | 必填 | 描述 |
|---|---|---|---|
ticker | 字符串 | 是 | 交易品种代码 |
quantity | 数字 | 是 | 正数表示买入,负数表示卖出 |
stopPrice | 数字 | 是 | 激活限价单的触发价格 |
limitPrice | 数字 | 是 | 结果订单的限价 |
timeValidity | 字符串 | 否 | DAY(默认)或 GOOD_TILL_CANCEL |
GET /api/v0/equity/orders (1 次请求/5秒)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders"
返回状态为 NEW、PARTIALLY_FILLED 等的订单对象数组。
GET /api/v0/equity/orders/{id} (1 次请求/1秒)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders/123456789"
DELETE /api/v0/equity/orders/{id} (50 次请求/分钟)
curl -X DELETE -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders/123456789"
如果取消请求被接受,则返回 200 OK。订单可能已被成交。
| 错误 | 原因 | 解决方案 |
|---|---|---|
InsufficientFreeForStocksBuy | 现金不足 | 检查 cash.availableToTrade |
SellingEquityNotOwned | 卖出数量超过持有数量 | 检查 quantityAvailableForTrading |
MarketClosed | 交易时间外 | 检查交易所时间表 |
GET /api/v0/equity/positions (1 次请求/1秒)
查询参数:
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
ticker | 字符串 | 否 | 按特定代码筛选(例如,AAPL_US_EQ) |
# 所有持仓
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/positions"
# 按代码筛选
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/positions?ticker=AAPL_US_EQ"
响应模式:
[
{
"instrument": {
"ticker": "AAPL_US_EQ",
"name": "Apple Inc",
"isin": "US0378331005",
"currency": "USD"
},
"quantity": 15.5,
"quantityAvailableForTrading": 12.5,
"quantityInPies": 3,
"currentPrice": 185.5,
"averagePricePaid": 170.25,
"createdAt": "2024-01-10T09:15:00Z",
"walletImpact": {
"currency": "GBP",
"totalCost": 2089.45,
"currentValue": 2275.1,
"unrealizedProfitLoss": 185.65,
"fxImpact": 12.3
}
}
]
| 字段 | 类型 | 描述 |
|---|---|---|
quantity | 数字 | 持有的总股数 |
quantityAvailableForTrading | 数字 | 可用于卖出的股数 |
quantityInPies | 数字 | 分配到投资组合的股数 |
currentPrice | 数字 | 当前价格(交易品种货币) |
averagePricePaid | 数字 | 每股平均成本 |
createdAt | 日期时间 | 持仓开仓日期 |
walletImpact.currency | 字符串 | 账户货币 |
walletImpact.totalCost | 数字 | 以账户货币计的总成本 |
walletImpact.currentValue | 数字 | 以账户货币计的当前价值 |
walletImpact.unrealizedProfitLoss | 数字 | 以账户货币计的盈亏 |
walletImpact.fxImpact | 数字 | 汇率对价值的影响 |
| 场景 | quantity | quantityAvailableForTrading | quantityInPies |
|---|---|---|---|
| 全部为直接持有 | 10 | 10 | 0 |
| 部分在投资组合中 | 10 | 7 | 3 |
| 全部在投资组合中 | 10 | 0 | 10 |
重要提示: 在下达卖出订单前,请务必检查 quantityAvailableForTrading。
当用户通过通用名称(例如,“SAP”、“Apple”、“AAPL”)引用交易品种时,您必须在进行任何订单、持仓或历史数据查询之前查找确切的 Trading 212 代码。切勿手动构建代码格式。
先缓存: 在调用 API 之前,始终检查
/tmp/t212_instruments.json。交易品种端点有 50 秒的速率限制,并返回约 5MB 数据。仅当缓存缺失或超过 1 小时时才调用 API。
通用搜索: 在三个有意义的字段中匹配用户的搜索词:ticker、name 或 shortName。使用一个变量(例如 SEARCH_TERM)并在每个字段上使用 test($q; "i"),以便“TSLA”、“Tesla”、“TL0”等能有效匹配。对于区域筛选(例如“美国股票”、“欧洲 SAP”),在 grep 之后使用 ISIN 前缀(前 2 个字符)作为国家代码或 currencyCode。
重要提示: 切勿自动选择交易品种。如果存在多个选项,您必须询问用户的偏好。
# SEARCH_TERM = 用户查询(例如 TSLA, Tesla, AAPL, SAP)
SEARCH_TERM="TSLA"
CACHE_FILE="/tmp/t212_instruments.json"
if [ -f "$CACHE_FILE" ] && [ $(($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE"))) -lt 3600 ]; then
# 搜索 ticker、name 或 shortName 字段
jq --arg q "$SEARCH_TERM" '[.[] | select((.ticker // "" | test($q; "i")) or (.name // "" | test($q; "i")) or (.shortName // "" | test($q; "i")))]' "$CACHE_FILE"
else
curl -s -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/instruments" > "$CACHE_FILE"
fi
GET /api/v0/equity/metadata/instruments (1 次请求/50秒)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/instruments"
响应模式:
[
{
"ticker": "AAPL_US_EQ",
"name": "Apple Inc",
"shortName": "AAPL",
"isin": "US0378331005",
"currencyCode": "USD",
"type": "STOCK",
"maxOpenQuantity": 10000,
"extendedHours": true,
"workingScheduleId": 123,
"addedOn": "2020-01-15T00:00:00Z"
}
]
| 字段 | 类型 | 描述 |
|---|---|---|
ticker | 字符串 | 唯一交易品种标识符 |
name | 字符串 | 完整交易品种名称 |
shortName | 字符串 | 简称(例如,AAPL) |
isin | 字符串 | 国际证券识别码 |
currencyCode | 字符串 | 交易货币(ISO 4217) |
type | 字符串 | 交易品种类型(见下文) |
maxOpenQuantity | 数字 | 允许的最大持仓规模 |
extendedHours | 布尔值 | 是否支持盘前盘后交易 |
workingScheduleId | 整数 | 交易所时间表引用 |
addedOn | 日期时间 | 添加到平台的时间 |
| 类型 | 描述 |
|---|---|
STOCK | 普通股 |
ETF | 交易所交易基金 |
CRYPTOCURRENCY | 加密货币 |
CRYPTO | 加密资产 |
FOREX | 外汇 |
FUTURES | 期货合约 |
INDEX | 指数 |
WARRANT | 权证 |
CVR | 或有价值权利 |
CORPACT | 公司行动 |
{SYMBOL}_{EXCHANGE}_{TYPE} - 示例:
AAPL_US_EQ - 美国交易所的苹果公司VUSA_LSE_EQ - 伦敦交易所的先锋标普 500BTC_CRYPTO - 比特币GET /api/v0/equity/metadata/exchanges (1 次请求/30秒)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/exchanges"
响应模式:
[
{
"id": 123,
"name": "NASDAQ",
"workingSchedules": [
{
"id": 456,
"timeEvents": [
{ "type": "PRE_MARKET_OPEN", "date": "2024-01-15T09:00:00Z" },
{ "type": "OPEN", "date": "2024-01-15T14:30:00Z" },
{ "type": "CLOSE", "date": "2024-01-15T21:00:00Z" },
{ "type": "AFTER_HOURS_CLOSE", "date": "2024-01-15T01:00:00Z" }
]
}
]
}
]
| 类型 | 描述 |
|---|---|
PRE_MARKET_OPEN | 盘前交易时段开始 |
OPEN | 常规交易开始 |
BREAK_START | 交易休息开始 |
BREAK_END | 交易休息结束 |
CLOSE | 常规交易结束 |
AFTER_HOURS_OPEN | 盘后交易时段开始 |
AFTER_HOURS_CLOSE | 盘后交易时段结束 |
OVERNIGHT_OPEN | 隔夜交易时段开始 |
所有历史端点都使用基于游标的分页,带有 nextPagePath。
| 参数 | 类型 | 默认值 | 最大值 | 描述 |
|---|---|---|---|---|
limit | 整数 | 20 | 50 | 每页项目数 |
cursor | 字符串/数字 | - | - | 分页游标(在 nextPagePath 中使用) |
ticker | 字符串 | - | - | 按代码筛选(订单、股息) |
time | 日期时间 | - | - | 分页时间(在 nextPagePath 中用于交易) |
#!/bin/bash
# 使用分页获取所有历史订单
NEXT_PATH="/api/v0/equity/history/orders?limit=50"
while [ -n "$NEXT_PATH" ]; do
echo "正在获取:$NEXT_PATH"
RESPONSE=$(curl -s -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL$NEXT_PATH")
# 处理项目(例如,保存到文件)
echo "$RESPONSE" | jq '.items[]' >> orders.json
# 获取下一页路径(如果没有更多页面,则为 null)
NEXT_PATH=$(echo "$RESPONSE" | jq -r '.nextPagePath // empty')
# 在请求之间等待 1 秒(50 次请求/分钟限制)
if [ -n "$NEXT_PATH" ]; then
sleep 1
fi
done
echo "已完成所有订单的获取"
GET /api/v0/equity/history/orders (50 次请求/分钟)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/orders?limit=50"
# 按代码筛选
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/orders?ticker=AAPL_US_EQ&limit=50"
响应模式:
{
"items
Note: The Trading 212 API is currently in beta and under active development. Some endpoints or behaviors may change.
| Environment | Base URL | Purpose |
|---|---|---|
| Demo | https://demo.trading212.com/api/v0 | Paper trading - test without real funds |
| Live | https://live.trading212.com/api/v0 | Real money trading |
10 buys 10 shares)-10 sells 10 shares)Only Invest and Stocks ISA accounts are supported.
Trading 212 uses custom tickers as unique identifiers for instruments. Always search for the Trading 212 ticker before making instrument requests.
HTTP Basic Auth with API Key (username) and API Secret (password).
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.
# 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 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:
35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF)7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo)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:
export T212_AUTH_HEADER="Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)"
Otherwise, the agent builds the header from T212_API_KEY and T212_API_SECRET when making requests.
Manual (placeholders):
# Format: T212_AUTH_HEADER = "Basic " + base64(API_KEY_ID:API_SECRET)
export T212_AUTH_HEADER="Basic $(echo -n "<YOUR_API_KEY_ID>:<YOUR_API_SECRET>" | base64)"
# Example with sample credentials:
export T212_AUTH_HEADER="Basic $(echo -n "35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF:7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo" | base64)"
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):
T212_AUTH_HEADER and T212_BASE_URL are set: use them in requests.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.T212_API_KEY_INVEST/T212_API_SECRET_INVEST and T212_API_KEY_STOCKS_ISA/): the user must clearly specify which account to target (Invest or Stocks ISA), unless they ask for information for . Use the Invest pair when the user refers to Invest, and the Stocks ISA pair when the user refers to ISA/Stocks ISA. (Invest and Stocks ISA)—and present or aggregate the results for both. (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 .Use the T212_AUTH_HEADER value in the Authorization header when it is set:
# 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:
# 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_HEADERmust be the full header value including theBasicprefix.# 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
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:
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:
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:
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.
# 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.
# 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:
# Demo credentials
export T212_DEMO_AUTH_HEADER="Basic $(echo -n "<DEMO_KEY_ID>:<DEMO_SECRET>" | base64)"
# Live credentials
export T212_LIVE_AUTH_HEADER="Basic $(echo -n "<LIVE_KEY_ID>:<LIVE_SECRET>" | base64)"
| Code | Cause | Solution |
|---|---|---|
| 401 | Invalid credentials | Check API key/secret, ensure no extra whitespace |
| 401 | Environment mismatch | LIVE API keys don't work with DEMO and vice versa - verify key matches target environment |
| 403 | Missing permissions | Check API permissions in Trading 212 settings |
| 408 | Request timed out | Retry the request |
| 429 | Rate limit exceeded | Wait for x-ratelimit-reset timestamp |
GET /api/v0/equity/account/summary (1 req/5s)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/account/summary"
Response Schema:
{
"id": 12345678,
"currency": "GBP",
"totalValue": 15250.75,
"cash": {
"availableToTrade": 2500.5,
"reservedForOrders": 150.0,
"inPies": 500.0
},
"investments": {
"currentValue": 12100.25,
"totalCost": 10500.0,
"realizedProfitLoss": 850.5,
"unrealizedProfitLoss": 1600.25
}
}
| Field | Type | Description |
|---|---|---|
id | integer | Primary trading account number |
currency | string | Primary account currency (ISO 4217) |
totalValue | number | Total account value in primary currency |
cash.availableToTrade | number | Funds available for investing |
cash.reservedForOrders | number |
| Type | Endpoint | Availability | Description |
|---|---|---|---|
| Market | /api/v0/equity/orders/market | Demo + Live | Execute immediately at best price |
| Limit | /api/v0/equity/orders/limit | Demo + Live | Execute at limit price or better |
| Stop | /api/v0/equity/orders/stop | Demo + Live | Market order when stop price reached |
| StopLimit | /api/v0/equity/orders/stop_limit | Demo + Live |
| Status | Description |
|---|---|
LOCAL | Order created locally, not yet sent |
UNCONFIRMED | Sent to exchange, awaiting confirmation |
CONFIRMED | Confirmed by exchange |
NEW | Active and awaiting execution |
CANCELLING | Cancel request in progress |
CANCELLED | Successfully cancelled |
| Value | Description |
|---|---|
DAY | Expires at midnight in exchange timezone |
GOOD_TILL_CANCEL | Active until filled or cancelled (default) |
| Value | Description |
|---|---|
QUANTITY | Order by number of shares (API supported) |
VALUE | Order by monetary value (not supported via API) |
| Value | Description |
|---|---|
API | Placed via this API |
IOS | iOS app |
ANDROID | Android app |
WEB | Web platform |
SYSTEM | System-generated |
AUTOINVEST | Autoinvest feature |
POST /api/v0/equity/orders/market (50 req/min)
# Buy 5 shares
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/market" \
-d '{"ticker": "AAPL_US_EQ", "quantity": 5}'
# Sell 3 shares (negative quantity)
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/market" \
-d '{"ticker": "AAPL_US_EQ", "quantity": -3}'
# Buy with extended hours enabled
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/market" \
-d '{"ticker": "AAPL_US_EQ", "quantity": 5, "extendedHours": true}'
Request Fields:
| Field | Type | Required | Description |
|---|---|---|---|
ticker | string | Yes | Instrument ticker (e.g., AAPL_US_EQ) |
quantity | number | Yes | Positive for buy, negative for sell |
extendedHours | boolean | No | Set true to allow execution in pre-market (4:00-9:30 ET) and after-hours (16:00-20:00 ET) sessions. Default: false |
Response:
{
"id": 123456789,
"type": "MARKET",
"ticker": "AAPL_US_EQ",
"instrument": {
"ticker": "AAPL_US_EQ",
"name": "Apple Inc",
"isin": "US0378331005",
"currency": "USD"
},
"quantity": 5,
"filledQuantity": 0,
"status": "NEW",
"side": "BUY",
"strategy": "QUANTITY",
"initiatedFrom": "API",
"extendedHours": false,
"createdAt": "2024-01-15T10:30:00Z"
}
POST /api/v0/equity/orders/limit (1 req/2s)
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/limit" \
-d '{"ticker": "AAPL_US_EQ", "quantity": 5, "limitPrice": 150.00, "timeValidity": "DAY"}'
Request Fields:
| Field | Type | Required | Description |
|---|---|---|---|
ticker | string | Yes | Instrument ticker |
quantity | number | Yes | Positive for buy, negative for sell |
limitPrice | number | Yes | Maximum price for buy, minimum for sell |
timeValidity | string | No | DAY (default) or |
POST /api/v0/equity/orders/stop (1 req/2s)
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/stop" \
-d '{"ticker": "AAPL_US_EQ", "quantity": -5, "stopPrice": 140.00, "timeValidity": "GOOD_TILL_CANCEL"}'
Request Fields:
| Field | Type | Required | Description |
|---|---|---|---|
ticker | string | Yes | Instrument ticker |
quantity | number | Yes | Positive for buy, negative for sell |
stopPrice | number | Yes | Trigger price (based on Last Traded Price) |
timeValidity | string | No | DAY (default) or |
POST /api/v0/equity/orders/stop_limit (1 req/2s)
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/orders/stop_limit" \
-d '{"ticker": "AAPL_US_EQ", "quantity": -5, "stopPrice": 145.00, "limitPrice": 140.00, "timeValidity": "DAY"}'
Request Fields:
| Field | Type | Required | Description |
|---|---|---|---|
ticker | string | Yes | Instrument ticker |
quantity | number | Yes | Positive for buy, negative for sell |
stopPrice | number | Yes | Trigger price to activate limit order |
limitPrice | number | Yes | Limit price for the resulting order |
GET /api/v0/equity/orders (1 req/5s)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders"
Returns array of Order objects with status NEW, PARTIALLY_FILLED, etc.
GET /api/v0/equity/orders/{id} (1 req/1s)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders/123456789"
DELETE /api/v0/equity/orders/{id} (50 req/min)
curl -X DELETE -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders/123456789"
Returns 200 OK if cancellation request accepted. Order may already be filled.
| Error | Cause | Solution |
|---|---|---|
InsufficientFreeForStocksBuy | Not enough cash | Check cash.availableToTrade |
SellingEquityNotOwned | Selling more than owned | Check quantityAvailableForTrading |
MarketClosed | Outside trading hours | Check exchange schedule |
GET /api/v0/equity/positions (1 req/1s)
Query Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
ticker | string | No | Filter by specific ticker (e.g., AAPL_US_EQ) |
# All positions
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/positions"
# Filter by ticker
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/positions?ticker=AAPL_US_EQ"
Response Schema:
[
{
"instrument": {
"ticker": "AAPL_US_EQ",
"name": "Apple Inc",
"isin": "US0378331005",
"currency": "USD"
},
"quantity": 15.5,
"quantityAvailableForTrading": 12.5,
"quantityInPies": 3,
"currentPrice": 185.5,
"averagePricePaid": 170.25,
"createdAt": "2024-01-10T09:15:00Z",
"walletImpact": {
"currency": "GBP",
"totalCost": 2089.45,
"currentValue": 2275.1,
"unrealizedProfitLoss": 185.65,
"fxImpact": 12.3
}
}
]
| Field | Type | Description |
|---|---|---|
quantity | number | Total shares owned |
quantityAvailableForTrading | number | Shares available to sell |
quantityInPies | number | Shares allocated to pies |
currentPrice | number | Current price (instrument currency) |
averagePricePaid | number |
| Scenario | quantity | quantityAvailableForTrading | quantityInPies |
|---|---|---|---|
| All direct holdings | 10 | 10 | 0 |
| Some in pie | 10 | 7 | 3 |
| All in pie | 10 | 0 | 10 |
Important: Always check quantityAvailableForTrading before placing sell orders.
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.jsonbefore 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.
# SEARCH_TERM = user query (e.g. TSLA, Tesla, AAPL, SAP)
SEARCH_TERM="TSLA"
CACHE_FILE="/tmp/t212_instruments.json"
if [ -f "$CACHE_FILE" ] && [ $(($(date +%s) - $(stat -f %m "$CACHE_FILE" 2>/dev/null || stat -c %Y "$CACHE_FILE"))) -lt 3600 ]; then
# Search ticker, name, or shortName fields
jq --arg q "$SEARCH_TERM" '[.[] | select((.ticker // "" | test($q; "i")) or (.name // "" | test($q; "i")) or (.shortName // "" | test($q; "i")))]' "$CACHE_FILE"
else
curl -s -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/instruments" > "$CACHE_FILE"
fi
GET /api/v0/equity/metadata/instruments (1 req/50s)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/instruments"
Response Schema:
[
{
"ticker": "AAPL_US_EQ",
"name": "Apple Inc",
"shortName": "AAPL",
"isin": "US0378331005",
"currencyCode": "USD",
"type": "STOCK",
"maxOpenQuantity": 10000,
"extendedHours": true,
"workingScheduleId": 123,
"addedOn": "2020-01-15T00:00:00Z"
}
]
| Field | Type | Description |
|---|---|---|
ticker | string | Unique instrument identifier |
name | string | Full instrument name |
shortName | string | Short symbol (e.g., AAPL) |
isin | string | International Securities ID |
currencyCode | string | Trading currency (ISO 4217) |
| Type | Description |
|---|---|
STOCK | Common stock |
ETF | Exchange-traded fund |
CRYPTOCURRENCY | Cryptocurrency |
CRYPTO | Crypto asset |
FOREX | Foreign exchange |
FUTURES | Futures contract |
{SYMBOL}_{EXCHANGE}_{TYPE} - Examples:
AAPL_US_EQ - Apple on US exchangeVUSA_LSE_EQ - Vanguard S&P 500 on LondonBTC_CRYPTO - BitcoinGET /api/v0/equity/metadata/exchanges (1 req/30s)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/exchanges"
Response Schema:
[
{
"id": 123,
"name": "NASDAQ",
"workingSchedules": [
{
"id": 456,
"timeEvents": [
{ "type": "PRE_MARKET_OPEN", "date": "2024-01-15T09:00:00Z" },
{ "type": "OPEN", "date": "2024-01-15T14:30:00Z" },
{ "type": "CLOSE", "date": "2024-01-15T21:00:00Z" },
{ "type": "AFTER_HOURS_CLOSE", "date": "2024-01-15T01:00:00Z" }
]
}
]
}
]
| Type | Description |
|---|---|
PRE_MARKET_OPEN | Pre-market session starts |
OPEN | Regular trading starts |
BREAK_START | Trading break begins |
BREAK_END | Trading break ends |
CLOSE | Regular trading ends |
AFTER_HOURS_OPEN | After-hours session starts |
All historical endpoints use cursor-based pagination with nextPagePath.
| 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) |
#!/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 /api/v0/equity/history/orders (50 req/min)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/orders?limit=50"
# Filter by ticker
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/orders?ticker=AAPL_US_EQ&limit=50"
Response Schema:
{
"items": [
{
"order": {
"id": 123456789,
"type": "MARKET",
"ticker": "AAPL_US_EQ",
"instrument": {
"ticker": "AAPL_US_EQ",
"name": "Apple Inc",
"isin": "US0378331005",
"currency": "USD"
},
"quantity": 5,
"filledQuantity": 5,
"status": "FILLED",
"side": "BUY",
"createdAt": "2024-01-15T10:30:00Z"
},
"fill": {
"id": 987654321,
"type": "TRADE",
"quantity": 5,
"price": 185.5,
"filledAt": "2024-01-15T10:30:05Z",
"tradingMethod": "TOTV",
"walletImpact": {
"currency": "GBP",
"fxRate": 0.79,
"netValue": 732.72,
"realisedProfitLoss": 0,
"taxes": [
{ "name": "STAMP_DUTY", "quantity": 3.66, "currency": "GBP" }
]
}
}
}
],
"nextPagePath": "/api/v0/equity/history/orders?limit=50&cursor=1705326600000"
}
| Type | Description |
|---|---|
TRADE | Regular trade execution |
STOCK_SPLIT | Stock split adjustment |
STOCK_DISTRIBUTION | Stock distribution |
FOP | Free of payment transfer |
FOP_CORRECTION | FOP correction |
CUSTOM_STOCK_DISTRIBUTION | Custom stock distribution |
| Method | Description |
|---|---|
TOTV | Traded on trading venue |
OTC | Over-the-counter |
| Type | Description |
|---|---|
COMMISSION_TURNOVER | Commission on turnover |
CURRENCY_CONVERSION_FEE | FX conversion fee |
FINRA_FEE | FINRA trading activity fee |
FRENCH_TRANSACTION_TAX | French FTT |
PTM_LEVY | Panel on Takeovers levy |
STAMP_DUTY | UK stamp duty |
GET /api/v0/equity/history/dividends (50 req/min)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/dividends?limit=50"
# Filter by ticker
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/dividends?ticker=AAPL_US_EQ&limit=50"
Response Schema:
{
"items": [
{
"ticker": "AAPL_US_EQ",
"instrument": {
"ticker": "AAPL_US_EQ",
"name": "Apple Inc",
"isin": "US0378331005",
"currency": "USD"
},
"type": "ORDINARY",
"amount": 12.5,
"amountInEuro": 14.7,
"currency": "GBP",
"tickerCurrency": "USD",
"grossAmountPerShare": 0.24,
"quantity": 65.5,
"paidOn": "2024-02-15T00:00:00Z",
"reference": "DIV-123456"
}
],
"nextPagePath": null
}
| Type | Description |
|---|---|
ORDINARY | Regular dividend |
BONUS | Bonus dividend |
INTEREST | Interest payment |
DIVIDEND | Generic dividend |
CAPITAL_GAINS | Capital gains distribution |
RETURN_OF_CAPITAL | Return of capital |
Note: Many additional US tax-specific types exist for 1042-S reporting.
GET /api/v0/equity/history/transactions (50 req/min)
Pagination:
First request: Must use only the limit parameter (no cursor, no timestamp)
Subsequent requests: Use the nextPagePath from the previous response, which includes cursor and timestamp automatically
Time filtering: Transactions cannot be filtered by time - pagination is the only way to navigate through historical data
curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/history/transactions?limit=50"
Response Schema:
{
"items": [
{
"type": "DEPOSIT",
"amount": 1000.0,
"currency": "GBP",
"dateTime": "2024-01-10T14:30:00Z",
"reference": "TXN-123456"
}
],
"nextPagePath": null
}
| Type | Description |
|---|---|
DEPOSIT | Funds deposited to account |
WITHDRAW | Funds withdrawn from account |
FEE | Fee charged |
TRANSFER | Internal transfer |
Request report: POST /api/v0/equity/history/exports (1 req/30s)
curl -X POST -H "Authorization: $T212_AUTH_HEADER" \
-H "Content-Type: application/json" \
"$T212_BASE_URL/api/v0/equity/history/exports" \
-d '{
"dataIncluded": {
"includeDividends": true,
"includeInterest": true,
"includeOrders": true,
"includeTransactions": true
},
"timeFrom": "2024-01-01T00:00:00Z",
"timeTo": "2024-12-31T23:59:59Z"
}'
Response:
{
"reportId": 12345
}
Poll for completion: GET /api/v0/equity/history/exports (1 req/min)
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/exports"
Response:
[
{
"reportId": 12345,
"status": "Finished",
"dataIncluded": {
"includeDividends": true,
"includeInterest": true,
"includeOrders": true,
"includeTransactions": true
},
"timeFrom": "2024-01-01T00:00:00Z",
"timeTo": "2024-12-31T23:59:59Z",
"downloadLink": "https://trading212-reports.s3.amazonaws.com/..."
}
]
Download the report:
# 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"
| Status | Description |
|---|---|
Queued | Report request received |
Processing | Report generation started |
Running | Report actively generating |
Finished | Complete - downloadLink available |
Canceled | Report cancelled |
Failed | Generation failed |
#!/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"
#!/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 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.
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 |
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):
# 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):
# 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
For data that doesn't change frequently, cache locally to reduce API calls:
#!/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"
cash.availableToTrade) before buy, positions (quantityAvailableForTrading) before sellWeekly Installs
176
Repository
GitHub Stars
50
First Seen
Feb 4, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykFail
Installed on
opencode157
codex153
gemini-cli152
github-copilot150
kimi-cli147
amp147
Skills CLI 使用指南:AI Agent 技能包管理器安装与管理教程
33,600 周安装
Mermaid.js v11 图表生成教程 - 流程图、时序图、类图等24+图表类型
160 周安装
summarize:命令行AI摘要工具,支持URL、PDF、YouTube视频内容快速总结
160 周安装
SvelteKit 2 + Svelte 5 + Tailwind v4 集成指南 - 现代Web应用开发技能
160 周安装
日志记录最佳实践指南:结构化日志、安全合规与性能优化
161 周安装
Microsoft 365 租户管理器:自动化脚本工具,助力全局管理员高效管理用户与安全策略
161 周安装
Basecamp CLI 命令大全:130个端点管理待办事项、消息、文件等项目管理功能
161 周安装
T212_API_SECRET_STOCKS_ISAhttps://${T212_ENV:-live}.trading212.comT212_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.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.| Cash reserved for pending orders |
cash.inPies | number | Uninvested cash inside pies |
investments.currentValue | number | Current value of all investments |
investments.totalCost | number | Cost basis of current investments |
investments.realizedProfitLoss | number | All-time realized P&L |
investments.unrealizedProfitLoss | number | Potential P&L if sold now |
| Limit order when stop price reached |
PARTIALLY_FILLED | Some shares executed |
FILLED | Completely executed |
REJECTED | Rejected by exchange |
REPLACING | Modification in progress |
REPLACED | Successfully modified |
GOOD_TILL_CANCELGOOD_TILL_CANCELtimeValidity| string |
| No |
DAY (default) or GOOD_TILL_CANCEL |
| Average cost per share |
createdAt | datetime | Position open date |
walletImpact.currency | string | Account currency |
walletImpact.totalCost | number | Total cost in account currency |
walletImpact.currentValue | number | Current value in account currency |
walletImpact.unrealizedProfitLoss | number | P&L in account currency |
walletImpact.fxImpact | number | Currency rate impact on value |
type | string | Instrument type (see below) |
maxOpenQuantity | number | Maximum position size allowed |
extendedHours | boolean | Whether extended hours trading is available |
workingScheduleId | integer | Reference to exchange schedule |
addedOn | datetime | When added to platform |
INDEX| Index |
WARRANT | Warrant |
CVR | Contingent value right |
CORPACT | Corporate action |
AFTER_HOURS_CLOSE | After-hours session ends |
OVERNIGHT_OPEN | Overnight session starts |
time| datetime |
| - |
| - |
Pagination time (used in nextPagePath for transactions) |
EQUITY_RIGHTS | Equity rights issue |
STAMP_DUTY_RESERVE_TAX | UK SDRT |
TRANSACTION_FEE | General transaction fee |
PROPERTY_INCOME| Property income (REITs) |
DEMERGER | Demerger distribution |
QUALIFIED_INVESTMENT_ENTITY | QIE distribution |
TRUST_DISTRIBUTION | Trust distribution |