Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Trade MCP Server

A Spring Boot-based Model Context Protocol (MCP) server for stock trading operations, integrated with Groww API and Spring AI.

πŸš€ Features

  • 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)

πŸ“‹ Prerequisites

  • Java 21
  • Maven 3.6+
  • PostgreSQL 12+
  • Groww API credentials (API Key and Secret)

πŸ› οΈ Technology Stack

  • 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

βš™οΈ Configuration

Environment Variables

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_key

Application Configuration File

Configure 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: 8082

Groww API Endpoints

The 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

πŸ—„οΈ Database Setup

Creating the Database

First, create a PostgreSQL database named trade_db:

psql -U postgres -c "CREATE DATABASE trade_db;"

Running the Schema Script

Then, run the schema script to create the instruments table:

psql -U your_username -d trade_db -f src/main/resources/schema.sql

Schema Details

The 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)

Hibernate Configuration

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

πŸ“¦ Installation

  1. Clone the repository:
git clone <repository-url>
cd trade-mcp-server
  1. Install dependencies:
./mvnw clean install
  1. Run the application:
./mvnw spring-boot:run

The server will start on http://localhost:8082

πŸ€– MCP-First Architecture

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 @McpTool annotations
  • 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.

πŸ“š MCP Best Practices

This implementation follows MCP best practices:

  1. Stateless Tool Design: Each tool is independent and can be called in any order
  2. Consistent Naming: Tool names follow snake_case convention (fetch_historic_data, create_new_order, etc.)
  3. Clear Descriptions: Each tool has a clear description explaining its purpose
  4. Type Safety: All parameters are strongly typed with validation
  5. Error Handling: Comprehensive error responses for debugging
  6. Pagination Support: Order tracking tools include pagination parameters
  7. Segment Support: Tools recognize different market segments (CASH, FNO, COMMODITY)

πŸ› οΈ MCP Tools

This server exposes the following MCP tools for AI agents to interact with trading operations.

Tool Categories

  • 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

Market Data Tools

1. fetch_historic_data

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"
}

2. fetch_entities

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"
}

Portfolio Tools

3. fetch_holdings

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

4. fetch_user_positions

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

5. fetch_position_trading_symbol

Retrieves position for a specific trading symbol within a segment.

Parameters:

  • segment (Segment): Market segment - CASH, FNO, or COMMODITY
  • tradingSymbol (String): Stock trading symbol (e.g., "TCS", "RELIANCE")

Returns: Position details with quantity, average price, and P&L

Order Management Tools

6. create_new_order

Creates a new buy or sell order with support for multiple order types.

Parameters:

  • request (CreateOrderRequest): Order details including:
    • tradingSymbol: Stock symbol
    • quantity: Number of shares
    • price: Order price
    • triggerPrice: Stop loss trigger price (for SL orders)
    • validity: DAY or IOC
    • exchange: NSE, BSE, or MCX
    • segment: CASH, FNO, or COMMODITY
    • product: CNC, INTRADAY, or MTF
    • orderType: MARKET, LIMIT, SL, or SL-M
    • transactionType: BUY or SELL
    • orderReferenceId: 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"
}

7. modify_order

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"
}

8. cancel_order

Cancels an existing open order.

Parameters:

  • request (CancelOrderRequest): Contains order ID to cancel

Example:

{
  "growwOrderId": "GMK39038RDT490CCVRO"
}

Order Tracking Tools

9. fetch_order_status

Fetches the current status of a specific order.

Parameters:

  • request (OrderStatusRequest): Contains order ID and segment

Returns: Order status, filled quantity, and order reference

10. fetch_trades_for_order

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

11. fetch_order_list

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

12. fetch_order_details

Fetches detailed information for a specific order.

Parameters:

  • request (OrderStatusRequest): Contains order ID and segment

Returns: Complete order details including execution information and timestamps

πŸ“Š Domain Models

Instruments Entity

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

Holdings Response

Represents user holdings with detailed information:

  • Holding: isin, tradingSymbol, quantity, averagePrice
  • Lock Details: pledgeQuantity, dematLockedQuantity, growwLockedQuantity, repledgeQuantity
  • Quantity Types: t1Quantity, dematFreeQuantity, corporateActionAdditionalQuantity, activeDematTransferQuantity

Positions Response

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

Create Order Request

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)

Create Order Response

Represents order placement response with order status:

  • Status: status (SUCCESS, FAILED)
  • Payload:
    • growwOrderId: Unique order ID from Groww
    • orderStatus: Current order status (OPEN, PENDING, EXECUTED, CANCELLED, REJECTED)
    • orderReferenceId: Client-provided order reference
    • remark: Additional information about the order

Modify Order Response

Represents order modification/cancellation response:

  • Status: status (SUCCESS, FAILED)
  • Payload:
    • growwOrderId: Unique order ID from Groww
    • orderStatus: Updated order status
    • remark: Modification confirmation message

Order Status Response

Represents current order status with execution details:

  • Status: status (SUCCESS, FAILED)
  • Payload:
    • growwOrderId: Unique order ID from Groww
    • orderStatus: Current order status
    • filledQuantity: Quantity executed so far
    • orderReferenceId: Client-provided order reference
    • remark: Status message

Order Trades Response

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

Order List Response

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

Enums

  • 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

πŸ—οΈ Architecture

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

Architecture Highlights

  • 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

πŸ” Key Features Implementation

CSV Batch Ingestion

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)

Code Optimization: OrderServiceHelper

Reduced code duplication in order management operations:

  • Centralized API Handling: OrderServiceHelper consolidates all REST API call logic (POST and GET)
  • Generic Methods: executePostCall() and executeGetCall() 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

Caching Strategy

  • 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

Repository Queries

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

πŸ§ͺ Testing

Run tests with:

./mvnw test

Running the Application

Using Maven Spring Boot Plugin:

./mvnw spring-boot:run

Using Java JAR:

./mvnw clean package
java -jar target/trade-mcp-server-0.0.1-SNAPSHOT.jar

With 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:run

πŸ“ License

This project is licensed under the terms specified in the LICENSE file.

πŸ‘€ Author

Navneet Prabhakar

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ž Support

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.

About

Spring AI MCP server for stock trading via Groww API, with PostgreSQL, JPA and Caffeine caching

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages