### Quickstart: Get Account Cash Balance Source: https://t212public-api-docs.redoc.ly/index A quickstart guide to retrieve your account's cash balance using cURL. It demonstrates how to generate and use the Authorization header with your API Key and API Secret. ```APIDOC ## Quickstart: Get Account Cash Balance ### Method GET ### Endpoint `/equity/account/cash` ### Description Retrieves the cash balance of your Trading 212 account. ### Request Example ```bash # Step 1: Replace with your actual credentials and Base64-encode them. CREDENTIALS=$(echo -n ":" | base64) # Step 2: Make the API call to the live environment using the encoded credentials. curl -X GET "https://live.trading212.com/api/v0/equity/account/cash" \ -H "Authorization: Basic $CREDENTIALS" ``` ### Response #### Success Response (200) - **cash_balance** (float) - The current cash balance of the account. #### Response Example ```json { "cash_balance": 15000.50 } ``` ``` -------------------------------- ### Place a Market Order - Go Example Source: https://t212public-api-docs.redoc.ly/index Go code snippet for placing a market order. This example demonstrates creating an HTTP client, constructing the POST request with headers and JSON body for immediate trade execution. ```go package main import ( "bytes" "fmt" "io/ioutil" "net/http" ) func main() { url := "https://api.example.com/api/v0/equity/orders/market" apiKey := "YOUR_API_KEY" jsonData := []byte(`{ "extendedHours": true, "quantity": 0.1, "ticker": "AAPL_US_EQ" }`) // Use backticks for multi-line raw string literal client := &http.Client{} req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Error creating request: %s\n", err) return } req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") res, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %s\n", err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Printf("Error reading response body: %s\n", err) return } fmt.Printf("Market order placed: %s\n", string(body)) } ``` -------------------------------- ### Place a Market Order - Java Example Source: https://t212public-api-docs.redoc.ly/index Java code snippet for placing a market order using Apache HttpClient. This example shows how to set up the HTTP POST request, including headers and the JSON payload, for immediate trade execution. ```java import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class MarketOrder { public static void main(String[] args) { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost request = new HttpPost("https://api.example.com/api/v0/equity/orders/market"); request.setHeader("Authorization", "Bearer YOUR_API_KEY"); request.setHeader("Content-Type", "application/json"); String jsonPayload = "{\"extendedHours\": true, \"quantity\": 0.1, \"ticker\": \"AAPL_US_EQ\"}"; StringEntity entity = new StringEntity(jsonPayload); request.setEntity(entity); client.execute(request, response -> { System.out.println("Market order placed: " + EntityUtils.toString(response.getEntity())); return null; }); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Place a Stop Order - Go Example Source: https://t212public-api-docs.redoc.ly/index Go code snippet for placing a stop order. This example demonstrates creating an HTTP client, constructing the POST request with headers and JSON body, specifying the stop price and time validity. ```go package main import ( "bytes" "fmt" "io/ioutil" "net/http" ) func main() { url := "https://api.example.com/api/v0/equity/orders/stop" apiKey := "YOUR_API_KEY" jsonData := []byte(`{ "quantity": 0.1, "stopPrice": 100.23, "ticker": "AAPL_US_EQ", "timeValidity": "DAY" }`) // Use backticks for multi-line raw string literal client := &http.Client{} req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Error creating request: %s\n", err) return } req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") res, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %s\n", err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Printf("Error reading response body: %s\n", err) return } fmt.Printf("Stop order placed: %s\n", string(body)) } ``` -------------------------------- ### Place a Stop Order - Java Example Source: https://t212public-api-docs.redoc.ly/index Java code snippet for placing a stop order using Apache HttpClient. This example shows how to set up the HTTP POST request, including headers and the JSON payload with stop price and time validity. ```java import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class StopOrder { public static void main(String[] args) { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost request = new HttpPost("https://api.example.com/api/v0/equity/orders/stop"); request.setHeader("Authorization", "Bearer YOUR_API_KEY"); request.setHeader("Content-Type", "application/json"); String jsonPayload = "{\"quantity\": 0.1, \"stopPrice\": 100.23, \"ticker\": \"AAPL_US_EQ\", \"timeValidity\": \"DAY\"}"; StringEntity entity = new StringEntity(jsonPayload); request.setEntity(entity); client.execute(request, response -> { System.out.println("Stop order placed: " + EntityUtils.toString(response.getEntity())); return null; }); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Get Order Response (JSON) Source: https://t212public-api-docs.redoc.ly/index Example JSON response for retrieving order details by ID. Includes creation time, quantities, prices, status, and ticker information. ```json { "creationTime": "2019-08-24T14:15:22Z", "extendedHours": true, "filledQuantity": 0, "filledValue": 0, "id": 0, "limitPrice": 0, "quantity": 0, "status": "LOCAL", "stopPrice": 0, "strategy": "QUANTITY", "ticker": "AAPL_US_EQ", "type": "LIMIT", "value": 0 } ``` -------------------------------- ### Place a Market Order - Python Example Source: https://t212public-api-docs.redoc.ly/index Python code snippet for placing a market order using the 'requests' library. It illustrates how to construct the API request with headers and the JSON body for immediate trade execution. ```python import requests import json api_url = "https://api.example.com/api/v0/equity/orders/market" api_key = "YOUR_API_KEY" headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } payload = { "extendedHours": True, "quantity": 0.1, "ticker": "AAPL_US_EQ" } try: response = requests.post(api_url, headers=headers, data=json.dumps(payload)) response.raise_for_status() # Raise an exception for bad status codes print("Market order placed:", response.json()) except requests.exceptions.RequestException as e: print(f"Error placing market order: {e}") if e.response: print("Response body:", e.response.text) ``` -------------------------------- ### Place a Market Order - Node.js Example Source: https://t212public-api-docs.redoc.ly/index Node.js code snippet for placing a market order using the 'axios' library. It shows how to structure the request with the necessary headers and JSON payload for immediate trade execution. ```javascript const axios = require('axios'); const marketOrder = async () => { try { const response = await axios.post('https://api.example.com/api/v0/equity/orders/market', { "extendedHours": true, "quantity": 0.1, "ticker": "AAPL_US_EQ" }, { headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' } }); console.log('Market order placed:', response.data); } catch (error) { console.error('Error placing market order:', error.response ? error.response.data : error.message); } }; marketOrder(); ``` -------------------------------- ### Place Stop-Limit Order (Curl) Source: https://t212public-api-docs.redoc.ly/index Example cURL command to place a Stop-Limit order using the Trading 212 API. Requires authentication with API key or credentials. ```curl curl -X POST \ 'https://demo.trading212.com/api/v0/equity/orders/stop_limit' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ \ "limitPrice": 100.23, \ "quantity": 0.1, \ "stopPrice": 100.23, \ "ticker": "AAPL_US_EQ", \ "timeValidity": "DAY" \ }' ``` -------------------------------- ### Get All Pending Equity Orders using cURL Source: https://t212public-api-docs.redoc.ly/index Retrieves a list of all active equity orders. This cURL command demonstrates how to authenticate and send a GET request to the /api/v0/equity/orders endpoint. ```shell curl -i -X GET \ -u : \ https://demo.trading212.com/api/v0/equity/orders ``` -------------------------------- ### GET /api/v0/equity/pies Source: https://t212public-api-docs.redoc.ly/index Fetches all pies for the account. Requires authentication with a secret key. ```APIDOC ## GET /api/v0/equity/pies ### Description Fetches all pies for the account. ### Method GET ### Endpoint `/api/v0/equity/pies` ### Parameters #### Query Parameters None #### Path Parameters None #### Request Body None ### Request Example ```bash curl -i -X GET \ -u : \ https://demo.trading212.com/api/v0/equity/pies ``` ### Response #### Success Response (200) ```json [ { "cash": 0, "dividendDetails": { "gained": 0, "inCash": 0, "reinvested": 0 }, "id": 0, "progress": 0.5, "result": { "priceAvgInvestedValue": 0, "priceAvgResult": 0, "priceAvgResultCoef": 0, "priceAvgValue": 0 }, "status": "AHEAD" } ] ``` #### Error Responses * 401: Bad API key * 403: Scope( pies:read ) missing for API key * 408: Timed-out * 429: Limited: 1 / 30s ``` -------------------------------- ### Place a Market Order - Curl Request Source: https://t212public-api-docs.redoc.ly/index Example curl command to place a market order. This demonstrates sending the JSON payload to the API endpoint for immediate trade execution. Use a positive quantity for buys and a negative quantity for sells. ```curl curl -X POST https://api.example.com/api/v0/equity/orders/market \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "extendedHours": true, "quantity": 0.1, "ticker": "AAPL_US_EQ" }' ``` -------------------------------- ### GET /equity/pies Source: https://context7.com/context7/t212public-api-docs_redoc_ly/llms.txt Fetches a summary of all investment pies, including cash, progress, and performance results. ```APIDOC ## Fetch All Pies ### Description List all investment pies. Returns summary information for all pies including cash, dividends, progress, and performance results. ### Method GET ### Endpoint /api/v0/equity/pies ### Parameters ### Request Body ### Request Example ```bash curl -X GET "https://demo.trading212.com/api/v0/equity/pies" \ -u "YOUR_API_KEY:YOUR_API_SECRET" ``` ### Response #### Success Response (200) - **id** (integer) - Unique identifier for the pie. - **status** (string) - Indicates if the pie is on track ('AHEAD') or behind ('BEHIND'). - **cash** (float) - Available cash within the pie. - **progress** (float) - Progress towards the pie's goal. - **result** (object) - Performance metrics. - **priceAvgValue** (float) - Average value of the pie. - **priceAvgInvestedValue** (float) - Average invested value in the pie. - **priceAvgResult** (float) - Average result (profit/loss) of the pie. - **priceAvgResultCoef** (float) - Average result coefficient. - **dividendDetails** (object) - Details about dividends. - **gained** (float) - Total dividends gained. - **inCash** (integer) - Dividends received in cash. - **reinvested** (float) - Dividends that were reinvested. #### Response Example ```json [ { "id": 12345, "status": "AHEAD", "cash": 500.00, "progress": 0.45, "result": { "priceAvgValue": 22500.00, "priceAvgInvestedValue": 20000.00, "priceAvgResult": 2500.00, "priceAvgResultCoef": 0.125 }, "dividendDetails": { "gained": 150.00, "inCash": 0, "reinvested": 150.00 } } ] ``` ### Rate Limit 1 request per 30 seconds ``` -------------------------------- ### Python: Create a Pie Source: https://t212public-api-docs.redoc.ly/index This Python script demonstrates how to create an investment pie via the Trading 212 API. It constructs a dictionary representing the pie's configuration and sends it as a JSON payload in a POST request. Replace placeholder values with your actual data and ensure you have the `requests` library installed. ```python import requests import base64 api_key = "your_api_key" api_secret = "your_api_secret" credentials_string = f"{api_key}:{api_secret}" encoded_credentials = base64.b64encode(credentials_string.encode('utf-8')).decode('utf-8') auth_header = f"Basic {encoded_credentials}" payload = { "dividendCashAction": "REINVEST", "endDate": "2019-08-24T14:15:22Z", "goal": 0, "icon": "string", "instrumentShares": { "AAPL_US_EQ": 0.5, "MSFT_US_EQ": 0.5 }, "name": "string" } headers = { 'Authorization': auth_header, 'Content-Type': 'application/json' } response = requests.post('https://demo.trading212.com/api/v0/equity/pies', json=payload, headers=headers) if response.status_code == 200: print("Pie created successfully:", response.json()) else: print(f"Error creating pie: {response.status_code} - {response.text}") ``` -------------------------------- ### GET /equity/metadata/exchanges Source: https://context7.com/context7/t212public-api-docs_redoc_ly/llms.txt Retrieves a list of all available exchanges and their trading schedules. ```APIDOC ## Get Exchange List ### Description List all available exchanges and schedules. Returns exchanges accessible to your account with working schedules and time events (open/close times). ### Method GET ### Endpoint /api/v0/equity/metadata/exchanges ### Parameters ### Request Body ### Request Example ```bash curl -X GET "https://demo.trading212.com/api/v0/equity/metadata/exchanges" \ -u "YOUR_API_KEY:YOUR_API_SECRET" ``` ### Response #### Success Response (200) - The response will be a list of exchanges, each containing details about its trading schedule and events. #### Response Example (Example response structure not provided in the source text, but would typically include exchange identifiers, name, open/close times, and trading session details.) ``` -------------------------------- ### Place a Stop Order - Python Example Source: https://t212public-api-docs.redoc.ly/index Python code snippet for placing a stop order using the 'requests' library. It demonstrates constructing the API request with headers and the JSON body, specifying the stop price and time validity. ```python import requests import json api_url = "https://api.example.com/api/v0/equity/orders/stop" api_key = "YOUR_API_KEY" headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } payload = { "quantity": 0.1, "stopPrice": 100.23, "ticker": "AAPL_US_EQ", "timeValidity": "DAY" } try: response = requests.post(api_url, headers=headers, data=json.dumps(payload)) response.raise_for_status() # Raise an exception for bad status codes print("Stop order placed:", response.json()) except requests.exceptions.RequestException as e: print(f"Error placing stop order: {e}") if e.response: print("Response body:", e.response.text) ``` -------------------------------- ### Authentication Source: https://t212public-api-docs.redoc.ly/index Explains how to authenticate API requests using HTTP Basic Authentication with your API Key and API Secret. Provides examples for generating the Authorization header in Linux/macOS and Python. ```APIDOC ## Authentication The API uses HTTP Basic Authentication. Your `API Key` is the username and your `API Secret` is the password. ### Building the Authorization Header **Linux or macOS (Terminal):** ```bash # This command outputs the required Base64-encoded string for your header. echo -n ":" | base64 ``` **Python:** ```python import base64 api_key = "" api_secret = "" credentials = f"{api_key}:{api_secret}" encoded_credentials = base64.b64encode(credentials.encode()).decode() authorization_header = f"Basic {encoded_credentials}" print(f"Authorization: {authorization_header}") ``` ``` -------------------------------- ### GET /api/v0/equity/account/info Source: https://context7.com/context7/t212public-api-docs_redoc_ly/llms.txt Fetch basic account details. Returns account ID and base currency code for the authenticated trading account. ```APIDOC ## Get Account Information Fetch basic account details Returns account ID and base currency code for the authenticated trading account. ### Method GET ### Endpoint `/api/v0/equity/account/info` ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```bash curl -X GET "https://live.trading212.com/api/v0/equity/account/info" \ -u "YOUR_API_KEY:YOUR_API_SECRET" ``` ### Response #### Success Response (200) - **currencyCode** (string) - Base currency code of the account - **id** (integer) - Unique identifier for the account #### Response Example ```json { "currencyCode": "USD", "id": 987654 } ``` ### Rate Limiting - Limit: 1 request per 30 seconds ``` -------------------------------- ### Place a Market Order - JSON Payload Source: https://t212public-api-docs.redoc.ly/index Example JSON payload for placing a market order. This order will be executed immediately at the next available price. Ensure 'quantity' is positive for buy orders and negative for sell orders. 'extendedHours' allows trading outside regular sessions. ```JSON { "extendedHours": true, "quantity": 0.1, "ticker": "AAPL_US_EQ" } ``` -------------------------------- ### Get All Pending Orders (Bash) Source: https://context7.com/context7/t212public-api-docs_redoc_ly/llms.txt Retrieves a list of all currently active and unfilled orders. Returns detailed information for each order, including its status and parameters. Requires API key and secret for authentication. ```bash curl -X GET "https://demo.trading212.com/api/v0/equity/orders" \ -u "YOUR_API_KEY:YOUR_API_SECRET" ``` -------------------------------- ### Get Exchange List - Bash Request Source: https://context7.com/context7/t212public-api-docs_redoc_ly/llms.txt Retrieves a list of all available exchanges accessible to the account, including their trading schedules and key time events like opening and closing times. This request requires API authentication. ```bash curl -X GET "https://demo.trading212.com/api/v0/equity/metadata/exchanges" \ -u "YOUR_API_KEY:YOUR_API_SECRET" ``` -------------------------------- ### Place a Stop Order - Node.js Example Source: https://t212public-api-docs.redoc.ly/index Node.js code snippet for placing a stop order using the 'axios' library. It shows how to structure the request with the necessary headers and JSON payload, including the stop price and time validity. ```javascript const axios = require('axios'); const stopOrder = async () => { try { const response = await axios.post('https://api.example.com/api/v0/equity/orders/stop', { "quantity": 0.1, "stopPrice": 100.23, "ticker": "AAPL_US_EQ", "timeValidity": "DAY" }, { headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' } }); console.log('Stop order placed:', response.data); } catch (error) { console.error('Error placing stop order:', error.response ? error.response.data : error.message); } }; stopOrder(); ``` -------------------------------- ### 200 OK Response Sample for Get All Pending Orders Source: https://t212public-api-docs.redoc.ly/index Returns a list of pending equity orders. This JSON sample details the structure of each order object, including its ID, status, type, and quantity. ```json [ { "creationTime": "2019-08-24T14:15:22Z", "extendedHours": true, "filledQuantity": 0, "filledValue": 0, "id": 0, "limitPrice": 0, "quantity": 0, "status": "LOCAL", "stopPrice": 0, "strategy": "QUANTITY", "ticker": "AAPL_US_EQ", "type": "LIMIT", "value": 0 } ] ``` -------------------------------- ### Place a Stop Order - Curl Request Source: https://t212public-api-docs.redoc.ly/index Example curl command to place a stop order. This demonstrates sending the JSON payload to the API endpoint, specifying the trigger price and time validity for the order. ```curl curl -X POST https://api.example.com/api/v0/equity/orders/stop \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "quantity": 0.1, "stopPrice": 100.23, "ticker": "AAPL_US_EQ", "timeValidity": "DAY" }' ``` -------------------------------- ### Get Order by ID (Curl) Source: https://t212public-api-docs.redoc.ly/index Example cURL command to retrieve a specific pending order using its unique numerical ID. Useful for checking order status. Requires authentication. ```curl curl -i -X GET \ -u : \ 'https://demo.trading212.com/api/v0/equity/orders/{id}' ``` -------------------------------- ### Go: Create a Pie Source: https://t212public-api-docs.redoc.ly/index This Go code snippet illustrates how to create an investment pie using the Trading 212 API. It constructs the necessary authentication header and the JSON request body, then sends a POST request using the `net/http` package. Ensure you handle JSON marshalling and potential errors appropriately. ```go package main import ( "encoding/base64" "encoding/json" "fmt" "net/http" "bytes" ) func main() { apiKey := "your_api_key" apiSecret := "your_api_secret" credentials := fmt.Sprintf("%s:%s", apiKey, apiSecret) encodedCredentials := base64.StdEncoding.EncodeToString([]byte(credentials)) authHeader := "Basic " + encodedCredentials payload := map[string]interface{}{ "dividendCashAction": "REINVEST", "endDate": "2019-08-24T14:15:22Z", "goal": 0, "icon": "string", "instrumentShares": map[string]float64{ "AAPL_US_EQ": 0.5, "MSFT_US_EQ": 0.5, }, "name": "string", } jsonPayload, err := json.Marshal(payload) if err != nil { fmt.Println("Error marshalling JSON:", err) return } client := &http.Client{} req, err := http.NewRequest("POST", "https://demo.trading212.com/api/v0/equity/pies", bytes.NewBuffer(jsonPayload)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Authorization", authHeader) req.Header.Set("Content-Type", "application/json") resp, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { var result map[string]interface{} if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { fmt.Println("Error decoding response:", err) } else { fmt.Println("Pie created successfully:", result) } } else { fmt.Printf("Error creating pie: %d - %s\n", resp.StatusCode, resp.Status) } } ``` -------------------------------- ### Get All Pending Orders Source: https://t212public-api-docs.redoc.ly/index Retrieves a list of all orders that are currently active. ```APIDOC ## GET /api/v0/equity/orders ### Description Retrieves a list of all orders that are currently active (i.e., not yet filled, cancelled, or expired). ### Method GET ### Endpoint /api/v0/equity/orders ### Parameters None ### Request Example ```bash curl -i -X GET \ -u : \ https://demo.trading212.com/api/v0/equity/orders ``` ### Response #### Success Response (200) - **creationTime** (string) - The time the order was created (ISO 8601 format). - **extendedHours** (boolean) - Indicates if the order is for extended hours trading. - **filledQuantity** (number) - The quantity of the order that has been filled. - **filledValue** (number) - The value of the filled portion of the order. - **id** (number) - The unique identifier for the order. - **limitPrice** (number) - The limit price for the order. - **quantity** (number) - The total quantity of the order. - **status** (string) - The current status of the order (e.g., LOCAL). - **stopPrice** (number) - The stop price for the order. - **strategy** (string) - The strategy used for the order (e.g., QUANTITY). - **ticker** (string) - The ticker symbol of the instrument. - **type** (string) - The type of order (e.g., LIMIT). - **value** (number) - The total value of the order. #### Response Example ```json [ { "creationTime": "2019-08-24T14:15:22Z", "extendedHours": true, "filledQuantity": 0, "filledValue": 0, "id": 0, "limitPrice": 0, "quantity": 0, "status": "LOCAL", "stopPrice": 0, "strategy": "QUANTITY", "ticker": "AAPL_US_EQ", "type": "LIMIT", "value": 0 } ] ``` ``` -------------------------------- ### Fetch all open positions Source: https://t212public-api-docs.redoc.ly/index Fetch an open positions for your account. Provides a real-time overview of all your open positions, including quantity, average price, and current profit or loss. ```APIDOC ## Fetch all open positions ### Description Fetch an open positions for your account. Provides a real-time overview of all your open positions, including quantity, average price, and current profit or loss. ### Method GET ### Endpoint /api/v0/equity/portfolio ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```bash curl -i -X GET \ -u : \ https://demo.trading212.com/api/v0/equity/portfolio ``` ### Response #### Success Response (200) - **averagePrice** (number) - The average purchase price of the position. - **currentPrice** (number) - The current market price of the instrument. - **frontend** (string) - The platform where the position was opened. - **fxPpl** (number) - Foreign exchange profit or loss. - **initialFillDate** (string) - The date and time when the position was initially filled (ISO 8601 format). - **maxBuy** (number) - The maximum amount that can be bought. - **maxSell** (number) - The maximum amount that can be sold. - **pieQuantity** (number) - The quantity of the instrument within a pie. - **ppl** (number) - The profit or loss for the position. - **quantity** (number) - The current quantity of the instrument held. - **ticker** (string) - The ticker symbol of the instrument. #### Response Example ```json [ { "averagePrice": 0, "currentPrice": 0, "frontend": "API", "fxPpl": 0, "initialFillDate": "2019-08-24T14:15:22Z", "maxBuy": 0, "maxSell": 0, "pieQuantity": 0, "ppl": 0, "quantity": 0, "ticker": "AAPL_US_EQ" } ] ``` ``` -------------------------------- ### GET /api/v0/history/dividends Source: https://context7.com/context7/t212public-api-docs_redoc_ly/llms.txt Retrieves dividend payment history, allowing filtering by ticker and pagination. ```APIDOC ## GET /api/v0/history/dividends ### Description Retrieve dividend payment history. Lists all dividend payments received with filtering and pagination. Includes gross amount per share and total amounts in account currency. ### Method GET ### Endpoint https://demo.trading212.com/api/v0/history/dividends ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of dividends to return per page. Maximum value is 50. - **ticker** (string) - Optional - Filter dividends by a specific instrument ticker. - **cursor** (string) - Optional - A cursor for fetching the next page of results. #### Request Body None ### Request Example ```bash curl -X GET "https://demo.trading212.com/api/v0/history/dividends?limit=20" \ -u "YOUR_API_KEY:YOUR_API_SECRET" # Filter by ticker curl -X GET "https://demo.trading212.com/api/v0/history/dividends?ticker=AAPL_US_EQ&limit=50" \ -u "YOUR_API_KEY:YOUR_API_SECRET" ``` ### Response #### Success Response (200) - **items** (array) - An array of dividend objects. - **reference** (string) - A unique reference identifier for the dividend payment. - **ticker** (string) - The ticker symbol of the instrument for which the dividend was paid. - **type** (string) - The type of payment (e.g., "DIVIDEND"). - **quantity** (number) - The number of shares held at the time of the dividend payment. - **grossAmountPerShare** (number) - The gross dividend amount paid per share. - **amount** (number) - The total gross dividend amount received in the instrument's currency. - **amountInEuro** (number) - The total dividend amount converted to the account's base currency (e.g., EUR). - **paidOn** (string) - The date when the dividend was paid, in ISO 8601 format. - **nextPagePath** (string) - A URL path to retrieve the next page of results, if available. #### Response Example ```json { "items": [ { "reference": "DIV-2025-001", "ticker": "AAPL_US_EQ", "type": "DIVIDEND", "quantity": 50.0, "grossAmountPerShare": 0.24, "amount": 12.00, "amountInEuro": 11.20, "paidOn": "2025-10-01T00:00:00.000Z" } ], "nextPagePath": "/api/v0/history/dividends?cursor=1234567890&limit=20" } ``` ### Rate Limit 6 requests per minute ### Max Limit 50 items per request ``` -------------------------------- ### Create Pie Source: https://context7.com/context7/t212public-api-docs_redoc_ly/llms.txt Create a new investment pie portfolio, defining target allocations across multiple instruments for automated diversified investing. ```APIDOC ## POST /api/v0/equity/pies ### Description Create investment pie portfolio. Investment pies allow automated diversified investing by specifying target allocations across multiple instruments. Dividends can be reinvested or paid to cash. ### Method POST ### Endpoint /api/v0/equity/pies ### Parameters #### Request Body - **name** (string) - Required - The name of the investment pie. - **icon** (string) - Optional - An icon identifier for the pie (e.g., "BRIEFCASE"). - **goal** (float) - Optional - The target investment goal amount. - **endDate** (string) - Optional - The target end date for the investment goal (ISO 8601 format). - **dividendCashAction** (string) - Optional - Action to take with dividends (e.g., "REINVEST", "PAY_IN_CASH"). Defaults to REINVEST if not specified. - **instrumentShares** (object) - Required - An object mapping instrument tickers to their target allocation share (e.g., {"AAPL_US_EQ": 0.30}). - **[ticker]** (float) - Required - The allocation share for the instrument. ### Request Example ```json { "name": "Tech Growth Portfolio", "icon": "BRIEFCASE", "goal": 50000.00, "endDate": "2026-12-31T23:59:59Z", "dividendCashAction": "REINVEST", "instrumentShares": { "AAPL_US_EQ": 0.30, "MSFT_US_EQ": 0.25, "GOOGL_US_EQ": 0.25, "NVDA_US_EQ": 0.20 } } ``` ### Response #### Success Response (200) (Details of the created pie, structure may vary based on API implementation. Typically includes ID, name, and configuration.) #### Response Example (Example response structure not provided in the source text. Usually returns details of the created pie.) ``` -------------------------------- ### GET /api/v0/equity/orders Source: https://context7.com/context7/t212public-api-docs_redoc_ly/llms.txt Retrieves a list of all currently pending (unfilled, uncanceled, unexpired) orders. ```APIDOC ## Get All Pending Orders List all active unfilled orders. Retrieves all orders that are currently active (not filled, cancelled, or expired). Returns order details including type, status, prices, and quantities. ### Method GET ### Endpoint /api/v0/equity/orders ### Parameters None ### Request Example ```bash curl -X GET "https://demo.trading212.com/api/v0/equity/orders" \ -u "YOUR_API_KEY:YOUR_API_SECRET" ``` ### Response #### Success Response (200) Returns an array of order objects. Each object contains: - **id** (integer) - Unique identifier for the order. - **type** (string) - Type of the order (e.g., "LIMIT", "STOP"). - **status** (string) - Current status of the order (e.g., "WORKING", "LOCAL"). - **ticker** (string) - Ticker symbol of the security. - **quantity** (number) - The quantity of shares for the order. - **limitPrice** (number) - The limit price set for the order. - **stopPrice** (number) - The stop price set for the order. - **filledQuantity** (number) - Quantity of shares already filled. - **filledValue** (number) - Total value of the filled portion of the order. - **creationTime** (string) - ISO 8601 timestamp of when the order was created. - **strategy** (string) - Order strategy (e.g., "QUANTITY"). - **extendedHours** (boolean) - Indicates if the order is for extended hours trading. - **value** (number) - Total value of the order. #### Response Example ```json [ { "id": 123456789, "type": "LIMIT", "status": "WORKING", "ticker": "AAPL_US_EQ", "quantity": 10.0, "limitPrice": 150.00, "stopPrice": 0, "filledQuantity": 0, "filledValue": 0, "creationTime": "2025-10-11T09:00:00.000Z", "strategy": "QUANTITY", "extendedHours": false, "value": 0 }, { "id": 987654321, "type": "STOP", "status": "LOCAL", "ticker": "TSLA_US_EQ", "quantity": -5.0, "stopPrice": 200.00, "limitPrice": 0, "filledQuantity": 0, "filledValue": 0, "creationTime": "2025-10-11T10:30:00.000Z", "strategy": "QUANTITY", "extendedHours": false, "value": 0 } ] ``` ### Rate Limiting 1 request per 5 seconds. ``` -------------------------------- ### Create Investment Pie using cURL Source: https://context7.com/context7/t212public-api-docs_redoc_ly/llms.txt Creates a new investment pie portfolio, allowing for automated diversified investing with specified instrument allocations and dividend reinvestment options. Requires API key and secret for authentication. ```bash curl -X POST "https://demo.trading212.com/api/v0/equity/pies" \ -u "YOUR_API_KEY:YOUR_API_SECRET" \ -H "Content-Type: application/json" \ -d '{ "name": "Tech Growth Portfolio", "icon": "BRIEFCASE", "goal": 50000.00, "endDate": "2026-12-31T23:59:59Z", "dividendCashAction": "REINVEST", "instrumentShares": { "AAPL_US_EQ": 0.30, "MSFT_US_EQ": 0.25, "GOOGL_US_EQ": 0.25, "NVDA_US_EQ": 0.20 } }' ```