Skip to content

Repository files navigation

DelayEdge - Automated Trading System for HTMW

Python 3.8+ License: MIT

A trading bot for HowTheMarketWorks.com, a stock market simulator used in school investing competitions. It trades on the 3 to 15 minute lag between HTMW's quoted prices and real-time Yahoo Finance prices.

No real money is involved. HTMW is a paper-trading game with fake balances. This was built for a school competition, and the "$20,000" below is simulator currency.

The interesting part is not the trading. It is the general problem underneath: two feeds describe the same asset, one lags the other, and you have to decide when the gap is real, how long it will take to close, and whether acting on it beats the cost of acting. That is the same shape as cache staleness, replica lag, and sensor fusion.

Overview

The system:

  1. Scans for stocks with the biggest gains in the last 3 minutes
  2. Selects the most profitable opportunity (by total profit, not just percentage)
  3. Buys all-in ($20,000) on the single best opportunity
  4. Monitors the position until HTMW price catches up to the entry real-time price
  5. Sells automatically when HTMW reaches the fixed target price

Key Features

  • Fixed Target Price: Target is set once at purchase time (Yahoo Finance real-time price) and never changes
  • Market Hours Protection: Only trades during market hours (6:30 AM - 1:00 PM PST, Mon-Fri)
  • All-In Strategy: Invests $20,000 per trade on the single most profitable opportunity
  • Position Tracking: Uses CSV file as primary source of truth, with JSON metadata backup
  • Failed Stock Filtering: Tracks and avoids stocks that cause errors
  • Automated Execution: Fully automated trading with minimal manual intervention

Prerequisites

Before you begin, ensure you have:

  • Python 3.8 or higher - Download Python
  • HTMW Account - A registered account on HowTheMarketWorks.com
  • HTMW Cookies - Your authentication cookies from HTMW (see setup instructions below)

Installation

Step 1: Clone the Repository

git clone https://github.com/yourusername/delayedge.git
cd delayedge

Step 2: Install Python Dependencies

pip install -r requirements.txt

Required packages:

  • requests - HTTP library for API calls
  • yfinance - Yahoo Finance data retrieval
  • python-dotenv - Environment variable management
  • beautifulsoup4 - HTML parsing
  • pytz (optional but recommended) - Timezone handling

Step 3: Configure HTMW Cookies

  1. Log into HTMW in your web browser
  2. Install a cookie export extension (e.g., "EditThisCookie" for Chrome/Edge)
  3. Export your cookies as JSON:
    • Click the extension icon
    • Select "Export" → "JSON"
    • Copy the entire JSON array
  4. Create a .env file in the project root:
    touch .env
  5. Add your cookies to the .env file:
    HTMW_COOKIES=[{"name":"cookie1","value":"value1",...},{"name":"cookie2","value":"value2",...}]
    
    Important: The JSON must be on a single line with no line breaks.

Step 4: Configure Settings (Optional)

Edit config/config.json to customize trading parameters:

{
  "threshold_pct": 0.001,
  "order_size": 0,
  "max_positions": 10,
  "refresh_interval": 10,
  "num_stocks": 50,
  "min_cash_reserve": 10000.0,
  "profit_target_pct": 0.002,
  "test_mode": false,
  "target_trade_value": 100.0
}

Key settings:

  • num_stocks: Number of stocks to scan (default: 50)
  • max_trade_value: Maximum trade value per position (default: $20,000)
  • max_positions: Maximum simultaneous positions (default: 1)
  • threshold_pct: Minimum gap percentage to trade (default: 0.25%)
  • test_mode: Enable test mode (no actual trades)

Usage

delayedge_v2.py is the current entry point. It splits the HTMW API out into htmw_client.py, so the trading logic and the site-specific request building can be read and changed separately.

python delayedge_v2.py              # scan and trade
python delayedge_v2.py --scan       # scan only, place no orders
python delayedge_v2.py --once       # one scan cycle, then exit
python delayedge_v2.py --test-trade CSCO   # buy and sell a single share end to end

Start with --scan. It shows which gaps it finds and what it would do, without submitting anything.

delayedge.py is the original single-file version, kept because it is a smaller thing to read first.

Original version options

python delayedge.py --config config/my_config.json
python delayedge.py --test          # no orders placed
python delayedge.py --cycles 10
python delayedge.py --num-stocks 100

Tests

