Your first program
By the end of this page you will have a program that signs in, shows your portfolio, finds Apple’s ticker, checks its market is open, previews an order and then places it on demo, logging every step. It uses practice money, so nothing here can cost you anything.
The whole program
Section titled “The whole program”Here it is in full. The steps below explain each part.
import { consoleLogger, InstrumentNotFoundError, OrderOutcomeUnknownError, OrderRejectedError, Trading212,} from "@kkkermit/trading212.js";
// 1. Connect, with info logging so every order is recorded.const t212 = Trading212.fromEnv({ logger: consoleLogger({ level: "info" }) });const me = await t212.verify();console.log(`Account ${me.accountId} on ${me.environment}, trading ${me.trading}`);
// 2. Look at what you have.const { totalValue, cash } = await t212.portfolio.snapshot();console.log(`Total ${totalValue}, cash ${cash}`);
// 3. Turn a name into a Trading 212 ticker.let ticker: string;try { ticker = (await t212.instruments.resolve("Apple", { currency: "USD" })).ticker;} catch (error) { if (error instanceof InstrumentNotFoundError) console.error(error.hint); throw error;}
// 4. Check the market is open.const market = await t212.exchanges.status(ticker);if (!market.open) { console.log( `The market is ${market.session}; it opens ${market.nextOpen?.toISOString()}`, ); process.exit(0);}
// 5. Preview the order, then place it and wait for the fill.const preview = await t212.orders.buy({ ticker, quantity: 1 }, { dryRun: true });console.log("Would send", preview.body);
try { const order = await t212.orders.buy({ ticker, quantity: 1 }); const settled = await t212.orders.waitFor(order); console.log(`Order ${settled.id}: ${settled.status}`);} catch (error) { if (error instanceof OrderRejectedError) console.error(`Refused: ${error.hint}`); else if (error instanceof OrderOutcomeUnknownError) console.error(error.hint); else throw error;}const { consoleLogger, InstrumentNotFoundError, OrderOutcomeUnknownError, OrderRejectedError, Trading212,} = require("@kkkermit/trading212.js");
async function main() { // 1. Connect, with info logging so every order is recorded. const t212 = Trading212.fromEnv({ logger: consoleLogger({ level: "info" }) }); const me = await t212.verify(); console.log(`Account ${me.accountId} on ${me.environment}, trading ${me.trading}`);
// 2. Look at what you have. const { totalValue, cash } = await t212.portfolio.snapshot(); console.log(`Total ${totalValue}, cash ${cash}`);
// 3. Turn a name into a Trading 212 ticker. let ticker; try { ticker = (await t212.instruments.resolve("Apple", { currency: "USD" })).ticker; } catch (error) { if (error instanceof InstrumentNotFoundError) console.error(error.hint); throw error; }
// 4. Check the market is open. const market = await t212.exchanges.status(ticker); if (!market.open) { console.log( `The market is ${market.session}; it opens ${market.nextOpen?.toISOString()}`, ); process.exit(0); }
// 5. Preview the order, then place it and wait for the fill. const preview = await t212.orders.buy({ ticker, quantity: 1 }, { dryRun: true }); console.log("Would send", preview.body);
try { const order = await t212.orders.buy({ ticker, quantity: 1 }); const settled = await t212.orders.waitFor(order); console.log(`Order ${settled.id}: ${settled.status}`); } catch (error) { if (error instanceof OrderRejectedError) console.error(`Refused: ${error.hint}`); else if (error instanceof OrderOutcomeUnknownError) console.error(error.hint); else throw error; }}
main().catch((error) => { console.error(error); process.exitCode = 1;});Run it:
node --env-file=.env first-order.cjs # JavaScriptnpx tsx --env-file=.env first-order.mts # TypeScriptStep by step
Section titled “Step by step”-
Connect, with logging.
Trading212.fromEnv()readsT212_ENV,T212_API_KEYandT212_API_SECRET. Its argument sets any other option; here a console logger atinfo, so every order you send is written to the terminal.verify()makes one request and tells you which account the key belongs to, so a wrong key fails here rather than halfway through. -
Look at what you have.
portfolio.snapshot()combines the account summary and your positions into totals and a list of holdings, each with its value, profit and share of the portfolio. -
Find the ticker.
instruments.resolve("Apple", { currency: "USD" })turns what a person would type into exactly one instrument. If nothing matches, or several match equally well, it throwsInstrumentNotFoundError, whosehintlists the closest tickers. -
Check the market.
exchanges.status(ticker)reads Trading 212’s trading hours. A market order placed while the market is closed is refused, so the program stops early and says when it next opens. -
Preview, then place the order.
{ dryRun: true }builds the exact request without sending it. Thenorders.buy()sends it, andorders.waitFor()checks it until it is filled, cancelled or rejected. Thecatchtells apart a refusal, where nothing was traded, from an unknown outcome, where you must check before trying again.
What you will see
Section titled “What you will see”Account 12345678 on demo, trading enabledTotal 10432.18, cash 2410.50Would send { 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 214 ms endpoint=placeMarketOrder status=200 …Order 4231112: FILLEDThe numbers are your account’s. If the market is closed, you will instead see when it next opens.
Try changing it
Section titled “Try changing it”- Sell instead:
t212.orders.sell({ ticker, quantity: 1 }), or everything you hold witht212.orders.sellAll(ticker). - Place a limit order that only fills at your price; see Orders.
- Run it against the fake Trading 212 instead of demo; see Testing your code.
- Make it run every morning; see Recipes.