trading212-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Trading 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

环境

EnvironmentBase URLPurpose
Demo
https://demo.trading212.com/api/v0
Paper trading - test without real funds
Live
https://live.trading212.com/api/v0
Real money trading
环境基础URL用途
模拟(Demo)
https://demo.trading212.com/api/v0
模拟交易 - 无真实资金测试
实盘(Live)
https://live.trading212.com/api/v0
真实资金交易

Order Quantity Convention

订单数量规则

  • Positive quantity = BUY (e.g.,
    10
    buys 10 shares)
  • Negative quantity = SELL (e.g.,
    -10
    sells 10 shares)
  • 正数 = 买入(例如:
    10
    表示买入10股)
  • 负数 = 卖出(例如:
    -10
    表示卖出10股)

Account Types

账户类型

Only Invest and Stocks ISA accounts are supported.
仅支持InvestStocks 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.
T212_API_KEY
+
T212_API_SECRET
, or
T212_API_KEY_INVEST
+
T212_API_SECRET_INVEST
, or
T212_API_KEY_STOCKS_ISA
+
T212_API_SECRET_STOCKS_ISA
). You do not need all four account-specific vars; having only the Invest pair or only the Stocks ISA pair is enough. Check for any combination that gives at least one usable key+secret pair.
bash
undefined
在引导用户完成认证配置前,先检查是否已配置凭证:
语义规则: 当存在至少一套完整的凭证组时,即视为已配置:一套完整凭证组指同一账户的key+secret(例如
T212_API_KEY
+
T212_API_SECRET
,或
T212_API_KEY_INVEST
+
T212_API_SECRET_INVEST
,或
T212_API_KEY_STOCKS_ISA
+
T212_API_SECRET_STOCKS_ISA
)。无需配置所有四组账户特定变量;仅配置Invest组或仅配置Stocks ISA组即可。检查是否存在任意一组可用的key+secret对。
bash
undefined

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.
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 InWorks WithDoes 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:
  1. You're using the correct API key for the target environment
  2. The API key was generated in the same environment (LIVE or DEMO) you're trying to access
API密钥与特定环境绑定,无法跨环境使用。
API密钥创建环境可用于不可用于
实盘(LIVE)账户
live.trading212.com
demo.trading212.com
模拟(DEMO)账户
demo.trading212.com
live.trading212.com
如果收到401错误,请验证:
  1. 你正在为目标环境使用正确的API密钥
  2. API密钥是在你尝试访问的同一环境(实盘或模拟)中生成的

Get Credentials

获取凭证

  1. Decide which environment to use - LIVE (real money) or DEMO (paper trading)
  2. Open Trading 212 app (mobile or web)
  3. Switch to the correct account - Make sure you're in LIVE or DEMO mode matching your target environment
  4. Navigate to Settings > API
  5. Generate a new API key pair - you'll receive:
    • API Key (ID) (e.g.,
      35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF
      )
    • API Secret (e.g.,
      7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo
      )
  6. Store the credentials separately for each environment if you use both
  1. 确定要使用的环境 - 实盘(真实资金)或模拟(纸盘交易)
  2. 打开Trading 212应用(移动端或网页端)
  3. 切换到正确的账户 - 确保你处于与目标环境匹配的实盘或模拟模式
  4. 导航到设置 > API
  5. 生成新的API密钥对 - 你将收到:
    • API Key(ID)(例如:
      35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF
    • API Secret(例如:
      7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo
  6. 分别存储各环境的凭证(如果同时使用两个环境)

Building the Auth Header

构建认证请求头

Combine your API Key (ID) and Secret with a colon, base64 encode, and prefix with
Basic 
for the Authorization header.
Optional: To precompute the header from key/secret, you can set:
bash
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):
bash
undefined
将API Key(ID)和Secret用冒号连接,进行base64编码,然后在前面添加
Basic 
作为Authorization请求头。
可选操作: 要提前从key/secret计算请求头,可以设置:
bash
export T212_AUTH_HEADER="Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)"
否则,Agent会在发起请求时从
T212_API_KEY
T212_API_SECRET
构建请求头。
手动构建(占位符):
bash
undefined

Format: 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)"
undefined
export T212_AUTH_HEADER="Basic $(echo -n "35839398ZFVKUxpHzPiVsxKdOtZdaDJSrvyPF:7MOzYJlVJgxoPjdZJCEH3fO9ee7A0NzLylFFD4-3tlo" | base64)"
undefined

