Trading 212 API Update 🛠️

The apparent error that I can see from the shared code snippet, is the setting the quantity. To sell, you need to pass the quantity as negative. I can help further if you can share the code.

Hi!
I use the API mostly to get account data, and I still don’t use the Trading212 card, but I want to start as soon as I see that I can control my balance. So, it would be usefull:

  • Separate balance for Main Envelope and Expenses Envelope. I need to keep a record of my investmentes appart from my current expenses.
  • Notifications in the app for every use of the card, with information of cashback, so I can record the cash that got out, and where to, and what got in, and where to. Or some kind of API request that can give me the last operations of the card, with that info.
    I manage almost everything with my bank, but I want to change all that I can to T212, so this something I need to keep my records.
    Thanks in advance, and thanks for your services!
    FragMenthor.

Yes, I was passing the quantity as negative (the snippet shows the output only). I think the code works cause it worked to sell one but not the ones I had?

This is my code to buy/sell - the quantity is always a positive number, but in the payload I have a - in front of the value:

def buy(ticker, quantity):
    url = f"{API_BASE}/orders/market"
    payload = {
        "quantity": quantity,
        "ticker": ticker
    }

    print(f"Buying {quantity} x {ticker}")
    resp = requests.post(url, json=payload, headers=HEADERS, auth=(API_KEY,SECRET_KEY))
    data = resp.json()


def sell(ticker, quantity):
    url = f"{API_BASE}/orders/market"
    payload = {
        "quantity": -quantity,
        "ticker": ticker
    }

    print(f"Selling {quantity} x {ticker}")
    resp = requests.post(url, json=payload, headers=HEADERS, auth=(API_KEY,SECRET_KEY))
    data = resp.json()

I will do more testing and see if I can find out what’s going on…

Oh, I figured out why now… The reason was that I had a stop loss set for the original 90 shares so I could not sell any via the API. When I bought an extra one, this one had no stop loss so I could sell it with my code! :slight_smile:

2 Likes

I just multiply portfolio[‘quantity’] and portfolio[‘currentPrice‘] and I have current value in local currency.

I use metadata/instruments[‘shortName‘]. It can be historical, but I don’t have to parse the ticker.

Endpoint “/api/v0/equity/orders/market” doesn’t respect my account settings and sell my positions for main account currency (EUR) istead of asset currency. When I sell on WEB i sell for CAD, when I sell by API I sell for EUR.

Endpoint “/api/v0/equity/orders/market” requires “extendedHours” value, but theres no place in api where I can get this value.

It should be available in “Instrument List”, “Exchange List” or “Fetch all open positions” endopint, or the enpoint instead of throwing “ExtendedHoursTradingNotAllowed” exception should place the normal order if extended hours order is not allowed.

Now I have to place extended hour order, check exception, if exception exists I place normal order. One unnecessary api call.

1 Like

@KrisG After some testing, I finally figured out the issue… the API Beta currently works only with CFD accounts. I initially thought it also supported Invest accounts.

Is there any chance this feature will be made available for Invest accounts too? It would be great to have API access across both, especially since I generated the key from my Invest account.

My final launch test went smoothly… until I realised it was limited to CFD only, after doing a check which account type.

Hi,

currently this endpoint /api/v0/equity/account/cash returns summary balance in EUR currency. It would be nice to have separate balance for all currencies.

1 Like

ha! I missed this update about being available on live accounts…. AMAZING, thanks you @Team212 @KrisG It took about 30 seconds to read the docs and code against it. It works perfectly as far as I can tell so far. :melting_face:

1 Like

Thank you for adding market orders! That’s what we’ve all been waiting for :slight_smile:

It would be also great if you could add an option to pick which currency to use for orders. Or at least have the backend use the most suitable one instead of always the default.

Use case: I have both USD and EUR (default). I want to spend USD on US stocks, but right now it always takes EUR.

Also, sometimes it’s more useful to place orders by value, not by quantity. It would be great to have that option as well, or as others mentioned — have an easy way to get exchange rates, stock prices.

2 Likes

Hello. Has anyone already built such a tool or started integrating the new API for journaling/reporting purposes?

I’d really appreciate some guidance or examples on how to connect it with Notion or Google Sheets, ideally to automatically log trades, balances, and calculate profit/loss for tax reporting

Hello everyone,

Can someone please confirm whether the API Update is currently working with real Invest accounts, or if it’s still limited to CFD accounts only?

I’ve run several tests and got consistent results:
:one: Status 200 but HTML responses → API appears deliberately blocked
:two: Status 401/403 → Authentication rejected
:three: No functional API access even with correct credentials

Just trying to confirm whether this limitation is intentional or still being rolled out for Invest accounts.

Are pie market orders supported?

1 Like

I confirm. I use this API to get my portfolio and for market buy/sell in real account. You have to generate new API key, with secret.

1 Like

@KrisG @Bogi.H Using the app, I can buy 40 Tesla stocks, but when I am placing a buy order for 20 Tesla using api, it returns {‘code’: ‘UNDEFINED’, ‘clarification’: ‘InsufficientFreeForStocksException’}. I have retrieved the cash balance using API and it shows that I have sufficient cash. Please let me know if I am missing something. Thank you :folded_hands:

I have attached the code block.

BASE_URL = "https://live.trading212.com/api/v0"
def place_market_order(self, symbol, amount):
url = f"{BASE_URL}/equity/orders/market"
payload = {"extendedHours": True, "quantity": amount, "ticker": symbol}
headers = {"Content-Type": "application/json", "Authorization": self.header}
response = requests.post(url, json=payload, headers=headers)
data = response.json()
return data

Do you have enough EUR on you account? API won’t buy for USD.

In the app, you can place order up to 95% of your cash. The calculation for the 95% could be flawed. If I change the order to 2, it works. Hence, I can confirm that I can place orders with USD.

You can place orders with USD by API?

1 Like