YellowBar

How it works

Automated Options Trading with Inside Bars

This is an automated stock trading robot that I built to make money in the stock market without having to sit at a computer all day watching charts.

The robot monitors SPY for technical patterns (inside bars), executes automated options trades via Alpaca API based on breakout signals, and manages positions with predefined risk parameters. Features include real-time market data analysis, customizable trading strategies with take-profit/stop-loss automation, email notifications for trade events, and comprehensive risk management controls (position sizing, daytrade limits).

Implemented using TypeScript with background task scheduling.

How the System Works: Step-by-Step

1. Inside Bar Pattern Detection [Automated Scanning]

Every few minutes, the system automatically scans SPY stock charts looking for a specific pattern called an "inside bar." Think of this like a coiled spring - it happens when the stock price gets compressed into a tighter range than the previous period, often indicating that a big price movement is coming soon. The system uses real-time market data from Alpaca's API to analyze the most recent price bars, comparing current highs and lows against previous periods. When the current bar's high is lower than the previous bar's high AND the current bar's low is higher than the previous bar's low, an inside bar is detected. This creates a setup where the price is "trapped" in a narrow range, building pressure for a breakout move.

2. Breakout Monitoring [Real-time Surveillance]

Once an inside bar pattern is identified, the system immediately begins monitoring for a "breakout" - the moment when the stock price breaks above or below the inside bar's range with conviction. This is where the magic happens: the system watches every price tick in real-time, waiting for SPY to decisively move above the inside bar's high (bullish breakout) or below its low (bearish breakout). The monitoring process runs continuously using background tasks that can detect these movements within seconds of them occurring. If no breakout happens within a specified time window, the monitoring automatically terminates to avoid false signals, keeping the system focused only on the highest-probability trading opportunities.

3. Breakout Signal Processing [Decision Engine]

When a breakout is confirmed, the system immediately springs into action with its decision-making engine. This step determines whether to execute a trade based on multiple safety checks and market conditions. The system first verifies that no other trades have been placed that day (to avoid over-trading), then assesses the breakout direction to determine whether to buy call options (betting the price will continue up) or put options (betting it will continue down). The processing engine also evaluates account status, available buying power, and current day-trading limits imposed by regulations. Only if all conditions are favorable does the system proceed to the next step. This careful validation process ensures that every trade meets strict criteria before risking capital.

4. Options Order Construction [Smart Positioning]

With a confirmed breakout signal, the system intelligently constructs the perfect options order tailored to current market conditions and account size. It calculates the optimal strike price based on the breakout direction - typically choosing at-the-money or slightly out-of-the-money options for the best balance of cost and profit potential. The system automatically determines position size by allocating a predetermined percentage of available cash, ensuring consistent risk management across all trades. It then fetches real-time options pricing data to calculate exactly how many contracts can be purchased within the budget. The order construction process also selects same-day expiration options (0DTE) to maximize sensitivity to price movements while minimizing time decay, creating focused bets on immediate market direction following the breakout.

5. Order Execution [Automated Trading]

The system executes the carefully constructed options order through Alpaca's brokerage API with military precision and built-in safeguards. Using market orders for immediate execution, it places the trade within seconds of the breakout confirmation, capturing the momentum before other traders can react. The execution engine includes intelligent retry logic - if an order is rejected due to insufficient buying power, it automatically reduces the quantity and tries again, ensuring that some position is captured even if the full intended size isn't available. Every order attempt is logged and monitored, with email notifications sent for both successful executions and any errors that occur. This automation eliminates the emotional hesitation and delayed reactions that plague human traders, especially during fast-moving market conditions where seconds can mean the difference between profit and loss.

6. Position Monitoring [Active Management]

Once an options position is successfully opened, the system transitions into active monitoring mode, continuously tracking the trade's performance throughout the trading session. Using background tasks that run independently of the main scanning process, it fetches real-time position data every few minutes, calculating current profit/loss, percentage gains, and time remaining until expiration. The monitoring system applies predefined exit rules: automatically closing positions when they reach a target profit level (typically 25-50% gains) or hit a maximum loss threshold to protect capital. This constant surveillance means the system never "forgets" about an open position or lets emotions override disciplined risk management. The monitoring continues until the position is either manually closed by the exit rules or expires worthless at the end of the trading day.

7. Position Closure [Profit Realization]

The final step occurs when the monitoring system determines it's time to exit the position, either to lock in profits or limit losses. The closure process executes a market sell order for 100% of the position, converting the options contracts back to cash immediately. The system handles all the technical details of position closure, including proper order formatting, API communication, and error handling if the initial closure attempt fails. Upon successful closure, comprehensive email notifications are sent with complete trade details: entry and exit prices, total profit or loss, percentage return, and trade duration. This automated closure ensures that the system never holds positions longer than intended and always follows the predetermined risk management rules, removing the human tendency to "let winners run too long" or "hold losers hoping they'll recover." The entire cycle then resets, ready to scan for the next inside bar opportunity.

Why it's useful: Instead of me having to stare at charts all day and make emotional decisions about when to buy and sell, this system does it automatically based on proven patterns, removing human emotion and fatigue from trading decisions. The result: It's like having a disciplined, emotionless trading assistant that works 24/7, follows strict rules, and sends me email updates about what it's doing with my money.

Built in
2025
Built with
Alpaca API
Monitors
SPY
Strategy
Inside Bars

Request access