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.
The system:
- Scans for stocks with the biggest gains in the last 3 minutes
- Selects the most profitable opportunity (by total profit, not just percentage)
- Buys all-in ($20,000) on the single best opportunity
- Monitors the position until HTMW price catches up to the entry real-time price
- Sells automatically when HTMW reaches the fixed target price
- 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
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)
git clone https://github.com/yourusername/delayedge.git
cd delayedgepip install -r requirements.txtRequired packages:
requests- HTTP library for API callsyfinance- Yahoo Finance data retrievalpython-dotenv- Environment variable managementbeautifulsoup4- HTML parsingpytz(optional but recommended) - Timezone handling
- Log into HTMW in your web browser
- Install a cookie export extension (e.g., "EditThisCookie" for Chrome/Edge)
- Export your cookies as JSON:
- Click the extension icon
- Select "Export" → "JSON"
- Copy the entire JSON array
- Create a
.envfile in the project root:touch .env
- Add your cookies to the
.envfile:Important: The JSON must be on a single line with no line breaks.HTMW_COOKIES=[{"name":"cookie1","value":"value1",...},{"name":"cookie2","value":"value2",...}]
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)
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 endStart 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.
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 100python -m pytest tests/ -q25 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.
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
- 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
The system uses a .env file for sensitive configuration:
HTMW_COOKIES: JSON array of your HTMW authentication cookies
- Never commit your
.envfile to version control - Never share your HTMW cookies publicly
- The
.envfile is automatically ignored by git (see.gitignore)
- 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.
- Ensure your
.envfile exists in the project root - Verify the
HTMW_COOKIESvariable 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
Install pytz for better timezone handling:
pip install pytz- Verify your HTMW cookies are still valid (they may expire)
- Check your internet connection
- Ensure HTMW service is accessible
For more detailed information, see the docs/ folder:
docs/extra/QUICKSTART.md- Quick start guidedocs/extra/PROJECT_STRUCTURE.md- Detailed project structuredocs/extra/OPTIMIZATIONS.md- Performance optimizationsdocs/STRATEGIES.txt- Trading strategies documentation
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
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