Making 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
    T212_AUTH_HEADER
    and
    T212_BASE_URL
    are set:
    use them in requests.
  • Else if
    T212_API_KEY
    and
    T212_API_SECRET
    are set:
    use this pair (single account). Build header as
    Basic $(echo -n "$T212_API_KEY:$T212_API_SECRET" | base64)
    and base URL as
    https://${T212_ENV:-live}.trading212.com
    . Do not guide the user to derive or merge; you do it.
  • Else if both account-specific pairs are set (
    T212_API_KEY_INVEST
    /
    T212_API_SECRET_INVEST
    and
    T212_API_KEY_STOCKS_ISA
    /
    T212_API_SECRET_STOCKS_ISA
    ): the user must clearly specify which account to target (Invest or Stocks ISA), unless they ask for information for all accounts. Use the Invest pair when the user refers to Invest, and the Stocks ISA pair when the user refers to ISA/Stocks ISA. If the user wants information for all accounts, make multiple API calls—one per account (Invest and Stocks ISA)—and present or aggregate the results for both. If it is not clear from context which account to use (and they did not ask for all accounts), ask for confirmation before making API calls (e.g. "Which account should I use — Invest or Stocks ISA?"). Do not assume. Build the header from the chosen key/secret and base URL as
    https://${T212_ENV:-live}.trading212.com
    .
  • Else if only the Invest pair is set (
    T212_API_KEY_INVEST
    and
    T212_API_SECRET_INVEST
    ): use this pair for requests; if the user asks about Stocks ISA, only the Invest account is configured.
  • Else if only the Stocks ISA pair is set (
    T212_API_KEY_STOCKS_ISA
    and
    T212_API_SECRET_STOCKS_ISA
    ): use this pair for requests; if the user asks about Invest, only the Stocks ISA account is configured.
Use the
T212_AUTH_HEADER
value in the Authorization header when it is set:
bash
undefined
发起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
    ):用户必须明确指定目标账户(Invest或Stocks ISA),除非他们要求获取所有账户的信息。当用户提到Invest时使用Invest组,提到ISA/Stocks ISA时使用Stocks ISA组。如果用户需要所有账户的信息,发起多个API调用——每个账户一个(Invest和Stocks ISA)——并展示或汇总两个账户的结果。 如果上下文无法明确要使用哪个账户(且用户未要求所有账户),在发起API调用前请确认(例如:“我应该使用哪个账户——Invest还是Stocks ISA?”)。不要假设。从选定的key/secret构建请求头,基础URL为
    https://${T212_ENV:-live}.trading212.com
  • 否则,如果仅设置了Invest组凭证
    T212_API_KEY_INVEST
    T212_API_SECRET_INVEST
    ):使用这组凭证发起请求;如果用户询问Stocks ISA,说明仅配置了Invest账户。
  • 否则,如果仅设置了Stocks ISA组凭证
    T212_API_KEY_STOCKS_ISA
    T212_API_SECRET_STOCKS_ISA
    ):使用这组凭证发起请求;如果用户询问Invest,说明仅配置了Stocks ISA账户。
T212_AUTH_HEADER
已设置时,在Authorization请求头中使用该值:
bash
undefined

When 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"

When only primary vars are set, use the inline form in the curl:

```bash
curl -H "Authorization: $T212_AUTH_HEADER"
"${T212_BASE_URL}/api/v0/equity/account/summary"

当仅设置了主变量时,在curl中使用内联形式:

```bash

When 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"

> **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"

> **警告:** `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 (
T212_API_KEY
+
T212_API_SECRET
) = one account (Invest or Stocks ISA). To use all accounts (Invest and Stocks ISA), the user must set two sets of key/secret:
T212_API_KEY_INVEST
/
T212_API_SECRET_INVEST
and
T212_API_KEY_STOCKS_ISA
/
T212_API_SECRET_STOCKS_ISA
. When both pairs are set, the user must clearly specify which account to target; if it is not clear from context, ask for confirmation (Invest or Stocks ISA) before making API calls.
Primary (single account): Set these for consistent setup with the plugin README:
bash
export T212_API_KEY="your-api-key"       # API Key (ID) from Trading 212
export T212_API_SECRET="your-api-secret"
export T212_ENV="demo"                   # or "live" (defaults to "live" if unset)
Account-specific (Invest and/or Stocks ISA): Set only the pair(s) you use. One complete set (key + secret for the same account) is enough. For example, only Invest:
bash
export T212_API_KEY_INVEST="your-invest-api-key"
export T212_API_SECRET_INVEST="your-invest-api-secret"
export T212_ENV="demo"                   # or "live"
For both accounts, set both pairs:
bash
export T212_API_KEY_INVEST="your-invest-api-key"
export T212_API_SECRET_INVEST="your-invest-api-secret"
export T212_API_KEY_STOCKS_ISA="your-stocks-isa-api-key"
export T212_API_SECRET_STOCKS_ISA="your-stocks-isa-api-secret"
export T212_ENV="demo"                   # or "live" (applies to both)
Optional – precomputed (for scripts or if the user prefers): The user can set the auth header and base URL from the primary vars, but they do not need to; when making API calls you (the agent) must build the header and base URL from primary vars if these are not set.
bash
undefined
单个账户 vs 所有账户: API密钥对应单个账户。一组key/secret对(
T212_API_KEY
+
T212_API_SECRET
)= 一个账户(Invest或Stocks ISA)。要使用所有账户(Invest和Stocks ISA),用户必须设置两组key/secret:
T212_API_KEY_INVEST
/
T212_API_SECRET_INVEST
T212_API_KEY_STOCKS_ISA
/
T212_API_SECRET_STOCKS_ISA
。当两组凭证都已设置时,用户必须明确指定目标账户;如果上下文无法明确,在发起API调用前请确认(Invest或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
undefined

Build 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.

```bash
export 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密钥仅能与匹配的环境一起使用。

