125 lines
6.4 KiB
Markdown
125 lines
6.4 KiB
Markdown
# Trading212 "Touch & Turn" Scalping Bot
|
|
|
|
This project implements the "Touch & Turn" scalping strategy (Opening Range Liquidity Reversal) in Python for the Trading212 API. It is specifically designed to trade US Equities at the 09:30 EST market open.
|
|
|
|
## ⚠️ Disclaimer
|
|
**This software is for educational purposes only.** Trading in financial markets involves a high degree of risk. Always use the practice/demo environment (`demo.trading212.com`) to test strategies before using real money.
|
|
|
|
---
|
|
|
|
## Strategy Overview
|
|
|
|
The strategy capitalizes on the initial liquidity and volatility of the US market open.
|
|
|
|
1. **The Setup:** Captures the high and low of the first 15-minute candle (09:30 - 09:45 EST).
|
|
2. **The Filter:** The range of this opening candle must be at least **25%** of the stock's 14-day Average True Range (ATR). If the market is too quiet, no trade is taken.
|
|
3. **The Trigger:**
|
|
- If the opening candle closes **Bearish** (Close < Open), the bot prepares a **LONG** entry at the candle's Low.
|
|
- If the opening candle closes **Bullish** (Close > Open), the bot prepares a **SHORT** entry at the candle's High.
|
|
4. **The Targets:**
|
|
- **Take Profit (TP):** The 38.2% Fibonacci retracement level of the opening candle's range.
|
|
- **Stop Loss (SL):** Placed to ensure a Risk:Reward ratio of 1:2 (Risking 1 unit to make 2).
|
|
5. **Time Exit:** All open positions are forcefully closed at 11:00 EST to avoid mid-day chop.
|
|
|
|
---
|
|
|
|
## Installation & Setup
|
|
|
|
1. **Clone the repository and set up a virtual environment:**
|
|
```bash
|
|
python3 -m venv venv
|
|
source venv/bin/activate
|
|
```
|
|
|
|
2. **Install dependencies:**
|
|
```bash
|
|
pip install -r requirements.txt
|
|
```
|
|
*(Note: The `prettytable` library was recently added for backtesting outputs. Run `pip install prettytable` if it's missing from your requirements file).*
|
|
|
|
3. **Configure Environment Variables:**
|
|
Create a `.env` file in the root directory based on `.env.example`:
|
|
```ini
|
|
TRADING212_API_KEY_ID=your_key_id_here
|
|
TRADING212_API_KEY=your_api_key_here
|
|
TRADING212_BASE_URL=https://demo.trading212.com/api/v0/
|
|
```
|
|
*You can generate your API Key and ID inside the Trading212 app under Settings -> API.*
|
|
|
|
4. **Verify Connection:**
|
|
Run the test script to ensure your credentials are correct and you can read your account balance:
|
|
```bash
|
|
python3 test_api_connection.py
|
|
```
|
|
|
|
---
|
|
|
|
## The Workflow & Scripts
|
|
|
|
This repository is split into the live execution bot and several helper scripts to find the best assets to trade.
|
|
|
|
### 1. Finding ISA-Eligible Tickers
|
|
If you are trading from a UK Trading212 Stocks ISA, you are restricted from trading US-domiciled ETFs and certain other assets.
|
|
|
|
Run the ISA candidate script to fetch all available instruments, filter for ISA-compliant US Stocks, and rank a basket of popular tech stocks by their current volatility (ATR %):
|
|
```bash
|
|
PYTHONPATH=. python3 scripts/find_isa_candidates.py
|
|
```
|
|
*This script outputs a leaderboard to the console and saves `isa_watchlist.csv`.*
|
|
|
|
### 2. Backtesting the Watchlist
|
|
High volatility doesn't always guarantee a strategy works on a specific stock. You must backtest.
|
|
|
|
Run the backtesting engine. It will automatically read the `isa_watchlist.csv` generated in the previous step and simulate the strategy over the last ~60 trading days (using 15m data from Yahoo Finance).
|
|
```bash
|
|
PYTHONPATH=. python3 scripts/backtest.py
|
|
```
|
|
*This will output a leaderboard ranked by **Net PnL (in Risk Multiples/R)**. Identify the top 2-3 performing tickers (e.g., `NFLX`, `UBER`, `MSFT`) to configure the live bot.*
|
|
|
|
### 3. Running the Live Bot
|
|
Once you have identified the best tickers for the day, the orchestrator will automatically spin up threads to monitor and trade them.
|
|
|
|
Start the bot before the US market opens (09:30 EST):
|
|
```bash
|
|
python3 main.py
|
|
```
|
|
The bot will:
|
|
1. Initialize and run the ISA scanner.
|
|
2. Backtest the top candidates and pick the **Top 3** with the highest historical R-multiple profit.
|
|
3. Spawn isolated background threads for each ticker to wait for exactly 09:45 EST.
|
|
4. Evaluate the opening candle, calculate risk-adjusted position sizes, and place the necessary Entry, Take Profit, and Stop Loss orders.
|
|
5. Poll for order fills and gracefully flatten all open positions at exactly 11:00 EST.
|
|
|
|
---
|
|
|
|
## Risk Management & Position Sizing
|
|
|
|
The bot uses dynamic **Risk-Based Position Sizing**. It does not buy a fixed number of shares. Instead, it calculates the distance between the Entry price and the Stop Loss price to determine the "Risk per Share".
|
|
|
|
By default, the bot risks **1% of your account balance** per trade.
|
|
|
|
**Virtual Balances:**
|
|
If you are testing on a demo account with a massive starting balance (e.g., £5,000) but plan to trade live with a much smaller amount, you can override the risk calculation to maintain psychological perspective. Set `VIRTUAL_STARTING_BALANCE=250` in your `.env` file. The bot will pretend your account only has £250 and will size its fraction share purchases to risk exactly £2.50 per trade.
|
|
|
|
---
|
|
|
|
## Logging & PnL Tracking
|
|
|
|
The bot provides comprehensive monitoring out of the box:
|
|
|
|
- **Console & File Logging:** All activity (entries, fills, errors) is logged to the console and simultaneously appended to a daily file in the `logs/` directory (e.g., `logs/bot_2026-04-14.log`).
|
|
- **PnL Tracking:** A running ledger of all closed trades is kept in `pnl_tracking.csv`. This file records the Ticker, Direction, Entry/Exit prices, the reason for the exit (e.g., "TP Hit" or "11:00 Time Exit"), and the Profit/Loss measured in Risk Multiples (R). You can import this CSV into Excel or Python to chart your strategy's performance over time.
|
|
|
|
---
|
|
|
|
## Utility Scripts
|
|
|
|
- `scripts/get_available_tickers.py`: Fetches the raw metadata for all 16,000+ instruments available on Trading212 and saves them to `available_instruments.json` and `available_tickers.csv`. Useful if you want to manually search for new tickers outside the default tech/growth basket.
|
|
|
|
## Architecture
|
|
|
|
* **`src/api/client.py`:** Handles REST HTTP basic authentication and request formatting for the Trading212 API.
|
|
* **`src/strategy/touch_turn.py`:** The core logic engine. Fetches market data via Yahoo Finance, calculates ATR and Fibonacci levels, and returns the trade parameters.
|
|
* **`src/strategy/scanner.py`:** The ranking engine used to sort tickers by ATR volatility.
|
|
* **`src/execution/manager.py`:** Consumes the trade parameters and places the orders via the API client.
|