
By Anthony Zender
This content is for educational and informational purposes only and should not be construed as investment advice, a recommendation, or an offer to buy or sell any securities. Any strategies discussed are illustrative only and may not be suitable for all investors. This article reflects the experience of an individual user, is not representative of all customers, and should not be considered an endorsement or guarantee of future performance. The views and opinions expressed are those of the author and do not reflect or represent the views and opinions of Alpaca. Alpaca does not recommend any specific securities or investment strategies.
The Idea That Sat for Eighteen Years
My day job is full-cycle accounting, including accounts payable (AP), payroll, benefits, and multi-jurisdiction tax, for a mechanical contracting firm. I have a bachelor's degree in financial management and an MBA. Understanding finance wasn't what stopped me from building software; programming was.
In August 2007, as a capstone project, I wrote a paper on a peer-to-peer wagering exchange: players competing directly, funds in escrow, payouts released on a confirmed result. I understood exactly what I wanted it to do. I had no way to build it. No computer science (CS) background, and "learn to code" was never a real answer to "I need this built correctly, including the parts where money moves." The idea sat for eighteen years until AI coding assistants closed the one gap that had always blocked it.
From PeerPlay to an Execution Guard
That 2007 paper became PeerPlay, a peer-to-peer skill-wagering platform for video game tournaments. I filed a provisional patent application on it in November 2025.
Tournament settlement is where the system demands real rigor: a payout has to fire exactly once, not twice. I hit this directly while testing the settlement path, as a simulated crash and retry reached the payout logic a second time. No duplicate payment occurred, but the test showed that catching it manually wasn't a real answer. That gap between "I caught it this time" and "the system can't do this" is what led to the next thing.
In January 2026, I built SafeAgent, a duplicate-execution guard based on claim-before-execute and durable receipts. The first caller claims a stable identity for the action before anything happens. A later call with that same identity either gets back the settled result, or learns that the original attempt is still unresolved, instead of blindly executing again. It's a narrower, more honest claim than "exactly once": the guard is designed to prevent duplicate execution and makes an unresolved outcome visible. It does not, by itself, guarantee the underlying action succeeded.
This gap can arise when an AI agent retries a tool call without checking whether the action already happened. I built adapters and examples for several agent frameworks (Claude via Model Context Protocol [MCP], LangChain, CrewAI, plain Python function calls), and SafeAgent is listed in the official MCP registry. I also opened a public bug report against CrewAI describing this exact failure class and proposed the same claim-before-execute pattern as a fix. A few other engineers working the same problem have referenced SafeAgent in that thread as one implementation of it.
It’s open source (on GitHub, PyPI, and the MCP registry) because this isn't a PeerPlay-specific problem. It's plumbing.
The Bot, and How It Actually Works
Please note that any securities mentioned are used in the trading bot as an example, and are not considered investment advice.
By February 2026, I'd built a momentum strategy trading QQQ-correlated leveraged exchange-traded funds (ETFs), specifically TQQQ on the bullish side and SQQQ on the bearish side, guarded by SafeAgent starting in March.
Leveraged and inverse ETFs involve additional risks, including increased volatility, amplified losses, and the effects of daily resetting and compounding. Their performance over periods longer than one day may differ significantly from their stated daily objectives and they may not be suitable for all investors.

