
By Rudraksh Mishra
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 or cryptocurrencies. 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 author was not compensated for this content but did receive nominal promotional items from Alpaca.
Backtesting and paper trading involve hypothetical or simulated results that may differ materially from actual trading performance. Risk-management techniques do not guarantee against investment losses.
Background: Why I Built This
My path into algorithmic trading started in 2023 with a simple hunch: some stock pairs drift apart and snap back together, and a Z-score could measure the gap. I wrote a handful of rule-based scripts to test that idea. They worked well enough to be interesting and poorly enough to be humbling, but lacked a comprehensive risk-management framework, mechanisms for adapting to changing market conditions, and independently managed exit orders if my machine went offline during trading.
That last gap sent me looking for a brokerage that offered an API-based trading environment, well-documented developer tools, with a paper trading environment I could iterate on freely. That search led me to Alpaca.
Two years and several rewrites later, those scripts have become Elite-Bot: a multi-strategy system combining statistical arbitrage, volatility-aware regime detection, and a small committee of LLM agents, all integrated with broker-managed order functionality designed to support predefined exit instructions.. This piece covers why I rebuilt the architecture, how the current system works, an honest read of where the results stand, and what comes next.
The Problem That Forced a Redesign
The original bot was a straight line: compute a signal, decide, send a market order. Nothing sat between that order and the market if something upstream failed. A crashed process, a dropped connection, a restart at the wrong moment, any of these could leave a position open with no exit attached, potentially increasing exposure to market movements and trading losses.
That failure mode reframed my priorities. I wanted certain exit instructions to be managed through the brokerage platform rather than depending entirely on my application remaining operational. While this approach can help address certain operational risks, it does not eliminate market risk or guarantee order execution.
Technical Deep Dive
The system runs as a paper-trading terminal connected to Alpaca’s Paper Trading API. Equity, buying power, open P&L, simulated positions s on one screen, with the underlying strategy and execution layers described below feeding it:

Pre-configured exit, by design
The redesign added an abstract order management layer between the strategy signals and Alpaca's Trading API. Every entry is designed to use a bracket order that includes predefined take-profit and stop-loss instructions, subject to applicable order requirements and execution conditions.
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import (
MarketOrderRequest, TakeProfitRequest, StopLossRequest
)
from alpaca.trading.enums import OrderSide, TimeInForce, OrderClass
entry_req = MarketOrderRequest(
symbol=ticker,
qty=shares,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY,
order_class=OrderClass.BRACKET,
take_profit=TakeProfitRequest(limit_price=take_profit_price),
stop_loss=StopLossRequest(stop_price=stop_loss_price),
)
order = trade_client.submit_order(entry_req)Once the entry order is filled and the associated exit orders are active, the brokerage platform can manage those instructions without requiring my application to remain continuously connected. However, bracket orders and stop-loss instructions are subject to market conditions and execution limitations and do not guarantee an exit at a specified price or prevent investment losses. Of everything in this rebuild, separating certain order-management functions from my own infrastructure is the single change I'd prioritize if I were starting over.
The strategy layer
- Statistical arbitrage core: Pairs are still selected on Z-score dislocation, but the hedge ratio between legs is estimated with a Kalman filter instead of held static, so it can be updated as the relationship between instruments drifts.
- Volatility gating: a GARCH(1,1) model estimates current volatility and is used to evaluate potential entries, including whether to reduce position sizes or refrain from entering positions when estimated volatility is elevated relative to recent history.
- Regime detection: A Hidden Markov Model estimates potential market regimes, since a mean-reversion signal that behaves one way in a range-bound market doesn't necessarily hold in a trending one.
- Position sizing: A half-Kelly approach, a fractional version of the Kelly criterion, is used to inform position sizing while accounting for estimated risk and return characteristics. The methodology does not eliminate drawdown or investment risk.
A simplified view of how the hedge ratio and sizing decision come together before a candidate ever reaches the LLM layer:
# simplified — dynamic hedge ratio + volatility-gated, half-Kelly sizing
kf.predict()
kf.update(price_y)
hedge_ratio = kf.x[0] # Kalman filter state estimate spread = price_y - hedge_ratio * price_x
z_score = (spread - spread.rolling(window).mean()) / spread.rolling(window).std() current_vol = garch_model.forecast(horizon=1).variance.values[-1] ** 0.5
vol_ok = current_vol < vol_threshold # gate entries in elevated-vol regimes if abs(z_score) > entry_threshold and vol_ok:
kelly_fraction = (win_prob * payoff_ratio - (1 - win_prob)) / payoff_ratio
position_size = 0.5 * kelly_fraction * portfolio_value # half-KellyThe pair scanner below illustrates the system's analysis of a watchlist, with each row displaying a candidate pair, its calculated Z-score, and the corresponding simulated trading signal:

A committee, not a single model
Rather than asking one language model to evaluate a trade end-to-end, Elite-Bot routes each candidate through a small committee of models built with CrewAI, each reviewing the proposal from a different angle before a combined view is reached. Every agent returns a structured proposal rather than free-form text, so the committee's output stays comparable and available for subsequent review and analysis.
proposal = {
"ticker_pair": ("KO", "PEP"),
"direction": "long_spread",
"thesis": "Z-score dislocation with hedge ratio stable over trailing window",
"z_score": -2.34,
"regime": "range_bound", # from the HMM #
"vol_gate": "pass", # from the GARCH filter #
"confidence_score": 0.68,
"position_size_pct": 3.1, # from half-Kelly sizing #
}This process introduces additional latency, with the multi-agent review typically taking approximately 8–15 seconds in the author's testing environment. As a result, the system is not designed for latency-sensitive execution.. It's built to add a layer of qualitative review on top of the quantitative signal. A separate Q-learning component handles execution timing for trades the committee has already approved, and is designed to inform execution timing for trade candidates evaluated by the committee rather than the approval decision itself.
Every decision, gate, and guard rail logs to a terminal so the reasoning stays inspectable rather than opaque, including safety checks like a market-hours guard that holds the bot outside its defined trading window:

Experimenting with Alpaca's MCP Server
Alongside the SDK integration above, I've spent time experimenting with Alpaca's MCP Server as a way to expose trading tools to an agent layer through a standard protocol, rather than hand-writing tool schemas per framework. This remains an experimental branch rather than a production path.The current paper-trading implementation uses Alpaca’s API to submit simulated orders, but it's a direction I plan to keep developing, since it could remove a meaningful amount of boilerplate the next time I wire in a new agent framework.
I want to be direct about what this is and isn't. With a sample size of fourteen trades, the win rate can swing heavily with just a couple of additional outcomes, making it statistically unreliable for my own evaluation. It also says nothing about the size of wins relative to losses, or how the strategy would hold up through a genuine drawdown period. I haven't yet formalized equity-curve-level tracking with drawdown and risk-adjusted return across a larger sample, and I don't want to imply a level of validation this project hasn't reached.
Rather than emphasize preliminary hypothetical performance, I believe it is more useful to demonstrate how the system’s components fit together:

Building out a larger, more statistically meaningful evaluation, proper equity-curve tracking across many more trades, purged cross-validation to limit lookahead bias, and a deflated Sharpe ratio that accounts for the number of variants I've tested, is the next milestone before I'd call any of this validated.
Any trading signals, account information, or performance-related illustrations are hypothetical or simulated and do not represent actual trading results. Simulated outcomes may differ materially from live trading and are not indicative of future performance.
What I'd Change, and What's Next
If I were starting over, equity-curve and drawdown tracking would be there from day one instead of arriving later. A backtested win rate is cheap to compute early and easy to over-index on. A more comprehensive evaluation requires additional metrics, including drawdown analysis, risk-adjusted returns, and testing across different market conditions. I would rather have built that evaluation framework into the system from the start.
Next on the roadmap:
- Formalizing equity-curve and P&L tracking end-to-end
- Purged cross-validation and a deflated Sharpe ratio with trial logging, to help assess potential overfitting from testing many variants
- A Granger causality pre-filter and a data quality audit layer
- Correlation-aware position sizing and portfolio-level volatility targeting
- Extending the MCP Server experiment toward production, if it keeps proving out
- Widening the trading universe gradually, gated behind validation at each step
New modules are initially disabled by default and are evaluated before being incorporated into the active configuration.
Closing Thought
The biggest architectural change for me was moving critical exit order instructions from logic that depended entirely on my own process to broker-hosted order functionality. While these controls do not eliminate market or execution risks, that experience changed how I think about failure modes in automated trading systems.
Resources
For readers interested in learning more about the tools and workflows discussed, the following developer resources provide additional information:
- Alpaca's Trading API – the place to start
- Alpaca Paper Trading – set up a paper account, same API, same execution
- Alpaca Market Data API – historical and real-time data
- alpaca-py on GitHub
- Alpaca’s MCP Server for Trading API
About the Author
Rudraksh Mishra is a final-year Computer Science (Honours) student and AI engineer focused on applied machine learning and quantitative systems. He recently completed an AI Engineer contract building a RAG-powered legal assistant, and built Elite-Bot independently as a research project exploring how statistical models and LLM-based agents can work together under broker-enforced risk controls. He is currently exploring full-time roles across AI/GenAI engineering, data science, and forward-deployed engineering. Rudraksh's GitHub for more.
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.
This article 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 security.. The views expressed are those of the author and do not necessarily reflect those of Alpaca. Alpaca does not recommend any specific securities, or investment strategies. Examples provided are illustrative only and are not indicative of future results. All investments involve risk, including the possible loss of principal. Past performance, hypothetical results, and backtested results do not guarantee future returns.
Automated and algorithmic trading involve risks, including coding errors, inaccurate data, connectivity failures, system interruptions, model errors, and unintended or duplicate orders. AI-generated outputs may be inaccurate, incomplete, or inconsistent and should not be relied upon as investment advice. Automated systems require appropriate testing, monitoring, and controls and do not eliminate the risk of loss.
The views expressed are those of the author and do not necessarily reflect those of Alpaca. Alpaca does not endorse or recommend the trading system or investment strategies described in this article.
Securities brokerage services are provided by Alpaca Securities LLC ("Alpaca Securities"), 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.




