Sponsored by Deepsite.site

MCP Order Flow Server

Created By
fintools-ai6 months ago
This is the mcp to fetch and get order flow information
Content

MCP Order Flow Server

A Fast MCP server that provides real-time order flow analysis for options trading decisions. This server consumes quote data from Redis and provides structured analysis through MCP tools.

🎯 Overview

This server analyzes order flow data to help LLM agents make informed options trading decisions by providing:

  • Real-time momentum indicators: Bid/ask lifts, drops, and price movements
  • Size dynamics: Volume patterns, large order detection, acceleration
  • Pattern detection: Absorption, stacking, sweeps, momentum shifts
  • Support/resistance levels: Significant price levels from order flow
  • Market behavior flags: Simple YES/NO indicators for LLM interpretation

🏗️ Architecture

System Overview

[Data Broker] → Redis → [This Server] → MCP Tool → LLM Agent
                  ↑           ↓
                  └─ Background Processing (1s) ←┘

Detailed Sequence Flow

sequenceDiagram
    participant LLM as LLM Agent
    participant MCP as MCP Server
    participant Redis as Redis
    participant Processor as Background Processor

    Note over Processor,Redis: Background Processing (Every 1s)
    loop Every Second
        Processor->>Redis: Get quotes (10s, 60s, 300s)
        Processor->>Processor: Calculate metrics & detect patterns
        Processor->>Redis: Save metrics, patterns, levels
    end

    Note over LLM,Redis: Tool Request Flow
    LLM->>MCP: analyze_order_flow("SPY", "5mins")
    MCP->>Redis: Get quotes, metrics, patterns
    Redis-->>MCP: Aggregated data
    MCP->>MCP: Format XML response
    MCP-->>LLM: Structured analysis

View complete sequence diagram →

🚀 Quick Start

Prerequisites

Installation

# Clone repository
git clone https://github.com/yourusername/mcp-order-flow-server.git
cd mcp-order-flow-server

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Running the Server

# Quick start with helper script
chmod +x dev_start.sh
./dev_start.sh

# Or run directly
python -m src.mcp_server

📊 MCP Tool Reference

analyze_order_flow

Analyzes order flow data for options trading decisions.

Example Request:*

result = await analyze_order_flow(
    ticker="SPY",
    history="5mins",
    include_patterns=True
)

Example Response:

<order_flow_data ticker="SPY" timestamp="2025-01-15T10:30:45" current_price="450.27">
  <current_quote>
    <bid price="450.25" size="5000" />
    <ask price="450.30" size="2000" />
    <bid_ask_ratio>2.5</bid_ask_ratio>
  </current_quote>
  
  <momentum>
    <last_10s>
      <bid_price_change>0.08</bid_price_change>
      <bid_lifts>3</bid_lifts>
    </last_10s>
    <last_60s>
      <bid_lifts>39</bid_lifts>
      <bid_drops>21</bid_drops>
    </last_60s>
  </momentum>
  
  <behaviors>
    <bid_stacking>YES</bid_stacking>
    <momentum_building>YES</momentum_building>
  </behaviors>
  
  <detected_patterns>
    <pattern>
      <type>absorption</type>
      <side>bid</side>
      <strength>strong</strength>
    </pattern>
  </detected_patterns>
</order_flow_data>

🔍 Pattern Detection

Absorption Pattern

Detects large orders absorbing market flow at specific price levels.

  • Trigger: Stable price with high volume (>8k avg size)
  • Significance: Institutional accumulation/distribution

Stacking Pattern

Identifies building walls of orders on bid or ask.

  • Trigger: Consecutive large orders (>5k) with increasing sizes
  • Significance: Support/resistance building

Momentum Shift

Detects directional pressure changes.

  • Trigger: 2:1 or greater lift/drop ratio
  • Significance: Trend initiation or reversal

Sweep Detection

Identifies sudden large size changes.

  • Trigger: >15k size change between consecutive quotes
  • Significance: Aggressive execution, stop hunting

⚙️ Configuration

Environment Variables

# Redis Configuration
export REDIS_HOST=localhost
export REDIS_PORT=6379
export REDIS_DB=0
export REDIS_PASSWORD=

# Server Configuration
export LOG_LEVEL=INFO
export PROCESSOR_INTERVAL=1  # Processing frequency in seconds

Redis Data Structure

Key PatternTypeDescriptionTTL
orderflow:quotes:{ticker}Sorted SetRaw quotes3600s
orderflow:metrics:{ticker}:{window}HashCalculated metrics60-600s
orderflow:patterns:{ticker}Sorted SetDetected patterns3600s
orderflow:levels:{ticker}:{side}Sorted SetPrice levels3600s

🛠️ Development

Project Structure

src/
├── mcp_server.py           # FastMCP server entry point
├── tools/
│   └── order_flow_tool.py  # MCP tool implementation
├── processors/
│   ├── order_flow_processor.py  # Main processing logic
│   ├── metrics_calculator.py    # Momentum & size metrics
│   ├── pattern_detector.py      # Pattern identification
│   └── behavior_analyzer.py     # Market behavior flags
├── storage/
│   └── redis_client.py     # Redis operations
└── formatters/
    └── state_manager.py    # XML response formatting

Adding New Patterns

  1. Add detection logic to src/processors/pattern_detector.py:
def _detect_your_pattern(self, quotes: List[Dict]) -> Optional[Dict]:
    # Pattern detection logic
    return {
        'type': 'your_pattern',
        'timestamp': time.time() * 1000,
        # Pattern-specific fields
    }
  1. Update pattern detector to call your method
  2. Add XML formatting in state manager

🔗 Integration

Claude Desktop Configuration

{
  "mcpServers": {
    "order-flow": {
      "command": "python",
      "args": ["-m", "src.mcp_server"],
      "cwd": "/path/to/mcp-order-flow-server",
      "env": {
        "REDIS_HOST": "localhost",
        "REDIS_PORT": "6379"
      }
    }
  }
}
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
ChatWiseThe second fastest AI chatbot™
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
WindsurfThe new purpose-built IDE to harness magic
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
DeepChatYour AI Partner on Desktop
Playwright McpPlaywright MCP server
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
CursorThe AI Code Editor
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Serper MCP ServerA Serper MCP Server
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
Amap Maps高德地图官方 MCP Server
Tavily Mcp
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。