Getting started
The first two steps need no Trading 212 account at all. New to trading APIs, or to async and await? Read
Key concepts first; it takes five minutes.
-
Install the package.
Terminal window npm install @kkkermit/trading212.jsTerminal window pnpm add @kkkermit/trading212.jsTerminal window yarn add @kkkermit/trading212.jsTerminal window bun add @kkkermit/trading212.jsYou need Node 22 or later, Bun, or Deno, which imports it as
npm:@kkkermit/trading212.js. The library runs on servers only: Trading 212 refuses requests from web pages, and a key shipped to a browser is public, so the client refuses to start in one. -
Try it without a key.
The fake Trading 212 in
@kkkermit/trading212.js/testingis the real client talking to an in-memory account, so you can see how everything behaves first. Save the JavaScript astry.cjsand run it withnode try.cjs, or the TypeScript astry.mtsand run it withnpx tsx try.mts:try.mts import { createFakeTrading212 } from "@kkkermit/trading212.js/testing";// A real client talking to an in-memory Trading 212: no key, no network.const { client } = createFakeTrading212({ state: { cash: 1000 } });const apple = await client.instruments.resolve("Apple");console.log(`"Apple" is ${apple.ticker}`);const order = await client.orders.buy({ ticker: apple.ticker, quantity: 2 });const filled = await client.orders.waitFor(order);console.log(`Order ${filled.id} is ${filled.status}`);const { cash, holdings } = await client.portfolio.snapshot();console.log(`Cash left: ${cash}. Holding: ${holdings.map((holding) => holding.ticker).join(", ")}`,);try.cjs const { createFakeTrading212 } = require("@kkkermit/trading212.js/testing");async function main() {// A real client talking to an in-memory Trading 212: no key, no network.const { client } = createFakeTrading212({ state: { cash: 1000 } });const apple = await client.instruments.resolve("Apple");console.log(`"Apple" is ${apple.ticker}`);const order = await client.orders.buy({ ticker: apple.ticker, quantity: 2 });const filled = await client.orders.waitFor(order);console.log(`Order ${filled.id} is ${filled.status}`);const { cash, holdings } = await client.portfolio.snapshot();console.log(`Cash left: ${cash}. Holding: ${holdings.map((holding) => holding.ticker).join(", ")}`,);}main().catch((error) => {console.error(error);process.exitCode = 1;});The same thing, with a refusal and its hint, is in
examples/try-it-offline.ts. -
Make a key.
In the Trading 212 app, open Settings > API (Beta) and generate a key.
- Choose the environment first. A key made in practice mode works on demo only; one made with real money works on live only. There are only these two: “production” is live, and “paper” or “sandbox” is demo.
- Tick only the permissions the program needs. The API coverage page lists which method needs which.
- The secret is shown once. Copy it straight into the next step.
- Optionally restrict the key to fixed IP addresses.
-
Store it.
Make a
.envfile next to your code, and make sure git ignores it:.env T212_ENV=demoT212_API_KEY=your-keyT212_API_SECRET=your-secretTerminal window echo .env >> .gitignoreIf you keep a key per environment, set
T212_DEMO_API_KEY/T212_DEMO_API_SECRETandT212_LIVE_API_KEY/T212_LIVE_API_SECRETinstead, and switch withT212_ENV. The library never reads.envitself; your runtime loads it, as in step 6. -
Check it.
Terminal window npx @kkkermit/trading212.js doctor --env-file .envThe doctor signs in, then tries one read for each permission and reports which are missing. It never prints your key or secret, and never places an order.
-
Write your first script.
app.mts import { Trading212 } from "@kkkermit/trading212.js";// Reads T212_ENV, T212_API_KEY and T212_API_SECRET.const t212 = Trading212.fromEnv();const me = await t212.verify();console.log(`Signed in to account ${me.accountId} on ${me.environment}.`);const { totalValue, cash, holdings } = await t212.portfolio.snapshot();console.log(`Total ${totalValue}, of which cash ${cash}.`);for (const holding of holdings) {const percent = (holding.weight * 100).toFixed(1);console.log(`${holding.ticker}: ${holding.quantity} shares, ${percent}% of the portfolio`,);}app.cjs const { Trading212 } = require("@kkkermit/trading212.js");async function main() {// Reads T212_ENV, T212_API_KEY and T212_API_SECRET.const t212 = Trading212.fromEnv();const me = await t212.verify();console.log(`Signed in to account ${me.accountId} on ${me.environment}.`);const { totalValue, cash, holdings } = await t212.portfolio.snapshot();console.log(`Total ${totalValue}, of which cash ${cash}.`);for (const holding of holdings) {const percent = (holding.weight * 100).toFixed(1);console.log(`${holding.ticker}: ${holding.quantity} shares, ${percent}% of the portfolio`,);}}main().catch((error) => {console.error(error);process.exitCode = 1;});Run it with your
.envloaded:Terminal window node --env-file=.env app.cjsTypes are included. Run with tsx, or compile with
tsc:Terminal window npx tsx --env-file=.env app.mtsBun loads
.envby itself:Terminal window bun app.mtsImport from
npm:@kkkermit/trading212.js, then:Terminal window deno run --allow-net --allow-env --env-file=.env app.mts
You can also pass the options yourself instead of using fromEnv():
const t212 = new Trading212({ environment: "demo", apiKey: process.env.T212_API_KEY ?? "", apiSecret: process.env.T212_API_SECRET ?? "",});Going live
Section titled “Going live”Make a second key in real-money mode, set T212_ENV=live, and run the doctor again. A live client cannot trade:
orders, cancellations and pie changes throw TradingDisabledError until you opt in.
const t212 = Trading212.fromEnv({ trading: "enabled" });Where next
Section titled “Where next”- Orders to place your first demo trade.
- Configuration for every option.
- Errors for what each error means.