Orders
Every order needs a key with the orders:execute permission. On live, the client must also be created with
trading: "enabled"; until then every order throws TradingDisabledError and nothing is sent.
| Method | Does |
|---|---|
orders.buy(order, options?) |
Buys. The quantity is positive; type defaults to market |
orders.sell(order, options?) |
Sells. The quantity is positive and the sign is set for you |
orders.sellAll(ticker) |
Sells everything you can of one holding, at market |
orders.market(), limit(), stop(), stopLimit() |
Send exactly what you give them; a negative quantity sells |
orders.waitFor(order) |
Waits until an order is filled, cancelled or rejected |
orders.list() |
Orders that are still working |
orders.get(id) |
One working order |
orders.cancel(id) |
Asks Trading 212 to cancel a working order |
Full signatures are in the method reference.
Place an order and wait for it
Section titled “Place an order and wait for it”import { OrderOutcomeUnknownError, OrderRejectedError, Trading212, TradingDisabledError,} from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
try { const order = await t212.orders.buy({ ticker: "AAPL_US_EQ", quantity: 0.5 }); console.log(`Order ${order.id} sent, status ${order.status}`);
const settled = await t212.orders.waitFor(order, { timeoutMs: 60_000 }); console.log( `Order ${settled.id} is ${settled.status}: ${settled.filledQuantity} shares`, );} catch (error) { if (error instanceof OrderRejectedError) { // Trading 212 said no, and nothing was traded. error.reason is its code. console.error(`Refused: ${error.reason}. ${error.hint}`); } else if (error instanceof OrderOutcomeUnknownError) { // It may have gone through. Look before you send it again. console.error(error.message, error.hint); } else if (error instanceof TradingDisabledError) { console.error('This client only reads. Pass trading: "enabled" to place orders.'); } else { throw error; }}const { OrderOutcomeUnknownError, OrderRejectedError, Trading212, TradingDisabledError,} = require("@kkkermit/trading212.js");
async function main() { const t212 = Trading212.fromEnv();
try { const order = await t212.orders.buy({ ticker: "AAPL_US_EQ", quantity: 0.5 }); console.log(`Order ${order.id} sent, status ${order.status}`);
const settled = await t212.orders.waitFor(order, { timeoutMs: 60_000 }); console.log( `Order ${settled.id} is ${settled.status}: ${settled.filledQuantity} shares`, ); } catch (error) { if (error instanceof OrderRejectedError) { // Trading 212 said no, and nothing was traded. error.reason is its code. console.error(`Refused: ${error.reason}. ${error.hint}`); } else if (error instanceof OrderOutcomeUnknownError) { // It may have gone through. Look before you send it again. console.error(error.message, error.hint); } else if (error instanceof TradingDisabledError) { console.error('This client only reads. Pass trading: "enabled" to place orders.'); } else { throw error; } }}
main().catch((error) => { console.error(error); process.exitCode = 1;});buy() and sell() take a positive quantity and set the direction themselves, so a stray minus sign cannot turn
a sale into a purchase. waitFor() polls the order once a second, its rate limit. Once the order stops being pending,
Trading 212 answers 404, so from then on waitFor() looks it up in the history instead, which needs the
history:orders permission. timeoutMs bounds the whole wait; after it, waitFor() throws TimeoutError, and the
order may still fill.
Order types
Section titled “Order types”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 });const { Trading212 } = require("@kkkermit/trading212.js");
async function main() { 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 });}
main().catch((error) => { console.error(error); process.exitCode = 1;});| Type | Fills | Needs | Limit |
|---|---|---|---|
market |
now, at the next price | nothing else | 50 / minute |
limit |
at limitPrice or better |
limitPrice, timeValidity |
1 / 2 s |
stop |
as a market order once the price reaches stopPrice |
stopPrice, timeValidity |
1 / 2 s |
stopLimit |
as a limit order at limitPrice once stopPrice is hit |
stopPrice, limitPrice, timeValidity |
1 / 2 s |
timeValidity is "DAY", which expires at midnight in the exchange’s time zone, or "GOOD_TILL_CANCEL", which
stays until it fills or you cancel it. It is required on every non-market order, so an order never depends on a
default. extendedHours: true lets a market order fill outside regular hours, and is allowed on market orders only.
The lower-level market(), limit(), stop() and stopLimit() take the same fields without type, and send
exactly what you give them, with the API’s own convention that a negative quantity sells:
await t212.orders.market({ ticker: "AAPL_US_EQ", quantity: -2 }); // sells 2What is checked before sending
Section titled “What is checked before sending”Before any request, the client checks that:
- the ticker has no spaces;
- the quantity is a finite number, not zero, with at most 4 decimal places;
- prices are positive;
timeValidityis"DAY"or"GOOD_TILL_CANCEL";- no field is given that the order type does not use;
- a buy is for no more than the instrument’s
maxOpenQuantity, once this client has loaded the instrument list, for example throughinstruments.resolve(). The spec does not define that field; the client reads it as the most of an instrument an account may hold. Sells are never checked, so a lowered limit cannot stop you selling what you hold, and the list is never downloaded for this, so without it Trading 212 makes the call.
Every problem goes into one ValidationError, with error.issues listing them. Nothing is sent.
Quantities
Section titled “Quantities”Orders take at most 4 decimal places; positions can hold 8. truncateQuantity() cuts towards zero using the number’s
exact digits, never floating-point arithmetic, so it can never round up past what you own:
import { isValidQuantity, truncateQuantity } from "@kkkermit/trading212.js";
truncateQuantity(12.09032128); // 12.0903isValidQuantity(0.12345); // false: 5 decimal placesThe API does not support placing an order by value, such as “£50 of Apple”.
Sell a whole position
Section titled “Sell a whole position”import { Trading212, ValidationError } from "@kkkermit/trading212.js";
const t212 = Trading212.fromEnv();
try { // Sells quantityAvailableForTrading, cut to 4 decimal places, at market. const order = await t212.orders.sellAll("AAPL_US_EQ"); console.log(`Selling ${Math.abs(order.quantity ?? 0)} shares in order ${order.id}`);} catch (error) { // Nothing held, or everything is in pies or reserved by pending orders. if (error instanceof ValidationError) console.error(error.message, error.hint); else throw error;}const { Trading212, ValidationError } = require("@kkkermit/trading212.js");
async function main() { const t212 = Trading212.fromEnv();
try { // Sells quantityAvailableForTrading, cut to 4 decimal places, at market. const order = await t212.orders.sellAll("AAPL_US_EQ"); console.log(`Selling ${Math.abs(order.quantity ?? 0)} shares in order ${order.id}`); } catch (error) { // Nothing held, or everything is in pies or reserved by pending orders. if (error instanceof ValidationError) console.error(error.message, error.hint); else throw error; }}
main().catch((error) => { console.error(error); process.exitCode = 1;});sellAll() reads the position’s quantityAvailableForTrading, truncates it to 4 decimal places and sells that at
market. Shares in pies or reserved by pending orders are left alone. It needs the portfolio permission as well as
orders:execute.
Preview with a dry run
Section titled “Preview with a dry run”import { Trading212 } from "@kkkermit/trading212.js";
// A live client with trading off: it can preview orders but never send them.const t212 = Trading212.fromEnv();
const preview = await t212.orders.buy( { ticker: "AAPL_US_EQ", quantity: 1 }, { dryRun: true },);
console.log(preview.method, preview.url); // POST https://…/api/v0/equity/orders/marketconsole.log(preview.body); // { ticker: "AAPL_US_EQ", quantity: 1 }console.log( preview.wouldSend ? "This client would send it" : "Trading is off for this client",);const { Trading212 } = require("@kkkermit/trading212.js");
async function main() { // A live client with trading off: it can preview orders but never send them. const t212 = Trading212.fromEnv();
const preview = await t212.orders.buy( { ticker: "AAPL_US_EQ", quantity: 1 }, { dryRun: true }, );
console.log(preview.method, preview.url); // POST https://…/api/v0/equity/orders/market console.log(preview.body); // { ticker: "AAPL_US_EQ", quantity: 1 } console.log( preview.wouldSend ? "This client would send it" : "Trading is off for this client", );}
main().catch((error) => { console.error(error); process.exitCode = 1;});A dry run checks the order and builds the exact request, then returns it instead of sending it. It works on a live
client with trading off, and wouldSend says whether this client would send it for real. TypeScript knows the
difference: { dryRun: true } returns a DryRunResult, and anything else an Order.
Working orders and cancelling
Section titled “Working orders and cancelling”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}`);}const { Trading212 } = require("@kkkermit/trading212.js");
async function main() { 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}`); }}
main().catch((error) => { console.error(error); process.exitCode = 1;});cancelAll() cancels every working order, or one ticker’s, one request each, and returns a result per order:
requested, gone when it had already filled or been cancelled, unknown when the cancellation may or may not have
arrived, or failed with the error. One failure does not stop the rest; aborting its signal stops it before the
next order.
A successful cancel() means Trading 212 accepted the request; the order can still fill first. Cancelling an order
that has already gone throws NotFoundError. At most 50 orders may be pending per ticker.
To hear when orders fill or are cancelled without asking yourself, use a watcher.
When an order fails
Section titled “When an order fails”| Error | Means |
|---|---|
ValidationError |
Refused before sending; fix what error.issues lists |
OrderRejectedError |
Refused by Trading 212; error.reason is its code, such as min-quantity-exceeded |
TradingDisabledError |
Trading is off for this client, as it is on live by default; nothing was sent |
OrderOutcomeUnknownError |
It may have gone through. orders.findAfterUnknown(error) looks for it |
NetworkError (sent: false) |
It never left your machine, so it is safe to send again |
MissingScopeError |
The key lacks orders:execute |
Finding an order whose outcome is unknown
Section titled “Finding an order whose outcome is unknown”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.`); }}const { OrderOutcomeUnknownError, Trading212 } = require("@kkkermit/trading212.js");
async function main() { const t212 = Trading212.fromEnv(); const request = { ticker: "AAPL_US_EQ", quantity: 1 }; const pause = (ms) => 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.`); } }}
main().catch((error) => { console.error(error); process.exitCode = 1;});findAfterUnknown(error) takes the OrderOutcomeUnknownError and looks for the order among the working orders and
the recent history, matching its ticker, direction, type, quantity and prices, and only orders created within five
minutes of error.sentAt (change it with windowMs). It never sends anything, so whether to place the order again
stays your decision:
status |
Means |
|---|---|
found |
It reached Trading 212: do not send it again. Check order.status, as it may be rejected |
not-found |
Nothing like it is working or in the recent history |
unclear |
Several orders match, one is like it but differs, or none does but the history is too long to read whole |
An order that has the same ticker, direction and time but differs in a detail, such as its quantity or where it was
placed from, makes the answer unclear rather than not-found, so a detail Trading 212 lists differently can never
make an order that went through look as if it did not. When the answer is unclear, check the app before sending
anything. Trading 212 does not say how long a new order takes to appear in its lists, so wait a few seconds and look twice before deciding it was not placed, as the example does. It needs orders:read and history:orders.
A refusal says in plain words what the order broke, such as
a quantity of 0.1 is below the smallest Trading 212 accepts for this order, 1.33914872., and carries the limit as a
number: error.minQuantity, error.maxQuantity, error.maxDecimals or error.ownedQuantity. Too small, too large,
too many decimal places, selling more than you own and not enough cash have all been seen on demo; a closed market is
recognised by its expected code. The errors guide has the full
table.