Content
# FUTU API Wrapper
This is a Flask application that wraps the Futu OpenD API into a RESTful API.
## Roadmap [WIP]
- [x] Interface for querying historical K-line data of specified securities
- [x] Interface for querying capital flow data of specified securities
- [x] Interface for querying capital distribution data of specified securities
- [x] Interface for querying historical K-line quota of accounts
- [ ] Support for MCP protocol in the above interfaces
## Features
- RESTful API implemented based on the Flask framework
- API interface protected by Bearer token authentication
- Architecture design that separates routing and business logic
- Authentication mechanism implemented via middleware
## Project Structure
```
├── app/ # Main application directory
│ ├── __init__.py # Application initialization
│ ├── api/ # API route definitions
│ │ ├── __init__.py # API package initialization
│ │ ├── routes.py # Route registration
│ │ ├── stock_api.py # Stock-related APIs
│ │ └── basic_api.py # Basic functionality APIs
│ ├── middleware/ # Middleware
│ │ ├── __init__.py # Middleware package initialization
│ │ └── auth.py # Authentication middleware
│ └── services/ # Service layer
│ ├── __init__.py # Service layer package initialization
│ ├── stock_service.py # Stock data service
│ └── basic_service.py # Basic functionality service
├── .pre-commit-config.yaml # Pre-commit configuration file
├── pyproject.toml # Project configuration and dependency management
├── uv.lock # uv lock file
├── Dockerfile # Docker build file
└── run.py # Application entry point
```
## Environment Requirements
- Python 3.9+
- Flask 2.0.1
- futu-api 9.2.5208
- Gunicorn 20.1.0 (for production)
## Installation and Running
### Install using uv (recommended)
```bash
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Clone the repository
git clone https://github.com/jorben/mcp-futu-api.git
cd mcp-futu-api
# Install dependencies and create a virtual environment
uv sync
```
### Install using conda
If you are using a conda environment, use the following commands to install dependencies:
```bash
conda create -n mcp-futu-api python=3.9
conda activate mcp-futu-api
# Clone the repository
git clone https://github.com/jorben/mcp-futu-api.git
cd mcp-futu-api
# Install dependencies
pip install -e .
```
### Environment Variable Configuration
You can configure environment variables in two ways:
1. Set directly in the system:
```bash
# Linux/Mac
export API_TOKEN=your_secure_token
export FUTU_HOST=127.0.0.1 # Default is the local Futu OpenD client address
export FUTU_PORT=11111 # Default is the local Futu OpenD client port
# Windows
set API_TOKEN=your_secure_token
set FUTU_HOST=127.0.0.1
set FUTU_PORT=11111
```
2. Create a `.env` file (recommended for development environment):
```
API_TOKEN=your_secure_token
FUTU_HOST=127.0.0.1
FUTU_PORT=11111
```
**Note**: If you do not set `API_TOKEN`, the system will use the default value `dev_token_for_testing` (only for development environment).
## Development Tools
### Code Formatting and Checking (Ruff)
This project uses [Ruff](https://github.com/astral-sh/ruff) for code formatting and static checking. Ruff is a very fast Python code checker and formatter.
#### Usage
```bash
# Run with uv (recommended)
uv run ruff check . # Check code
uv run ruff check . --fix # Check and auto-fix
uv run ruff format . # Format code
# Run directly (requires activating the virtual environment)
ruff check . # Check code
ruff check . --fix # Check and auto-fix
ruff format . # Format code
```
#### Ruff Configuration
The Ruff configuration for the project is in the `pyproject.toml` file, including:
- Line length limit: 88 characters
- Enabled check rules: pycodestyle, pyflakes, isort, flake8-bugbear, etc.
- Code formatting: use double quotes, space indentation
### Git Commit Hooks (Pre-commit)
This project is configured with [pre-commit](https://pre-commit.com/) hooks that automatically run code checks and formatting before each commit.
#### Install Pre-commit Hooks
```bash
# Install development dependencies (including pre-commit) using uv
uv sync --group dev
pre-commit install
```
#### Manually Run Pre-commit
```bash
# Run on all files
uv run pre-commit run --all-files
# Run on staged files
uv run pre-commit run
```
#### Pre-commit Configuration
The `.pre-commit-config.yaml` file configures the following hooks:
- **Ruff Check and Format**: Automatically fixes code style issues
- **Basic Checks**: Removes trailing spaces, checks YAML/TOML syntax, checks for merge conflicts, etc.
### Running the Application
#### Development Environment
```bash
# Run with uv (recommended)
uv run python run.py
```
The application will start at `http://0.0.0.0:15000`.
#### Production Environment
Use Gunicorn as the WSGI server:
```bash
# Run with uv (recommended)
uv run gunicorn --bind 0.0.0.0:15000 --workers 4 --timeout 120 run:app
# Or run in the python environment
gunicorn --bind 0.0.0.0:15000 --workers 4 --timeout 120 run:app
```
Parameter explanations:
- `--bind`: Bind address and port
- `--workers`: Number of worker processes, recommended to set to 2-4 times the number of CPU cores
- `--timeout`: Request timeout (seconds)
- `run:app`: Import path of the application instance
### Docker Deployment
You can also deploy this application using Docker:
```bash
# Build Docker image
docker build -t mcp-futu-api .
# Run container
docker run -d -p 15000:15000 -e API_TOKEN=your_token -e FUTU_HOST=host.docker.internal -e FUTU_PORT=11111 --name mcp-futu-api mcp-futu-api
```
**Note**:
1. When running in Docker, if you want to connect to the Futu OpenD client on the host machine, use `host.docker.internal` as the value for FUTU_HOST.
2. The Docker image defaults to using Gunicorn as the production server.
## API Documentation
### Get Historical K-line Data
```
GET /api/stock/history_kline
```
**Request Header:**
```
Authorization: Bearer your_token_here
```
**Request Parameters:**
| Parameter | Type | Required | Description |
|-----------|--------|----------|--------------------------------------|
| code | string | Yes | Stock code, e.g., HK.00700 |
| start | string | No | Start date, format YYYY-MM-DD |
| end | string | No | End date, format YYYY-MM-DD |
| max_count | int | No | Maximum records per page, default 1000 |
| ktype | string | No | K-line type, optional values: K_DAY (daily), K_WEEK (weekly), K_MON (monthly), K_QUARTER (quarterly), K_YEAR (yearly), K_1M (1 minute), K_5M (5 minutes), K_15M (15 minutes), K_30M (30 minutes), K_60M (60 minutes), K_3M (3 minutes), default is K_DAY |
| autype | string | No | Adjustment type, optional values: NONE (no adjustment), QFQ (forward adjustment), HFQ (backward adjustment), default is QFQ |
**Example:**
```
GET /api/stock/history_kline?code=HK.00700&start=2023-01-01&end=2023-02-01&ktype=K_DAY&autype=QFQ
```
**Response:**
Returns K-line data in JSON format.
**Response Field Descriptions:**
| Field | Type | Description |
|-----------------|--------|---------------------|
| code | str | Stock code |
| name | str | Stock name |
| time_key | str | K-line time |
| open | float | Opening price |
| close | float | Closing price |
| high | float | Highest price |
| low | float | Lowest price |
| pe_ratio | float | Price-to-earnings ratio |
| turnover_rate | float | Turnover rate |
| volume | int | Trading volume |
| turnover | float | Trading amount |
| change_rate | float | Price change rate |
| last_close | float | Last closing price |
### Get Stock Capital Flow Data
```
GET /api/stock/capital_flow
```
**Request Header:**
```
Authorization: Bearer your_token_here
```
**Request Parameters:**
| Parameter | Type | Required | Description |
|-----------|--------|----------|--------------------------------------|
| code | string | Yes | Stock code, e.g., HK.00700 |
| start | string | No | Start date, format YYYY-MM-DD |
| end | string | No | End date, format YYYY-MM-DD |
| period_type| string| No | Period type, optional values: DAY (daily), WEEK (weekly), MONTH (monthly), INTRADAY (real-time), default is DAY |
**Example:**
```
GET /api/stock/capital_flow?code=HK.00700&start=2023-01-01&end=2023-02-01&period_type=DAY
```
**Response:**
Returns capital flow data in JSON format.
**Response Field Descriptions:**
| Field | Type | Description |
|----------------------|--------|-----------------------------------------------|
| in_flow | float | Overall net inflow |
| main_in_flow | float | Net inflow from main large orders (valid only for daily, weekly, and monthly periods) |
| super_in_flow | float | Net inflow from super large orders |
| big_in_flow | float | Net inflow from large orders |
| mid_in_flow | float | Net inflow from medium orders |
| sml_in_flow | float | Net inflow from small orders |
| capital_flow_item_time| str | Start time |
| last_valid_time | str | Last valid time of the data (valid only for real-time periods) |
### Get Stock Capital Distribution Data
```
GET /api/stock/capital_distribution
```
**Request Header:**
```
Authorization: Bearer your_token_here
```
**Request Parameters:**
| Parameter | Type | Required | Description |
|-----------|--------|----------|--------------------------------------|
| code | string | Yes | Stock code, e.g., HK.00700 |
**Example:**
```
GET /api/stock/capital_distribution?code=HK.00700
```
**Response:**
Returns capital distribution data in JSON format.
**Response Field Descriptions:**
| Field | Type | Description |
|----------------------|--------|-----------------------------------------------|
| capital_in_super | float | Inflow amount from super large orders |
| capital_in_big | float | Inflow amount from large orders |
| capital_in_mid | float | Inflow amount from medium orders |
| capital_in_small | float | Inflow amount from small orders |
| capital_out_super | float | Outflow amount from super large orders |
| capital_out_big | float | Outflow amount from large orders |
| capital_out_mid | float | Outflow amount from medium orders |
| capital_out_small | float | Outflow amount from small orders |
| update_time | str | Update time string |
### Get Historical K-line Quota
```
GET /api/basic/history_kline_quota
```
**Request Header:**
```
Authorization: Bearer your_token_here
```
**Response:**
```json
{
"used": 100, // Used quota
"available": 900 // Available quota
}
```
## Troubleshooting
### Package Management Issues
#### uv Related Issues
If the uv command is not recognized, ensure it is correctly installed and added to PATH:
```bash
# Reinstall uv
curl -LsSf https://astral.sh/uv/install.sh | sh
# Or install using pip
pip install uv
```
#### Virtual Environment Issues
If there are issues with the virtual environment, you can delete and recreate it:
```bash
# Delete the existing virtual environment
rm -rf .venv
# Reinstall dependencies
uv sync --group dev
```
### Code Quality Tool Issues
#### Ruff Configuration Issues
If Ruff checks fail, please check the configuration:
```bash
# View current configuration
uv run ruff check --show-settings
# Ignore specific files
echo "exclude = ['migrations/', '*.pb2.py']" >> pyproject.toml
```
#### Pre-commit Hook Issues
If pre-commit hooks fail to execute:
```bash
# Reinstall hooks
uv run pre-commit uninstall
uv run pre-commit install
# Update hooks
uv run pre-commit autoupdate
# Skip hook commit (not recommended)
git commit --no-verify
```
### Authentication Issues
Ensure that the Authorization is correctly set in the request header, formatted as `Bearer your_token_here`, where `your_token_here` should match the value of the environment variable `API_TOKEN`.
### Production Environment Considerations
1. Do not use the Flask development server (`python run.py`) to run the application in a production environment.
2. Always use Gunicorn or another production-grade WSGI server.
3. Ensure that the appropriate number of worker processes (workers) and timeout settings are configured.
4. It is recommended to use a reverse proxy (such as Nginx) to handle SSL termination and load balancing.
Connection Info
You Might Also Like
valuecell
Valuecell is a Python project for efficient data management.
hexstrike-ai
HexStrike AI is an AI-powered MCP cybersecurity automation platform with 150+ tools.
AP2
AP2 provides code samples and demos for the Agent Payments Protocol.
mcp-local-rag
A local, privacy-focused document search server using MCP for semantic search.
xiaohongshu
AI-powered web app for auto-generating and publishing content on Xiaohongshu.
finance-trading-ai-agents-mcp
An open-source MCP server for financial analysis and trading, supporting...