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

推荐订阅源

Google Online Security Blog
Google Online Security Blog
S
Security @ Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
人人都是产品经理
人人都是产品经理
The Hacker News
The Hacker News
W
WeLiveSecurity
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
博客园 - 司徒正美
雷峰网
雷峰网
L
LINUX DO - 最新话题
博客园 - 叶小钗
云风的 BLOG
云风的 BLOG
The Last Watchdog
The Last Watchdog
V2EX - 技术
V2EX - 技术
S
Security Affairs
有赞技术团队
有赞技术团队
月光博客
月光博客
T
Threatpost
T
Tor Project blog
O
OpenAI News
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
V
V2EX
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
博客园 - 三生石上(FineUI控件)
D
Docker
AWS News Blog
AWS News Blog
AI
AI
P
Proofpoint News Feed
K
Kaspersky official blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
D
Darknet – Hacking Tools, Hacker News & Cyber Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
Securelist
F
Fortinet All Blogs
F
Full Disclosure
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
量子位
Hacker News - Newest:
Hacker News - Newest: "LLM"
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
P
Palo Alto Networks Blog
Cyberwarzone
Cyberwarzone
Cisco Talos Blog
Cisco Talos Blog
美团技术团队
N
News | PayPal Newsroom
T
The Blog of Author Tim Ferriss
MyScale Blog
MyScale Blog

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
The Bug That Cost Me Three Weeks: Why Your SL/TP Logic Is Probably Wrong
Vuk Stanic · 2026-04-27 · via DEV Community

This is the story of a production bug I fixed, turned into a book. It's also why most algorithmic traders fail.

Every algorithmic trader thinks they understand stop-loss and take-profit (SL/TP). Most are wrong. Not subtly wrong — catastrophically wrong in ways that don't show up in backtesting but destroy live systems.

This is the opening chapter of my second book, and it's the reason I wrote the whole series.

The Naive Implementation

Here's what the original code looked like in our production system:

struct Position {
    entry_price: Decimal,
    sl_price: Decimal,
    tp_price: Decimal,
    sl_triggered: bool,
    tp_triggered: bool,
}

fn check_sl_tp(position: &mut Position, current_price: Decimal) {
    if current_price <= position.sl_price && !position.sl_triggered {
        position.sl_triggered = true;
        close_position(position);
    }

    if current_price >= position.tp_price && !position.tp_triggered {
        position.tp_triggered = true;
        close_position(position);
    }
}

Enter fullscreen mode Exit fullscreen mode

Looks reasonable, right? Check price against SL/TP levels, set a flag, close if triggered.

It failed in production. Here's why.

Failure Mode 1: Flag-Based Checking Doesn't Track What Actually Happened

The problem with sl_triggered: bool is that it tells you that something happened, but not what actually happened.

Consider this sequence in a fast-moving market:

T=0:    Price at $105.00, position long with SL at $100.00
T=1:    Price drops to $99.95 (below SL!)
T=2:    Your check runs, sets sl_triggered = true
T=3:    Your system submits close order at $99.95
T=4:    Price bounces back to $100.50
T=5:    Exchange confirms: fill at $99.95

Enter fullscreen mode Exit fullscreen mode

Your code set sl_triggered = true when price crossed $100.00. The exchange filled you at $99.95. Your flag doesn't tell you what fill price you actually got.

More critically: In step T=4, before the exchange confirmed the fill, your code thought "SL triggered, position closed." But the position wasn't actually closed yet — it was in flight.

This is the state vs event confusion. Your flag tracks an event (trigger), not a state (position actually closed).

Failure Mode 2: Re-Entry on the Next Tick

Here's where it gets really bad. After the SL triggers:

T=10:   Price moves back up to $102.00
T=11:   Your strategy sees "price is $102, no open position"
T=12:   Strategy decides to re-enter long
T=13:   New position opened at $102.00
T=14:   Price drops again to $99.90
T=15:   Another SL triggered, another loss

Enter fullscreen mode Exit fullscreen mode

Your system has no memory that the previous close was an SL close. It just sees "no position, price looks good, buy."

This is the re-entry problem — and it's more expensive than the original loss.

The Correct Mental Model

SL/TP should be state-based, not event-based. Instead of "did we trigger?" think "what should we do given the current state and price?"

enum PositionState {
    Open,           // Position is active, checks are running
    ClosePending,   // Close order submitted, waiting for fill
    Closed,         // Position fully exited, no more checks
}

struct Position {
    entry_price: Decimal,
    sl_price: Decimal,
    tp_price: Decimal,
    state: PositionState,

    // Track the close order, not just the trigger
    close_order_id: Option<u64>,
    close_trigger_price: Option<Decimal>,
    opened_at_ns: u64,
    close_submitted_at_ns: Option<u64>,
    closed_at_ns: Option<u64>,
}

Enter fullscreen mode Exit fullscreen mode

Key difference: The close_order_id field tracks the actual close order, not just a trigger flag. If you have a close order ID, the position is in ClosePending state. If it's filled, the state transitions to Closed.

enum SLTPAction {
    Nothing,
    TriggerSL,
    TriggerTP,
}

fn check_sl_tp(position: &Position, current_price: Decimal) -> SLTPAction {
    if position.state != PositionState::Open {
        return SLTPAction::Nothing;
    }

    if current_price <= position.sl_price {
        SLTPAction::TriggerSL
    } else if current_price >= position.tp_price {
        SLTPAction::TriggerTP
    } else {
        SLTPAction::Nothing
    }
}

fn on_action(position: &mut Position, action: SLTPAction, current_price: Decimal) -> Result<(), Error> {
    match action {
        SLTPAction::Nothing => Ok(()),
        SLTPAction::TriggerSL | SLTPAction::TriggerTP => {
            let order_id = submit_close_order(position, current_price)?;
            position.state = PositionState::ClosePending;
            position.close_order_id = Some(order_id);
            position.close_trigger_price = Some(current_price);
            position.close_submitted_at_ns = Some(current_timestamp_ns());
            Ok(())
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Why Backtesting Misses This

In backtesting, prices are usually bar-based (OHLC). The SL/TP check happens once per bar at the close. In live trading, you're checking every tick. A tick-based system might check SL/TP 100 times per second.

The bug manifests in live trading because:

  1. Price crosses SL
  2. Your check runs, returns TriggerSL
  3. You submit close order
  4. Meanwhile, price bounces back above SL
  5. Your check runs again, sees price above SL, does nothing
  6. But your close order is still pending...

The flag-based approach doesn't know that a close order is already in flight. It sees price above SL and would try to trade again.

The Actual Production Failure

Our original system had this flow:

1. Position opened at $100.00, SL = $98.00, TP = $102.00
2. Price drops to $97.50
3. check_sl_tp() sets sl_triggered = true
4. close_position() called
5. Position state set to "closing" (but not "closed")
6. Order submitted to exchange
7. Network latency = 50ms
8. Price bounces back to $99.00
9. check_sl_tp() runs again — price above SL, does nothing
10. Strategy continues to next tick
11. Exchange confirms fill at $97.50
12. Position is now closed

Enter fullscreen mode Exit fullscreen mode

All good so far. But then:

13. Next tick arrives
14. Strategy sees: "no open position, price is $99, this looks like a buy"
15. New position opened at $99.00
16. Price drops again to $97.50
17. Another SL triggered

Enter fullscreen mode Exit fullscreen mode

The problem: Steps 13-15 happened while the close order was still in flight. The strategy saw "no position" because the position was in "closing" state but hadn't confirmed "closed" yet.

We fixed this by adding close order tracking — the system now knows that a close is pending and doesn't allow new positions until the close is confirmed.

What I Learned

Two things:

1. State machines over flags. Every position should follow a clear state machine: Open → ClosePending → Closed. Transitions happen on confirmed events, not on trigger signals.

2. Backtesting lies to you. The bug never appeared in backtesting because we checked once per bar. In live trading, the race condition happens between ticks. Your backtest looks perfect. Your live account doesn't.


This is Chapter 1 of "The Circuit Breaker Problem" — one of five books in the Trading System Engineering Bundle. All written by an engineer who actually built a production trading engine from scratch. Code templates included.

What's in the bundle:

  • Order Engine Architecture — FIFO matching, order book data structures
  • The Circuit Breaker Problem — SL/TP bugs, trailing stops, re-entry prevention
  • Data Pipeline — TVC3 binary format, ring buffers, VPIN
  • Risk Management Engineering — commission handling, Kelly criterion, drawdown
  • Backtest Architecture — look-ahead bias, slippage modeling, walk-forward analysis

$20 per book, $80 for the bundle. Free preview: Book 2, Chapter 1.