```bash

For 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

**提示:** 如果同时使用两个环境,使用不同的变量名:

```bash

Demo 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)"
undefined
export T212_LIVE_AUTH_HEADER="Basic $(echo -n "<LIVE_KEY_ID>:<LIVE_SECRET>" | base64)"
undefined

Common Auth Errors

常见认证错误

CodeCauseSolution
401Invalid credentialsCheck API key/secret, ensure no extra whitespace
401Environment mismatchLIVE API keys don't work with DEMO and vice versa - verify key matches target environment
403Missing permissionsCheck API permissions in Trading 212 settings
408Request timed outRetry the request
429Rate limit exceededWait for
x-ratelimit-reset
timestamp

错误码原因解决方案
401凭证无效检查API key/secret,确保没有多余空格
401环境不匹配实盘API密钥无法用于模拟环境,反之亦然 - 验证密钥与目标环境匹配
403缺少权限在Trading 212设置中检查API权限
408请求超时重试请求
429超出速率限制等待
x-ratelimit-reset
时间戳

Account

账户

Get Account Summary

获取账户摘要

GET /api/v0/equity/account/summary
(1 req/5s)
bash
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/summary
(限制:1次请求/5秒)
bash
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

账户字段

FieldTypeDescription
id
integerPrimary trading account number
currency
stringPrimary account currency (ISO 4217)
totalValue
numberTotal account value in primary currency
cash.availableToTrade
numberFunds available for investing
cash.reservedForOrders
numberCash reserved for pending orders
cash.inPies
numberUninvested cash inside pies
investments.currentValue
numberCurrent value of all investments
investments.totalCost
numberCost basis of current investments
investments.realizedProfitLoss
numberAll-time realized P&L
investments.unrealizedProfitLoss
numberPotential P&L if sold now

字段类型描述
id
integer主交易账户编号
currency
string账户主货币(ISO 4217标准)
totalValue
number账户总价值(以主货币计)
cash.availableToTrade
number可用于投资的资金
cash.reservedForOrders
number为挂单预留的现金
cash.inPies
numberPies中的未投资现金
investments.currentValue
number所有投资的当前价值
investments.totalCost
number当前投资的成本基准
investments.realizedProfitLoss
number历史已实现盈亏
investments.unrealizedProfitLoss
number若当前卖出的潜在盈亏

Orders

订单

Order Types

订单类型

TypeEndpointAvailabilityDescription
Market
/api/v0/equity/orders/market
Demo + LiveExecute immediately at best price
Limit
/api/v0/equity/orders/limit
Demo + LiveExecute at limit price or better
Stop
/api/v0/equity/orders/stop
Demo + LiveMarket order when stop price reached
StopLimit
/api/v0/equity/orders/stop_limit
Demo + LiveLimit order when stop price reached
类型端点可用环境描述
市价单(Market)
/api/v0/equity/orders/market
模拟+实盘以最优价格立即执行
限价单(Limit)
/api/v0/equity/orders/limit
模拟+实盘以限价或更优价格执行
止损单(Stop)
/api/v0/equity/orders/stop
模拟+实盘当达到止损价格时触发市价单
止损限价单(StopLimit)
/api/v0/equity/orders/stop_limit
模拟+实盘当达到止损价格时触发限价单

Order Statuses

订单状态

StatusDescription
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
PARTIALLY_FILLED
Some shares executed
FILLED
Completely executed
REJECTED
Rejected by exchange
REPLACING
Modification in progress
REPLACED
Successfully modified
状态描述
LOCAL
本地创建的订单,尚未发送到交易所
UNCONFIRMED
已发送到交易所,等待确认
CONFIRMED
已被交易所确认
NEW
活跃状态,等待执行
CANCELLING
取消请求处理中
CANCELLED
已成功取消
PARTIALLY_FILLED
部分份额已执行
FILLED
全部份额已执行
REJECTED
被交易所拒绝
REPLACING
修改请求处理中
REPLACED
已成功修改

Time Validity

时间有效性

ValueDescription
DAY
Expires at midnight in exchange timezone
GOOD_TILL_CANCEL
Active until filled or cancelled (default)
描述
DAY
在交易所时区的午夜到期
GOOD_TILL_CANCEL
保持活跃直到成交或被取消(默认值)

Order Strategy

订单策略

ValueDescription
QUANTITY
Order by number of shares (API supported)
VALUE
Order by monetary value (not supported via API)
描述
QUANTITY
按份额数下单(API支持)
VALUE
按金额下单(API不支持)

Initiated From

发起来源

ValueDescription
API
Placed via this API
IOS
iOS app
ANDROID
Android app
WEB
Web platform
SYSTEM
System-generated
AUTOINVEST
Autoinvest feature
描述
API
通过本API下单
IOS
iOS应用
ANDROID
Android应用
WEB
网页平台
SYSTEM
系统生成
AUTOINVEST
自动投资功能

Place Market Order

下市价单

POST /api/v0/equity/orders/market
(50 req/min)
bash
undefined
POST /api/v0/equity/orders/market
(限制:50次请求/分钟)
bash
undefined

Buy 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}'
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)

卖出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": -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:**

```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}'

**请求字段:**

| 字段 | 类型 | 是否必填 | 描述 |
| --------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| `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/limit
(1 req/2s)
bash
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:
FieldTypeRequiredDescription
ticker
stringYesInstrument ticker
quantity
numberYesPositive for buy, negative for sell
limitPrice
numberYesMaximum price for buy, minimum for sell
timeValidity
stringNo
DAY
(default) or
GOOD_TILL_CANCEL
POST /api/v0/equity/orders/limit
(限制:1次请求/2秒)
bash
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
string交易工具代码
quantity
number正数表示买入,负数表示卖出
limitPrice
number买入的最高价格,卖出的最低价格
timeValidity
string
DAY
(默认值)或
GOOD_TILL_CANCEL

Place Stop Order

下止损单

POST /api/v0/equity/orders/stop
(1 req/2s)
bash
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:
FieldTypeRequiredDescription
ticker
stringYesInstrument ticker
quantity
numberYesPositive for buy, negative for sell
stopPrice
numberYesTrigger price (based on Last Traded Price)
timeValidity
stringNo
DAY
(default) or
GOOD_TILL_CANCEL
POST /api/v0/equity/orders/stop
(限制:1次请求/2秒)
bash
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
string交易工具代码
quantity
number正数表示买入,负数表示卖出
stopPrice
number触发价格(基于最新成交价)
timeValidity
string
DAY
(默认值)或
GOOD_TILL_CANCEL

Place Stop-Limit Order

下止损限价单

POST /api/v0/equity/orders/stop_limit
(1 req/2s)
bash
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:
FieldTypeRequiredDescription
ticker
stringYesInstrument ticker
quantity
numberYesPositive for buy, negative for sell
stopPrice
numberYesTrigger price to activate limit order
limitPrice
numberYesLimit price for the resulting order
timeValidity
stringNo
DAY
(default) or
GOOD_TILL_CANCEL
POST /api/v0/equity/orders/stop_limit
(限制:1次请求/2秒)
bash
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
string交易工具代码
quantity
number正数表示买入,负数表示卖出
stopPrice
number触发限价单的价格
limitPrice
number最终订单的限价
timeValidity
string
DAY
(默认值)或
GOOD_TILL_CANCEL

Get Pending Orders

获取挂单

GET /api/v0/equity/orders
(1 req/5s)
bash
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
(限制:1次请求/5秒)
bash
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}
(1 req/1s)
bash
curl -H "Authorization: $T212_AUTH_HEADER" \
  "$T212_BASE_URL/api/v0/equity/orders/123456789"
GET /api/v0/equity/orders/{id}
(限制:1次请求/1秒)
bash
curl -H "Authorization: $T212_AUTH_HEADER" \
  "$T212_BASE_URL/api/v0/equity/orders/123456789"

Cancel Order

取消订单

DELETE /api/v0/equity/orders/{id}
(50 req/min)
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}
(限制:50次请求/分钟)
bash
curl -X DELETE -H "Authorization: $T212_AUTH_HEADER" \
  "$T212_BASE_URL/api/v0/equity/orders/123456789"
如果取消请求被接受,返回200 OK。订单可能已经成交。

Common Order Errors

常见订单错误

ErrorCauseSolution
InsufficientFreeForStocksBuy
Not enough cashCheck
cash.availableToTrade
SellingEquityNotOwned
Selling more than ownedCheck
quantityAvailableForTrading
MarketClosed
Outside trading hoursCheck exchange schedule

错误原因解决方案
InsufficientFreeForStocksBuy
资金不足检查
cash.availableToTrade
SellingEquityNotOwned
卖出份额超过持仓检查
quantityAvailableForTrading
MarketClosed
非交易时间检查交易所时间表

Positions

持仓

Get All Positions

获取所有持仓

GET /api/v0/equity/positions
(1 req/1s)
Query Parameters:
ParameterTypeRequiredDescription
ticker
stringNoFilter by specific ticker (e.g.,
AAPL_US_EQ
)
bash
undefined
GET /api/v0/equity/positions
(限制:1次请求/1秒)
查询参数:
参数类型是否必填描述
ticker
string按特定代码过滤(例如:
AAPL_US_EQ
bash
undefined

All positions

所有持仓

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"

Filter by ticker

按代码过滤

curl -H "Authorization: $T212_AUTH_HEADER"
"$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"

**响应结构:**

```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

持仓字段

FieldTypeDescription
quantity
numberTotal shares owned
quantityAvailableForTrading
numberShares available to sell
quantityInPies
numberShares allocated to pies
currentPrice
numberCurrent price (instrument currency)
averagePricePaid
numberAverage cost per share
createdAt
datetimePosition open date
walletImpact.currency
stringAccount currency
walletImpact.totalCost
numberTotal cost in account currency
walletImpact.currentValue
numberCurrent value in account currency
walletImpact.unrealizedProfitLoss
numberP&L in account currency
walletImpact.fxImpact
numberCurrency rate impact on value
字段类型描述
quantity
number持有的总份额
quantityAvailableForTrading
number可卖出的份额
quantityInPies
number分配到Pies中的份额
currentPrice
number当前价格(交易工具货币)
averagePricePaid
number每股平均成本
createdAt
datetime持仓开立日期
walletImpact.currency
string账户货币
walletImpact.totalCost
number总成本(账户货币)
walletImpact.currentValue
number当前价值(账户货币)
walletImpact.unrealizedProfitLoss
number盈亏(账户货币)
walletImpact.fxImpact
number汇率对价值的影响

Position Quantity Scenarios

持仓份额场景

ScenarioquantityquantityAvailableForTradingquantityInPies
All direct holdings10100
Some in pie1073
All in pie10010
Important: Always check
quantityAvailableForTrading
before placing sell orders.

场景quantityquantityAvailableForTradingquantityInPies
全部为直接持仓10100
部分在Pies中1073
全部在Pies中10010
重要提示: 在下单卖出前,务必检查
quantityAvailableForTrading

Instruments

交易工具

Ticker Lookup Workflow

代码查找流程

When users reference instruments by common names (e.g., "SAP", "Apple", "AAPL"), you must look up the exact Trading 212 ticker before making any order, position, or historical data queries. Never construct ticker formats manually.
CACHE FIRST: Always check
/tmp/t212_instruments.json
before calling the API. The instruments endpoint has a 50-second rate limit and returns ~5MB. Only call the API if cache is missing or older than 1 hour.
Generic search: Match the user's search term in the three meaningful fields: ticker, name, or shortName. Use one variable (e.g.
SEARCH_TERM
) with
test($q; "i")
on each field so "TSLA", "Tesla", "TL0", etc. match efficiently. For regional filtering (e.g. "US stocks", "European SAP"), use the ISIN prefix (first 2 characters) for country code or
currencyCode
after the grep.
IMPORTANT: Never auto-select instruments. If multiple options exist, you are required to ask the user for their preference.
bash
undefined
当用户通过通用名称引用交易工具时(例如:"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"),使用ISIN前缀(前2个字符作为国家代码)或在grep后使用
currencyCode
重要提示: 永远不要自动选择交易工具。如果存在多个选项,你必须询问用户的偏好。
bash
undefined

SEARCH_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
undefined
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

搜索代码、名称或短名字段

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
undefined

Get All Instruments

获取所有交易工具

GET /api/v0/equity/metadata/instruments
(1 req/50s)
bash
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/instruments
(限制:1次请求/50秒)
bash
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

交易工具字段

FieldTypeDescription
ticker
stringUnique instrument identifier
name
stringFull instrument name
shortName
stringShort symbol (e.g., AAPL)
isin
stringInternational Securities ID
currencyCode
stringTrading currency (ISO 4217)
type
stringInstrument type (see below)
maxOpenQuantity
numberMaximum position size allowed
extendedHours
booleanWhether extended hours trading is available
workingScheduleId
integerReference to exchange schedule
addedOn
datetimeWhen added to platform
字段类型描述
ticker
string交易工具唯一标识符
name
string交易工具全名
shortName
string短代码(例如:AAPL)
isin
string国际证券识别码
currencyCode
string交易货币(ISO 4217标准)
type
string交易工具类型(见下文)
maxOpenQuantity
number允许的最大持仓量
extendedHours
boolean是否支持盘前盘后交易
workingScheduleId
integer交易所时间表引用ID
addedOn
datetime上线平台的时间

Instrument Types

交易工具类型

TypeDescription
STOCK
Common stock
ETF
Exchange-traded fund
CRYPTOCURRENCY
Cryptocurrency
CRYPTO
Crypto asset
FOREX
Foreign exchange
FUTURES
Futures contract
INDEX
Index
WARRANT
Warrant
CVR
Contingent value right
CORPACT
Corporate action
类型描述
STOCK
普通股
ETF
交易所交易基金
CRYPTOCURRENCY
加密货币
CRYPTO
加密资产
FOREX
外汇
FUTURES
期货合约
INDEX
指数
WARRANT
权证
CVR
或有价值权利
CORPACT
公司行动

Ticker Format

代码格式

{SYMBOL}_{EXCHANGE}_{TYPE}
- Examples:
  • AAPL_US_EQ
    - Apple on US exchange
  • VUSA_LSE_EQ
    - Vanguard S&P 500 on London
  • BTC_CRYPTO
    - Bitcoin
{SYMBOL}_{EXCHANGE}_{TYPE}
- 示例:
  • AAPL_US_EQ
    - 苹果公司(美国交易所)
  • VUSA_LSE_EQ
    - 标普500先锋基金(伦敦交易所)
  • BTC_CRYPTO
    - 比特币

Get Exchange Metadata

获取交易所元数据

GET /api/v0/equity/metadata/exchanges
(1 req/30s)
bash
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/exchanges
(限制:1次请求/30秒)
bash
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

时间事件类型

TypeDescription
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
AFTER_HOURS_CLOSE
After-hours session ends
OVERNIGHT_OPEN
Overnight session starts

类型描述
PRE_MARKET_OPEN
盘前时段开始
OPEN
常规交易开始
BREAK_START
交易休市开始
BREAK_END
交易休市结束
CLOSE
常规交易结束
AFTER_HOURS_OPEN
盘后时段开始
AFTER_HOURS_CLOSE
盘后时段结束
OVERNIGHT_OPEN
隔夜时段开始

Historical Data

历史数据

All historical endpoints use cursor-based pagination with
nextPagePath
.
所有历史端点使用基于游标(cursor)的分页,带有
nextPagePath

Pagination Parameters

分页参数

ParameterTypeDefaultMaxDescription
limit
integer2050Items per page
cursor
string/number--Pagination cursor (used in
nextPagePath
)
ticker
string--Filter by ticker (orders, dividends)
time
datetime--Pagination time (used in
nextPagePath
for transactions)
参数类型默认值最大值描述
limit
integer2050每页条目数
cursor
string/number--分页游标(在
nextPagePath
中使用)
ticker
string--按代码过滤(订单、分红)
time
datetime--分页时间(在
nextPagePath
中用于交易记录)

Pagination Example

分页示例

bash
#!/bin/bash
bash
#!/bin/bash

Fetch all historical orders with pagination

分页获取所有历史订单

NEXT_PATH="/api/v0/equity/history/orders?limit=50"
while [ -n "$NEXT_PATH" ]; do echo "Fetching: $NEXT_PATH"
RESPONSE=$(curl -s -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL$NEXT_PATH")

Process items (e.g., save to file)

echo "$RESPONSE" | jq '.items[]' >> orders.json

Get next page path (null if no more pages)

NEXT_PATH=$(echo "$RESPONSE" | jq -r '.nextPagePath // empty')

Wait 1 second between requests (50 req/min limit)

if [ -n "$NEXT_PATH" ]; then sleep 1 fi done
echo "Done fetching all orders"
undefined
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 "已获取所有订单"
undefined

Historical Orders

历史订单

GET /api/v0/equity/history/orders
(50 req/min)
bash
curl -H "Authorization: $T212_AUTH_HEADER" \
  "$T212_BASE_URL/api/v0/equity/history/orders?limit=50"
GET /api/v0/equity/history/orders
(限制:50次请求/分钟)
bash
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:**

```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"

**响应结构:**

```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

成交类型

TypeDescription
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
EQUITY_RIGHTS
Equity rights issue
类型描述
TRADE
常规交易执行
STOCK_SPLIT
股票拆分调整
STOCK_DISTRIBUTION
股票分发
FOP
免费转账
FOP_CORRECTION
FOP修正
CUSTOM_STOCK_DISTRIBUTION
自定义股票分发
EQUITY_RIGHTS
股权发行

Trading Methods

交易方式

MethodDescription
TOTV
Traded on trading venue
OTC
Over-the-counter
方式描述
TOTV
在交易场所交易
OTC
场外交易

Tax Types (walletImpact.taxes)

税费类型(walletImpact.taxes)

TypeDescription
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
STAMP_DUTY_RESERVE_TAX
UK SDRT
TRANSACTION_FEE
General transaction fee
类型描述
COMMISSION_TURNOVER
成交额佣金
CURRENCY_CONVERSION_FEE
外汇转换费
FINRA_FEE
FINRA交易活动费
FRENCH_TRANSACTION_TAX
法国金融交易税
PTM_LEVY
收购委员会征费
STAMP_DUTY
英国印花税
STAMP_DUTY_RESERVE_TAX
英国印花税储备税
TRANSACTION_FEE
一般交易费

Historical Dividends

历史分红

GET /api/v0/equity/history/dividends
(50 req/min)
bash
curl -H "Authorization: $T212_AUTH_HEADER" \
  "$T212_BASE_URL/api/v0/equity/history/dividends?limit=50"
GET /api/v0/equity/history/dividends
(限制:50次请求/分钟)
bash
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:**

```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"

**响应结构:**

```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)

分红类型(常见)

TypeDescription
ORDINARY
Regular dividend
BONUS
Bonus dividend
INTEREST
Interest payment
DIVIDEND
Generic dividend
CAPITAL_GAINS
Capital gains distribution
RETURN_OF_CAPITAL
Return of capital
PROPERTY_INCOME
Property income (REITs)
DEMERGER
Demerger distribution
QUALIFIED_INVESTMENT_ENTITY
QIE distribution
TRUST_DISTRIBUTION
Trust distribution
Note: Many additional US tax-specific types exist for 1042-S reporting.
类型描述
ORDINARY
常规分红
BONUS
红利分红
INTEREST
利息支付
DIVIDEND
通用分红
CAPITAL_GAINS
资本利得分发
RETURN_OF_CAPITAL
资本返还
PROPERTY_INCOME
物业收入(房地产投资信托)
DEMERGER
分拆分发
QUALIFIED_INVESTMENT_ENTITY
QIE分发
TRUST_DISTRIBUTION
信托分发
注:存在更多美国税务特定类型,用于1042-S报告。

Account Transactions

账户交易记录

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
bash
undefined
GET /api/v0/equity/history/transactions
(限制:50次请求/分钟)
分页规则:
  • 首次请求: 必须仅使用
    limit
    参数(无游标,无时间戳)
  • 后续请求: 使用前一次响应中的
    nextPagePath
    ,其中会自动包含游标和时间戳
  • 时间过滤: 交易记录无法按时间过滤 - 分页是浏览历史数据的唯一方式
bash
undefined

First request - use only limit

首次请求 - 仅使用limit参数

curl -H "Authorization: $T212_AUTH_HEADER"
"$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"

**响应结构:**

```json
{
  "items": [
    {
      "type": "DEPOSIT",
      "amount": 1000.0,
      "currency": "GBP",
      "dateTime": "2024-01-10T14:30:00Z",
      "reference": "TXN-123456"
    }
  ],
  "nextPagePath": null
}

Transaction Types

交易记录类型

TypeDescription
DEPOSIT
Funds deposited to account
WITHDRAW
Funds withdrawn from account
FEE
Fee charged
TRANSFER
Internal transfer
类型描述
DEPOSIT
存入资金到账户
WITHDRAW
从账户提取资金
FEE
收取费用
TRANSFER
内部转账

CSV Reports

CSV报告

Request report:
POST /api/v0/equity/history/exports
(1 req/30s)
bash
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:
GET /api/v0/equity/history/exports
(1 req/min)
bash
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
请求报告:
POST /api/v0/equity/history/exports
(限制:1次请求/30秒)
bash
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
}
轮询完成状态:
GET /api/v0/equity/history/exports
(限制:1次请求/分钟)
bash
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
undefined

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_URL=$(curl -s -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/history/exports" | jq -r '.[0].downloadLink')

Download the CSV file

下载CSV文件

curl -o trading212_report.csv "$DOWNLOAD_URL"
undefined
curl -o trading212_report.csv "$DOWNLOAD_URL"
undefined

Report Status Values

报告状态值

StatusDescription
Queued
Report request received
Processing
Report generation started
Running
Report actively generating
Finished
Complete - downloadLink available
Canceled
Report cancelled
Failed
Generation failed

状态描述
Queued
已收到报告请求
Processing
报告生成已开始
Running
报告正在生成中
Finished
已完成 - 可获取downloadLink
Canceled
报告已取消
Failed
生成失败

Pre-Order Validation

下单前验证

Before BUY - Check Available Funds

买入前 - 检查可用资金

bash
#!/bin/bash
bash
#!/bin/bash

Validate funds before placing a buy order

下单买入前验证资金

TICKER="AAPL_US_EQ" QUANTITY=10 ESTIMATED_PRICE=185.00 ESTIMATED_COST=$(echo "$QUANTITY * $ESTIMATED_PRICE" | bc)
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"
undefined
AVAILABLE=$(curl -s -H "Authorization: $T212_AUTH_HEADER"
"$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 "确认: 资金充足,继续下单"
undefined

Before SELL - Check Available Shares

卖出前 - 检查可用份额

bash
#!/bin/bash
bash
#!/bin/bash

Validate 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")
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")
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:
HeaderDescription
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
每个API响应都包含速率限制头:
响应头描述
x-ratelimit-limit
周期内允许的总请求数
x-ratelimit-period
周期时长(秒)
x-ratelimit-remaining
剩余请求数
x-ratelimit-reset
限制重置的Unix时间戳
x-ratelimit-used
已发起的请求数

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
undefined

DON'T DO THIS - sends all requests at once

不要这样做 - 一次性发送所有请求

for ticker in AAPL_US_EQ MSFT_US_EQ GOOGL_US_EQ; do curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/positions?ticker=$ticker" & done wait

**Good approach (paced):**

```bash
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

**正确方式(间隔请求):**

```bash

DO THIS - space requests evenly

这样做 - 均匀间隔请求

for ticker in AAPL_US_EQ MSFT_US_EQ GOOGL_US_EQ; do curl -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/positions?ticker=$ticker" sleep 1.2 # 1.2 second between requests for 50 req/m limit done
undefined
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 # 对于每分钟50次请求的限制,间隔1.2秒
done
undefined

Caching Strategy

缓存策略

For data that doesn't change frequently, cache locally to reduce API calls:
bash
#!/bin/bash
对于不经常变化的数据,本地缓存以减少API调用:
bash
#!/bin/bash

Cache instruments list (changes rarely)

缓存交易工具列表(很少变化)

CACHE_FILE="/tmp/t212_instruments.json" CACHE_MAX_AGE=3600 # 1 hour
if [ -f "$CACHE_FILE" ]; then CACHE_AGE=$(($(date +%s) - $(stat -f %m "$CACHE_FILE"))) if [ "$CACHE_AGE" -lt "$CACHE_MAX_AGE" ]; then cat "$CACHE_FILE" exit 0 fi fi
CACHE_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"
cat "$CACHE_FILE"

---
curl -s -H "Authorization: $T212_AUTH_HEADER"
"$T212_BASE_URL/api/v0/equity/metadata/instruments" > "$CACHE_FILE"
cat "$CACHE_FILE"

---

Safety Guidelines

安全指南

  1. Test in demo first - Always validate workflows before live trading
  2. Validate before ordering - Check funds (
    cash.availableToTrade
    ) before buy, positions (
    quantityAvailableForTrading
    ) before sell
  3. Confirm destructive actions - Order placement and cancellation are irreversible
  4. API is not idempotent - Duplicate requests may create duplicate orders
  5. Never log credentials - Use environment variables
  6. Respect rate limits - Space requests evenly, never burst
  7. Max 50 pending orders - Per ticker, per account
  8. Cache metadata - Instruments and exchanges change rarely
  1. 先在模拟环境测试 - 实盘交易前始终验证工作流程
  2. 下单前验证 - 买入前检查资金(
    cash.availableToTrade
    ),卖出前检查持仓(
    quantityAvailableForTrading
  3. 确认破坏性操作 - 下单和取消订单是不可逆的
  4. API不是幂等的 - 重复请求可能会创建重复订单
  5. 永远不要记录凭证 - 使用环境变量
  6. 遵守速率限制 - 均匀间隔请求,不要批量发送
  7. 最多50个挂单 - 每个代码,每个账户
  8. 缓存元数据 - 交易工具和交易所信息很少变化