go-trading212

December 6, 2025 ยท View on GitHub

Go Reference GitHub Tag License Go Version coded-by-badge

Release Status Coverage Status Testing Status

A comprehensive Go client library for interacting with the Trading212 Rest API. This library provides a type-safe, idiomatic Go interface for managing your Trading212 account, placing orders, monitoring positions, and accessing historical trading data.

Features

  • ๐Ÿ” Secure Authentication - Built-in support for API key and secret authentication with secure string handling
  • ๐Ÿ“Š Account Management - Retrieve account summaries, cash balances, and investment metrics
  • ๐Ÿ“ˆ Order Management - Place and manage market, limit, stop, and stop-limit orders
  • ๐Ÿ” Instrument Discovery - Browse available instruments and exchange metadata
  • ๐Ÿ“ Position Tracking - Monitor open positions with real-time profit/loss data
  • ๐Ÿ“œ Historical Data - Access trading history, dividends, transactions, and generate CSV reports
  • ๐Ÿฅง Pies Management - Manage investment pies (deprecated API)
  • โšก Rate Limiting - Built-in rate limit handling to respect API constraints
  • ๐ŸŽฏ Type Safety - Full type safety with Go's strong typing system
  • ๐Ÿ”„ Iterator Support - Modern iterator-based API for streaming large datasets

Installation

go get github.com/cyrbil/go-trading212

Quick Start

Basic Setup

package main

import (
    "fmt"
    "log"
    
    "github.com/cyrbil/go-trading212/pkg/trading212"
)

func main() {
    // Initialize the API client
    api := trading212.NewAPILive(
        "your-api-key",
        "your-api-secret",
    )
    
    // Get account summary
    summary, err := api.Account.GetAccountSummary()
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Account ID: %d\n", summary.Id)
    fmt.Printf("Currency: %s\n", summary.Currency)
    fmt.Printf("Total Value: %.2f\n", summary.TotalValue)
    fmt.Printf("Available to Trade: %.2f\n", summary.Cash.AvailableToTrade)
}

Get All Open Positions

// Retrieve all open positions
positions, err := api.Positions.GetAllPositions()
if err != nil {
    log.Fatal(err)
}

for position := range positions {
    fmt.Printf("Position: %s - Quantity: %.2f - P/L: %.2f\n",
        position.Ticker,
        position.Quantity,
        position.UnrealizedProfitLoss,
    )
}

API Overview

The library is organized into logical operation groups:

Account Operations

  • GetAccountSummary() - Get account details, cash balance, and investment metrics

Instrument Operations

  • GetExchangesMetadata() - Get all exchanges and their working schedules
  • GetAllAvailableInstruments() - Get all tradable instruments

Order Operations

  • PlaceMarketOrder() - Place a market order
  • PlaceLimitOrder() - Place a limit order
  • PlaceStopOrder() - Place a stop order
  • PlaceStopLimitOrder() - Place a stop-limit order
  • GetAllPendingOrders() - Get all active orders
  • GetPendingOrderByID() - Get a specific pending order
  • CancelOrder() - Cancel an active order

Position Operations

  • GetAllPositions() - Get all open positions

Historical Events Operations

  • GetPaidOutDividends() - Get dividend payment history
  • GetHistoricalOrders() - Get historical order fills
  • GetTransactions() - Get account transactions
  • ListReports() - List available CSV reports
  • RequestReport() - Request a new CSV report

Pies Operations (Deprecated)

  • FetchAllPies() - Get all investment pies
  • CreatePie() - Create a new pie
  • FetchPie() - Get pie details
  • UpdatePie() - Update a pie
  • DeletePie() - Delete a pie
  • DuplicatePies() - Duplicate a pie

Configuration

API Domains

The library also supports demo or any trading212 environments:

// Demo environment (for testing)
api := trading212.NewAPI(
    trading212.APIDomainDemo,
    apiKey,
    apiSecret,
)

// Custom environment
api := trading212.NewAPI(
    trading212.APIDomain("api.domain"),
    apiKey,
    apiSecret,
)

Secure String

The library uses a SecureString type for API secrets to prevent accidental logging of sensitive credentials:

apiSecret := trading212.SecureString("your-secret-key")
// When printed, this will show "[REDACTED]" instead of the actual value
fmt.Println(apiSecret) // Output: [REDACTED]

Error Handling

All operations return errors that should be checked:

summary, err := api.Account().GetAccountSummary()
if err != nil {
    // Handle error appropriately
    log.Printf("Failed to get account summary: %v", err)
    return
}
// Use summary...

Rate Limiting

The library includes built-in rate limiting support. Rate limits are automatically tracked per endpoint to ensure compliance with Trading212 API constraints.

Requirements

  • Go 1.23 or higher
  • A Trading212 account with API access enabled
  • Valid API key and secret

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.

Disclaimer

This library is not affiliated with, endorsed by, or sponsored by Trading212. Use at your own risk.