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

推荐订阅源

S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
A
Arctic Wolf
Security Latest
Security Latest
Simon Willison's Weblog
Simon Willison's Weblog
I
Intezer
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Troy Hunt's Blog
Latest news
Latest news
Help Net Security
Help Net Security
S
Security Affairs
Webroot Blog
Webroot Blog
The Hacker News
The Hacker News
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tor Project blog
Forbes - Security
Forbes - Security
Google DeepMind News
Google DeepMind News
AWS News Blog
AWS News Blog
Attack and Defense Labs
Attack and Defense Labs
P
Proofpoint News Feed
www.infosecurity-magazine.com
www.infosecurity-magazine.com
H
Help Net Security
L
Lohrmann on Cybersecurity
S
SegmentFault 最新的问题
Google Online Security Blog
Google Online Security Blog
MongoDB | Blog
MongoDB | Blog
Cyberwarzone
Cyberwarzone
The Last Watchdog
The Last Watchdog
S
Securelist
N
News and Events Feed by Topic
S
Secure Thoughts
F
Fortinet All Blogs
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
M
MIT News - Artificial intelligence
F
Full Disclosure
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Microsoft Security Blog
Microsoft Security Blog
I
InfoQ
P
Privacy International News Feed
L
LangChain Blog
Know Your Adversary
Know Your Adversary
C
CERT Recently Published Vulnerability Notes

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
An Open-Source Gym-Style Backtesting Framework for Algorithmic Trading in Rust
Len · 2026-05-15 · via DEV Community

End-to-end Chapaty workflow from make run to generated tearsheet


End-to-end workflow: Running make run in the chapaty-template project executes the example strategy from this blog post and produces a QuantStats tearsheet.

TL;DR: Chapaty is an open-source Rust backtesting framework with a Gym-style [1] reset / step / act API for algorithmic trading. Strategy logic lives in a single act function. Order execution, matching engine, data sync, and reporting sit behind the simulation environment. For the example strategy in this post, a 400-point parameter grid over 9 years of end-of-day market data runs in ~1 second on an 8-core laptop.


One bottleneck in algorithmic trading workflows is the time from ideation to a backtest result.

Existing tools sit along two axes. Hosted platforms like QuantConnect, TradingView, and MetaTrader 5 offer accessible UIs but rely on closed simulators (and in some cases proprietary languages like Pine Script and MQL5) that you can't fully audit. Open-source alternatives in Rust like Nautilus Trader and Barter exist and cover backtesting and live trading. Chapaty is built around separating the algorithm completely from the framework. A Rust-native Agent trait with reset / act, observations handed in per step, and parameter grids as a first-class citizen.

To speed up the Build-Measure-Learn loop [2] for trading strategies, we need two things:

  1. An accessible framework that people are already comfortable with and that is well-established: Gym.
  2. A fast programming language with fearless concurrency, so we can natively run many different strategies in parallel: Rust.

The motivation for Chapaty was to unify these worlds in an open-source project, so that everyone has access to a framework for developing algorithms without having to focus on infrastructure.

The approach that worked was separating strategy logic from the order execution, matching engine, data syncing, and reporting. Now, all the strategy code lives in one place, so iterating on ideas no longer requires touching the rest of the pipeline.


Design Decisions

This is how Chapaty handles common backtesting pitfalls:

Timeframe Synchronization: To avoid look-ahead bias across different timeframes (e.g., mixing 1m, 1h, and Economic Calendar data), the simulation steps through time by selecting the next strictly monotonically increasing point_in_time timestamp across all data sources. It then extends the view on the data up to this point in time.

Synchronizing point-in-time data across multiple data streams


Synchronizing point-in-time data: the cursor advances to the next strictly monotonically increasing timestamp across all data streams (1-minute, 1-hour, and economic calendar). At each step, every event up to the cursor becomes visible to the agent.

Pessimistic Evaluation: If an entry and a take-profit/stop-loss occur in the exact same candle, the framework defaults to pessimistic evaluation. It assumes the worst-case scenario (e.g., the stop-loss was hit before the take-profit). You can toggle this to "optimistic" if preferred.

Slippage & Fees: Fills occur at the SL/TP price, and I manually subtract a percentage fee and slippage per trade in the journal to approximate real-world results without over-engineering the matching engine. Realism on fills and slippage is still pragmatic rather than microstructure-accurate. A future version will improve fill modeling.

Data Feeds: The framework is decoupled from the data. It can process any structured event with a point_in_time. Personally, I run it mostly on crypto (Binance Spot: OHLCV, Trades, TPO, Volume Profile across multiple timeframes) and economic calendar events. Because of the abstraction, it works equally well with traditional equities or futures.

