Skip to main content
Glama
trading-mcp-server

trading-mcp-server

by mukul8896

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_order returns a manual-placement recommendation (and a Telegram alert if configured). Nothing is executed.

  • paper — place_order fills in a simulated paper account. (default)

  • live — place_order places a real order — but only when ALLOW_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=live and ALLOW_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-server

Requires 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.server

It resolves its configuration and state from a home directory:

  1. TRADING_MCP_HOME environment variable, if set

  2. otherwise 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

get_trading_config, get_execution_mode, set_execution_mode, update_trading_config

Market data

fetch_live_price, fetch_historical_data, fetch_market_status, fetch_symbol_metadata, fetch_watchlist

Indicators

calculate_sma/ema/rsi/macd/bollinger_bands/atr/volume_analysis, detect_support_resistance, detect_trend, get_indicator_snapshot

News

fetch_latest_news, fetch_market_news, get_market_sentiment, get_sector_sentiment, fetch_news_articles, analyze_news_sentiment

Portfolio

fetch_portfolio, fetch_order_history, calculate_portfolio_exposure, calculate_unrealized_pnl

Risk (calculators)

calculate_position_size, calculate_stop_loss, calculate_target_price, check_max_daily_loss, check_portfolio_concentration

Strategy

evaluate_intraday_trade_setup, evaluate_swing_trade_setup, compare_multiple_symbols, scan_watchlist_for_intraday_opportunities, scan_watchlist_for_swing_opportunities, run_strategy_backtest

Paper trading

close_paper_position, fetch_paper_trades, fetch_paper_portfolio, calculate_paper_trading_performance, generate_paper_trading_report, reset_paper_account

Order execution

place_order (routes by EXECUTION_MODE)

Broker (read)

fetch_broker_funds, fetch_broker_positions, fetch_broker_holdings, fetch_broker_order_status

Notifications

send_notification (Telegram+Discord fan-out), send_telegram_notification, send_discord_notification, send_trade_alert

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 via trading_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 workflow

  • swing_trade_analysis(symbol) — swing/delivery workflow

  • paper_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 source

Configuration reference

The server reads only a few execution switches from <home>/.env (template: examples/.env.example):

Key

Values

Notes

EXECUTION_MODE

notify | paper | live

the one switch; default paper

ALLOW_LIVE_TRADING

true | false

human-only; live orders place only when true

NOTIFY_PAPER_ORDERS

true | false

Telegram alert on paper fills

PAPER_STARTING_CAPITAL

number

paper engine capital

BROKER_*

secrets

Angel One credentials (live + live data)

NEWS_API_KEY

secret

optional news search

TELEGRAM_BOT_TOKEN/TELEGRAM_CHAT_ID

secrets

Telegram notifications

DISCORD_TOKEN/DISCORD_CHANNEL_ID

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)

  1. Bump version in pyproject.toml and src/trading_mcp_server/__init__.py.

  2. python -m build (requires pip install build).

  3. python -m twine upload dist/* (requires a PyPI account + API token).

  4. Consumers then switch from pip install -e ../trading-mcp-server to pip install trading-mcp-server — no other change needed.

License

MIT

Available Tools

63 tools
analyze_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

    B3.1/5.0

    Scored across 63 tools

    Disambiguation3/5

    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.

    Naming Consistency4/5

    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.

    Tool Count3/5

    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.

    Completeness4/5

    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

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      C
      quality
      D
      maintenance
      Provides 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.
      31
      5
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables 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.
      7
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables 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
    • A
      license
      A
      quality
      B
      maintenance
      Provides 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.
      6
      MIT