trading-mcp-server
The trading-mcp-server provides AI agents with comprehensive tools for market analysis, strategy development, paper trading, and guarded live order execution (focused on Indian markets via NSE/Angel One SmartAPI).
Configuration & Mode Management
Get/update trading config, check effective trading mode (notify/paper/live), switch between paper and live modes, validate trading permissions.
Live trading requires an explicit
ALLOW_LIVE_TRADINGsafeguard set by a human in.env.
Market Data
Fetch live prices, historical OHLCV candles (multiple timeframes), market status, symbol metadata (token, lot size, tick size), and curated watchlist symbols.
Technical Indicators
Calculate SMA, EMA, RSI, MACD, Bollinger Bands, ATR, and volume analysis; detect support/resistance levels and trend direction; get all standard indicators in one snapshot call.
News & Sentiment
Fetch symbol-specific news with per-item sentiment, browse Indian market news by category/sentiment, get overall market mood, sector-by-sector sentiment, free-text news search (NewsAPI), and aggregate sentiment analysis.
Portfolio & Order History
Fetch portfolio and order history (paper or live), calculate per-position exposure vs. limits, and unrealized P&L.
Risk Calculators
Position sizing (risk % + stop-loss), ATR-based stop-loss suggestions, target price for desired R:R ratio, max daily loss check, portfolio concentration check, and full pre-trade validation.
Strategy Evaluation & Backtesting
Evaluate intraday (multi-timeframe) and swing trade setups, compare indicator snapshots for up to 10 symbols side-by-side, scan watchlist for intraday/swing opportunities ranked by confidence, and backtest built-in strategies (MA crossover, RSI reversal, MACD trend, breakout volume).
Paper Trading Engine
Place/close simulated orders, fetch paper trades and portfolio, calculate performance metrics (win rate, P&L, drawdown), generate full reports, and reset the account to starting capital.
Guarded Live Order Execution
Stage/validate orders (returns approval token) without executing, re-run validation separately, execute prepared intraday or delivery BUY orders after human approval token, block delivery SELL orders (recorded as recommendations only, never sent to broker), and list/cancel pending live orders.
Broker Read-Only Access
Fetch broker funds/margins, today's positions, delivery holdings, and order status by ID.
Notifications
Send free-text messages via Telegram or Discord, and send formatted 'ACTION REQUIRED' trade recommendation alerts.
Safety & Audit: All orders are logged; live trading requires explicit human approval via both an .env switch and a per-order token; delivery sell orders are never automatically executed.
Click on "Deploy 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-mcp-server evaluate intraday trade setup for RELIANCE"
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-mcp-server
A local MCP (Model Context Protocol) server that exposes safe trading tools for AI agents such as Claude Code and Copilot CLI. The agent does the reasoning; this server provides market data, technical indicators, news, sizing helpers, a paper-trading engine, backtesting, and a guarded broker layer (Angel One SmartAPI, NSE).
Execution model — one switch, three modes (EXECUTION_MODE):
notify—place_orderreturns a manual-placement recommendation (and a Telegram alert if configured). Nothing is executed.paper—place_orderfills in a simulated paper account. (default)live—place_orderplaces a real order — but only whenALLOW_LIVE_TRADING=true(a human-only switch in.env; no tool can change it). With it off, live orders degrade to notify.
Safety guarantees:
The broker is reached only when
EXECUTION_MODE=liveandALLOW_LIVE_TRADING=true.Delivery (CNC) sell is never sent to the broker in any mode — it always degrades to a notify recommendation so the user can verify holdings and sell manually.
Every order decision is appended to an audit log (
storage/trade_logs.jsonl).
Where trading policy lives: risk limits, intraday/swing selection, and position sizing are not in the server — they live in a client-side trading_config.yaml that your agent reads and enforces. The server only validates that orders are structurally well-formed. See docs/CLIENT_INTEGRATION.md.
Nothing produced by this server is financial advice.
Installation
# local development (editable, from a sibling checkout)
pip install -e ../trading-mcp-server
# with broker + scanner extras (needed for live data / Chartink watchlist)
pip install -e "../trading-mcp-server[broker,scanners]"
# future, once published to PyPI
pip install trading-mcp-serverRequires Python 3.10+.
Related MCP server: GearTrade MCP Server
Running the server
The server speaks MCP over stdio:
trading-mcp-server
# or
python -m trading_mcp_server.serverIt resolves its configuration and state from a home directory:
TRADING_MCP_HOMEenvironment variable, if setotherwise the current working directory
There it reads <home>/.env (execution mode, the live master switch, broker credentials) and writes <home>/storage/ (paper-trading state, audit log). This keeps the package independent of any repo path — point TRADING_MCP_HOME at your trading project.
Register in a client (e.g. .mcp.json for Claude Code):
{
"mcpServers": {
"trading-agent": {
"command": "trading-mcp-server",
"env": { "TRADING_MCP_HOME": "C:\\path\\to\\your\\trading-repo" }
}
}
}What it exposes
Tools (by category)
Category | Tools |
Config |
|
Market data |
|
Indicators |
|
News |
|
Portfolio |
|
Risk (calculators) |
|
Strategy |
|
Paper trading |
|
Order execution |
|
Broker (read) |
|
Notifications |
|
To open a position use
place_order(it routes to the paper engine in paper mode, the broker in live mode, or a recommendation in notify mode). Risk policy is enforced by your agent viatrading_config.yaml— see docs/CLIENT_INTEGRATION.md.
Resources
trading://config— current configuration (secrets redacted)trading://safety-rules— the safety rules the server enforces
Prompts
intraday_trade_analysis(symbol)— disciplined intraday workflowswing_trade_analysis(symbol)— swing/delivery workflowpaper_trading_review()— profitability review workflow
Backtest strategies built in: ma_crossover, rsi_reversal, macd_trend, breakout_volume.
Package structure
src/trading_mcp_server/
├── server.py # FastMCP entry point (create_server, main)
├── config.py # .env-backed TradingConfig — single source of truth
├── tools/ # MCP tool modules (one per category, register(mcp))
├── resources/ # MCP resources
├── prompts/ # MCP prompts
├── services/ # data provider, indicators, risk, validation, paper engine, broker safety layer
├── broker/ # SmartAPI adapter — the ONLY module talking to the real broker
├── backtest/ # engine + built-in strategies
└── utils/ # logging/audit, market hours, instrument lookup
tests/ # pytest suite (config, safety, paper engine, indicators, backtest)Development
pip install -e ".[dev]"
python -m pytest tests -q # run tests (no network, no broker needed)
python -m trading_mcp_server.server # run server from sourceConfiguration reference
The server reads only a few execution switches from <home>/.env (template:
examples/.env.example):
Key | Values | Notes |
|
| the one switch; default |
|
| human-only; live orders place only when |
|
| Telegram alert on paper fills |
| number | paper engine capital |
| secrets | Angel One credentials (live + live data) |
| secret | optional news search |
| secrets | Telegram notifications |
| secrets | Discord notifications |
Trading policy (risk limits, intraday/swing, sizing) is not here — it lives
in a client-side trading_config.yaml read by your agent. Template:
examples/trading_config.example.yaml.
Full guide: docs/CLIENT_INTEGRATION.md.
Publishing to PyPI (future)
Bump
versioninpyproject.tomlandsrc/trading_mcp_server/__init__.py.python -m build(requirespip install build).python -m twine upload dist/*(requires a PyPI account + API token).Consumers then switch from
pip install -e ../trading-mcp-servertopip install trading-mcp-server— no other change needed.
License
MIT
Available Tools
63 toolsanalyze_news_sentimentB
Aggregate sentiment counts for a symbol's recent news. The agent should read the texts (fetch_latest_news) for nuance — this is just the tally. For a market-wide read use get_market_sentiment instead.
Inputs: symbol (required).
block_delivery_sell_orderA
Record a delivery-sell RECOMMENDATION. The order is never sent to the broker — delivery sells require manual verification by the user.
Inputs: symbol (required), quantity (required), reason.
calculate_atrC
Average True Range — useful for stop-loss placement.
Inputs: symbol (required), period, timeframe.
calculate_bollinger_bandsC
Bollinger bands (latest values).
Inputs: symbol (required), period, timeframe.
calculate_emaC
Exponential moving average (latest value).
Inputs: symbol (required), period, timeframe.
calculate_macdC
MACD line, signal and histogram (latest values).
Inputs: symbol (required), timeframe.
calculate_paper_trading_performanceA
Performance metrics: win rate, P&L, drawdown — overall, per product type, and per strategy. Use this to judge profitability before considering live mode.
Inputs: no named parameters.
calculate_portfolio_exposureC
Per-position exposure vs MAX_POSITION_SIZE_PERCENT (paper portfolio).
Inputs: no named parameters.
calculate_position_sizeC
Quantity so the stop-loss loss equals risk_percent of capital, capped by MAX_POSITION_SIZE_PERCENT.
Inputs: capital (required), risk_percent (required), entry_price (required), stop_loss (required).
calculate_rsiC
Wilder RSI (latest value).
Inputs: symbol (required), period, timeframe.
calculate_smaC
Simple moving average (latest value).
Inputs: symbol (required), period, timeframe.
calculate_stop_lossC
ATR-based stop-loss suggestion from current price.
Inputs: symbol (required), side, atr_multiplier, timeframe.
calculate_target_priceB
Target price for a desired risk:reward given entry and stop.
Inputs: entry_price (required), stop_loss (required), risk_reward_ratio.
calculate_unrealized_pnlB
Paper portfolio P&L. Pass live_prices as {symbol: ltp} (e.g. from fetch_live_price) to include unrealized P&L.
Inputs: live_prices.
calculate_volume_analysisC
Volume vs its EMA, spike detection, 20-bar average.
Inputs: symbol (required), timeframe.
cancel_pending_live_orderC
Cancel a prepared live order before execution.
Inputs: approval_token (required).
check_max_daily_lossB
Whether today's realized paper P&L has hit MAX_DAILY_LOSS_PERCENT.
Inputs: no named parameters.
check_portfolio_concentrationC
Concentration check across open paper positions.
Inputs: no named parameters.
close_paper_positionC
Close an open paper position at the given price (or live LTP).
Inputs: symbol (required), product_type, price.
compare_multiple_symbolsB
Side-by-side indicator snapshots for up to 10 symbols.
Inputs: symbols (required), timeframe.
detect_support_resistanceC
Support/resistance levels from clustered swing pivots.
Inputs: symbol (required), timeframe.
detect_trendC
Trend direction from EMA stack + regression slope.
Inputs: symbol (required), timeframe.
evaluate_intraday_trade_setupB
Multi-timeframe (daily/1h/15m) intraday setup with a mechanical trade plan and confidence score.
Inputs: symbol (required).
evaluate_swing_trade_setupC
Daily-timeframe swing/delivery setup with support/resistance and a mechanical trade plan.
Inputs: symbol (required).
execute_delivery_buy_after_validationB
Execute a prepared DELIVERY BUY live order. Only call after the human has explicitly approved. Delivery SELL can never be executed through this system.
Inputs: approval_token (required).
execute_intraday_order_after_validationA
Execute a prepared INTRADAY live order. Only call after the human has explicitly approved the prepared order shown to them.
Inputs: approval_token (required).
fetch_broker_fundsA
Available funds/margins from the broker (requires credentials).
Inputs: no named parameters.
fetch_broker_holdingsC
Delivery holdings from the broker.
Inputs: no named parameters.
fetch_broker_order_statusC
Status of a broker order by id.
Inputs: order_id (required).
fetch_broker_positionsC
Today's positions from the broker.
Inputs: no named parameters.
fetch_historical_dataB
Historical OHLCV candles. timeframe: ONE_MINUTE|FIVE_MINUTE|FIFTEEN_MINUTE| THIRTY_MINUTE|ONE_HOUR|ONE_DAY. Dates ISO format (optional).
Inputs: symbol (required), timeframe, start_date, end_date, +1 more.
fetch_latest_newsA
Latest news items for one symbol with per-item sentiment. Matches the exact ticker OR a substring of the company name. The feed is the broad Indian-market stream (often small/mid-caps), so a given symbol may have no items right now — an empty list is a valid 'no recent news' answer.
Inputs: symbol (required).
fetch_live_priceA
Last traded price for an NSE symbol (requires broker credentials).
Inputs: symbol (required).
fetch_market_newsA
Broad Indian-market news feed (Tradient, free).
category: all | companies | <sub_category>, where sub_category is one of earnings-financial-results | corporate-actions | operational-updates | management-leadership | legal-compliance | product-launches-innovation | others. Matched against both category and sub_category. sentiment: all | positive | negative | neutral.
Each item: symbol, stock_name, title, text, sentiment, category, sub_category, sector, publish_date (epoch ms).
Inputs: category, sentiment.
fetch_market_statusC
Whether the market is open, pre-open or closed right now (IST).
Inputs: exchange.
fetch_news_articlesA
Free-text news search via NewsAPI (newsapi.org). Requires NEWS_API_KEY in the env. Best for stock-specific or thematic news the Tradient feed misses (e.g. 'Reliance Q1 results', 'RBI rate decision'). Leave query empty for broad Indian-market news (NSE/BSE/Nifty/FII/GDP/RBI...) — useful for a general market read. NewsAPI provides NO sentiment label — read article_text to judge. Set full_text=True to also fetch each article's body (slower). days = lookback window in days (default 1). indian_only (default True) restricts results to Indian financial-news sources; set False for global coverage. Returns raw articles.
Inputs: query, days, full_text, indian_only.
fetch_order_historyB
Order history for the effective mode (paper orders, or broker order book).
Inputs: no named parameters.
fetch_paper_portfolioA
Paper account: cash, open positions, realized P&L.
Inputs: no named parameters.
fetch_paper_tradesC
Closed paper trades, optionally filtered by INTRADAY or DELIVERY.
Inputs: product_type.
fetch_portfolioA
Portfolio for the EFFECTIVE mode: paper portfolio in paper mode, broker holdings+positions in live mode.
Inputs: no named parameters.
fetch_symbol_metadataB
Instrument metadata: token, exchange, lot size, tick size.
Inputs: symbol (required).
fetch_watchlistA
Watchlist symbols: Chartink monthly-uptrend + RSI>50 scan, falling back to a static NIFTY list when the scan is unavailable.
Inputs: no named parameters.
generate_paper_trading_reportA
Full paper-trading report (performance + portfolio + recent trades).
Inputs: no named parameters.
get_current_trading_modeA
Effective trading mode. 'live' only when TRADING_MODE=live AND ALLOW_LIVE_TRADING=true.
Inputs: no named parameters.
get_indicator_snapshotA
All standard indicators in one call (RSI, EMAs, MACD, Bollinger, ATR, volume, trend, VWAP on intraday timeframes). Prefer this over many single calls.
Inputs: symbol (required), timeframe.
get_market_sentimentA
Overall market sentiment and trends from the whole news feed. Returns a sentiment tally + percentages, an overall mood (bullish|bearish|neutral), the most active themes (sub-categories), and representative positive/ negative headlines. Use this for a top-down read of market mood before drilling into a specific symbol.
Inputs: no named parameters.
get_sector_sentimentA
Sentiment broken down by sector (from the Tradient feed). Returns each sector with a positive/negative/neutral tally and a mood label, sorted by news volume. Use to see which sectors are active and how the mood skews.
Inputs: no named parameters.
get_trading_configA
Current trading configuration (secrets redacted). The single source of truth for mode, permissions and risk limits.
Inputs: no named parameters.
list_pending_live_ordersC
Prepared live orders awaiting human approval.
Inputs: no named parameters.
place_paper_orderA
Place a SIMULATED order in the paper account. If price is omitted the live LTP is used (requires broker credentials). The full validation checklist is enforced here too.
Inputs: symbol (required), side (required), quantity (required), price, +5 more.
prepare_orderA
Validate and STAGE an order. Never executes. In live mode returns an approval_token; the human must approve before execution. Delivery sells are blocked and returned as recommendation-only.
Inputs: symbol (required), side (required), quantity (required), entry_price (required), +4 more.
reset_paper_accountA
Reset the paper account to starting capital, erasing simulated history. Requires confirm=true.
Inputs: confirm.
run_strategy_backtestB
Backtest a built-in strategy (ma_crossover | rsi_reversal | macd_trend | breakout_volume) on historical data. Returns trades, win rate, P&L, drawdown.
Inputs: strategy_name (required), symbol (required), timeframe, start_date, +2 more.
scan_watchlist_for_intraday_opportunitiesA
Evaluate the watchlist for intraday setups, ranked by confidence score. Slow: fetches three timeframes per symbol.
Inputs: max_symbols.
scan_watchlist_for_swing_opportunitiesC
Evaluate the watchlist for swing setups, ranked by confidence score.
Inputs: max_symbols.
send_telegram_notificationA
Send a free-text message to the configured Telegram chat.
Requires TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID in .env; if either is missing, returns {'sent': False, 'reason': 'telegram_not_configured'} without raising. parse_mode: HTML | Markdown | none. This sends a MESSAGE ONLY and never places an order.
Inputs: message (required), parse_mode.
send_trade_alertA
Format an 'ACTION REQUIRED' trade recommendation and send it to Telegram for the human to place manually (used in notify-only mode).
side: BUY | SELL; trade_type: intraday | delivery; mode: paper | live. Sends a RECOMMENDATION ONLY — it does NOT place any order. The returned dict always includes 'preview' (the message text) so the agent can also surface it inline even when Telegram is not configured.
Inputs: symbol (required), side (required), quantity (required), trade_type (required), +6 more.
switch_to_live_modeA
Set TRADING_MODE=live. NOTE: real orders remain impossible until a human also sets ALLOW_LIVE_TRADING=true in .env.
Inputs: no named parameters.
switch_to_paper_modeA
Set TRADING_MODE=paper (always safe).
Inputs: no named parameters.
update_trading_configA
Update runtime-updatable config keys in .env (risk limits, intraday/swing enable flags). Live-trading switches, ALLOW_DELIVERY_SELL and credentials can NOT be changed here — a human must edit .env.
Inputs: updates (required).
validate_order_before_executionC
Re-run the full validation checklist for an order without staging it.
Inputs: symbol (required), side (required), quantity (required), entry_price (required), +3 more.
validate_trade_against_risk_rulesB
Full pre-trade validation checklist: permissions, market status, risk limits, stop/target presence, risk:reward, position size, daily loss, open positions. Run this BEFORE any paper or live order.
Inputs: symbol (required), side (required), quantity (required), entry_price (required), +3 more.
validate_trading_permissionsB
Check config permissions for a prospective order (no market/risk checks). side: BUY|SELL, product_type: INTRADAY|DELIVERY.
Inputs: symbol (required), side (required), product_type (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 63 tools
Many tools serve similar purposes (e.g., multiple news/sentiment tools, multiple validation tools), which could cause an agent to select the wrong one. However, descriptions provide some clarifying context, and core distinctions exist between paper/live modes and different analysis types.
Tool names predominantly follow a verb_noun pattern (e.g., calculate_ema, fetch_live_price). Minor deviations like block_delivery_sell_order and prepare_order break the pattern slightly, but overall consistency is high.
63 tools is high for a trading server. While many are necessary (indicators, risk checks, orders, news), some could be consolidated (e.g., indicators into a single snapshot tool, which already exists as get_indicator_snapshot). The count feels bloated but still manageable.
The tool surface covers paper trading, live trading, risk validation, indicators, news, backtesting, and integrations. Notable gaps include direct order modification, full live order history, and more granular order status. However, core workflows are well-supported.
Maintenance
Related MCP Connectors
Guardrails for trading agents. Built-in risk management, 100+ tools for strategy R&D, 12+ venues.
Unified financial infrastructure connecting AI agents directly to trade live/demo brokerage accounts, Web3 non-custodial wallets, real-time market data across equities, ETFs, crypto, forex, options, DeFi swaps, and prediction markets, institutional research feeds, and algorithmic strategy backtesters.
Quant research for AI agents: point-in-time data, backtests and paper trading for stocks and crypto.
Build, backtest, and deploy quantitative trading strategies from your AI agent.
Related MCP Servers
- AlicenseCqualityDmaintenanceProvides AI agents with institutional-grade quantitative finance tools including real-time market data, paper trading via Alpaca, risk analysis with Monte Carlo simulations, backtesting, and multi-source news sentiment analysis for portfolio management and trading strategy development.315MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to perform cryptocurrency trading analysis and execution with 38+ tools including real-time market data, technical indicators, risk management, and support for both paper trading and live execution on Hyperliquid.7MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to execute stock trading operations with built-in risk controls and human approval workflows. Supports paper trading simulation, real brokerage integration (Alpaca, Tradier), backtesting, sentiment analysis, and portfolio management while maintaining strict separation between AI intelligence and trade execution.MIT
- AlicenseAqualityBmaintenanceProvides AI agents with a TradingView-centric toolkit for screener queries, historical FX data, pattern scanning, chart rendering, backtesting, Pine tooling, and optional account/desktop integration.6MIT