The matching engine, the fill logic, the look-ahead handling: they're all in the repository. You can read exactly how a trade gets evaluated. That matters more for backtesting than for most software. If you can't audit the simulator, you can't trust the result. It's the reason why Chapaty needs to be open source.


Backtesting 400 Parameter Combinations in 1 Second (with a Stop-and-Reverse SMA Crossover)

By isolating the strategy logic in an act function that receives an Observation, the strategy remains independent from the OHLCV data feed.

Here is how we can implement a Stop-and-Reverse SMA Crossover in three steps. To keep things fast, we will use a StreamingSma helper to handle the rolling calculations.

Step 1: Define the Agent State. First, we create our Agent structure. We need to define the market, our parameters (which allows us to easily run a grid search later), and our internal state cache. The last_processed_ts is used to prevent double-processing.

// Brings StreamingSma into scope
use chapaty::prelude::*;

pub struct DemoAgent {
   // Unique identifier for the market (e.g., BTC-USDT)
   pub ohlcv_id: OhlcvId,

   // Strategy parameters
   pub fast_period: u16,
   pub slow_period: u16,

   // === Internal ===

   // Streaming indicators to avoid O(n) window recalculations
   fast_sma: StreamingSma,
   slow_sma: StreamingSma,

   // Internal state cache
   current_fast: Option<f64>,
   current_slow: Option<f64>,
   trade_counter: i64,
   last_processed_ts: Option<DateTime<Utc>>,
}

Enter fullscreen mode Exit fullscreen mode

Step 2: Implement the Execution Logic. Next, we implement the Agent trait. The logic flows in a strict pipeline: safely fetch the data → update internal state (idempotency check) → verify the signal → execute the trade.

