A Spring Boot-based Model Context Protocol (MCP) server for stock trading operations, integrated with Groww API and Spring AI.
- MCP Server Integration: Built with Spring AI MCP Server for seamless AI integration
- Groww API Integration: Fetch real-time and historical market data from Groww
- Instruments Management: Comprehensive CRUD operations for financial instruments
- CSV Data Ingestion: Bulk import instruments data from CSV files with batch processing
- Token Management: Automated token generation and caching for Groww API
- Historic Data Retrieval: Fetch candlestick data for technical analysis
- Holdings Management: Fetch and monitor user holdings with detailed position information
- Positions Tracking: Real-time position tracking by segment and trading symbol
- Order Placement: Place buy/sell orders with support for multiple order types (Market, Limit, SL, SL-M)
- Order Management: Modify, cancel, and track orders with real-time status updates
- Trade Execution: Fetch executed trades and detailed trade information
- Order History: Retrieve comprehensive order list and order details
- PostgreSQL Database: Persistent storage with JPA/Hibernate
- Caching: Caffeine cache implementation for improved performance
- Code Optimization: Refactored order service with centralized API handler (OrderServiceHelper)
- Java 21
- Maven 3.6+
- PostgreSQL 12+
- Groww API credentials (API Key and Secret)
- Framework: Spring Boot 3.5.10
- AI Integration: Spring AI 1.1.2 with MCP Server Support
- Database: PostgreSQL 42.7.9 with Spring Data JPA
- HTTP Client: Apache HttpClient 5.5
- Caching: Caffeine Cache 3.2.3 with Spring Cache abstraction
- CSV Processing: Apache Commons CSV 1.11.0
- Code Generation: Project Lombok (Annotations: @Data, @Builder, @Slf4j, etc.)
- Build Tool: Maven
- Java: 21
Create the following environment variables:
# Database Configuration
export DB_URL=jdbc:postgresql://localhost:5432/trade_db
export DB_USERNAME=your_db_username
export DB_PASSWORD=your_db_password
# Groww API Configuration
export GROWW_API_KEY=your_groww_api_key
export GROWW_SECRET_KEY=your_groww_secret_keyConfigure settings in application.yaml:
spring:
datasource:
url: ${DB_URL}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
ai:
mcp:
server:
enabled: true
name: trade-mcp-server
version: 1.0.0
groww:
api-key: ${GROWW_API_KEY}
secret: ${GROWW_SECRET_KEY}
base-url: https://api.groww.in/v1/
server:
port: 8082The application is configured with the following Groww API endpoints:
- Token Generation:
token/api/access - Historic Data:
historical/candle/range - Holdings:
holdings/user - Positions:
positions/user,positions/trading-symbol - Orders:
order/list,order/create,order/details,order/modify,order/cancel,order/status,order/trades
First, create a PostgreSQL database named trade_db:
psql -U postgres -c "CREATE DATABASE trade_db;"Then, run the schema script to create the instruments table:
psql -U your_username -d trade_db -f src/main/resources/schema.sqlThe schema includes:
- Instruments Table: Main table for storing financial instruments with 22 fields
- Indexes: Optimized queries with indexes on:
name(instrument name search)trading_symbol(stock symbol lookup)exchange(market exchange filtering)segment(market segment filtering)
The application uses hibernate.ddl-auto=none, meaning:
- β Manual schema management via SQL scripts
- β Better control over migrations
- β Safer for production environments
- β Schema changes require explicit SQL execution
- Clone the repository:
git clone <repository-url>
cd trade-mcp-server- Install dependencies:
./mvnw clean install- Run the application:
./mvnw spring-boot:runThe server will start on http://localhost:8082
This application is designed as an MCP Server for AI agent interactions. All trading operations are exposed as MCP tools rather than REST APIs:
- AI-Native: Tools are optimized for AI agents (Claude, ChatGPT, etc.)
- Type-Safe: All tools use strongly-typed request/response models
- Self-Documenting: Tool descriptions are embedded in the code using
@McpToolannotations - REST APIs: Limited to internal operations (token generation, CSV ingestion)
To interact with this server, connect it to an MCP-compatible AI client using the Spring AI MCP protocol.
This implementation follows MCP best practices:
- Stateless Tool Design: Each tool is independent and can be called in any order
- Consistent Naming: Tool names follow snake_case convention (
fetch_historic_data,create_new_order, etc.) - Clear Descriptions: Each tool has a clear description explaining its purpose
- Type Safety: All parameters are strongly typed with validation
- Error Handling: Comprehensive error responses for debugging
- Pagination Support: Order tracking tools include pagination parameters
- Segment Support: Tools recognize different market segments (CASH, FNO, COMMODITY)
This server exposes the following MCP tools for AI agents to interact with trading operations.
- Market Data Tools (2): Historic data and instrument search
- Portfolio Tools (3): Holdings and positions management
- Order Management Tools (3): Order placement, modification, and cancellation
- Order Tracking Tools (4): Order status, trades, history, and details
Total: 12 MCP Tools
Retrieves historical candlestick data (OHLCV - Open, High, Low, Close, Volume) for technical analysis and charting.
Parameters:
request(HistoricDataRequest): Contains symbol, exchange, interval, from and to dates
Supported Intervals: 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M
Example:
{
"symbol": "RELIANCE",
"exchange": "NSE",
"interval": "1D",
"from": "2026-01-01",
"to": "2026-02-05"
}Searches and retrieves financial instruments from the database based on partial name matching, exchange, and segment.
Parameters:
request(EntityRequest): Contains name, exchange (NSE, BSE, MCX), and segment (CASH, FNO, COMMODITY)
Returns: List of instruments with trading symbols, lot sizes, tick sizes, and trading permissions
Example:
{
"name": "RELIANCE",
"exchange": "NSE",
"segment": "CASH"
}Retrieves all holdings from the user's Groww portfolio with detailed quantity and price information.
Parameters: None
Returns: Holdings with quantity, average price, locked quantities, and free quantities
Retrieves current open positions for a specified market segment.
Parameters:
segment(Segment): Market segment - CASH, FNO, or COMMODITY
Returns: Positions with credit/debit quantities, prices, and realized P&L
Retrieves position for a specific trading symbol within a segment.
Parameters:
segment(Segment): Market segment - CASH, FNO, or COMMODITYtradingSymbol(String): Stock trading symbol (e.g., "TCS", "RELIANCE")
Returns: Position details with quantity, average price, and P&L
Creates a new buy or sell order with support for multiple order types.
Parameters:
request(CreateOrderRequest): Order details including:tradingSymbol: Stock symbolquantity: Number of sharesprice: Order pricetriggerPrice: Stop loss trigger price (for SL orders)validity: DAY or IOCexchange: NSE, BSE, or MCXsegment: CASH, FNO, or COMMODITYproduct: CNC, INTRADAY, or MTForderType: MARKET, LIMIT, SL, or SL-MtransactionType: BUY or SELLorderReferenceId: Unique client reference
Example:
{
"tradingSymbol": "WIPRO",
"quantity": 100,
"price": 2500,
"triggerPrice": 2450,
"validity": "DAY",
"exchange": "NSE",
"segment": "CASH",
"product": "CNC",
"orderType": "SL",
"transactionType": "BUY",
"orderReferenceId": "Ab-654321234-1628190"
}Modifies an existing order's price and/or quantity.
Parameters:
request(ModifyOrderRequest): Contains order ID and new parameters (price, quantity, validity)
Example:
{
"growwOrderId": "GMK39038RDT490CCVRO",
"price": 2550,
"quantity": 150,
"validity": "DAY"
}Cancels an existing open order.
Parameters:
request(CancelOrderRequest): Contains order ID to cancel
Example:
{
"growwOrderId": "GMK39038RDT490CCVRO"
}Fetches the current status of a specific order.
Parameters:
request(OrderStatusRequest): Contains order ID and segment
Returns: Order status, filled quantity, and order reference
Fetches all trades associated with a specific order.
Parameters:
request(OrderTradesRequest): Contains order ID, segment, page number, and page size
Returns: List of executed trades with price, quantity, timestamps, and settlement details
Fetches the list of all orders for a specific segment.
Parameters:
segment(Segment): CASH, FNO, or COMMODITY
Returns: List of orders with complete order details, execution status, and metadata
Fetches detailed information for a specific order.
Parameters:
request(OrderStatusRequest): Contains order ID and segment
Returns: Complete order details including execution information and timestamps
Represents financial instruments with fields:
- Basic Info:
id,name,exchange,segment - Trading Details:
tradingSymbol,exchangeToken,growwSymbol - Metadata:
instrumentType,series,isin - Derivatives:
underlyingSymbol,expiryDate,strikePrice - Trading Parameters:
lotSize,tickSize,freezeQuantity - Permissions:
buyAllowed,sellAllowed,isIntraday
Represents user holdings with detailed information:
- Holding:
isin,tradingSymbol,quantity,averagePrice - Lock Details:
pledgeQuantity,dematLockedQuantity,growwLockedQuantity,repledgeQuantity - Quantity Types:
t1Quantity,dematFreeQuantity,corporateActionAdditionalQuantity,activeDematTransferQuantity
Represents user positions with comprehensive position tracking:
- Position Details:
tradingSymbol,exchange,symbolIsin,product - Credit Info:
creditQuantity,creditPrice,carryForwardCreditQuantity,carryForwardCreditPrice - Debit Info:
debitQuantity,debitPrice,carryForwardDebitQuantity,carryForwardDebitPrice - Net Values:
quantity,netPrice,netCarryForwardQuantity,netCarryForwardPrice,realisedPnl
Represents order placement request with trading parameters:
- Instrument Details:
tradingSymbol,exchange,segment - Order Parameters:
quantity,price,triggerPrice,validity - Order Type:
orderType(MARKET, LIMIT, SL, SL-M),transactionType(BUY, SELL) - Product Type:
product(CNC, INTRADAY, MTF) - Reference:
orderReferenceId(unique order reference)
Represents order placement response with order status:
- Status:
status(SUCCESS, FAILED) - Payload:
growwOrderId: Unique order ID from GrowworderStatus: Current order status (OPEN, PENDING, EXECUTED, CANCELLED, REJECTED)orderReferenceId: Client-provided order referenceremark: Additional information about the order
Represents order modification/cancellation response:
- Status:
status(SUCCESS, FAILED) - Payload:
growwOrderId: Unique order ID from GrowworderStatus: Updated order statusremark: Modification confirmation message
Represents current order status with execution details:
- Status:
status(SUCCESS, FAILED) - Payload:
growwOrderId: Unique order ID from GrowworderStatus: Current order statusfilledQuantity: Quantity executed so farorderReferenceId: Client-provided order referenceremark: Status message
Represents list of trades executed for an order:
- Status:
status(SUCCESS, FAILED) - Payload:
tradeList: Array of executed trades containing:- Trade Details:
price,quantity,isin,tradingSymbol - Order References:
growwOrderId,exchangeOrderId,orderReferenceId - Trade References:
growwTradeId,exchangeTradeId,settlementNumber - Status & Type:
tradeStatus,transactionType(BUY, SELL) - Market Info:
exchange,segment,product - Timestamps:
createdAt,tradeDatetime - Metadata:
remark
- Trade Details:
Represents list of orders for a segment:
- Status:
status(SUCCESS, FAILED) - Payload:
orderList: Array of orders containing:- Order Identification:
growwOrderId,tradingSymbol,orderReferenceId - Order Status:
orderStatus,amoStatus - Order Parameters:
quantity,price,triggerPrice,validity - Execution Details:
filledQuantity,remainingQuantity,averageFillPrice - Position Info:
deliverableQuantity - Order Type:
orderType(MARKET, LIMIT, SL, SL-M),transactionType(BUY, SELL) - Market Info:
exchange,segment,product - Timestamps:
createdAt,exchangeTime,tradeDate - Metadata:
remark
- Order Identification:
- Exchange: NSE, BSE, MCX
- Segment: CASH, FNO, COMMODITY
- CandleIntervals: 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M
- OrderType: MARKET, LIMIT, SL (Stop Loss), SL-M (Stop Loss Market)
- OrderStatus: OPEN, PENDING, EXECUTED, CANCELLED, REJECTED
- ProductType: CNC (Cash & Carry), INTRADAY, MTF (Margin Trading Facility)
- TransactionType: BUY, SELL
The application follows a layered architecture pattern with clear separation of concerns:
com.navneet.trade/
βββ config/ # Configuration classes
β βββ CacheConfig.java # Caffeine cache configuration
βββ constants/ # Application constants and enums
β βββ CandleIntervals.java # Supported candle intervals
β βββ Exchange.java # Market exchanges (NSE, BSE, MCX)
β βββ Segment.java # Market segments (CASH, FNO, COMMODITY)
β βββ OrderType.java # Order types (MARKET, LIMIT, SL, SL-M)
β βββ OrderStatus.java # Order statuses
β βββ ProductType.java # Product types (CNC, INTRADAY, MTF)
β βββ TransactionType.java # Transaction types (BUY, SELL)
β βββ GrowwConstants.java # Groww API constants
βββ controller/ # REST controllers (internal use only)
β βββ GrowwController.java # Token generation & CSV ingestion
β βββ OrderController.java # Disabled - testing purposes only
βββ entity/ # JPA entities and data access
β βββ Instruments.java # Instrument entity with @Entity annotation
β βββ dto/
β β βββ InstrumentsDto.java # DTO for data transfer
β βββ repo/
β βββ InstrumentsRepo.java # Spring Data JPA repository
βββ models/ # Request/Response models for API contracts
β βββ request/ # Request DTOs
β β βββ EntityRequest.java
β β βββ HistoricDataRequest.java
β β βββ TokenRequest.java
β β βββ CreateOrderRequest.java
β β βββ ModifyOrderRequest.java
β β βββ CancelOrderRequest.java
β β βββ OrderStatusRequest.java
β β βββ OrderTradesRequest.java
β βββ response/ # Response DTOs
β βββ TokenResponse.java
β βββ HistoricDataResponse.java
β βββ HoldingsResponse.java
β βββ PositionsResponse.java
β βββ CreateOrderResponse.java
β βββ ModifyOrderResponse.java
β βββ OrderStatusResponse.java
β βββ OrderTradesResponse.java
β βββ OrderListResponse.java
βββ service/ # Business logic and service layer
β βββ GrowwService.java # Groww-related operations interface
β βββ OrderService.java # Order management interface
β βββ impl/ # Service implementations
β β βββ GrowwServiceImpl.java # Implements Groww operations
β β βββ OrderServiceImpl.java # Implements order operations
β βββ helper/ # Helper classes for code reuse
β βββ GrowwServiceHelper.java # Centralized Groww API calls
β βββ OrderServiceHelper.java # Centralized order API calls
βββ utils/ # Utility and helper functions
βββ GrowwUtils.java # Groww-specific utilities
βββ RestUtils.java # REST API utilities
- Layered Architecture: Clear separation between controller, service, and repository layers
- Helper Pattern: OrderServiceHelper and GrowwServiceHelper consolidate API calls and reduce code duplication
- Repository Pattern: Spring Data JPA for database access with custom queries
- Service Interface Pattern: Abstract business logic behind service interfaces
- DTO Pattern: Request/Response models provide API contracts and validation
- Enum Pattern: Type-safe constants using enums instead of string literals
The system uses an iterator pattern for memory-efficient CSV processing:
- Line-by-Line Reading: Reads CSV files without loading entire file into memory
- Batch Processing: Builds batches of configurable size (e.g., 1000 records)
- Bulk Insert: Uses
instrumentsRepo.saveAll()for efficient batch insertion - Memory Efficient: Ideal for processing large CSV files (100K+ records)
Reduced code duplication in order management operations:
- Centralized API Handling: OrderServiceHelper consolidates all REST API call logic (POST and GET)
- Generic Methods:
executePostCall()andexecuteGetCall()handle all API interactions - Response Handling: Unified JSON deserialization and error handling
- Result: 50% reduction in OrderServiceImpl code (192 β 96 lines)
- Benefit: Bug fixes and enhancements in API communication now happen in one place
- Token Caching: Groww API tokens cached with configurable expiry
- Cache Eviction: Support for manual cache eviction
- High Performance: Caffeine cache for sub-millisecond lookups
- Spring Integration: Seamless integration with Spring's @Cacheable annotation
Custom JPA queries for flexible instrument searching:
findDistinctByNameContainingIgnoreCaseAndExchangeAndSegment(
String name, String exchange, String segment
)- Case-Insensitive Search: Finds instruments regardless of case
- Flexible Filtering: Filter by exchange and segment simultaneously
- Distinct Results: Removes duplicate entries
Run tests with:
./mvnw testUsing Maven Spring Boot Plugin:
./mvnw spring-boot:runUsing Java JAR:
./mvnw clean package
java -jar target/trade-mcp-server-0.0.1-SNAPSHOT.jarWith Environment Variables:
export DB_URL=jdbc:postgresql://localhost:5432/trade_db
export DB_USERNAME=postgres
export DB_PASSWORD=yourpassword
export GROWW_API_KEY=your_key
export GROWW_SECRET_KEY=your_secret
./mvnw spring-boot:runThis project is licensed under the terms specified in the LICENSE file.
Navneet Prabhakar
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
For issues and questions, please open an issue in the repository.
Note: This is a development server. Ensure proper security measures are in place before deploying to production.