Automated trading introduces unique operational risks, including technical failure and execution errors. This section describes my specific implementation for educational purposes, not as a recommended strategy.
For illustrative purposes, the core logic I implemented derives a directional read from QQQ market data (price relative to volume-weighted average price [VWAP] and moving averages, short-term return direction) and scores it into a bull, bear, or flat signal. Entries require that score to hold, not a single tick crossing a line, which is intended to reduce whipsaw entries in noisy conditions.
Everything around the entry took more iteration than the entry itself:
Exits. A position is intended to close on a hard loss stop, a trailing stop once it's shown profit, or a timed exit for a position that's gone nowhere. Markets spend a lot of time doing nothing decisive, and a strategy that can't recognize that may incur repeated losses during periods without a clear trend. These exit controls are designed to manage risk but do not guarantee that an order will be accepted or executed, or that losses will be limited to a predetermined amount.
Cooldowns. After a losing exit, the bot is prevented from re-entering for a set period. This limits repeated entries immediately after a loss.
Regime filter. I added this after the strategy incurred several small losses in a row on a day with no clear trend. It measures how efficiently price is actually moving in one direction and blocks new entries when that efficiency is too low.
Daily limits and end-of-day handling. My momentum bot caps trade frequency and exposure each day. A separate opening-range-breakout bot uses its own end-of-day rule: it cancels outstanding orders and flattens before the close so it does not intentionally carry overnight exposure.
Alpaca sits underneath all of it as the brokerage infrastructure. Market data, order submission, order status, and position records all come from Alpaca's Trading API, and the bot's reconciliation logic treats Alpaca's account state as authoritative over its own internal memory of what it thinks happened, which turned out to matter more than I expected.
Alpaca's paper trading environment uses the same API specification as live trading, allowing me to test order submission, order handling, and reconciliation using simulated executions. However, paper trading does not fully replicate live market conditions, and simulated results may differ materially from actual trading outcomes.
Alpaca's paper environment gave me the same API specification as live trading, with orders simulated instead of routed to a real market. That made it genuinely useful for testing code paths, order handling, and state transitions without risking capital. It's not a substitute for live execution: simulated fills don't reproduce every effect of liquidity, latency, queue position, or market impact, but it's the right place to find out where your assumptions about your own code are wrong before exposing real capital to those assumptions.
The Exit That Wouldn't Confirm
On August 18, during paper trading the bot went long TQQQ on a qualifying signal, then tried to exit two minutes later when the signal reversed. Alpaca rejected the exit, returning a 403 response on all three retry attempts. That was a clear rejection, not silence, but it left real uncertainty behind it: why the broker had rejected it, whether the position was actually still open, and how the bot should safely proceed.
[09:32:04] ENTER BULL symbol=TQQQ qty=6 score=7 reasons=above_vwap,vwap_rising,near_high
[09:33:16] STAY BULL score=-4 bull_score=1 bear_score=5 pnl_pct=-0.0054
[09:34:06] ORDER RETRY 1/3 sell TQQQ qty=3: 403 Forbidden
[09:34:09] ORDER RETRY 2/3 sell TQQQ qty=3: 403 Forbidden
[09:34:11] ORDER RETRY 3/3 sell TQQQ qty=3: 403 Forbidden
[09:34:11] ORDER ERROR exit TQQQ: 403 Client Error — retries exhausted
[09:34:25] SAFEAGENT EXIT SKIP: duplicate exit blocked TQQQ qty=3
entry=2026-08-18T09:32:04 reason=LOSS_STOP_BULL
After the guarded exit attempt had exhausted its broker retries, SafeAgent prevented the same claimed action from being started again blindly. No duplicate order occurred, but because Alpaca had rejected every submission, there was also no completed exit to return. The guard stopped uncontrolled replay; it did not close the position or determine the correct recovery action. It did not resolve the underlying question. Alpaca still showed the TQQQ position open, so the bot correctly refused to open a new position on top of one it couldn't verify and stayed blocked that way for more than six hours, until I intervened manually.
Nothing duplicated. But something did break: the recovery path. Duplicate suppression prevented the repeated action in this instance and the system still failed operationally, because refusing to repeat a mistake isn't the same as knowing how to recover from one.
What actually closed the gap in the bot wasn’t a smarter retry loop. It was adding an explicit reconciliation step: capture the real rejection reason instead of a bare error code, query Alpaca directly for current orders and position before assuming anything, and only create a new claim once that reconciliation shows a genuinely new action is actually warranted, never simply because the old one failed or went uncertain. A fresh claim without that check would defeat the entire point of the guard. If reconciliation can’t establish the truth, the system alerts a human instead of guessing.
Duplicate suppression is not successful execution, and successful execution is not reconciliation. SafeAgent handled duplicate suppression. I had to build the reconciliation step separately.
What I'd Tell a Non-Technical Person Starting Today
I don't have a CS background. Everything here got built by describing precisely what I wanted and checking the output against reality instead of trusting it.
More than once, what my bot's own log claimed and what Alpaca's order history actually showed didn't match. That gap, the system's story about itself versus the broker's record, is why reconciliation matters more than a smarter entry signal.
What I'd do differently: wire the guard into the very first bot instead of running early experiments unguarded, and build the reconciliation step before the first rejected order needed it, not after.
What's Next
The system I'm building now is aimed at reconciliation, not prediction. It pulls a bot's own signals, errors, and execution history together with Alpaca's actual orders and positions, so I can ask a basic operational question directly: does the bot's account of what happened agree with the broker's record? The August 18 incident is what made that need concrete. The goal isn't another signal generator; it's a clearer way to see when an automated system and its broker have quietly diverged.
Resources
- SafeAgent on PyPI
- How to Start Paper Trading Alpaca's Trading API
- Paper Trading vs Live Trading
- From Z-Score to a Multi-agent Trading Committee
- Building My Own Quant Trading Agent with Code and AI
About the Author
Anthony Zender is a full-cycle accountant handling payroll, multi-jurisdiction tax compliance, and reconciliation for a mechanical contracting firm in Ohio. He has a bachelor's degree in financial management and an MBA. He builds trading systems and open-source infrastructure as a side project, with no formal programming background.
This article reflects the experience of an individual user and is for educational and informational purposes only. The views and opinions expressed are those of the author and do not necessarily reflect those of Alpaca. The content does not constitute investment advice or a recommendation to buy or sell any security. Alpaca does not endorse or recommend any specific securities, trading systems, or investment strategies discussed.
The Paper Trading API is offered by AlpacaDB, Inc. and does not require real money or permit a user to transact in real securities in the market. Providing use of the Paper Trading API is not an offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, given or in any manner endorsed by AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate and the information made available through the Paper Trading API is not an offer or solicitation of any kind in any jurisdiction where AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate (collectively, “Alpaca”) is not authorized to do business.
Automated trading involves risks, including technical failures, inaccurate or delayed data, duplicate or unintended orders, rejected orders, and execution errors. AI-generated code and outputs may contain errors or inaccuracies. Automated safeguards, including duplicate-execution prevention and reconciliation mechanisms, do not guarantee successful order execution, prevent all errors, or eliminate the risk of financial loss.
Leveraged and inverse ETFs involve significant risks, including amplified losses, increased volatility, and the effects of daily resetting and compounding. Their performance over periods longer than one day may differ significantly from their stated daily objectives. These products may not be suitable for all investors.
All investments involve risk, including the possible loss of principal. Investors should carefully consider their investment objectives, financial circumstances, and risk tolerance before investing.
Securities brokerage services are provided by Alpaca Securities LLC (dba "Alpaca Clearing"), member FINRA/SIPC, a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.
This is not an offer, solicitation of an offer, or advice to buy or sell securities or open a brokerage account in any jurisdiction where Alpaca Securities is not registered or licensed, as applicable
For additional information, please review Alpaca's Disclosure Library.