(If you want to add more complex take-profit/stop-loss logic or other entry signals later, you simply extend this act implementation. I've kept it minimal here for brevity).

impl Agent for DemoAgent {
    fn act(&mut self, obs: Observation) -> ChapatyResult<Actions> {
        let market_view = &obs.market_view;

        // 1. Fetch the latest candle safely
        let Some(candle) = market_view.ohlcv().last_event(&self.ohlcv_id) else {
            return Ok(Actions::no_op());
        };

        // 2. Update Internal State (Idempotency check)
        if self.last_processed_ts != Some(candle.close_timestamp) {
            self.current_fast = self.fast_sma.update(candle.close.0);
            self.current_slow = self.slow_sma.update(candle.close.0);
            self.last_processed_ts = Some(candle.close_timestamp);
        }

        // 3. Check Signal Validity
        let (Some(fast), Some(slow)) = (self.current_fast, self.current_slow) else {
            return Ok(Actions::no_op()); // SMAs are still warming up
        };

        // 4. Look up active positions
        let agent_id = self.identifier();
        let active_trade = obs.states.find_active_trade_for_agent(&agent_id);
        let market_id: MarketId = self.ohlcv_id.into();

        let mut actions = Actions::new();

        // 5. Signal Logic (Stop-and-Reverse)
        if fast > slow {
            // Bullish Trend
            if let Some((_, state)) = active_trade {
                if state.trade_type() == &TradeType::Short {
                    // Close the Short
                    actions.add(market_id, self.close_market(state.trade_id()));
                    // Open a Long
                    actions.add(market_id, self.open(TradeType::Long));
                }
            } else {
                // Flat -> Open Long
                actions.add(market_id, self.open(TradeType::Long));
            }
        } else if fast < slow {
            // Bearish Trend
            if let Some((_, state)) = active_trade {
                if state.trade_type() == &TradeType::Long {
                    // Close the Long
                    actions.add(market_id, self.close_market(state.trade_id()));
                    // Open a Short
                    actions.add(market_id, self.open(TradeType::Short));
                }
            } else {
                // Flat -> Open Short
                actions.add(market_id, self.open(TradeType::Short));
            }
        }

        Ok(actions)
    }
}

Enter fullscreen mode Exit fullscreen mode

To keep the act method readable, the actual order creation is put in helper methods. Passing entry_price: None directly translates into a market order.

impl DemoAgent {
    fn open(&mut self, trade_type: TradeType) -> Action {
        self.trade_counter += 1;
        Action::Open(OpenCmd {
            agent_id: self.identifier(),
            trade_id: TradeId(self.trade_counter),
            trade_type,
            quantity: Quantity(1.0),
            entry_price: None, // Market Order
            stop_loss: None,
            take_profit: None,
        })
    }

    fn close_market(&self, trade_id: TradeId) -> Action {
        Action::MarketClose(MarketCloseCmd {
            agent_id: self.identifier(),
            trade_id,
            quantity: None,
        })
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Scaling it up with Parallel Grid Search. Now that we have a safe, idempotent agent, we can initialise a grid of them to run many parameter combinations in parallel.

pub struct DemoAgentGrid {
    ohlcv_id: OhlcvId,
    fast_period: GridAxis,
    slow_period: GridAxis,
}

impl DemoAgentGrid {
    pub fn baseline(ohlcv_id: OhlcvId) -> ChapatyResult<Self> {
        Ok(Self {
            ohlcv_id,
            fast_period: GridAxis::new("10", "30", "1")?,
            slow_period: GridAxis::new("40", "60", "1")?,
        })
    }

    pub fn build(self) -> (usize, Vec<(usize, DemoAgent)>) {
        let fasts = self.fast_period.generate();
        let slows = self.slow_period.generate();

        // 1. Eagerly collect valid combinations into a flat Vector
        let valid_args = iproduct!(fasts, slows)
            // Example filter: Fast must be less than Slow
            .filter(|(f, s)| f < s)
            .collect::<Vec<_>>();

        let total_combinations = valid_args.len();
        let ohlcv_id = self.ohlcv_id;

        // 2. Map to Agent instances
        let agents = valid_args
            .into_iter()
            .enumerate()
            .map(|(uid, (fast, slow))| (uid, DemoAgent::new(ohlcv_id, fast as u16, slow as u16)))
            .collect::<Vec<_>>();

        (total_combinations, agents)
    }
}

// In main.rs run:
// let (count, agents) = DemoAgentGrid::baseline(ohlcv)?.build();
// let leaderboard = env.evaluate_agents(agents.into_iter().par_bridge(), 100, count as u64)?;

Enter fullscreen mode Exit fullscreen mode

Grid search is parallelised across cores via Rayon. On an 8-core M2 MacBook Air, this simple SMA crossover grid (~400 parameter combinations over ~9 years of BTC daily candles) runs in roughly one second.


Generated Reports

Every run produces a full set of artifacts in chapaty/reports/:

tearsheet.html: QuantStats [3] report (Sharpe, Sortino, drawdown, rolling stats, vs-benchmark)

Cumulative returns of SMA 20/50 crossover on BTC-USDT vs S&P 500


Cumulative returns of a bidirectional SMA 20/50 crossover on BTC-USDT (EoD) vs. the S&P 500 benchmark.

Heat map of monthly returns for SMA 20/50 crossover on BTC-USDT


Heat map of monthly returns for the bidirectional SMA 20/50 crossover on BTC-USDT (EoD).

portfolio_performance.csv: aggregate metrics

equity_curve.csv / cumulative_returns.csv: time series for custom plots

trade_statistics.csv: per-trade summary stats

leaderboard.csv: top-N agents from a grid search, ranked

(Note: This is a truncated view showing just the top 3 results for a few key metrics. The full output ranks all agents across all performance statistics.)

Top-ranked agents from the leaderboard.csv output


Top-ranked agents across selected performance metrics, from the generated leaderboard.csv.

journal.csv: every trade, fully traceable (entry/exit UTC timestamps, prices, exit reason, realised PnL in ticks and dollars)

(Note: Here is a peek at a simplified version of the journal. I've hidden a few of the more verbose columns like exact stop-loss/take-profit hits and expected metrics for readability here, but the actual output tracks the full state of every trade.)

Simplified journal entries showing trade logs


Simplified journal entries. Every trade is logged with entry/exit timestamps, prices, and realised PnL.

Final Thoughts

This approach really sped up my iteration loop, but I'm biased as I've worked with Gym-style APIs before, and the reset / step / act pattern feels natural to me.

Sweeping 400 parameter combinations is great for exploration, but it's also a fast way to curve-fit. The numbers in the leaderboard above are in-sample by construction. They tell you which parameters would have worked on the data you already have. They don't tell you which ones will work on the data you haven't seen yet. Anything past the exploration stage needs a proper out-of-sample split (walk-forward, train/test, or both) before any conclusion about a strategy holds up. Chapaty gives you the speed to run the search. The discipline to validate it is on you.


Accessing the Code

The template repo has a make run quick-start that reproduces the demo above. It also ships with prompt templates for LLM-assisted development.

https://github.com/LenWilliamson/chapaty-template


References

[1] Farama Foundation, Gymnasium (2024), https://github.com/Farama-Foundation/Gymnasium

[2] E. Ries, The Lean Startup (2011), Crown Business

[3] R. Aroussi, QuantStats: Portfolio analytics for quants (2019), https://github.com/ranaroussi/quantstats