Skip to content

Logging and hooks

The client says nothing until you give it a logger. Then it writes one line per event, with every field passed through the same redaction as errors, so no credential ever reaches a log.

logging-console.mts
import { consoleLogger, Trading212 } from "@kkkermit/trading212.js";
// info shows every order and every warning; debug adds every read.
const t212 = Trading212.fromEnv({ logger: consoleLogger({ level: "info" }) });
await t212.orders.buy({ ticker: "AAPL_US_EQ", quantity: 1 });
// [trading212] INFO Sending POST /api/v0/equity/orders/market endpoint=placeMarketOrder attempt=1
// [trading212] INFO POST /api/v0/equity/orders/market returned 200 in 212 ms endpoint=placeMarketOrder …

consoleLogger({ level }) writes one line per event to the console, dropping anything below level (default info). Each line starts with [trading212] and the level, then the message, then the fields as key=value:

[trading212] INFO Sending POST /api/v0/equity/orders/market endpoint=placeMarketOrder attempt=1
[trading212] INFO POST /api/v0/equity/orders/market returned 200 in 212 ms endpoint=placeMarketOrder status=200 durationMs=212 rateLimitRemaining=49
[trading212] WARN Retrying GET /api/v0/equity/account/summary in 480 ms. endpoint=getAccountSummary attempt=1 delayMs=480 code=server

logger: console works too: it shows every level, with the fields as an object.

A level on its own is a shortcut for consoleLogger({ level }):

logging-level.mts
import { Trading212 } from "@kkkermit/trading212.js";
// The same as passing logger: consoleLogger({ level: "debug" }).
const t212 = new Trading212({
environment: "demo",
apiKey: process.env.T212_DEMO_API_KEY ?? "",
apiSecret: process.env.T212_DEMO_API_SECRET ?? "",
logger: "debug",
});
await t212.account.summary();
// [trading212] DEBUG Sending GET /api/v0/equity/account/summary endpoint=getAccountSummary attempt=1

With Trading212.fromEnv(), setting T212_LOG=debug in the environment does the same without changing any code.

Level When
debug Every read: the request, and the answer with its status, duration and remaining budget; short rate-limit waits; a read that failed for good
info Everything that changes your account: orders, cancellations, pie changes and report requests, each with its answer, and the reason when one is refused
warn An order that may or may not have gone through; every retry; rate-limit waits of 5 s or more; the first call to a deprecated endpoint; a baseUrl that is not Trading 212’s; a cache store that failed
error Never. The library throws, and you decide what to log

So the default info level gives you a record of every order and its outcome, and stays quiet about reads. Response bodies are never logged, and a logger that throws cannot break a request.

A refused order is logged with the reason and what to do about it. This is the line demo’s real refusal of a too-small order produces:

[trading212] INFO POST /api/v0/equity/orders/limit was refused: a quantity of 0.1 is below the smallest Trading 212 accepts for this order, 1.33914872. endpoint=placeLimitOrder code=order_rejected status=400 apiCode=min-quantity-exceeded traceId=523a4ed1240a1f94650c814a50c5485a hint="The order is too small. Raise the quantity to at least `error.minQuantity`, the smallest Trading 212 accepts for it."
Field Means
endpoint The library’s name for the endpoint, such as placeMarketOrder
attempt 1 for the first try, then 2, 3 … for retries of a read
status The HTTP status
durationMs How long the answer took
rateLimitRemaining Calls left in this period, from Trading 212’s headers
delayMs, waitMs How long a retry or a rate-limit wait will take
code, apiCode The error’s stable code, and Trading 212’s own code
traceId Trading 212’s reference for the request, to quote to its support
hint What to do about it
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();

pino and bunyan take (fields, message); fieldsFirst() swaps the arguments. Any other logger works if it has debug, info, warn and error methods that take (message, fields):

logging-custom.mts
import { type LogFields, type Logger, Trading212 } from "@kkkermit/trading212.js";
// Any object with these four methods is a logger. Fields arrive with credentials removed.
const logger: Logger = {
debug: () => {},
info: (message: string, fields?: LogFields) =>
console.log(new Date().toISOString(), message, fields),
warn: (message: string, fields?: LogFields) =>
console.warn(new Date().toISOString(), message, fields),
error: (message: string, fields?: LogFields) =>
console.error(new Date().toISOString(), message, fields),
};
const t212 = Trading212.fromEnv({ logger });
await t212.verify();

silentLogger, which ignores everything, is the default.

try {
await t212.orders.buy(order);
} catch (error) {
if (isTrading212Error(error)) logger.error(error.message, error.toLog());
throw error;
}

toLog() returns name, message, code, hint, status, request, rateLimit, body, apiCode and the cause’s message: everything needed to debug, nothing secret. console.error(error) is safe too.

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));
Hook Called with
onRequest { endpoint, method, path, attempt }, before each attempt
onResponse The same, plus { status, durationMs, rateLimit }, after each answer
onRetry The same as onRequest, plus { delayMs, error }, before a retry
onRateLimitWait { endpoint, waitMs }, before waiting for budget
onError The same as onRequest, plus { error }, once a request has failed

Hook events contain no credentials, and an exception thrown in a hook is ignored.

hooks-errors.mts
import { Trading212 } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv({
hooks: {
// Called once for every request that fails, after any retries, wherever it was made.
onError: ({ endpoint, attempt, error }) => {
console.error(
`${endpoint} failed after ${attempt} attempts: ${error.code}`,
error.traceId ?? "",
);
// For example: Sentry.captureException(error, { extra: error.toLog() });
},
},
});
await t212.account.summary();

onError is called once for each request that fails, after any retries, with the error the call throws, so a service such as Sentry can hear about every failure, including ones inside a watcher or a wait. That includes a request refused before it was sent, such as one with trading off, an invalid timeoutMs, or one that waited too long for rate-limit budget. attempt is the attempt it failed on, or 0 when none was started.

It is not called when you abort a call, unless it was an order already sent, whose outcome is then unknown; for a 404 the library expects, such as orders.waitFor() finding an order has left the pending list; or for a check a method makes before it builds a request, such as validating an order. The error still reaches your code as usual.

Before anything is logged, attached to an error or recorded by the testing kit, the client removes:

  • your API key, secret and their Base64 form, wherever they appear in a string;
  • any other Basic … credential;
  • values under keys such as authorization, secret, password, apiKey, token and cookie;
  • the query string of signed download links.