An AI-powered trading assistant platform for OpenAlgo, leveraging Machine Conversation Protocol (MCP) and Large Language Models to provide intelligent trading capabilities.
OpenAlgo MCP integrates the powerful OpenAlgo trading platform with advanced AI capabilities through:
- An MCP server that exposes OpenAlgo API functions as tools for AI interaction
- An intelligent client application providing a conversational interface for trading
This bridge between OpenAlgo's trading capabilities and AI allows for a natural language interface to complex trading operations, making algorithmic trading more accessible to users of all technical backgrounds.
- Order Management: Place, modify, and cancel orders with support for various order types (market, limit, stop-loss)
- Advanced Order Types: Basket orders, split orders, and smart orders with position sizing
- Options Trading: Single-leg and multi-leg options orders with ATM/ITM/OTM offset support
- Market Data Access: Real-time quotes, multi-quotes, market depth, option chains, and historical data
- Portfolio Management: Track holdings, positions, order books, and trade history
- Account Information: Monitor funds, margins, margin calculator, and trading limits
- Utilities: Trading holidays, market timings, Telegram alerts, analyzer mode
- Smart parsing and formatting of instrument symbols across exchanges
- Support for equity, futures, and options symbology
- Built-in knowledge of common indices and exchange-specific formats
- Natural language interface for all trading operations
- Contextual understanding of trading terminology and concepts
- Guided assistance for complex trading operations
- Real-time data presentation in human-readable formats
openalgo-mcp/
├── .env # Common environment configuration
├── .env.example # Example configuration template
├── requirements.txt # Common dependencies for both client and server
├── LICENSE # MIT License
├── server/ # MCP Server implementation
│ ├── server.py # OpenAlgo MCP server code
└── client/ # Client implementation
├── trading_agent.py # AI assistant client code
- Python 3.9+ installed
- OpenAlgo platform installed and configured
- OpenAI API key (for the client component)
git clone https://github.com/marketcalls/openalgo-mcp.git
cd openalgo-mcp/mcpserver# Create and activate virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt# Copy example environment file
cp .env.example .env
# Edit the .env file with your API keys and settings
# vim .env or use any text editorcd server
python server.pyThe server supports the following options:
--api-key: OpenAlgo API key (alternative to setting in .env)--host: OpenAlgo API host URL (default: http://127.0.0.1:5000)--port: Server port (default: 8001)--mode: Server transport mode - 'stdio' or 'sse' (default: sse)
cd client
python trading_agent.pyThe client supports these options:
--host: MCP server host (default: from .env)--port: MCP server port (default: from .env)--model: OpenAI model to use (default: from .env)
The project uses a unified configuration approach with environment variables:
- Common configuration is stored in the root
.envfile - Component-specific configuration can be set in
server/.envorclient/.env - Common settings will be loaded first, then possibly overridden by component-specific settings
-
OpenAlgo API Key - Set in
.envasOPENALGO_API_KEY- Required for accessing the OpenAlgo trading platform
- Obtain from your OpenAlgo account dashboard
-
OpenAI API Key - Set in
.envasOPENAI_API_KEY(for the client only)- Required for the AI assistant capabilities
- Obtain from OpenAI Platform
The OpenAlgo MCP implementation provides comprehensive API coverage including:
-
Order Management:
place_order: Standard order placement with target, stoploss, trailing_sl supportmodify_order: Order modification with parameter validationcancel_order: Order cancellation by IDcancel_all_orders: Cancel all orders for a strategyget_order_status: Get status of a specific order
-
Advanced Order Types:
place_basket_order: Place multiple orders simultaneouslyplace_split_order: Split large orders into smaller chunksplace_smart_order: Position-aware order placement
-
Options Trading:
place_options_order: Single-leg options with ATM/ITM/OTM offsetplace_options_multi_order: Multi-leg strategies (spreads, iron condor, straddles)get_option_symbol: Get option symbol for specific strike and expiryget_option_chain: Real-time option chain with all strikesget_option_greeks: Calculate delta, gamma, theta, vega, rhoget_synthetic_future: Calculate synthetic future using put-call parity
-
Market Data:
get_quote: Latest market quotesget_multi_quotes: Quotes for multiple symbols in single requestget_depth: Order book depth dataget_history: Historical price data with various timeframessearch_instruments: Search instruments by name or symbolget_expiry_dates: Get derivative expiry datesget_instruments: Download all instruments for an exchange
-
Account Information:
get_funds: Available funds and marginget_holdings: Portfolio holdingsget_position_book,get_order_book,get_trade_book: Trading recordsget_open_position: Get position for specific symbolclose_all_positions: Close all positions for a strategycalculate_margin: Calculate margin requirements
-
Symbol Information:
get_symbol_metadata: Detailed symbol informationget_all_tickers: Available trading symbolsget_intervals: Supported timeframes for historical data
-
Utilities:
get_holidays: Trading holidays for a yearget_timings: Exchange trading timings for a datesend_telegram_alert: Send Telegram notificationsanalyzer_status: Get analyzer mode statusanalyzer_toggle: Toggle between analyze (simulated) and live mode
The implementation uses FastMCP with SSE (Server-Sent Events) transport for real-time communication and includes proper error handling, logging, and parameter validation.
The OpenAlgo MCP Server is built using the FastMCP library and exposes OpenAlgo trading functionality through a comprehensive set of tools. It uses Server-Sent Events (SSE) as the primary transport mechanism for real-time communication.
- Framework: Uses FastMCP with Starlette for the web server
- Transport: Server-Sent Events (SSE) for real-time bidirectional communication
- API Client: Wraps the OpenAlgo API with appropriate error handling and logging
- Configuration: Uses environment variables with command-line override capabilities
The server exposes over 35 trading-related tools, including:
- Order Management: place_order, modify_order, cancel_order, cancel_all_orders, get_order_status
- Advanced Orders: place_basket_order, place_split_order, place_smart_order
- Options Trading: place_options_order, place_options_multi_order, get_option_symbol, get_option_chain, get_option_greeks, get_synthetic_future
- Market Data: get_quote, get_multi_quotes, get_depth, get_history, get_intervals, search_instruments, get_expiry_dates, get_instruments
- Account Information: get_funds, get_holdings, get_position_book, get_order_book, get_trade_book, get_open_position, close_all_positions, calculate_margin
- Symbol Information: get_symbol_metadata, get_all_tickers
- Utilities: get_holidays, get_timings, send_telegram_alert, analyzer_status, analyzer_toggle
The Trading Assistant client provides a user-friendly interface to interact with the OpenAlgo platform through natural language. It uses OpenAI's language models to interpret user commands and invoke the appropriate trading functions.
- Framework: Uses Agno agent framework with OpenAI Chat models
- UI: Rich console interface with custom styling for an enhanced terminal experience
- Symbol Helper: Built-in utilities for correct symbol formatting across exchanges
- Error Handling: Comprehensive exception handling with user-friendly feedback
- Natural Language Interface: Understands trading terminology and concepts
- Symbol Format Assistance: Helps construct proper symbol formats for equities, futures, and options
- Data Presentation: Formats market data in clean, readable formats
- Contextual Awareness: Maintains conversation history to provide contextual responses
If you're having trouble connecting to the MCP server:
-
Verify the server is running:
cd server python server.pyYou should see output indicating the server is running on the configured port.
-
Check environment variables:
- Ensure
MCP_HOSTandMCP_PORTin.envmatch the server's configuration - Verify that
SERVER_PORTis the same asMCP_PORT
- Ensure
-
Test local connectivity:
- Try accessing
http://localhost:8001/ssein your browser (replace 8001 with your configured port) - You should see a message indicating the endpoint is for SSE connections
- Try accessing
If you see 403 Forbidden or authentication errors:
-
Check your API key:
- Verify your OpenAlgo API key in the
.envfile is correct and active - Ensure the API key has the necessary permissions for the operations you're trying to perform
- Verify your OpenAlgo API key in the
-
Verify API host:
- Make sure
OPENALGO_API_HOSTpoints to the correct endpoint - For testing, the default value
http://127.0.0.1:5000should work if you're running OpenAlgo locally
- Make sure
- Silent failures in the client:
- The client uses a SilentFilter for logging to provide a clean interface
- If you suspect issues, temporarily modify the logging configuration in
trading_agent.py - Check that the OpenAI API key is valid if you experience model generation failures
This project is made possible by the following open-source projects and tools:
-
OpenAlgo: The powerful trading platform that powers all trading operations in this project
-
Model Context Protocol (MCP): The communication protocol that enables AI agents to use tools and APIs
-
Agno: The agent framework used for building the trading assistant client
This project was inspired by Zerodha MCP, which pioneered the use of Machine Conversation Protocol for trading applications. The OpenAlgo MCP project adapts and extends this concept for the OpenAlgo trading platform, with a focus on enhanced symbol handling, comprehensive trading operations, and a more user-friendly interface.
If your symbol-related requests are failing:
-
Follow format guidelines:
- Equity symbols: Simple uppercase symbol (e.g.,
INFY,SBIN) - Futures:
[BaseSymbol][Year][Month][Date]FUT(e.g.,BANKNIFTY24APR24FUT) - Options:
[BaseSymbol][Date][Month][Year][Strike][OptionType](e.g.,NIFTY28MAR2420800CE)
- Equity symbols: Simple uppercase symbol (e.g.,
-
Use the SymbolHelper class:
- The client includes formatting assistance methods that can help construct proper symbols
For more detailed logging, enable debugging in the .env file:
SERVER_DEBUG=true
This will output additional information to help diagnose connection and API issues.
This project is licensed under the Apache-2.0 license - see the LICENSE file for details.
- This project was inspired by Zerodha MCP, which is licensed under the Apache License 2.0. While no code has been directly copied, this project builds upon the concept and architecture introduced by Zerodha MCP.
- OpenAlgo for the powerful trading platform
- MCP (Machine Conversation Protocol) for the communication framework
- AGNO for the AI agent infrastructure