Skip to main content
Glama

📈 TradingCLI

A fast, local-first paper-trading and market-simulation toolkit for your terminal.

CI Python License Scope SQLite

Multi-account portfolios · advanced simulated orders · options and futures · terminal dashboard · backtesting · alerts · automation · MCP

IMPORTANT

TradingCLI is strictly alocal paper-trading simulator. It never routes orders to a live broker and is not a source of personalized financial advice.

🖥️ Screenshots

Paper-trading workflow

Offline report and benchmark

TradingCLI quickstart terminal

TradingCLI simulation report and benchmark

The captures use a disposable demo database and deterministic static prices; they contain no real portfolio or credential data.

Related MCP server: tastytrade-mcp

✨ Highlights

Area

What is included

⚡ Fast terminal UX

Roughly 20 ms median installed startup, persistent quote cache, offline-first dashboard

💼 Portfolio simulation

Multiple accounts, deposits, withdrawals, P&L, time-weighted returns and reconciliation

🧾 Advanced orders

Market, limit, stop, stop-limit, trailing, bracket, OCO, OTO and multi-leg options

🌍 Instruments

Equities, ETFs, crypto, FX, futures and equity options

🧪 Research

Current-holdings backtests, walk-forward SMA tests, portfolio optimization and performance metrics

🔔 Local operations

Alerts, JSONL notifications, reports, quote streaming, scheduling, backups and encrypted copies

🤖 Agent ready

Local stdio MCP server with core, advanced and compatibility profiles

🛡️ Durable storage

SQLite WAL, fixed precision, 56 data guards, migration backups and owner-only permissions

🧭 Contents

🛡️ Scope and safety

TradingCLI is a local paper-trading simulator. It never places live brokerage orders, and its Yahoo Finance data is not an exchange-grade feed. Do not use it as the sole source for financial decisions or expose its stdio MCP server as an unauthenticated network service.

Fetching prices, news, history, and option chains sends held, pending, or watchlisted symbols to Yahoo Finance through yfinance. See SECURITY.md for the local-data and network privacy model.

📦 Install

Requires Python 3.10 or newer.

python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install .
tradingcli --version

For development:

uv sync --locked --extra dev
uv run python run_tests.py

uv.lock pins the complete cross-platform dependency graph. Use the locked uv workflow for CI and repeatable deployments; the plain pip install above is the lightweight end-user path.

🚀 Quick start

Launch the dashboard and first-run setup wizard:

tradingcli

Examples:

tradingcli accounts
tradingcli buy AAPL 5
tradingcli positions
tradingcli market
tradingcli backtest --lookback-days 3650

Inspect all command families without touching market data:

tradingcli --help-all
tradingcli --schema

📊 Dashboard and research

Press g in the dashboard to open Backtesting & Graphs. It shows the selected portfolio's live performance curve beside a backtesting.py current-holdings backtest, including return, CAGR, volatility, Sharpe, Sortino, costs, and maximum drawdown. The backtest universe is read directly from that account's open positions in SQLite; another account's tickers are never mixed in. Choose 6m, 1y, 2y, 5y, 10y, max, or an exact number of days when opening the view; pressing Enter requests five years. Reported CAGR uses the actual elapsed calendar interval.

The backtest asks a specific retrospective question: how today's open quantities and current cash would have performed if held unchanged over the selected history. Because today's holdings are known in advance, it has look-ahead and survivorship bias and is not an out-of-sample strategy test. Adjusted daily Yahoo prices are used. Options are clearly reported as skipped because reliable point-in-time option-chain history is unavailable; futures use continuous series without roll costs.

Current-performance returns are time-weighted, so deposits and withdrawals do not masquerade as trading gains or losses. Live marks and historical symbols load concurrently, and the graph/backtest pair reuses overlapping history.

🧾 Orders, options and market data

Alpaca-style order lifecycle:

tradingcli order submit AAPL --side buy --qty 10 --type limit --limit-price 185
tradingcli order submit AAPL --side sell --qty 10 --type trailing-stop --trail-percent 3
tradingcli order get --order-id 1
tradingcli order replace 1 --limit-price 184
tradingcli order cancel-all
tradingcli order submit AAPL --side buy --qty 10 --type limit --limit-price 180 --dry-run
tradingcli position close AAPL --percent 50
tradingcli position close-all

Bracket, OCO, and OTO exits use --take-profit, --stop-loss, and optionally --stop-loss-limit. Orders support quantity or notional sizing, client order IDs, time-in-force values, and eligible extended-hours limit orders.

Options, watchlists, and research:

tradingcli option get AAPL270115C00100000
tradingcli option exercise AAPL270115C00100000
tradingcli option do-not-exercise AAPL270115C00100000
tradingcli watchlist create Tech --symbols AAPL,MSFT,NVDA
tradingcli watchlist quotes Tech
tradingcli calendar --start 2026-07-01 --end 2026-07-31
tradingcli data bars AAPL --timeframe 1Day --limit 30
tradingcli data snapshot AAPL
tradingcli data movers