python -m pytest tests/ -q

25 tests, no network and no HTMW account needed. They cover the two things that decide whether a trade is correct:

  • Position accounting (tests/test_position.py) — that a gap smaller than the $20 round-trip commission is reported as a loss, where break-even sits, and that a position saved and reloaded keeps the same entry time. A position written by an older build has no timezone offset, and reading it back as UTC would shift every hold time and sell on the wrong schedule.
  • Order encoding (tests/test_order_form.py) — that BUY/SELL/SHORT/COVER and each order type map to the codes HTMW expects, since a wrong code submits a different trade than intended. These also document the current fallback: an unrecognised action silently becomes a buy.

Project Structure

delayedge/
├── delayedge.py              # Main trading system
├── README.md                 # This file
├── requirements.txt          # Python dependencies
├── LICENSE                   # License file
├── CONTRIBUTING.md           # Contribution guidelines
├── .gitignore               # Git ignore rules
├── .env                     # Your HTMW cookies (create this, not in repo)
├── config/
│   └── config.json          # Configuration file
├── data/                    # Runtime data (auto-generated, gitignored)
│   ├── OpenPositions_*.csv  # Position tracking
│   ├── failed_stocks.json   # Failed stock tracking
│   └── positions_metadata.json
├── scripts/                 # Utility scripts
│   ├── test_execution_price.py
│   ├── test_gap_strategy.py
│   ├── market_hours_arbitrage.py
│   └── price_gap_monitor.py
└── docs/                    # Documentation
    ├── README.md
    ├── DATA_SOURCES.txt
    ├── HTMW_API.txt
    ├── LEGAL_ETHICS.txt
    ├── MODELS.txt
    ├── PIPELINE.txt
    ├── SCORING_AND_REPORTS.txt
    ├── STRATEGIES.txt
    ├── UI_FLOW.txt
    └── extra/               # Additional docs
        ├── OPTIMIZATIONS.md
        ├── PROJECT_STRUCTURE.md
        ├── QUICKSTART.md
        ├── README_ARBITRAGE.md
        ├── README_ORDER_MONITORING.md
        └── SUMMARY.md

Configuration Details

Trading Parameters

  • Market Hours: 6:30 AM - 1:00 PM PST, Monday-Friday
  • Fixed Target: Target price is set at purchase time and never changes (prevents "chasing a moving target")
  • All-In Strategy: Currently configured for 1 position at a time, $20,000 per trade
  • Data Files: All runtime data (CSV, JSON) are stored in the data/ folder

Environment Variables

The system uses a .env file for sensitive configuration:

  • HTMW_COOKIES: JSON array of your HTMW authentication cookies

Security & Privacy

  • Never commit your .env file to version control
  • Never share your HTMW cookies publicly
  • The .env file is automatically ignored by git (see .gitignore)

Important Notes

  • Market Hours Only: System only trades during market hours (6:30 AM - 1:00 PM PST)
  • Fixed Target: The target price is set at purchase time and never changes
  • All-In Strategy: Currently configured for 1 position at a time, $20,000 per trade
  • Educational Purpose: This project is for educational purposes only. Use at your own risk.

Troubleshooting

"No cookies loaded from .env file"

  • Ensure your .env file exists in the project root
  • Verify the HTMW_COOKIES variable is set correctly
  • Make sure the JSON is on a single line with no line breaks
  • Check that cookie names and values are properly formatted

"pytz not installed" warning

Install pytz for better timezone handling:

pip install pytz

Price fetching errors

  • Verify your HTMW cookies are still valid (they may expire)
  • Check your internet connection
  • Ensure HTMW service is accessible

Additional Documentation

For more detailed information, see the docs/ folder:

  • docs/extra/QUICKSTART.md - Quick start guide
  • docs/extra/PROJECT_STRUCTURE.md - Detailed project structure
  • docs/extra/OPTIMIZATIONS.md - Performance optimizations
  • docs/STRATEGIES.txt - Trading strategies documentation

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Disclaimer

This project is for educational purposes only. Trading involves risk, and past performance does not guarantee future results. Use at your own risk. The authors and contributors are not responsible for any financial losses incurred from using this software.


Made for the HTMW trading community

About

Automated trading system for HowTheMarketWorks.com that exploits price delays between real-time market data and HTMW's delayed prices to identify and execute profitable arbitrage opportunities.

Topics

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages