bennycode / trading212-api

https://bennycode.com/trading212-api
MIT License
1 stars 1 forks source link
api exchange sdk stocks trading trading212 typescript

Trading 212 API for TypeScript

Language Details License Package Version


Motivation

This Trading 212 API can be used with TypeScript and comes with many useful features such as automatic reconnects and response validation.

Implemented Endpoints

Features

Usage

Installation

npm

npm install trading212-api

REST Example

The demo section provides many examples on how to use "trading212-api". There is also an automatically generated API documentation. For a quick start, here is a simple example for a REST request:

import {APIClient} from 'trading212-api';

const baseURL = APIClient.URL_LIVE;
const client = new APIClient(baseURL, 'apiKey');

const info = await client.rest.account.getInfo();
console.log(info);

API Key Generation

In order to generate an API key, you can follow the official instructions. Basically, you need to login, click on your account and do the following:

  1. Click "Switch to Practice" in order to generate an API key for the demo code, otherwise a live API key will be generated
  2. Go to "Settings"
  3. Click on "API (Beta)"

Development

If cloning the project locally, you can also add a .env file to configure the API client (see .env.defaults). This allows you to run all demo scripts.

Example

npm run demo:account

Browser API

[!CAUTION] The Trading212 Browser API is quite unstable. Even on their web client, authentication requests sometimes fail while other requests succeed.

The official Trading212 API does not support placing orders in a live environment. To address this, the library includes an experimental Browser API that uses a headless Chrome browser for programmatic trading.

The Browser API will need to log in with your username and password, so ensure you set the following environment parameters in your .env file:

TRADING212_HEADLESS_BROWSER=false
TRADING212_EMAIL=name@mail.com
TRADING212_PASSWORD=secret

This technique will log in locally using your credentials and save them in the "credentials" directory. This prevents unnecessary re-logins, as the login token remains valid for the session.

Here's how to use the Browser API:

import {initClient} from 'trading212-api';

const client = await initClient();

const accountSummary = await client.browser.accounts.getSummary();
console.log(accountSummary.cash.free);

Locally you can test it with:

npm start

Discoveries

The Trading212 Browser API will show this error when submitting an empty object ({}):

data: { code: 'InternalError' }

To fix it, we have to submit an empty array ([]):

await axios.post<AccountSummary>(ACCOUNT_SUMMARY_URL, [], {
  headers: {
    ...auth.headers,
    Cookie: toCookieString(cookies),
    'User-Agent': getUserAgent(),
    'X-Trader-Client': `application=WC4, version=1.0.0, dUUID=${duuid}`,
  },
});

When the "credentials" are wrong or expired, the API will show:

{
  "code": "AuthenticationFailed",
  "context": {
    "type": "InvalidSession"
  },
  "errorMessage": "Invalid account session cookie"
}

In such cases, simply delete the "credentials" directory and try again.

Inspiration

The Browser API is build on findings from the article "I Reverse-Engineered Trading212’s Web APIs ". You can find the matching Python code in the TradingTOT library on GitHub.

Internals

This library utilizes axios for HTTP calls. You can configure the axios instance using interceptors if needed. Retries are handled by axios-retry, and payloads are validated with Zod. Unit tests are implemented with nock and the headless browser is controlled via Playwright.

Contributions

Here are some best practices PRs that show how to add endpoints:

Resources

Documentation

Tools

Others