Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Trading 212 MCP ServerShow my open positions and total portfolio performance"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Trading 212 MCP Server
A comprehensive Model Context Protocol (MCP) server for seamless integration with the Trading 212 API. This server enables AI assistants like Claude to interact with your Trading 212 investment account, providing full access to account management, portfolio tracking, order execution, and historical data analysis.
Deployment Options:
Local installation with Node.js
Docker container (production-ready)
Docker Compose for easy orchestration
Features
π¦ Account Management
Get account information (currency, ID)
View cash balances (free, invested, blocked, total)
Retrieve comprehensive account summaries
π Portfolio Management
List all open positions
Get detailed position information by ticker
Real-time profit/loss tracking
π Order Management
View all active orders
Place market, limit, stop, and stop-limit orders
Cancel pending orders
Support for DAY and GTC (Good Till Cancelled) orders
Extended hours trading support
π Market Data & Instruments
Search and filter thousands of tradeable instruments
Access instrument metadata (ISIN, currency, type, trading schedules)
View exchange information and trading hours
π₯§ Investment Pies
List all investment pies (portfolio buckets)
Create new pies with custom allocations
Update and delete existing pies
Configure dividend reinvestment settings
π Historical Data
Access order history with pagination
Retrieve dividend payment records
View complete transaction history
Export data to CSV for specified time periods
β‘ Performance & Observability
Automatic rate limit tracking and headers
Zod schema validation for type safety
Comprehensive error handling with custom error classes
Production-grade structured logging (Pino)
Support for both demo and live environments
Debug mode for API request/response inspection
Installation
Prerequisites
Node.js 24+ installed
Trading 212 account (Invest or ISA)
Trading 212 API key (see Setup Guide)
Option 1: Docker (Recommended for Production)
The easiest way to deploy the MCP server is using Docker:
# Clone the repository
git clone https://github.com/enderekici/trading212-mcp.git
cd trading212-mcp
# Create .env file with your API key
echo "TRADING212_API_KEY=your_api_key_here" > .env
echo "TRADING212_ENVIRONMENT=demo" >> .env
# Start with Docker Compose
docker-compose up -dSee DOCKER.md for comprehensive Docker deployment guide.
Option 2: Local Installation
Install and build from source:
# Install dependencies
npm install
# Build the project
npm run buildConfiguration
Getting Your API Key
Open the Trading 212 app (mobile or web)
Navigate to Settings β API (Beta)
Click Generate API Key
Configure permissions:
β Account data (read) - View account information
β History (read) - Access historical data
β Orders (read/write) - View and place orders
β Portfolio (read) - View positions
(Optional) Set IP address whitelist for additional security
Copy your API key and store it securely
β οΈ Security Warning: Never commit your API key to version control or share it publicly.
Environment Variables
Create a .env file in the project root:
# Required: Your Trading 212 API key
TRADING212_API_KEY=your_api_key_here
# Optional: Environment (demo or live), defaults to demo
TRADING212_ENVIRONMENT=demo
# Optional: Log level (trace, debug, info, warn, error, fatal), defaults to info
LOG_LEVEL=info
# Optional: Node environment (development or production), defaults to development
NODE_ENV=developmentEnvironments:
demo- Paper trading environment (recommended for testing)API Base URL:
https://demo.trading212.com/api/v0Uses paper trading account (no real money)
Safe for testing and development
Default value if not specified
live- Real money trading environmentAPI Base URL:
https://live.trading212.com/api/v0Uses real money trading account
Use with caution
β οΈ Important: Your API key is environment-specific. A demo API key only works with TRADING212_ENVIRONMENT=demo, and a live API key only works with TRADING212_ENVIRONMENT=live. You cannot mix them.
π For detailed information about environments, see
Log Levels:
trace- Most verbose, logs every detaildebug- Detailed logs including API requests, rate limits, and debug infoinfo- Standard operation logs (default, recommended)warn- Only warnings and errorserror- Only errorsfatal- Only fatal errors
Node Environment:
development- Pretty-printed colored logs (human-readable)production- JSON logs (for structured logging systems)
MCP Integration
This server works with any MCP-compatible client. It supports two transports:
Transport | Use when | Start command |
stdio | Client spawns the process |
|
Streamable HTTP | Server runs separately |
|
Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):
Stdio (recommended):
{
"mcpServers": {
"trading212": {
"command": "trading212-mcp",
"env": {
"TRADING212_API_KEY": "your_api_key_here",
"TRADING212_ENVIRONMENT": "demo"
}
}
}
}HTTP (start server first with
{
"mcpServers": {
"trading212": {
"url": "http://localhost:3012/mcp"
}
}
}Docker (stdio):
{
"mcpServers": {
"trading212": {
"command": "docker",
"args": [
"run", "--rm", "-i",
"-e", "TRADING212_API_KEY=your_api_key_here",
"-e", "TRADING212_ENVIRONMENT=demo",
"trading212-mcp:latest"
]
}
}
}Claude Code
Add to .claude/settings.json or run claude mcp add:
Stdio:
{
"mcpServers": {
"trading212": {
"command": "trading212-mcp",
"env": {
"TRADING212_API_KEY": "your_api_key_here",
"TRADING212_ENVIRONMENT": "demo"
}
}
}
}HTTP (start server first):
{
"mcpServers": {
"trading212": {
"url": "http://localhost:3012/mcp"
}
}
}Cursor
Add to Cursor's MCP settings (Settings > MCP Servers > Add):
{
"mcpServers": {
"trading212": {
"command": "trading212-mcp",
"env": {
"TRADING212_API_KEY": "your_api_key_here",
"TRADING212_ENVIRONMENT": "demo"
}
}
}
}Windsurf
Add to ~/.codeium/windsurf/mcp_config.json:
{
"mcpServers": {
"trading212": {
"command": "trading212-mcp",
"env": {
"TRADING212_API_KEY": "your_api_key_here",
"TRADING212_ENVIRONMENT": "demo"
}
}
}
}VS Code (Copilot)
Add to .vscode/mcp.json in your workspace or user settings:
{
"servers": {
"trading212": {
"command": "trading212-mcp",
"env": {
"TRADING212_API_KEY": "your_api_key_here",
"TRADING212_ENVIRONMENT": "demo"
}
}
}
}Gemini CLI
Add to ~/.gemini/settings.json:
{
"mcpServers": {
"trading212": {
"command": "trading212-mcp",
"env": {
"TRADING212_API_KEY": "your_api_key_here",
"TRADING212_ENVIRONMENT": "demo"
}
}
}
}OpenAI Codex CLI
Add to ~/.codex/config.json:
{
"mcpServers": {
"trading212": {
"command": "trading212-mcp",
"env": {
"TRADING212_API_KEY": "your_api_key_here",
"TRADING212_ENVIRONMENT": "demo"
}
}
}
}Any MCP-Compatible Client
For stdio, point your client at the trading212-mcp command (or node dist/index.js) with the required env vars. For HTTP, start the server first (trading212-mcp --http --port 3012) and point your client at http://localhost:3012/mcp.
Setup Methods Comparison
Method | Pros | Cons | Best For |
Global npm | Fast, simple | Requires Node.js installed | Most users |
Docker (stdio) | Isolated, consistent | Slightly slower startup (~2s) | Production, teams |
HTTP transport | Decoupled, shareable | Must start server separately | Remote, multi-client |
Local build | Full control | Manual updates | Contributors |
See DOCKER.md for advanced Docker deployment options including persistent containers.
Available Tools
Account Management
get_account_info
Retrieve account metadata including currency code and account ID.
Example:
Get my account informationget_account_cash
Get detailed cash balance information.
Returns: Free cash, total, invested, blocked amounts, and more.
Example:
How much cash do I have available?get_account_summary
Get comprehensive account summary with all balances and P&L.
Example:
Show me my complete account summaryPortfolio Management
get_portfolio
List all open positions with current values and profit/loss.
Example:
What stocks do I own?get_position
Get detailed information about a specific position.
Parameters:
ticker(string, required) - The ticker symbol (e.g., "AAPL", "TSLA")
Example:
Show me my Apple position detailsOrder Management
get_orders
Retrieve all active orders.
Example:
What are my pending orders?get_order
Get detailed information about a specific order.
Parameters:
orderId(number, required) - The order ID
Example:
Show me details for order 12345cancel_order
Cancel an active order.
Parameters:
orderId(number, required) - The order ID to cancel
Example:
Cancel order 12345place_market_order
Place a market order to execute immediately at the current market price.
Parameters:
ticker(string, required) - Ticker symbolquantity(number, required) - Quantity to buy (positive) or sell (negative)timeValidity(string, optional) - "DAY" or "GTC" (default: "DAY")
Example:
Buy 10 shares of Apple at market priceplace_limit_order
Place a limit order to execute at a specified price or better.
Parameters:
ticker(string, required) - Ticker symbolquantity(number, required) - Quantity to buy/selllimitPrice(number, required) - Maximum buy price or minimum sell pricetimeValidity(string, optional) - "DAY" or "GTC"
Example:
Place a limit order to buy 5 shares of Tesla at $200place_stop_order
Place a stop order that becomes a market order when triggered.
Parameters:
ticker(string, required) - Ticker symbolquantity(number, required) - Quantity to buy/sellstopPrice(number, required) - Price that triggers the ordertimeValidity(string, optional) - "DAY" or "GTC"
Example:
Place a stop order to sell 10 shares of MSFT if price drops below $300place_stop_limit_order
Place a stop-limit order that becomes a limit order when triggered.
Parameters:
ticker(string, required) - Ticker symbolquantity(number, required) - Quantity to buy/sellstopPrice(number, required) - Price that triggers the orderlimitPrice(number, required) - Limit price once triggeredtimeValidity(string, optional) - "DAY" or "GTC"
Example:
Place a stop-limit order to sell GOOGL at $140 with stop at $145Instruments & Market Data
get_instruments
List all tradeable instruments with optional search filtering.
Parameters:
search(string, optional) - Filter by ticker, name, or ISIN
Example:
Search for all Apple instrumentsget_exchanges
Get information about exchanges and trading schedules.
Example:
Show me exchange trading hoursInvestment Pies
get_pies
List all investment pies with their configurations.
Example:
Show me all my piesget_pie
Get detailed information about a specific pie.
Parameters:
pieId(number, required) - The pie ID
Example:
Show details for pie 123create_pie
Create a new investment pie.
Parameters:
name(string, required) - Pie name (1-50 characters)icon(string, required) - Icon identifierinstrumentShares(object, required) - Ticker to allocation mappingdividendCashAction(string, required) - "REINVEST" or "TO_ACCOUNT_CASH"goal(number, optional) - Investment goal amount
Example:
Create a new pie called "Tech Portfolio" with 50% AAPL and 50% GOOGL, reinvesting dividendsupdate_pie
Update an existing pie configuration.
Parameters:
pieId(number, required) - The pie IDOther parameters same as create_pie (all optional)
Example:
Update pie 123 to change allocation to 60% AAPL and 40% GOOGLdelete_pie
Delete an investment pie.
Parameters:
pieId(number, required) - The pie ID to delete
Example:
Delete pie 123Historical Data
get_order_history
Get historical orders with pagination support.
Parameters:
cursor(number, optional) - Pagination cursorlimit(number, optional) - Results per page (default: 50)ticker(string, optional) - Filter by ticker
Example:
Show me my order history for the last monthget_dividends
Get dividend payment history.
Parameters:
cursor(number, optional) - Pagination cursorlimit(number, optional) - Results per pageticker(string, optional) - Filter by ticker
Example:
Show me all dividends received this yearget_transactions
Get complete transaction history.
Parameters:
cursor(number, optional) - Pagination cursorlimit(number, optional) - Results per page
Example:
Show me my recent transactionsrequest_export
Request a CSV export of account data.
Parameters:
timeFrom(string, required) - Start date (ISO 8601 format)timeTo(string, required) - End date (ISO 8601 format)includeDividends(boolean, optional) - Include dividends (default: true)includeInterest(boolean, optional) - Include interest (default: true)includeOrders(boolean, optional) - Include orders (default: true)includeTransactions(boolean, optional) - Include transactions (default: true)
Example:
Export all my data from January 1st to December 31st 2024Example Conversations
Portfolio Analysis
User: What's my current portfolio performance?
Claude: Let me check your account summary and portfolio.
[Calls get_account_summary and get_portfolio]
You have a total portfolio value of $10,523.45 with an overall profit of $523.45 (+5.2%).
Your positions:
- AAPL: 10 shares at $150.00 (avg $145.00) - +$50.00 profit
- GOOGL: 5 shares at $140.00 (avg $135.00) - +$25.00 profit
- TSLA: 8 shares at $200.00 (avg $210.00) - -$80.00 lossOrder Placement
User: Buy 5 shares of Microsoft at market price
Claude: I'll place a market order for 5 shares of MSFT.
[Calls place_market_order]
Order placed successfully:
- Order ID: 12345
- Ticker: MSFT
- Quantity: 5
- Type: MARKET
- Status: CONFIRMED
- Filled at: $350.25 per shareHistorical Analysis
User: How much have I received in dividends this year?
Claude: Let me check your dividend history.
[Calls get_dividends]
You've received $125.50 in dividends this year:
- AAPL: $45.00 (3 payments)
- MSFT: $50.50 (4 payments)
- JNJ: $30.00 (2 payments)Rate Limits
Trading 212 API enforces rate limits on a per-endpoint basis. This MCP server automatically tracks rate limit information via response headers:
x-ratelimit-limit- Maximum requests allowedx-ratelimit-remaining- Requests remainingx-ratelimit-reset- Unix timestamp when limit resets
Known Limits:
Account Summary: 1 request / 5 seconds
Market Orders: 1 request / 2 seconds
Limit Orders: 1 request / 2 seconds
The server will throw an error if you exceed rate limits. Always check the error messages for rate limit information.
Error Handling
All errors are returned with descriptive messages:
{
"error": "Trading 212 API Error (401): Invalid API key"
}Common errors:
401 Unauthorized - Invalid API key
403 Forbidden - Insufficient permissions
404 Not Found - Resource doesn't exist
429 Too Many Requests - Rate limit exceeded
500 Internal Server Error - Trading 212 service issue
Development
Run in Development Mode
npm run devBuild for Production
npm run buildWatch Mode (Auto-rebuild)
npm run watchAPI Documentation
For complete API documentation, visit:
Supported Account Types
β Invest Accounts (General trading accounts)
β ISA Accounts (UK tax-advantaged accounts)
β CFD Accounts (Not supported by Trading 212 API)
Limitations
API is currently in BETA and under active development
No WebSocket/streaming support (REST only)
Pies API is deprecated and won't receive further updates
CFD accounts are not supported
Rate limits apply per account (not per API key)
Security Best Practices
Never commit API keys to version control
Use environment variables for sensitive configuration
Enable IP whitelisting if possible
Test in demo environment before using live
Use minimal permissions needed for your use case
Rotate API keys regularly
Monitor API usage through rate limit headers
Logging and Debugging
The Trading 212 MCP server includes professional structured logging powered by Pino, providing production-grade observability and debugging capabilities.
Log Levels
Control logging verbosity with the LOG_LEVEL environment variable:
# Development - detailed logs
LOG_LEVEL=debug npm run dev
# Production - minimal logs
LOG_LEVEL=warn node dist/index.jsAvailable levels (from most to least verbose):
trace- Everything including internal detailsdebug- API requests, rate limits, detailed operationsinfo- Server startup, tool executions (default)warn- Warnings and potential issueserror- Errors onlyfatal- Fatal errors causing shutdown
Log Output Formats
Development mode (pretty-printed, colored):
NODE_ENV=development npm run devExample output:
[16:32:15.423] INFO: Starting Trading 212 MCP server
environment: "demo"
version: "1.0.0"
nodeVersion: "v20.10.0"
platform: "darwin"
logLevel: "info"Production mode (structured JSON):
NODE_ENV=production npm startExample output:
{"level":"info","time":"2026-02-10T16:32:15.423Z","msg":"Starting Trading 212 MCP server","environment":"demo","version":"1.0.0"}Debugging API Requests
Enable debug logging to see all API calls and rate limit info:
LOG_LEVEL=debug node dist/index.jsDebug logs include:
API request method and endpoint
Rate limit headers (limit, remaining, reset time)
Warnings when approaching rate limits
Request/response timing
Error details with context
Error Tracking
The server uses structured error classes for better debugging:
AuthError- API key issues (401)ApiError- API request failures (4xx, 5xx)RateLimitError- Rate limit exceeded (429)ValidationError- Invalid request parameters (400)
All errors are logged with:
Error type and code
HTTP status code
Contextual information
Request details
Stack traces (in non-production)
Example Debug Session
# Enable detailed logging
export LOG_LEVEL=debug
export NODE_ENV=development
# Run the server
npm run devLook for these log entries:
[DEBUG] API request - Shows every API call
[DEBUG] Rate limit info - Track API quota usage
[WARN] Approaching rate limit - Proactive warnings
[ERROR] Tool execution failed - Detailed error contextLogging in Claude Desktop
When running through Claude Desktop, logs are written to stderr and can be viewed in:
macOS:
tail -f ~/Library/Logs/Claude/mcp*.logWindows:
Get-Content "$env:APPDATA\Claude\Logs\mcp*.log" -WaitTroubleshooting
Server Not Appearing in Claude Desktop
Verify the path in
claude_desktop_config.jsonis absoluteEnsure the project is built (
npm run build)Check that
dist/index.jsexistsRestart Claude Desktop completely
Check Claude Desktop logs for errors
Authentication Errors
Verify API key is correct in
.envor configCheck that API key has required permissions
Ensure you're using the correct environment (demo/live)
Verify IP whitelist settings if enabled
Rate Limit Errors
Wait for the rate limit window to reset
Check
x-ratelimit-resetheader for reset timeReduce frequency of API calls
Implement caching where appropriate
Contributing
Contributions are welcome! Please:
Fork the repository
Create a feature branch
Make your changes with tests
Submit a pull request
License
MIT License - see LICENSE file for details
Disclaimer
This is an unofficial integration. Always test thoroughly in the demo environment before using with real money. Trading involves risk, and you should only invest what you can afford to lose.
Support
For issues with this MCP server:
Open an issue on GitHub
For Trading 212 API issues:
Acknowledgments
Built with:
Zod for schema validation
Made with β€οΈ for the Trading 212 and AI community