trading212-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTrading 212 API
Trading 212 API
Note: The Trading 212 API is currently in beta and under active development. Some endpoints or behaviors may change.
注意: Trading 212 API目前处于beta测试版,正在积极开发中。部分端点或行为可能会发生变化。
Quick Reference
快速参考
Environments
环境
| Environment | Base URL | Purpose |
|---|---|---|
| Demo | | Paper trading - test without real funds |
| Live | | Real money trading |
| 环境 | 基础URL | 用途 |
|---|---|---|
| 模拟(Demo) | | 模拟交易 - 无真实资金测试 |
| 实盘(Live) | | 真实资金交易 |
Order Quantity Convention
订单数量规则
- Positive quantity = BUY (e.g., buys 10 shares)
10 - Negative quantity = SELL (e.g., sells 10 shares)
-10
- 正数 = 买入(例如:表示买入10股)
10 - 负数 = 卖出(例如:表示卖出10股)
-10
Account Types
账户类型
Only Invest and Stocks ISA accounts are supported.
仅支持Invest和Stocks ISA账户。
Instrument Identifiers
交易工具标识符
Trading 212 uses custom tickers as unique identifiers for instruments.
Always search for the Trading 212 ticker before making instrument requests.
Trading 212使用自定义代码(ticker)作为交易工具的唯一标识符。在发起交易工具相关请求前,必须先搜索对应的Trading 212代码。
Authentication
认证
HTTP Basic Auth with API Key (username) and API Secret (password).
使用API Key(用户名)和API Secret(密码)进行HTTP Basic认证。
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. + , or + , or + ). 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.
T212_API_KEYT212_API_SECRETT212_API_KEY_INVESTT212_API_SECRET_INVESTT212_API_KEY_STOCKS_ISAT212_API_SECRET_STOCKS_ISAbash
undefined在引导用户完成认证配置前,先检查是否已配置凭证:
语义规则: 当存在至少一套完整的凭证组时,即视为已配置:一套完整凭证组指同一账户的key+secret(例如 + ,或 + ,或 + )。无需配置所有四组账户特定变量;仅配置Invest组或仅配置Stocks ISA组即可。检查是否存在任意一组可用的key+secret对。
T212_API_KEYT212_API_SECRETT212_API_KEY_INVESTT212_API_SECRET_INVESTT212_API_KEY_STOCKS_ISAT212_API_SECRET_STOCKS_ISAbash
undefinedExample: 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.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 "已配置(Invest账户);若配置了T212_API_KEY_STOCKS_ISA和T212_API_SECRET_STOCKS_ISA,则同时支持Stocks ISA账户"
elif [ -n "$T212_API_KEY_STOCKS_ISA" ] && [ -n "$T212_API_SECRET_STOCKS_ISA" ]; then
echo "已配置(Stocks ISA账户);若配置了T212_API_KEY_INVEST和T212_API_SECRET_INVEST,则同时支持Invest账户"
else
echo "未找到完整的凭证组"
fi
如果存在任意完整凭证组,跳过完整配置流程,直接进行API调用;发起请求时,使用下方“发起请求”中的优先级顺序(当存在多组凭证时,选择与用户账户上下文匹配的组)。无需引导用户运行衍生命令或合并密钥到请求头中。仅当不存在完整凭证组时,才引导用户完成下方的完整配置流程。
> **重要提示:** 在发起任何API调用前,务必询问用户要使用的环境:**实盘(LIVE,真实资金)**还是**模拟(DEMO,纸盘交易)**。不要默认环境。API Keys Are Environment-Specific
API密钥与环境绑定
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 | | |
| DEMO account | | |
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
API密钥与特定环境绑定,无法跨环境使用。
| API密钥创建环境 | 可用于 | 不可用于 |
|---|---|---|
| 实盘(LIVE)账户 | | |
| 模拟(DEMO)账户 | | |
如果收到401错误,请验证:
- 你正在为目标环境使用正确的API密钥
- API密钥是在你尝试访问的同一环境(实盘或模拟)中生成的
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
- API Key (ID) (e.g.,
- Store the credentials separately for each environment if you use both
- 确定要使用的环境 - 实盘(真实资金)或模拟(纸盘交易)
- 打开Trading 212应用(移动端或网页端)
- 切换到正确的账户 - 确保你处于与目标环境匹配的实盘或模拟模式
- 导航到设置 > API
- 生成新的API密钥对 - 你将收到:
- API Key(ID)(例如:)
35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF - API Secret(例如:)
7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo
- API Key(ID)(例如:
- 分别存储各环境的凭证(如果同时使用两个环境)
Building the Auth Header
构建认证请求头
Combine your API Key (ID) and Secret with a colon, base64 encode, and prefix with for the Authorization header.
Basic Optional: To precompute the header from key/secret, you can set:
bash
export T212_AUTH_HEADER="Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)"Otherwise, the agent builds the header from and when making requests.
T212_API_KEYT212_API_SECRETManual (placeholders):
bash
undefined将API Key(ID)和Secret用冒号连接,进行base64编码,然后在前面添加作为Authorization请求头。
Basic 可选操作: 要提前从key/secret计算请求头,可以设置:
bash
export T212_AUTH_HEADER="Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)"否则,Agent会在发起请求时从和构建请求头。
T212_API_KEYT212_API_SECRET手动构建(占位符):
bash
undefinedFormat: T212_AUTH_HEADER = "Basic " + base64(API_KEY_ID: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 "<你的API_KEY_ID>:<你的API_SECRET>" | base64)"
Example with sample credentials:
使用示例凭证的例子:
export T212_AUTH_HEADER="Basic $(echo -n "35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF:7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo" | base64)"
undefinedexport T212_AUTH_HEADER="Basic $(echo -n "35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF:7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo" | base64)"
undefinedMaking Requests
发起请求
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 and
T212_AUTH_HEADERare set: use them in requests.T212_BASE_URL - Else if and
T212_API_KEYare set: use this pair (single account). Build header asT212_API_SECRETand base URL asBasic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64). Do not guide the user to derive or merge; you do it.https://${T212_ENV:-live}.trading212.com - Else if both account-specific pairs are set (/
T212_API_KEY_INVESTandT212_API_SECRET_INVEST/T212_API_KEY_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 asT212_API_SECRET_STOCKS_ISA.https://${T212_ENV:-live}.trading212.com - Else if only the Invest pair is set (and
T212_API_KEY_INVEST): use this pair for requests; if the user asks about Stocks ISA, only the Invest account is configured.T212_API_SECRET_INVEST - Else if only the Stocks ISA pair is set (and
T212_API_KEY_STOCKS_ISA): use this pair for requests; if the user asks about Invest, only the Stocks ISA account is configured.T212_API_SECRET_STOCKS_ISA
Use the value in the Authorization header when it is set:
T212_AUTH_HEADERbash
undefined发起API调用时,使用第一个适用的选项(语义上:选择与用户账户匹配的凭证组,或仅有的一组凭证):
- 如果已设置和
T212_AUTH_HEADER: 在请求中使用它们。T212_BASE_URL - 否则,如果已设置和
T212_API_KEY: 使用这组凭证(单个账户)。构建请求头为T212_API_SECRET,基础URL为Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)。无需引导用户衍生或合并;由你自动处理。https://${T212_ENV:-live}.trading212.com - 否则,如果同时设置了两组账户特定凭证(/
T212_API_KEY_INVEST和T212_API_SECRET_INVEST/T212_API_KEY_STOCKS_ISA):用户必须明确指定目标账户(Invest或Stocks ISA),除非他们要求获取所有账户的信息。当用户提到Invest时使用Invest组,提到ISA/Stocks ISA时使用Stocks ISA组。如果用户需要所有账户的信息,发起多个API调用——每个账户一个(Invest和Stocks ISA)——并展示或汇总两个账户的结果。 如果上下文无法明确要使用哪个账户(且用户未要求所有账户),在发起API调用前请确认(例如:“我应该使用哪个账户——Invest还是Stocks ISA?”)。不要假设。从选定的key/secret构建请求头,基础URL为T212_API_SECRET_STOCKS_ISA。https://${T212_ENV:-live}.trading212.com - 否则,如果仅设置了Invest组凭证(和
T212_API_KEY_INVEST):使用这组凭证发起请求;如果用户询问Stocks ISA,说明仅配置了Invest账户。T212_API_SECRET_INVEST - 否则,如果仅设置了Stocks ISA组凭证(和
T212_API_KEY_STOCKS_ISA):使用这组凭证发起请求;如果用户询问Invest,说明仅配置了Stocks ISA账户。T212_API_SECRET_STOCKS_ISA
当已设置时,在Authorization请求头中使用该值:
T212_AUTH_HEADERbash
undefinedWhen T212_AUTH_HEADER and T212_BASE_URL are set:
当T212_AUTH_HEADER和T212_BASE_URL已设置时:
curl -H "Authorization: $T212_AUTH_HEADER"
"${T212_BASE_URL}/api/v0/equity/account/summary"
"${T212_BASE_URL}/api/v0/equity/account/summary"
When only primary vars are set, use the inline form in the curl:
```bashcurl -H "Authorization: $T212_AUTH_HEADER"
"${T212_BASE_URL}/api/v0/equity/account/summary"
"${T212_BASE_URL}/api/v0/equity/account/summary"
当仅设置了主变量时,在curl中使用内联形式:
```bashWhen only T212_API_KEY, T212_API_SECRET, T212_ENV are set:
当仅设置了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"
"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
> ```curl -H "Authorization: Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)"
"https://${T212_ENV:-live}.trading212.com/api/v0/equity/account/summary"
"https://${T212_ENV:-live}.trading212.com/api/v0/equity/account/summary"
> **警告:** `T212_AUTH_HEADER`必须是包含`Basic `前缀的完整请求头值。
>
> ```bash
> # 错误 - 仅使用base64编码内容,缺少"Basic "前缀
> curl -H "Authorization: <仅base64内容>" ... # 这将无法生效!
>
> # 正确 - 使用T212_AUTH_HEADER(包含"Basic <base64内容>")
> curl -H "Authorization: $T212_AUTH_HEADER" ... # 这将生效
> ```Environment Variables
环境变量
Single account vs all accounts: API keys are for a single account. One key/secret pair ( + ) = one account (Invest or Stocks ISA). To use all accounts (Invest and Stocks ISA), the user must set two sets of key/secret: / and / . 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.
T212_API_KEYT212_API_SECRETT212_API_KEY_INVESTT212_API_SECRET_INVESTT212_API_KEY_STOCKS_ISAT212_API_SECRET_STOCKS_ISAPrimary (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
undefined单个账户 vs 所有账户: API密钥对应单个账户。一组key/secret对( + )= 一个账户(Invest或Stocks ISA)。要使用所有账户(Invest和Stocks ISA),用户必须设置两组key/secret: / 和 / 。当两组凭证都已设置时,用户必须明确指定目标账户;如果上下文无法明确,在发起API调用前请确认(Invest或Stocks ISA)。
T212_API_KEYT212_API_SECRETT212_API_KEY_INVESTT212_API_SECRET_INVESTT212_API_KEY_STOCKS_ISAT212_API_SECRET_STOCKS_ISA主变量(单个账户): 设置这些变量以与插件README保持一致的配置:
bash
export T212_API_KEY="你的-api-key" # 来自Trading 212的API Key(ID)
export T212_API_SECRET="你的-api-secret"
export T212_ENV="demo" # 或"live"(如果未设置,默认值为"live")账户特定变量(Invest和/或Stocks ISA): 仅设置你使用的组。一组完整的凭证(同一账户的key + secret)即可。例如,仅设置Invest账户:
bash
export T212_API_KEY_INVEST="你的-invest-api-key"
export T212_API_SECRET_INVEST="你的-invest-api-secret"
export T212_ENV="demo" # 或"live"如果要设置两个账户,同时设置两组变量:
bash
export T212_API_KEY_INVEST="你的-invest-api-key"
export T212_API_SECRET_INVEST="你的-invest-api-secret"
export T212_API_KEY_STOCKS_ISA="你的-stocks-isa-api-key"
export T212_API_SECRET_STOCKS_ISA="你的-stocks-isa-api-secret"
export T212_ENV="demo" # 或"live"(对两个账户都生效)可选 - 预计算变量(适用于脚本或用户偏好): 用户可以从主变量设置认证请求头和基础URL,但这不是必须的;当发起API调用时,如果这些变量未设置,你(Agent)必须从主变量构建请求头和基础URL。
bash
undefinedBuild auth header and base URL from T212_API_KEY, T212_API_SECRET, T212_ENV
从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"
**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.
```bashexport T212_AUTH_HEADER="Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)"
export T212_BASE_URL="https://${T212_ENV:-live}.trading212.com"
**替代方案(手动设置):** 如果你不想在环境变量中存储key/secret,可以直接设置衍生变量。记住:API密钥仅能与匹配的环境一起使用。
```bashFor DEMO (paper trading)
模拟(DEMO)环境(纸盘交易)
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 "<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
实盘(LIVE)环境(真实资金)- 在实盘账户中生成单独的凭证
export T212_AUTH_HEADER="Basic $(echo -n "<LIVE_API_KEY_ID>:<LIVE_API_SECRET>" | base64)"
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_BASE_URL="https://live.trading212.com"
**Tip:** If you use both environments, use separate variable names:
```bash
**提示:** 如果同时使用两个环境,使用不同的变量名:
```bashDemo credentials
模拟环境凭证
export T212_DEMO_AUTH_HEADER="Basic $(echo -n "<DEMO_KEY_ID>:<DEMO_SECRET>" | base64)"
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)"
undefinedexport T212_LIVE_AUTH_HEADER="Basic $(echo -n "<LIVE_KEY_ID>:<LIVE_SECRET>" | base64)"
undefinedCommon Auth Errors
常见认证错误
| 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 |
| 错误码 | 原因 | 解决方案 |
|---|---|---|
| 401 | 凭证无效 | 检查API key/secret,确保没有多余空格 |
| 401 | 环境不匹配 | 实盘API密钥无法用于模拟环境,反之亦然 - 验证密钥与目标环境匹配 |
| 403 | 缺少权限 | 在Trading 212设置中检查API权限 |
| 408 | 请求超时 | 重试请求 |
| 429 | 超出速率限制 | 等待 |
Account
账户
Get Account Summary
获取账户摘要
GET /api/v0/equity/account/summarybash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/account/summary"Response Schema:
json
{
"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
}
}GET /api/v0/equity/account/summarybash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/account/summary"响应结构:
json
{
"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
}
}Account Fields
账户字段
| Field | Type | Description |
|---|---|---|
| integer | Primary trading account number |
| string | Primary account currency (ISO 4217) |
| number | Total account value in primary currency |
| number | Funds available for investing |
| number | Cash reserved for pending orders |
| number | Uninvested cash inside pies |
| number | Current value of all investments |
| number | Cost basis of current investments |
| number | All-time realized P&L |
| number | Potential P&L if sold now |
| 字段 | 类型 | 描述 |
|---|---|---|
| integer | 主交易账户编号 |
| string | 账户主货币(ISO 4217标准) |
| number | 账户总价值(以主货币计) |
| number | 可用于投资的资金 |
| number | 为挂单预留的现金 |
| number | Pies中的未投资现金 |
| number | 所有投资的当前价值 |
| number | 当前投资的成本基准 |
| number | 历史已实现盈亏 |
| number | 若当前卖出的潜在盈亏 |
Orders
订单
Order Types
订单类型
| Type | Endpoint | Availability | Description |
|---|---|---|---|
| Market | | Demo + Live | Execute immediately at best price |
| Limit | | Demo + Live | Execute at limit price or better |
| Stop | | Demo + Live | Market order when stop price reached |
| StopLimit | | Demo + Live | Limit order when stop price reached |
| 类型 | 端点 | 可用环境 | 描述 |
|---|---|---|---|
| 市价单(Market) | | 模拟+实盘 | 以最优价格立即执行 |
| 限价单(Limit) | | 模拟+实盘 | 以限价或更优价格执行 |
| 止损单(Stop) | | 模拟+实盘 | 当达到止损价格时触发市价单 |
| 止损限价单(StopLimit) | | 模拟+实盘 | 当达到止损价格时触发限价单 |
Order Statuses
订单状态
| Status | Description |
|---|---|
| Order created locally, not yet sent |
| Sent to exchange, awaiting confirmation |
| Confirmed by exchange |
| Active and awaiting execution |
| Cancel request in progress |
| Successfully cancelled |
| Some shares executed |
| Completely executed |
| Rejected by exchange |
| Modification in progress |
| Successfully modified |
| 状态 | 描述 |
|---|---|
| 本地创建的订单,尚未发送到交易所 |
| 已发送到交易所,等待确认 |
| 已被交易所确认 |
| 活跃状态,等待执行 |
| 取消请求处理中 |
| 已成功取消 |
| 部分份额已执行 |
| 全部份额已执行 |
| 被交易所拒绝 |
| 修改请求处理中 |
| 已成功修改 |
Time Validity
时间有效性
| Value | Description |
|---|---|
| Expires at midnight in exchange timezone |
| Active until filled or cancelled (default) |
| 值 | 描述 |
|---|---|
| 在交易所时区的午夜到期 |
| 保持活跃直到成交或被取消(默认值) |
Order Strategy
订单策略
| Value | Description |
|---|---|
| Order by number of shares (API supported) |
| Order by monetary value (not supported via API) |
| 值 | 描述 |
|---|---|
| 按份额数下单(API支持) |
| 按金额下单(API不支持) |
Initiated From
发起来源
| Value | Description |
|---|---|
| Placed via this API |
| iOS app |
| Android app |
| Web platform |
| System-generated |
| Autoinvest feature |
| 值 | 描述 |
|---|---|
| 通过本API下单 |
| iOS应用 |
| Android应用 |
| 网页平台 |
| 系统生成 |
| 自动投资功能 |
Place Market Order
下市价单
POST /api/v0/equity/orders/marketbash
undefinedPOST /api/v0/equity/orders/marketbash
undefinedBuy 5 shares
买入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}'
-H "Content-Type: application/json"
"$T212_BASE_URL/api/v0/equity/orders/market"
-d '{"ticker": "AAPL_US_EQ", "quantity": 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}'
-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)
卖出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}'
-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": -3}'
-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}'
-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:**
```json
{
"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"
}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}'
-H "Content-Type: application/json"
"$T212_BASE_URL/api/v0/equity/orders/market"
-d '{"ticker": "AAPL_US_EQ", "quantity": 5, "extendedHours": true}'
**请求字段:**
| 字段 | 类型 | 是否必填 | 描述 |
| --------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| `ticker` | string | 是 | 交易工具代码(例如:`AAPL_US_EQ`) |
| `quantity` | number | 是 | 正数表示买入,负数表示卖出 |
| `extendedHours` | boolean | 否 | 设置为`true`以允许在盘前(美国东部时间4:00-9:30)和盘后(美国东部时间16:00-20:00)时段执行。默认值:`false` |
**响应:**
```json
{
"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"
}Place Limit Order
下限价单
POST /api/v0/equity/orders/limitbash
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 |
|---|---|---|---|
| string | Yes | Instrument ticker |
| number | Yes | Positive for buy, negative for sell |
| number | Yes | Maximum price for buy, minimum for sell |
| string | No | |
POST /api/v0/equity/orders/limitbash
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"}'请求字段:
| 字段 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| string | 是 | 交易工具代码 |
| number | 是 | 正数表示买入,负数表示卖出 |
| number | 是 | 买入的最高价格,卖出的最低价格 |
| string | 否 | |
Place Stop Order
下止损单
POST /api/v0/equity/orders/stopbash
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 |
|---|---|---|---|
| string | Yes | Instrument ticker |
| number | Yes | Positive for buy, negative for sell |
| number | Yes | Trigger price (based on Last Traded Price) |
| string | No | |
POST /api/v0/equity/orders/stopbash
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"}'请求字段:
| 字段 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| string | 是 | 交易工具代码 |
| number | 是 | 正数表示买入,负数表示卖出 |
| number | 是 | 触发价格(基于最新成交价) |
| string | 否 | |
Place Stop-Limit Order
下止损限价单
POST /api/v0/equity/orders/stop_limitbash
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 |
|---|---|---|---|
| string | Yes | Instrument ticker |
| number | Yes | Positive for buy, negative for sell |
| number | Yes | Trigger price to activate limit order |
| number | Yes | Limit price for the resulting order |
| string | No | |
POST /api/v0/equity/orders/stop_limitbash
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"}'请求字段:
| 字段 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| string | 是 | 交易工具代码 |
| number | 是 | 正数表示买入,负数表示卖出 |
| number | 是 | 触发限价单的价格 |
| number | 是 | 最终订单的限价 |
| string | 否 | |
Get Pending Orders
获取挂单
GET /api/v0/equity/ordersbash
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/ordersbash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders"返回状态为NEW、PARTIALLY_FILLED等的订单对象数组。
Get Order by ID
通过ID获取订单
GET /api/v0/equity/orders/{id}bash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders/123456789"GET /api/v0/equity/orders/{id}bash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders/123456789"Cancel Order
取消订单
DELETE /api/v0/equity/orders/{id}bash
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.
DELETE /api/v0/equity/orders/{id}bash
curl -X DELETE -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/orders/123456789"如果取消请求被接受,返回200 OK。订单可能已经成交。
Common Order Errors
常见订单错误
| Error | Cause | Solution |
|---|---|---|
| Not enough cash | Check |
| Selling more than owned | Check |
| Outside trading hours | Check exchange schedule |
| 错误 | 原因 | 解决方案 |
|---|---|---|
| 资金不足 | 检查 |
| 卖出份额超过持仓 | 检查 |
| 非交易时间 | 检查交易所时间表 |
Positions
持仓
Get All Positions
获取所有持仓
GET /api/v0/equity/positionsQuery Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| string | No | Filter by specific ticker (e.g., |
bash
undefinedGET /api/v0/equity/positions查询参数:
| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| string | 否 | 按特定代码过滤(例如: |
bash
undefinedAll positions
所有持仓
curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/positions"
"$T212_BASE_URL/api/v0/equity/positions"
curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/positions"
"$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"
"$T212_BASE_URL/api/v0/equity/positions?ticker=AAPL_US_EQ"
**Response Schema:**
```json
[
{
"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
}
}
]curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/positions?ticker=AAPL_US_EQ"
"$T212_BASE_URL/api/v0/equity/positions?ticker=AAPL_US_EQ"
**响应结构:**
```json
[
{
"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
}
}
]Position Fields
持仓字段
| Field | Type | Description |
|---|---|---|
| number | Total shares owned |
| number | Shares available to sell |
| number | Shares allocated to pies |
| number | Current price (instrument currency) |
| number | Average cost per share |
| datetime | Position open date |
| string | Account currency |
| number | Total cost in account currency |
| number | Current value in account currency |
| number | P&L in account currency |
| number | Currency rate impact on value |
| 字段 | 类型 | 描述 |
|---|---|---|
| number | 持有的总份额 |
| number | 可卖出的份额 |
| number | 分配到Pies中的份额 |
| number | 当前价格(交易工具货币) |
| number | 每股平均成本 |
| datetime | 持仓开立日期 |
| string | 账户货币 |
| number | 总成本(账户货币) |
| number | 当前价值(账户货币) |
| number | 盈亏(账户货币) |
| number | 汇率对价值的影响 |
Position Quantity Scenarios
持仓份额场景
| 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 before placing sell orders.
quantityAvailableForTrading| 场景 | quantity | quantityAvailableForTrading | quantityInPies |
|---|---|---|---|
| 全部为直接持仓 | 10 | 10 | 0 |
| 部分在Pies中 | 10 | 7 | 3 |
| 全部在Pies中 | 10 | 0 | 10 |
重要提示: 在下单卖出前,务必检查。
quantityAvailableForTradingInstruments
交易工具
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 checkbefore 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./tmp/t212_instruments.json
Generic search: Match the user's search term in the three meaningful fields: ticker, name, or shortName. Use one variable (e.g. ) with 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 after the grep.
SEARCH_TERMtest($q; "i")currencyCodeIMPORTANT: Never auto-select instruments. If multiple options exist, you are required to ask the user for their preference.
bash
undefined当用户通过通用名称引用交易工具时(例如:"SAP"、"Apple"、"AAPL"),你必须在发起任何订单、持仓或历史数据查询前,查找准确的Trading 212代码。永远不要手动构造代码格式。
优先使用缓存: 在调用API前,务必检查。交易工具端点有50秒的速率限制,返回数据约5MB。仅当缓存缺失或超过1小时时,才调用API。/tmp/t212_instruments.json
通用搜索: 在三个有意义的字段中匹配用户的搜索词:代码(ticker)、名称(name)或短名称(shortName)。使用一个变量(例如),对每个字段使用,这样"TSLA"、"Tesla"、"TL0"等都能高效匹配。对于区域过滤(例如:"美国股票"、"欧洲SAP"),使用ISIN前缀(前2个字符作为国家代码)或在grep后使用。
SEARCH_TERMtest($q; "i")currencyCode重要提示: 永远不要自动选择交易工具。如果存在多个选项,你必须询问用户的偏好。
bash
undefinedSEARCH_TERM = user query (e.g. TSLA, Tesla, AAPL, SAP)
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
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
"$T212_BASE_URL/api/v0/equity/metadata/instruments" > "$CACHE_FILE" fi
undefinedSEARCH_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
搜索代码、名称或短名字段
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
"$T212_BASE_URL/api/v0/equity/metadata/instruments" > "$CACHE_FILE" fi
undefinedGet All Instruments
获取所有交易工具
GET /api/v0/equity/metadata/instrumentsbash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/instruments"Response Schema:
json
[
{
"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"
}
]GET /api/v0/equity/metadata/instrumentsbash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/instruments"响应结构:
json
[
{
"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"
}
]Instrument Fields
交易工具字段
| Field | Type | Description |
|---|---|---|
| string | Unique instrument identifier |
| string | Full instrument name |
| string | Short symbol (e.g., AAPL) |
| string | International Securities ID |
| string | Trading currency (ISO 4217) |
| string | Instrument type (see below) |
| number | Maximum position size allowed |
| boolean | Whether extended hours trading is available |
| integer | Reference to exchange schedule |
| datetime | When added to platform |
| 字段 | 类型 | 描述 |
|---|---|---|
| string | 交易工具唯一标识符 |
| string | 交易工具全名 |
| string | 短代码(例如:AAPL) |
| string | 国际证券识别码 |
| string | 交易货币(ISO 4217标准) |
| string | 交易工具类型(见下文) |
| number | 允许的最大持仓量 |
| boolean | 是否支持盘前盘后交易 |
| integer | 交易所时间表引用ID |
| datetime | 上线平台的时间 |
Instrument Types
交易工具类型
| Type | Description |
|---|---|
| Common stock |
| Exchange-traded fund |
| Cryptocurrency |
| Crypto asset |
| Foreign exchange |
| Futures contract |
| Index |
| Warrant |
| Contingent value right |
| Corporate action |
| 类型 | 描述 |
|---|---|
| 普通股 |
| 交易所交易基金 |
| 加密货币 |
| 加密资产 |
| 外汇 |
| 期货合约 |
| 指数 |
| 权证 |
| 或有价值权利 |
| 公司行动 |
Ticker Format
代码格式
{SYMBOL}_{EXCHANGE}_{TYPE}- - Apple on US exchange
AAPL_US_EQ - - Vanguard S&P 500 on London
VUSA_LSE_EQ - - Bitcoin
BTC_CRYPTO
{SYMBOL}_{EXCHANGE}_{TYPE}- - 苹果公司(美国交易所)
AAPL_US_EQ - - 标普500先锋基金(伦敦交易所)
VUSA_LSE_EQ - - 比特币
BTC_CRYPTO
Get Exchange Metadata
获取交易所元数据
GET /api/v0/equity/metadata/exchangesbash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/exchanges"Response Schema:
json
[
{
"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" }
]
}
]
}
]GET /api/v0/equity/metadata/exchangesbash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/metadata/exchanges"响应结构:
json
[
{
"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" }
]
}
]
}
]Time Event Types
时间事件类型
| Type | Description |
|---|---|
| Pre-market session starts |
| Regular trading starts |
| Trading break begins |
| Trading break ends |
| Regular trading ends |
| After-hours session starts |
| After-hours session ends |
| Overnight session starts |
| 类型 | 描述 |
|---|---|
| 盘前时段开始 |
| 常规交易开始 |
| 交易休市开始 |
| 交易休市结束 |
| 常规交易结束 |
| 盘后时段开始 |
| 盘后时段结束 |
| 隔夜时段开始 |
Historical Data
历史数据
All historical endpoints use cursor-based pagination with .
nextPagePath所有历史端点使用基于游标(cursor)的分页,带有。
nextPagePathPagination Parameters
分页参数
| Parameter | Type | Default | Max | Description |
|---|---|---|---|---|
| integer | 20 | 50 | Items per page |
| string/number | - | - | Pagination cursor (used in |
| string | - | - | Filter by ticker (orders, dividends) |
| datetime | - | - | Pagination time (used in |
| 参数 | 类型 | 默认值 | 最大值 | 描述 |
|---|---|---|---|---|
| integer | 20 | 50 | 每页条目数 |
| string/number | - | - | 分页游标(在 |
| string | - | - | 按代码过滤(订单、分红) |
| datetime | - | - | 分页时间(在 |
Pagination Example
分页示例
bash
#!/bin/bashbash
#!/bin/bashFetch 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")
"$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"
undefinedNEXT_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")
"$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 "已获取所有订单"
undefinedHistorical Orders
历史订单
GET /api/v0/equity/history/ordersbash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/orders?limit=50"GET /api/v0/equity/history/ordersbash
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"
"$T212_BASE_URL/api/v0/equity/history/orders?ticker=AAPL_US_EQ&limit=50"
**Response Schema:**
```json
{
"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"
}curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/history/orders?ticker=AAPL_US_EQ&limit=50"
"$T212_BASE_URL/api/v0/equity/history/orders?ticker=AAPL_US_EQ&limit=50"
**响应结构:**
```json
{
"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"
}Fill Types
成交类型
| Type | Description |
|---|---|
| Regular trade execution |
| Stock split adjustment |
| Stock distribution |
| Free of payment transfer |
| FOP correction |
| Custom stock distribution |
| Equity rights issue |
| 类型 | 描述 |
|---|---|
| 常规交易执行 |
| 股票拆分调整 |
| 股票分发 |
| 免费转账 |
| FOP修正 |
| 自定义股票分发 |
| 股权发行 |
Trading Methods
交易方式
| Method | Description |
|---|---|
| Traded on trading venue |
| Over-the-counter |
| 方式 | 描述 |
|---|---|
| 在交易场所交易 |
| 场外交易 |
Tax Types (walletImpact.taxes)
税费类型(walletImpact.taxes)
| Type | Description |
|---|---|
| Commission on turnover |
| FX conversion fee |
| FINRA trading activity fee |
| French FTT |
| Panel on Takeovers levy |
| UK stamp duty |
| UK SDRT |
| General transaction fee |
| 类型 | 描述 |
|---|---|
| 成交额佣金 |
| 外汇转换费 |
| FINRA交易活动费 |
| 法国金融交易税 |
| 收购委员会征费 |
| 英国印花税 |
| 英国印花税储备税 |
| 一般交易费 |
Historical Dividends
历史分红
GET /api/v0/equity/history/dividendsbash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/dividends?limit=50"GET /api/v0/equity/history/dividendsbash
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"
"$T212_BASE_URL/api/v0/equity/history/dividends?ticker=AAPL_US_EQ&limit=50"
**Response Schema:**
```json
{
"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
}curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/history/dividends?ticker=AAPL_US_EQ&limit=50"
"$T212_BASE_URL/api/v0/equity/history/dividends?ticker=AAPL_US_EQ&limit=50"
**响应结构:**
```json
{
"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
}Dividend Types (Common)
分红类型(常见)
| Type | Description |
|---|---|
| Regular dividend |
| Bonus dividend |
| Interest payment |
| Generic dividend |
| Capital gains distribution |
| Return of capital |
| Property income (REITs) |
| Demerger distribution |
| QIE distribution |
| Trust distribution |
Note: Many additional US tax-specific types exist for 1042-S reporting.
| 类型 | 描述 |
|---|---|
| 常规分红 |
| 红利分红 |
| 利息支付 |
| 通用分红 |
| 资本利得分发 |
| 资本返还 |
| 物业收入(房地产投资信托) |
| 分拆分发 |
| QIE分发 |
| 信托分发 |
注:存在更多美国税务特定类型,用于1042-S报告。
Account Transactions
账户交易记录
GET /api/v0/equity/history/transactionsPagination:
- First request: Must use only the parameter (no cursor, no timestamp)
limit - Subsequent requests: Use the from the previous response, which includes cursor and timestamp automatically
nextPagePath - Time filtering: Transactions cannot be filtered by time - pagination is the only way to navigate through historical data
bash
undefinedGET /api/v0/equity/history/transactions分页规则:
- 首次请求: 必须仅使用参数(无游标,无时间戳)
limit - 后续请求: 使用前一次响应中的,其中会自动包含游标和时间戳
nextPagePath - 时间过滤: 交易记录无法按时间过滤 - 分页是浏览历史数据的唯一方式
bash
undefinedFirst request - use only limit
首次请求 - 仅使用limit参数
curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/history/transactions?limit=50"
"$T212_BASE_URL/api/v0/equity/history/transactions?limit=50"
**Response Schema:**
```json
{
"items": [
{
"type": "DEPOSIT",
"amount": 1000.0,
"currency": "GBP",
"dateTime": "2024-01-10T14:30:00Z",
"reference": "TXN-123456"
}
],
"nextPagePath": null
}curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/history/transactions?limit=50"
"$T212_BASE_URL/api/v0/equity/history/transactions?limit=50"
**响应结构:**
```json
{
"items": [
{
"type": "DEPOSIT",
"amount": 1000.0,
"currency": "GBP",
"dateTime": "2024-01-10T14:30:00Z",
"reference": "TXN-123456"
}
],
"nextPagePath": null
}Transaction Types
交易记录类型
| Type | Description |
|---|---|
| Funds deposited to account |
| Funds withdrawn from account |
| Fee charged |
| Internal transfer |
| 类型 | 描述 |
|---|---|
| 存入资金到账户 |
| 从账户提取资金 |
| 收取费用 |
| 内部转账 |
CSV Reports
CSV报告
Request report: (1 req/30s)
POST /api/v0/equity/history/exportsbash
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:
json
{
"reportId": 12345
}Poll for completion: (1 req/min)
GET /api/v0/equity/history/exportsbash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/exports"Response:
json
[
{
"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:
bash
undefined请求报告: (限制:1次请求/30秒)
POST /api/v0/equity/history/exportsbash
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"
}'响应:
json
{
"reportId": 12345
}轮询完成状态: (限制:1次请求/分钟)
GET /api/v0/equity/history/exportsbash
curl -H "Authorization: $T212_AUTH_HEADER" \
"$T212_BASE_URL/api/v0/equity/history/exports"响应:
json
[
{
"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/..."
}
]下载报告:
bash
undefinedGet 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')
"$T212_BASE_URL/api/v0/equity/history/exports" | jq -r '.[0].downloadLink')
DOWNLOAD_URL=$(curl -s -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/history/exports" | jq -r '.[0].downloadLink')
"$T212_BASE_URL/api/v0/equity/history/exports" | jq -r '.[0].downloadLink')
Download the CSV file
下载CSV文件
curl -o trading212_report.csv "$DOWNLOAD_URL"
undefinedcurl -o trading212_report.csv "$DOWNLOAD_URL"
undefinedReport Status Values
报告状态值
| Status | Description |
|---|---|
| Report request received |
| Report generation started |
| Report actively generating |
| Complete - downloadLink available |
| Report cancelled |
| Generation failed |
| 状态 | 描述 |
|---|---|
| 已收到报告请求 |
| 报告生成已开始 |
| 报告正在生成中 |
| 已完成 - 可获取downloadLink |
| 报告已取消 |
| 生成失败 |
Pre-Order Validation
下单前验证
Before BUY - Check Available Funds
买入前 - 检查可用资金
bash
#!/bin/bashbash
#!/bin/bashValidate funds before placing a buy order
下单买入前验证资金
TICKER="AAPL_US_EQ"
QUANTITY=10
ESTIMATED_PRICE=185.00
ESTIMATED_COST=$(echo "$QUANTITY * $ESTIMATED_PRICE" | bc)
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')
"$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"
undefinedAVAILABLE=$(curl -s -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/account/summary" | jq '.cash.availableToTrade')
"$T212_BASE_URL/api/v0/equity/account/summary" | jq '.cash.availableToTrade')
echo "预估成本: $ESTIMATED_COST"
echo "可用资金: $AVAILABLE"
if (( $(echo "$ESTIMATED_COST > $AVAILABLE" | bc -l) )); then
echo "错误: 资金不足"
exit 1
fi
echo "确认: 资金充足,继续下单"
undefinedBefore SELL - Check Available Shares
卖出前 - 检查可用份额
bash
#!/bin/bashbash
#!/bin/bashValidate position before placing a sell order
下单卖出前验证持仓
TICKER="AAPL_US_EQ"
SELL_QUANTITY=5
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")
"$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"
---POSITION=$(curl -s -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/positions?ticker=$TICKER")
"$T212_BASE_URL/api/v0/equity/positions?ticker=$TICKER")
AVAILABLE_QTY=$(echo "$POSITION" | jq '.[0].quantityAvailableForTrading // 0')
echo "卖出数量: $SELL_QUANTITY"
echo "可卖出数量: $AVAILABLE_QTY"
if (( $(echo "$SELL_QUANTITY > $AVAILABLE_QTY" | bc -l) )); then
echo "错误: 份额不足(部分可能在Pies中)"
exit 1
fi
echo "确认: 份额充足,继续下单"
---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.
速率限制是按账户计算的,不是按API密钥或IP地址。如果你有多个应用使用同一个Trading 212账户,它们共享同一个速率限制池。
Response Headers
响应头
Every API response includes rate limit headers:
| Header | Description |
|---|---|
| Total requests allowed in period |
| Time period in seconds |
| Requests remaining |
| Unix timestamp when limit resets |
| Requests already made |
每个API响应都包含速率限制头:
| 响应头 | 描述 |
|---|---|
| 周期内允许的总请求数 |
| 周期时长(秒) |
| 剩余请求数 |
| 限制重置的Unix时间戳 |
| 已发起的请求数 |
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
undefined不要批量发送请求。 即使某个端点允许每分钟50次请求,一次性发送所有请求也可能触发速率限制并降低性能。均匀间隔你的请求,例如,每1.2秒发起一次调用,确保始终在限制范围内。
错误方式(批量请求):
bash
undefinedDON'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
"$T212_BASE_URL/api/v0/equity/positions?ticker=$ticker" & done wait
**Good approach (paced):**
```bashfor 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
"$T212_BASE_URL/api/v0/equity/positions?ticker=$ticker" & done wait
**正确方式(间隔请求):**
```bashDO 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
"$T212_BASE_URL/api/v0/equity/positions?ticker=$ticker" sleep 1.2 # 1.2 second between requests for 50 req/m limit done
undefinedfor 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 # 对于每分钟50次请求的限制,间隔1.2秒
"$T212_BASE_URL/api/v0/equity/positions?ticker=$ticker" sleep 1.2 # 对于每分钟50次请求的限制,间隔1.2秒
done
undefinedCaching Strategy
缓存策略
For data that doesn't change frequently, cache locally to reduce API calls:
bash
#!/bin/bash对于不经常变化的数据,本地缓存以减少API调用:
bash
#!/bin/bashCache 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_FILE="/tmp/t212_instruments.json"
CACHE_MAX_AGE=3600 # 1小时
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"
"$T212_BASE_URL/api/v0/equity/metadata/instruments" > "$CACHE_FILE"
cat "$CACHE_FILE"
---curl -s -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/metadata/instruments" > "$CACHE_FILE"
"$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 () before buy, positions (
cash.availableToTrade) before sellquantityAvailableForTrading - 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
- 先在模拟环境测试 - 实盘交易前始终验证工作流程
- 下单前验证 - 买入前检查资金(),卖出前检查持仓(
cash.availableToTrade)quantityAvailableForTrading - 确认破坏性操作 - 下单和取消订单是不可逆的
- API不是幂等的 - 重复请求可能会创建重复订单
- 永远不要记录凭证 - 使用环境变量
- 遵守速率限制 - 均匀间隔请求,不要批量发送
- 最多50个挂单 - 每个代码,每个账户
- 缓存元数据 - 交易工具和交易所信息很少变化