Portfolio rebalance suggestions are available through the MCP rebalance_suggest tool. They preserve the account's existing cash allocation, optimize only eligible long spot holdings, and explicitly skip shorts, futures, and options. When anything is skipped, the response is marked ok_partial and defines its weight scope explicitly. It is model output—not personalized investment advice.

🧰 Operations and simulation lab

An append-only double-entry ledger sits alongside the portfolio projection. Funding, fills, commissions, and migrated opening balances are balanced transactions; reconciliation can report or repair drift:

tradingcli ledger balances
tradingcli ledger reconcile
tradingcli ledger reconcile --repair

Execution simulation defaults to the legacy zero-cost/full-fill behavior. Configure commissions, adverse slippage, liquidity participation, and a maximum fill size per account:

tradingcli execution set --commission-bps 5 --slippage-bps 10 \
  --liquidity-fraction 0.5 --max-fill-quantity 100
tradingcli execution preview buy 250 185

Risk limits now include daily realized loss, peak-equity drawdown, per-symbol exposure, and concentration:

tradingcli risk --max-daily-loss 1000 --max-drawdown 0.10 \
  --max-symbol-exposure 25000 --max-concentration 0.30

Research, journal, automation, and interchange commands:

tradingcli strategy walk-forward AAPL
tradingcli journal add "Earnings breakout" --tags setup,earnings --symbol AAPL
tradingcli journal attribution
tradingcli automation add nightly-backup backup --interval-seconds 86400
tradingcli automation run-due
tradingcli broker export alpaca
tradingcli broker import ibkr trades.csv

Automations are persisted and keep run history, but TradingCLI does not install an operating-system daemon. Invoke automation run-due from cron, launchd, or another trusted scheduler.

Local simulation operations include cache warming, streaming marks, alerts, reports, performance diagnostics, and shell completion:

tradingcli quotes warm AAPL MSFT
tradingcli quotes stream AAPL MSFT --interval 5 --count 20 --check-alerts
tradingcli quotes daemon --interval 15 --check-alerts
tradingcli alert add aapl-breakout AAPL --above 225
tradingcli alert check --notify
tradingcli alert events
tradingcli report summary --save
tradingcli benchmark --iterations 20
tradingcli completion zsh > ~/.zfunc/_tradingcli

quotes daemon is a foreground local cache warmer; it never routes orders. Alerts are stored in SQLite. --notify also appends triggered events to the owner-private ~/.papertrade_notifications.jsonl inbox. Automations accept the additional safe actions quotes, alerts, and report.

Backups can be inventoried, retained, and restored. Restore requires --yes and first creates another consistent safety backup:

tradingcli backup list
tradingcli backup prune --keep 10
tradingcli backup restore /path/to/backup.db --yes

Authenticated encrypted snapshots protect portable database copies while the live SQLite file retains owner-only permissions:

PAPERTRADE_ENCRYPTION_PASSWORD='...' \
  tradingcli security encrypt-copy portfolio.db.enc
PAPERTRADE_ENCRYPTION_PASSWORD='...' \
  tradingcli security decrypt-copy portfolio.db.enc restored.db

An authenticated, loopback-only HTTP API exposes health, accounts, positions, journal entries, and order previews. Tokens must be at least 24 characters:

PAPERTRADE_API_TOKEN='replace-with-a-long-random-token' tradingcli serve

Static or file-backed prices can precede Yahoo for deterministic simulations or failover. Configure PAPERTRADE_PRICE_PROVIDERS=file,static,yahoo, PAPERTRADE_PRICE_FILE=./simulation-prices.json, PAPERTRADE_STATIC_PRICES='{"AAPL":185.25}', and optionally PAPERTRADE_PRICE_CACHE_TTL (15 seconds by default). Fresh Yahoo prices are cached in SQLite, so separate terminal invocations can reuse them without another network round trip. Set the TTL to 0 when every command must fetch.

Terminal quote, latest-trade, snapshot, and FX commands use a fast indicative quote path with bid and ask equal to the latest price. Library callers can request Yahoo's slower metadata lookup with latest_quote("AAPL", detailed=True).

Every command accepts one automation output flag: --json, --csv, or --quiet. --schema returns the command tree without accessing market data, and doctor checks physical integrity, logical relationships, fixed-precision storage, schema compatibility, and active database guards.

🤖 MCP server

Start the MCP server over standard input/output:

python3 mcp_server.py

The server defaults to a focused 63-tool core catalog. It uses canonical names, includes portfolio_backtest, order preview and lifecycle management, positions, watchlists, market data, health checks, and backups, and leaves destructive account deletion/reset out of the default agent surface. Core responses use one compact JSON contract: {"ok":true,"data":...} or {"ok":false,"error":{"code":"...","message":"..."}}.

