Skip to content

Recipes

Each recipe is a complete program. Save it, put your key in .env, and run it with node --env-file=.env file.cjs or npx tsx --env-file=.env file.mts. Try them on demo first.

Totals, then every holding with its value, weight and profit, formatted in the account’s currency.

portfolio-report.mts
import { Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
const snapshot = await t212.portfolio.snapshot();
const money = new Intl.NumberFormat("en-GB", {
style: "currency",
currency: snapshot.currency ?? "GBP",
});
console.log(
`Total ${money.format(snapshot.totalValue)}, cash ${money.format(snapshot.cash)}`,
);
console.log(`Unrealised profit ${money.format(snapshot.unrealisedProfitLoss)}`);
for (const holding of snapshot.holdings) {
const weight = `${(holding.weight * 100).toFixed(1)}%`;
const change =
holding.profitLossRatio === undefined
? ""
: ` (${(holding.profitLossRatio * 100).toFixed(1)}%)`;
console.log(
`${holding.ticker.padEnd(14)} ${money.format(holding.value).padStart(12)} ${weight}${change}`,
);
}

Adds up the dividends paid in one UK tax year, in total and per ticker.

dividends-total.mts
import { Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
// The UK tax year that started on 6 April 2026.
const { total, count, currency, byTicker } = await t212.history.dividends.total({
since: "2026-04-06",
until: "2027-04-06",
});
console.log(`${count} dividends, ${total.toFixed(2)} ${currency ?? ""}`);
for (const [ticker, amount] of Object.entries(byTicker))
console.log(ticker.padEnd(14), amount.toFixed(2));

A stop order sells at market once the price falls to your level, and GOOD_TILL_CANCEL keeps it working until it fills or you cancel it. This program shows every order type.

order-types.mts
import { Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
// Buy at 180 or less. DAY orders expire at midnight in the exchange's time zone.
await t212.orders.buy({
type: "limit",
ticker: "AAPL_US_EQ",
quantity: 1,
limitPrice: 180,
timeValidity: "DAY",
});
// A stop-loss: sell at market if the price falls to 150.
await t212.orders.sell({
type: "stop",
ticker: "AAPL_US_EQ",
quantity: 1,
stopPrice: 150,
timeValidity: "GOOD_TILL_CANCEL",
});
// Once the price reaches 150, place a limit sell at 148 or better.
await t212.orders.sell({
type: "stopLimit",
ticker: "AAPL_US_EQ",
quantity: 1,
stopPrice: 150,
limitPrice: 148,
timeValidity: "DAY",
});
// Market orders can also fill outside regular hours.
await t212.orders.buy({ ticker: "AAPL_US_EQ", quantity: 1, extendedHours: true });

When an order’s outcome is unknown, it may have gone through. findAfterUnknown() looks for it before you send it again:

safe-retry.mts
import { OrderOutcomeUnknownError, Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
const request = { ticker: "AAPL_US_EQ", quantity: 1 };
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
try {
await t212.orders.buy(request);
} catch (error) {
if (!(error instanceof OrderOutcomeUnknownError)) throw error;
// Trading 212 does not say how long a new order takes to appear in its lists, so look twice before resending.
await pause(5000);
let result = await t212.orders.findAfterUnknown(error);
if (result.status === "not-found") {
await pause(15_000);
result = await t212.orders.findAfterUnknown(error);
}
if (result.status === "found") {
console.log(`It reached Trading 212 (${result.order.status}). Not sending it again.`);
} else if (result.status === "not-found") {
console.log("No sign of it after 20 seconds, so sending it once more.");
await t212.orders.buy(request);
} else {
console.log(`Cannot tell (${result.reason}). Check the app before trying again.`);
}
}

Runs in the background and reports fills and cancellations, including orders placed in the app.

watch-orders.mts
import { Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
const orders = t212.watch.orders();
orders.on("filled", ({ order, fill }) => {
console.log(
`${order.side} ${order.quantity} ${order.ticker} filled at ${fill?.price ?? "?"}`,
);
});
orders.on("cancelled", ({ order }) => console.log(`Order ${order.id} was cancelled`));
orders.on("error", ({ error, willRetry }) =>
console.error(error.message, willRetry ? "(retrying)" : "(stopped)"),
);
// Stop watching after an hour.
setTimeout(() => orders.stop(), 60 * 60_000);

Waits for the market to open, then buys.

market-wait.mts
import { Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
const ticker = "AAPL_US_EQ";
if (!(await t212.exchanges.isOpen(ticker))) {
console.log("Closed. Waiting for the open…");
// Sleeps until the scheduled opening, up to four days so a weekend fits; extendedHours: true counts pre-market too.
await t212.exchanges.waitUntilOpen(ticker, { timeoutMs: 4 * 24 * 60 * 60_000 });
}
await t212.orders.buy({ ticker, quantity: 1 });

Cancels each order in turn and says what happened to it.

cancel-pending.mts
import { Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
for (const result of await t212.orders.cancelAll({ ticker: "AAPL_US_EQ" })) {
const { id } = result.order;
if (result.status === "requested")
console.log(`Asked Trading 212 to cancel order ${id}`);
else if (result.status === "gone") console.log(`Order ${id} had already gone`);
else if (result.status === "unknown")
console.log(`Order ${id} may or may not be cancelled: check orders.list()`);
else console.log(`Order ${id} could not be cancelled: ${result.error.message}`);
}

Runs every 15 minutes, keeps going through a bad moment, and stops cleanly on Ctrl+C. For anything run once a day, your system’s scheduler (cron, or Task Scheduler on Windows) is simpler than a program that never stops.

scheduled-report.mts
import { isTrading212Error, Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
const everyMinutes = 15;
async function report(): Promise<void> {
try {
const { totalValue, cash, takenAt } = await t212.portfolio.snapshot();
console.log(`${takenAt.toISOString()} total ${totalValue}, cash ${cash}`);
} catch (error) {
// Keep running on a bad moment; let anything unexpected stop the program.
if (!isTrading212Error(error)) throw error;
console.error(error.message, error.hint);
}
}
await report();
const timer = setInterval(() => void report(), everyMinutes * 60_000);
process.once("SIGINT", () => clearInterval(timer));
export-csv.mts
import { Trading212 } from "@kkkermit/trading212.js";
import { csvNumber, parseCsv } from "@kkkermit/trading212.js/csv";
const t212 = Trading212.fromEnv();
// Requests the report, waits for it (at least a minute) and downloads it.
const { report, csv } = await t212.reports.export(
{ from: "2026-01-01", to: "2026-12-31", include: { interest: false } },
{ onStatus: (current) => console.log(`Report ${current.reportId}: ${current.status}`) },
);
console.log(`Report ${report.reportId} has ${csv.length} characters`);
let deposits = 0;
for (const row of parseCsv(csv)) {
if (row.Action === "Deposit") deposits += csvNumber(row.Total) ?? 0;
}
console.log(`Deposited ${deposits.toFixed(2)} this year`);
cancel-a-call.mts
import { Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
// Give up on one call after 5 seconds, whatever the client's own timeout.
const summary = await t212.account.summary({ timeoutMs: 5_000 });
console.log(summary.totalValue);
// Or cancel calls yourself, such as when your program shuts down.
const controller = new AbortController();
process.once("SIGINT", () => controller.abort());
for await (const order of t212.history.orders.all({ signal: controller.signal })) {
console.log(order.order?.id);
}

Share the instrument list between processes

Section titled “Share the instrument list between processes”

The instrument list is about 5 MB. With several processes, keep one copy in Redis rather than one download each:

redis-cache.mts
import { type CacheStore, Trading212 } from "@kkkermit/trading212.js";
// Any client with get and set works; this is the shape of node-redis and ioredis.
interface RedisLike {
get(key: string): Promise<string | null>;
set(key: string, value: string, mode: "PX", ttlMs: number): Promise<unknown>;
del(key: string): Promise<unknown>;
}
declare const redis: RedisLike;
// redis is your connected node-redis or ioredis client.
const redisCache: CacheStore = {
// A null from Redis counts as a miss.
get: async (key) => {
const text = await redis.get(key);
return text === null ? undefined : (JSON.parse(text) as unknown);
},
set: (key, value, ttlMs) => redis.set(key, JSON.stringify(value), "PX", ttlMs),
delete: (key) => redis.del(key),
};
// Every process now shares one copy of the 5 MB instrument list.
const t212 = Trading212.fromEnv({ cache: redisCache });
await t212.instruments.list();
logging-pino.mts
import { fieldsFirst, Trading212 } from "@kkkermit/trading212.js";
import pino from "pino";
// pino and bunyan take (fields, message); fieldsFirst swaps the arguments.
const t212 = Trading212.fromEnv({ logger: fieldsFirst(pino({ level: "debug" })) });
await t212.account.summary();
hooks-metrics.mts
import { Trading212 } from "@kkkermit/trading212.js";
const counts = new Map<string, number>();
const t212 = Trading212.fromEnv({
hooks: {
onRequest: ({ endpoint, attempt }) => {
counts.set(endpoint, (counts.get(endpoint) ?? 0) + 1);
if (attempt > 1) console.log(`${endpoint}: attempt ${attempt}`);
},
onResponse: ({ endpoint, status, durationMs, rateLimit }) => {
console.log(
`${endpoint} ${status} in ${durationMs} ms, ${rateLimit?.remaining ?? "?"} left`,
);
},
onRetry: ({ endpoint, delayMs, error }) =>
console.log(`${endpoint} retries in ${delayMs} ms: ${error.code}`),
onRateLimitWait: ({ endpoint, waitMs }) =>
console.log(`${endpoint} waits ${waitMs} ms for budget`),
},
});
await t212.portfolio.snapshot();
console.log(Object.fromEntries(counts));