惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
About on SuperTechFans
Cloudbric
Cloudbric
C
CERT Recently Published Vulnerability Notes
G
GRAHAM CLULEY
V
Vulnerabilities – Threatpost
C
Cisco Blogs
T
Tenable Blog
P
Privacy International News Feed
T
The Exploit Database - CXSecurity.com
I
Intezer
AWS News Blog
AWS News Blog
IT之家
IT之家
博客园 - 司徒正美
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 【当耐特】
The Hacker News
The Hacker News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
博客园 - Franky
人人都是产品经理
人人都是产品经理
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
V
Visual Studio Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
H
Hacker News: Front Page
Latest news
Latest news
Scott Helme
Scott Helme
腾讯CDC
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
A
Arctic Wolf
S
Securelist
雷峰网
雷峰网
The GitHub Blog
The GitHub Blog
Project Zero
Project Zero
Google DeepMind News
Google DeepMind News
P
Palo Alto Networks Blog
F
Fortinet All Blogs
Schneier on Security
Schneier on Security
云风的 BLOG
云风的 BLOG
Security Archives - TechRepublic
Security Archives - TechRepublic
The Last Watchdog
The Last Watchdog
WordPress大学
WordPress大学
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 最新话题
S
Schneier on Security
NISL@THU
NISL@THU
Jina AI
Jina AI
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to capture gap-free L2 order book data from Binance
BaldQuant · 2026-06-02 · via DEV Community

BaldQuant

How to capture gap-free L2 order book data from Binance

Most homemade order book recorders are subtly wrong. They work fine in a terminal demo, produce files that open in pandas, and then quietly hand you garbage data — crossed books, missing updates, phantom price levels — that only shows up when a backtest produces an edge that evaporates live.

This post explains the failure modes, why they happen, and the protocol that prevents them. At the end I'll show the open-source tool I built that implements all of it.


Why order book capture is harder than it looks

Binance doesn't give you a live order book. It gives you two things:

  1. A REST snapshot — a point-in-time full book you fetch on demand
  2. A WebSocket diff stream — a sequence of incremental updates

Your job is to merge them into a coherent, continuously-updated book. That merge is where every homemade implementation goes wrong.

The common failures

Connecting to the diff stream after fetching the snapshot. If you fetch the snapshot first, then subscribe to diffs, you've already missed the updates that happened between the two. The gap is silent — the book just drifts wrong from the start.

Not buffering diffs during the snapshot fetch. The snapshot fetch takes 50–200ms over the network. You need to subscribe to the diff stream first, buffer every event that arrives while the snapshot is in flight, then replay the buffer. If you don't buffer, you drop updates.

Ignoring the sequence ID. Every diff event has an u field (the final update ID it covers) and a U field (the first). The snapshot has a lastUpdateId. Only diffs where U <= lastUpdateId + 1 <= u are valid seeds. If you find a gap — an event where the previous event's u doesn't match this event's expected predecessor — you're looking at missing data and your book is wrong.

Logging gaps instead of halting. A sequence break should be fatal. A book that's missing updates is not a book with a warning attached — it's a bad book. Writing it to disk with a log entry is worse than not writing it at all, because you won't see the warning in a year when you're building a model on the data.


The correct protocol for Binance USDT-M Futures

Binance documents a six-step process. Here it is, with the parts they underemphasize:

Step 1: Subscribe to the diff stream first

ws = connect("wss://fstream.binance.com/stream?streams=btcusdt@depth@100ms")

Start collecting events immediately. Don't wait for the snapshot. Don't process them yet — just buffer them.

Step 2: Fetch the REST snapshot

snapshot = GET("https://fapi.binance.com/fapi/v1/depth?symbol=BTCUSDT&limit=1000")
# snapshot["lastUpdateId"] is your seed

While this request is in flight, your WebSocket buffer is filling up with diffs. That's correct.

Step 3: Discard stale buffered events

Any buffered diff where u < lastUpdateId is older than your snapshot. Discard it.

Step 4: Find the first applicable diff

You need the first buffered event where:

U <= lastUpdateId + 1 <= u

This is the first diff that picks up exactly where the snapshot left off. If no buffered event satisfies this, your buffer window was too short — drop everything and restart from Step 1.

Step 5 (futures-specific): Verify the pu field

This is where futures differs from spot, and where most implementations copied from spot tutorials fail.

On USDT-M futures, every diff event has a pu field: the u value of the previous event. For every event after the first:

event["pu"] == previous_event["u"]

If this breaks, you have a gap — a missed event — and the book is corrupted. Halt and resync.

On spot, the equivalent check is U == last_u + 1. On futures, use pu == last_u. Don't mix them up.

Step 6: Apply diffs and maintain the book

For each diff event, update your price levels:

  • Qty > 0: set level
  • Qty == 0: remove level

After every update, check for a crossed book: if best bid >= best ask, something is wrong. Halt.


Invariants that must halt capture (not log-and-continue)

These are not warnings. If any of these fire, you stop writing data and resync:

Invariant What it catches
pu != last_u Missed diff event — book has a hole
best_bid >= best_ask Crossed book — merge logic is wrong
Out-of-order u Stale or duplicate event
Clock skew > 1s Local timestamps are unreliable
Stream silence > threshold Dead connection that didn't disconnect cleanly

The key point: log-and-continue produces a file that looks valid. Halt-and-resync produces a gap you can see. A visible gap is always better than invisible corruption.


What clean data looks like

After implementing this correctly, you get three streams per symbol, written to Parquet, partitioned by date:

books — full L2 snapshot at every diff event (~100ms cadence)

Field Notes
timestamp_ms Exchange event time
received_at_ms Local receive time — received_at_ms − timestamp_ms is your capture latency
update_id Sequence ID for gap verification
microprice (bid_qty × ask + ask_qty × bid) / (bid_qty + ask_qty)
imbalance bid_qty / (bid_qty + ask_qty) at best level
mid, spread Convenience columns
bid_price_N, bid_qty_N Full ladder, N levels per side

trades — aggregated trade events with taker_sign (+1 taker bought, −1 taker sold)

mark_price — Binance mark price, index price, and next funding rate at 1-second intervals

Having all three lets you correlate order flow imbalance with trade aggression and funding dynamics — the combination that most signal research requires.


The tool

I built binance-l2-capture to implement exactly this protocol. It runs on Python 3.11+, self-hosted, bring your own API key. The data never leaves your machine.

git clone https://github.com/Balleing/binance-l2-capture.git
cd binance-l2-capture
pip install -e .
cp .env.example .env   # add BINANCE_API_KEY
l2cap run              # data starts landing in ./data/

It implements the full six-step merge protocol, checks pu continuity on every event, halts on invariant violations rather than logging them, and auto-resyncs after a gap. On a $6/month VPS it captures two symbols continuously with no intervention.

The code is MIT, the core will stay free. If you're running more symbols or want a monitoring dashboard, I'm building a Pro tier — star the repo to follow along.


The one-line test for your existing capture

If you have an existing order book recorder, run this against a day of data:

import polars as pl

df = pl.scan_parquet("data/BTCUSDT/books/2024-06-01/*.parquet").collect()
gaps = (df["update_id"].diff().drop_nulls() != 1).sum()
print(f"Sequence gaps: {gaps}")

If gaps > 0, your book has holes. If it prints 0 but you weren't checking pu, re-read Step 5.


Questions, corrections, or "my backtest still blows up" — I'm @BaldQuant on X. The repo issues tab works too.