npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ibkr-flex-query-parser

v2.1.0

Published

IBKR Flex Query Report Parser for Option Trade Calendar Data

Readme

IBKR Flex Query Parser

解析 IBKR Flex Query CSV 报表,过滤日内期权(0DTE)交易,聚合每日已实现盈亏(FifoPnlRealized),输出交易日历 JSON。

架构

DataSource → Parser → FilterPipeline → FifoPnLAggregator → CalendarAggregator → Exporter

每层均有独立接口(IDataSource / IReportParser / ITradeFilter / ICalendarExporter),可独立替换或扩展。

src/
├── cli.ts                        # CLI 入口
├── index.ts                      # SDK 导出
├── core/engine.ts                # FlexQueryParserEngine(Facade 门面)
├── datasources/                  # 数据源层 (IDataSource, LocalFile, IBKRFlexWebService)
├── parsers/                      # 解析器层 (IReportParser, IBKRFlexCSVParser)
├── filters/                      # 过滤管道层 (ITradeFilter, AssetClass, DateRange, Intraday, Pipeline)
├── aggregators/                  # 聚合层 (FifoPnLAggregator, CalendarAggregator)
├── exporters/                    # 导出器层 (ICalendarExporter, JSONFileExporter, CSVFileExporter)
├── types/                        # ibkr.ts / calendar.ts 类型声明
└── utils/                        # date-utils.ts / errors.ts 工具与异常定义

快速上手

1. 配置 .env

IBKR_FLEX_TOKEN=your_token_here
IBKR_FLEX_QUERY_ID=your_query_id_here
OUTPUT_FILE=calendar_data.json

# 可选:导出按日期排序的期权明细 CSV(用于手动校验),留空则不导出
OPTION_TRADES_OUTPUT=output/option_trades.csv

# 可选:本金 (USD),用于计算年化收益率
INITIAL_CAPITAL=50000

Token 有效期默认 6 小时,过期后需在 IBKR 后台重新生成。
生成 Token 时 Valid For IP Address 建议留空,避免 IP 绑定导致 Code 1025。

2. 运行

# 从 IBKR API 获取数据
pnpm dev --start-date 2026-01-01 --end-date 2026-07-31

# 解析本地 CSV 文件
pnpm dev --file ./example/flex_query_data.csv

# 指定输出路径及导出期权明细 CSV
pnpm dev --file ./example/flex_query_data.csv --output ./dist/calendar_data.json --option-csv ./dist/option_trades.csv

CLI 参数:

| 参数 | 简写 | 说明 | | ------ | ------ | ------ | | --start-date | -s | 起始日期(YYYY-MM-DD 或 YYYYMMDD) | | --end-date | -e | 结束日期 | | --token | -t | 覆盖 .env Token | | --query-id | -q | 覆盖 .env Query ID | | --file | -f | 本地 CSV 文件路径 | | --output | -o | 输出 JSON 路径 | | --option-csv | -c | 导出按日期排序的期权明细 CSV 路径(用于校验) |

3. 构建与测试

pnpm build   # TypeScript 编译
pnpm test    # Vitest 单元测试

作为库使用

import { FlexQueryParserEngine, IBKRFlexWebServiceDataSource, IBKRFlexCSVParser, JSONFileExporter } from 'ibkr-flex-query-parser';

const engine = new FlexQueryParserEngine(
  new IBKRFlexWebServiceDataSource({ token, queryId }, { startDate, endDate }),
  new IBKRFlexCSVParser(),
  new JSONFileExporter('./calendar_data.json'),
  {
    dateRange: { startDate, endDate },
    initialCapital: 50000,
    optionTradesOutputPath: './output/option_trades.csv', // 可选
  }
);

const calendarData = await engine.run();

GitHub Actions 自动化配置

在 GitHub 仓库中设置 Settings -> Secrets and variables -> Actions:

必填 Secrets:

  • IBKR_FLEX_TOKEN: IBKR Web Service Token
  • IBKR_FLEX_QUERY_ID: Flex Query ID (如 1590689)

可选 Secrets / Variables(配置日期范围与本金):

  • START_DATE: 起始日期(例如 2026-01-01)
  • END_DATE: 结束日期(例如 2026-12-31,留空默认获取至今最新数据)
  • INITIAL_CAPITAL: 本金(例如 50000,用于计算年化收益率)

说明:手动触发工作流(workflow_dispatch)时,也可在 GitHub Actions 界面临时输入自定义的 startDate 和 endDate 进行区间拉取。

注意事项

  • IBKR 对同一 Query ID 限制每 1~2 分钟只能请求一次(Code 1025),触发后需等待 3~5 分钟再重试。
  • 日期区间同时在 API 层(fd / td 参数)和内存层(DateRangeFilter)生效,双重保障数据精度。
  • 导出的期权明细 CSV(OPTION_TRADES_OUTPUT)已按 TradeDate(日期升序)及交易时间排序,方便与交割单进行手动校验。