Select a broader catalog before starting the server when an agent needs it:

PAPERTRADE_MCP_PROFILE=advanced tradingcli-mcp  # 79 canonical tools
PAPERTRADE_MCP_PROFILE=full tradingcli-mcp      # all 86, legacy output

advanced adds destructive and specialist option/research/data operations. full adds the seven old aliases (buy, sell, cancel_order, close_position, quote, trade_history, and watchlist) for existing clients; compat is an alias for full. Set PAPERTRADE_MCP_RESPONSE_FORMAT=json|legacy to override a profile's response format. The mcp_catalog tool reports the active contract and complete tool list.

Mutating tools accept agent attribution and idempotency keys for safe retries from multiple independent MCP processes.

Portfolio data defaults to ~/.papertrade.db. Database files and sidecars are forced to owner-only 0600; the backup directory is 0700 and backups are 0600. Set PAPERTRADE_DB to use a different database path. Set PAPERTRADE_MARKET_TIMEOUT to change the default 15-second timeout used by historical-data requests.

⚙️ Configuration

Variable

Purpose

Default

PAPERTRADE_DB

SQLite portfolio path

~/.papertrade.db

PAPERTRADE_MARKET_TIMEOUT

Historical request timeout

15 seconds

PAPERTRADE_PRICE_CACHE_TTL

Cross-process price cache life

15 seconds

PAPERTRADE_PRICE_PROVIDERS

Ordered file, static, yahoo provider chain

static,yahoo

PAPERTRADE_PRICE_FILE

Deterministic local JSON price map

unset

PAPERTRADE_STATIC_PRICES

Inline JSON price map

{}

PAPERTRADE_NOTIFICATION_FILE

Alert notification JSONL inbox

~/.papertrade_notifications.jsonl

PAPERTRADE_API_TOKEN

Loopback API bearer token

unset

PAPERTRADE_ENCRYPTION_PASSWORD

Password used for encrypted copies

unset

PAPERTRADE_MCP_PROFILE

MCP catalog: core, advanced, full

core

Schema v6 normalizes money to 2 decimal places, prices to 6, and quantities to 8 using decimal half-even rounding. SQLite guards reject invalid domains, orphaned account/watchlist records, and values outside those precision contracts—even when a caller bypasses the CLI.

Opening an older on-disk database upgrades it automatically. Before any upgrade, TradingCLI writes a transactionally consistent snapshot beside the database in <database>.migrations/; both the directory and snapshot remain owner-only. A failed validation rolls back the migration and leaves the prior schema version and data intact. Databases created by a newer TradingCLI release are refused instead of being modified.

Yahoo Finance supplies the market data. Its historical quote/trade series and crypto top-of-book output are explicitly marked aggregated or indicative; Yahoo does not expose exchange tick tapes or full order-book depth.

🧑‍💻 Development and verification

Run the isolated contract suite:

python3 run_tests.py
ruff check .
python3 -m build

The runner discovers every test_*.py contract and executes each one in an isolated subprocess and temporary database. GitHub Actions runs the same checks on Python 3.10 and 3.13.

Contributions are welcome—see CONTRIBUTING.md. Security reports should follow SECURITY.md, not a public issue.

📄 License

Released under the MIT License.

A
license - permissive license
-
quality - not tested
B
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • F
    license
    -
    quality
    D
    maintenance
    Full-lifecycle algorithmic trading MCP server. AI strategy generation from plain English, backtesting, live bot deployment to 10+ brokers, portfolio monitoring, and prediction markets. Stocks, options, crypto, futures. 32 tools. Free tier.
    Last updated
  • F
    license
    A
    quality
    C
    maintenance
    MCP server for the tastytrade brokerage API, providing tools for account management, market data, and order execution.
    Last updated
    18
  • A
    license
    A
    quality
    A
    maintenance
    Toss Securities (토스증권) Open API MCP server for the Korean stock market. Supports real-time quotes, orderbook, candles, account holdings, buying power, and order management (create/modify/cancel) with a built-in safety gate requiring explicit confirmation before any real order is placed.
    Last updated
    17
    17
    1
    MIT
  • F
    license
    B
    quality
    C
    maintenance
    MCP server for Interactive Brokers via IB Gateway, enabling read access to account data and trading capabilities for paper accounts.
    Last updated
    11

View all related MCP servers

Related MCP Connectors

  • Hosted MCP for stocks, options, Greeks, brokers, order previews, alerts, and workflows.

  • Open-source MCP server for Zerodha Kite Connect. Portfolio, market data, backtesting, alerts.

  • Alpaca MCP — real-time US stock market data via the Alpaca Market Data API

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ryanrodrigues25200525-svg/tradingcli'

If you have feedback or need assistance with the MCP directory API, please join our Discord server