---
title: "我开源了 QQQ 末日期权自动交易系统 "
type: "Topics"
locale: "en"
url: "https://longbridge.com/en/topics/40122313.md"
description: "基于长桥 Python SDK，全自动交易 QQQ 0DTE 虚值期权。回测 761 笔/2.3 年，胜率 75.8%。本系统仅供参考学习部署，具体交易策略还需要自己优化。一、策略说明做什么全自动交易 QQQ 当日到期（0DTE）虚值期权，每天美东 09:35-15:50 期间自动检测信号、下单、持仓管理、平仓..."
datetime: "2026-04-23T03:06:19.000Z"
locales:
  - [en](https://longbridge.com/en/topics/40122313.md)
  - [zh-CN](https://longbridge.com/zh-CN/topics/40122313.md)
  - [zh-HK](https://longbridge.com/zh-HK/topics/40122313.md)
author: "[热血青年](https://longbridge.com/en/profiles/17928542.md)"
---

# 我开源了 QQQ 末日期权自动交易系统 

> 基于长桥 Python SDK，全自动交易 QQQ 0DTE 虚值期权。回测 761 笔/2.3 年，胜率 75.8%。

> 本系统仅供参考学习部署，具体交易策略还需要自己优化。

* * *

## 一、策略说明

### 做什么

全自动交易 **QQQ 当日到期（0DTE）虚值期权**，每天美东 09:35-15:50 期间自动检测信号、下单、持仓管理、平仓。

### 怎么做

**两条信号路径同时运行：**

**1\. 趋势突破（顺势）**

-   价格突破前 5 根 1 分钟 K 线的高点 → 买入 Call（做多）
-   价格跌破前 5 根 1 分钟 K 线的低点 → 买入 Put（做空）
-   4 层过滤：SMA20 趋势 + 量能确认 + 动量确认 + K 线实体

**2\. 衰竭反转（逆势）**

-   从日内高点回落≥0.2% → 买入 Call（抄底）
-   从日内低点反弹≥0.2% → 买入 Put（逃顶）
-   每天最多 1 次，防止频繁抄底

### 怎么管

**动态止盈：**

1.  亏损 25% → 止损全部平仓
2.  盈利 100% → 平仓一半（锁定利润）
3.  从最高盈利回撤 30% → 全部平仓
4.  持仓超过 15 分钟 → 超时平仓

**风控：**

-   每笔最小 10 张期权
-   日最大交易 8 笔
-   日亏损达 5% 停止交易

### 回测结果

指标

数值

总交易

761 笔 / 2.3 年

胜率

75.8%

总收益

+3111%

年化收益

354.8%

最大回撤

25.19%

* * *

## 二、环境准备

### 1\. 系统要求

-   Python 3.10+
-   Linux 或 WSL（Windows 原生不推荐）
-   长桥 API 密钥（需开通美股期权权限）

### 2\. 安装依赖

`pip install longbridge flask numpy scipy`

* * *

## 三、获取代码

`git clone` `https://github.com/1797346220/qqq-trading-system.git cd qqq-trading-system`

* * *

## 四、配置密钥

### 1\. 申请长桥 API

1.  访问 https://open.longportapp.com 注册账号
2.  创建应用，获取以下三个密钥：
    -   `APP_KEY`
    -   `APP_SECRET`
    -   `ACCESS_TOKEN`
3.  确保账户已开通美股期权交易权限

### 2\. 创建 .env 文件

在项目目录创建 `.env` 文件，填入你自己的密钥：

`LONGPORT_APP_KEY=你的 APP_KEY LONGPORT_APP_SECRET=你的 APP_SECRET LONGPORT_ACCESS_TOKEN=你的 ACCESS_TOKEN`

**⚠️ 重要：**`**.env**` **文件绝对不能提交到 Git！**

### 3\. 验证密钥

`import os with open('.env') as f:    for line in f:        line = line.strip()        if '=' in line and not line.startswith('#'):            k, v = line.split('=', 1)            os.environ.setdefault(k.strip(), v.strip().strip('"')) from longbridge.openapi import Config, QuoteContext config = Config.from_apikey_env() ctx = QuoteContext(config) quotes = ctx.quote(['QQQ.US']) print(f"QQQ: ${float(quotes[0].last_done):.2f}")`

如果输出 QQQ 价格，说明密钥配置成功。

* * *

## 五、启动系统

### 方式一：直接启动

`# 终端 1：启动交易引擎 PYTHONUNBUFFERED=1 python live_trader.py # 终端 2：启动 Web 仪表盘 PYTHONUNBUFFERED=1 python trader_web.py`

### 方式二：后台启动

`# 后台启动交易引擎 nohup PYTHONUNBUFFERED=1 python live_trader.py > trader.log 2>&1 & # 后台启动 Web 仪表盘 nohup PYTHONUNBUFFERED=1 python trader_web.py > web.log 2>&1 &`

### 方式三：watchdog 守护（推荐）

`python watchdog.py`

watchdog 会自动管理 live\_trader.py 的生命周期，崩溃后自动重启。

* * *

## 六、验证部署

### 1\. 检查进程

`ps aux | grep -E 'live_trader|trader_web' | grep -v grep`

应该看到两个 Python 进程在运行。

### 2\. 检查状态文件

`python -c " import json d = json.load(open('state.json')) print(f'连接: {d[\"connected\"]}') print(f'运行: {d[\"running\"]}') print(f'K 线数: {d[\"candle_count\"]}') "`

### 3\. 访问 Web 仪表盘

浏览器打开 `http://127.0.0.1:8080`

* * *

## 七、文件说明

文件

说明

`live_trader.py`

核心交易引擎

`trader_web.py`

Web 仪表盘

`watchdog.py`

守护进程

`update_gist.py`

同步交易记录

`.env`

密钥配置（不入库）

`state.json`

实时状态（自动生成）

`today.csv`

当日 K 线（自动生成）

`records/*.json`

交易记录（自动生成）

* * *

## 八、常见问题

### Q: ImportError: No module named 'longbridge'

`pip install longbridge`

### Q: 长桥 API 连接失败

检查：

1.  `.env` 文件是否存在且格式正确
2.  环境变量名是 `LONGPORT_*` 不是 `LONGBRIDGE_*`
3.  使用 `Config.from_apikey_env()` 不是 `Config.from_env()`

### Q: 信号检测无输出

检查：

1.  state.json 的 candle\_count 是否\>0
2.  当前时间是否在交易窗口内（美东 09:35-15:50）
3.  是否有持仓阻塞

### Q: 期权下单失败

检查：

1.  期权合约代码格式是否正确（.US 后缀 + 整数行权价）
2.  到期日是否用美东时间生成
3.  账户是否有期权交易权限

* * *

## 九、策略参数

如需调整策略，修改 `live_trader.py` 中的 CONFIG：

`CONFIG = {    'sl': 0.25,               # 止损 25%    'lookback': 5,            # 突破窗口 5 根 K 线    'vol_mult': 0.8,          # 量能倍数    'min_body': 0.0003,       # K 线实体 0.03%    'max_trades': 8,          # 日最大交易    'start_time': '09:35',    # 入场开始（美东）   'end_time': '15:50',      # 入场结束（美东）   # ... 其他参数见代码注释 }`

**⚠️ 修改后必须同步修改** `**trader_web.py**` **中的 CONFIG，然后重启两个进程。**

* * *

## 开源地址

https://github.com/1797346220/qqq-trading-system

* * *

## 免责声明

本系统仅供学习研究使用。期权交易具有高风险，可能导致本金损失。作者不对使用本系统产生的任何损失负责。

$XIAOMI-W(01810.HK) $Invesco QQQ Trust(QQQ.US)

### Related Stocks

- [QQQ.US](https://longbridge.com/en/quote/QQQ.US.md)
- [SQQQ.US](https://longbridge.com/en/quote/SQQQ.US.md)
- [PSQ.US](https://longbridge.com/en/quote/PSQ.US.md)
- [01810.HK](https://longbridge.com/en/quote/01810.HK.md)
- [81810.HK](https://longbridge.com/en/quote/81810.HK.md)
- [HXXD.SG](https://longbridge.com/en/quote/HXXD.SG.md)
- [XIACY.US](https://longbridge.com/en/quote/XIACY.US.md)

## Comments (84)

- **热血青年 · 2026-05-08T14:46:26.000Z · 👍 1**: The take-profit strategy shouldn't be too complex; the more conditions there are, the more likely bugs will occur.The same goes for entry condition filtering - if it's too strict, you'll only enter after the trend has already finished rising;if it's too loose, you're easily fooled by false signals, 
  - **卖飞的小韭菜** (2026-05-08T15:39:41.000Z): Buddy, I've also thought about and backtested this strategy of yours, and it turns out we had the same idea. Also, I had fewer trades than you today. The entry timing wasn't great yesterday or today; 
  - **卖飞的小韭菜** (2026-05-08T15:41:32.000Z): Today's
  - **热血青年** (2026-05-08T15:56:28.000Z): I didn't actually open that many positions; I took profits in many batches. My win rate for one-sided trends is very high, and I'm still optimizing for range-bound markets.
- **V震天 · 2026-05-04T08:20:06.000Z**: Bro, could you share your optimized strategy? My win rate is only 29%, it's so painful 😣
  - **新能源_87ba4G** (2026-05-08T08:14:31.000Z): Huh? I guessed about half of it, over 40%, that's so bad.
- **ian-914 · 2026-04-30T14:02:17.000Z**: Is it that the OPRA US stock options market data is going to start charging? 😂
  - **卖飞的小韭菜** (2026-04-30T14:12:06.000Z): Yes, you need to subscribe, continuous monthly subscription is 22 HKD, remember to get the API version.
  - **新能源_87ba4G** (2026-05-01T06:08:43.000Z): Boss, just buy the option? Don't need to buy Nasdaq to have QQQ's own data?
  - **卖飞的小韭菜** (2026-05-01T07:15:09.000Z): The API has stock market data but no options market data, so we need to buy it.
- **坚决不入坑 · 2026-04-29T17:10:59.000Z**: Boss
- **左侧+耐心 · 2026-04-29T05:48:59.000Z · 👍 1**: I tried to replicate it, and the win rate wasn't as high as the 75% you mentioned, bro🥲 Looks like there's still a long way to go.
  - **苏辂** (2026-04-30T14:35:01.000Z): I tried, and it's really hard to get a win rate over 50% 😭
  - **新能源_87ba4G** (2026-05-03T13:49:08.000Z): When backtesting, if you only have the QQQ price, how do you consider the relationship between the option price and the underlying stock price?
  - **零度热饮** (2026-05-03T14:30:26.000Z): Same, I thought it was my problem 😂
- **卖飞的小韭菜 · 2026-04-28T23:29:48.000Z**: Handing in the assignment, there are still many issues,1. The data on the web interface doesn't match Longbridge's.2. Many orders get rejected, bro, is your max_trades 8 the maximum number of trades per day?
  - **卖飞的小韭菜** (2026-04-28T23:45:41.000Z): It used up 30 million of my tokens in a single day, such a waste of tokens😭
  - **苏辂** (2026-04-29T04:46:16.000Z): Boss, I'm a bit confused about the profit-taking and stop-loss logic in points 1 and 4. Logically, it shouldn't close the position at this level of volatility, right?
  - **卖飞的小韭菜** (2026-04-29T04:57:36.000Z): Code issue, still being fixed. First day trial run, will check again tonight.
- **Eastwen · 2026-04-28T19:32:47.000Z**: Actually, this system just has an additional web UI.
- **明止 · 2026-04-28T03:42:19.000Z · 👍 1**: Thank you very much for sharing. It was implemented using Lobster auto-programming, with the addition of volatility impact parameters and a parameter control panel.
  - **热血青年** (2026-04-28T04:05:37.000Z): 👍🏻👍🏻👍🏻
- **duriancat · 2026-04-27T22:26:22.000Z**: Is it necessary to purchase US stock options market data?
  - **热血青年** (2026-04-28T04:05:43.000Z): Yes
  - **duriancat** (2026-04-28T12:35:39.000Z): Is buying OpenAPI's lv1 enough?
  - **新能源_87ba4G** (2026-05-08T08:13:24.000Z): The cheaper one
- **华尔该没有雪 · 2026-04-27T17:31:11.000Z**: Does Longbridge not have an API to fetch historical options data? How do you do backtesting?
  - **热血青年** (2026-04-28T04:06:42.000Z): Backtest qqq
  - **华尔该没有雪** (2026-04-28T05:34:24.000Z): Why are you backtesting the QQQ underlying stock for the options in this trade?
  - **新能源_87ba4G** (2026-05-04T05:27:10.000Z): Is it the price of the option? If it's an expiring option, can it be derived from the underlying stock price?
- **金裤衩 · 2026-04-27T16:43:35.000Z**: Is this backtesting result based on QQQ? Or is it based on options?
  - **热血青年** (2026-04-28T04:06:01.000Z): Q
- **热血青年 · 2026-04-27T14:11:09.000Z**: I'm responsible for having fun, you handle the rest automatically 😎$Invesco QQQ Trust(QQQ.US)
  - **不奋东西** (2026-04-27T14:14:01.000Z): Which identifier is for the simulated account? The real account is live.
  - **Seanyue** (2026-04-27T22:45:47.000Z): Why can't my simulated account trade US stock options?
  - **龙小瑞** (2026-04-28T03:10:56.000Z): Bro, I have a question. Could my order failure be caused by | USOption | You do not have access to the market's Open API data. Please visit the Quotes Store to purchase. |？
- **Seanyue · 2026-04-26T04:27:50.000Z · 👍 1**: I have no money in my trading account, so I tried this simulation over the weekend for fun.
- **忌贪忌躁忌赌落袋为安 · 2026-04-24T03:40:52.000Z**: This weekend, I also referred to your past shares to see if I could build my own system. Thanks for sharing.
- **不奋东西 · 2026-04-24T02:06:47.000Z**: Please provide the access settings for the simulated trading program, I'd like to try it too.
  - **热血青年** (2026-04-24T02:37:56.000Z): Check out my first two tutorials
  - **不奋东西** (2026-04-24T04:31:57.000Z): Good
- **梵天一页书 · 2026-04-24T01:17:37.000Z**: Only documents, no code? AI can't create something out of thin air either.
  - **热血青年** (2026-04-24T02:37:36.000Z): I've already given you the documents, why are you still worried about not having the code? Just let the AI generate it directly.
  - **卖飞的小韭菜** (2026-04-24T03:32:41.000Z): Just finished running it with cursor, will try it out tonight👀
  - **卖飞的小韭菜** (2026-04-24T03:51:50.000Z): Bro, just finished running and it prompted me that I might need to enable real-time options quote permissions. Bro, have you enabled yours?
- **tst · 2026-04-24T00:12:45.000Z**: Does the backtest include transaction fees?
  - **热血青年** (2026-04-24T02:36:47.000Z): Don't consider these in backtesting, focus mainly on win rate and success rate.
- **神威天将军 · 2026-04-23T19:29:40.000Z**: I just like selfless and dedicated bosses😎
- **风w长宜放眼量 · 2026-04-23T17:13:01.000Z**: I don't know how to program at all🥹
  - **热血青年** (2026-04-24T02:35:33.000Z): No need to know programming, AI will handle everything
- **Sonny96 · 2026-04-23T16:20:49.000Z**: What hardware is needed?
  - **热血青年** (2026-04-23T16:23:03.000Z): As long as you have a computer
