docs: finalize gemini.md with full technical specs and resilience logic

This commit is contained in:
pie
2026-05-15 17:56:07 +01:00
parent e71e833c71
commit ec65e86bd9
+33 -47
View File
@@ -1,60 +1,46 @@
# Trading212 Python Scalping Bot - "Touch & Turn" (Opening Range Reversal) # Trading212 Python Scalping Bot - "Touch & Turn" (Opening Range Reversal)
This project implements the "Touch & Turn" scalping strategy, originally designed for ProRealTime, translated into Python for the Trading212 API. It is optimized for the UK ISA environment using Inverse ETPs for shorting. This project implements the "Touch & Turn" scalping strategy for the Trading212 API, optimized for the UK ISA environment.
## Project Overview
* **Strategy:** Opening Range Liquidity Reversal (Touch & Turn).
* **Asset Class:** US Stocks (e.g., NVDA, ARM, TSLA).
* **Timeframe:** 15-minute chart.
* **Operating Window:** 09:30 - 11:00 EST (Opening of the US Regular Trading Session).
## Strategy Logic (The Workflow) ## Strategy Logic (The Workflow)
1. **Identify the Opening Candle:** Capture the `High`, `Low`, `Open`, and `Close` of the first 15-minute candle of the session (09:30 to 09:45 EST). 1. **Identify Opening Candle:** Capture the 15m candle (09:30 to 09:45 EST).
2. **Filter for Liquidity:** 2. **Filter for Liquidity:** Opening range must be >= 25% of 14-day ATR.
- The opening range (`High - Low`) must be at least **25% of the 14-day ATR**. If smaller, the bot stays flat.
3. **Determine Direction:** 3. **Determine Direction:**
- If the candle is **Bearish** (Close < Open): Prepare for a **LONG** entry. - Bearish (Close < Open): Prepare **LONG** (Buy at Low).
- If the candle is **Bullish** (Close > Open): Prepare for a **SHORT** entry. - Bullish (Close > Open): Prepare **SHORT** (Substitute with **3x Inverse ETP BUY** in ISA).
4. **ISA-Compliant Shorting:** 4. **Execution (09:45 EST):**
- Since standard shorting is forbidden in a UK ISA, the bot automatically substitutes SHORT signals with **BUY orders for 3x Inverse ETPs** (e.g., 3SLA for TSLA). - Entry via **Market Order** for immediate fill.
5. **Execution:** - **Actual Fill Price** fetched from portfolio is used for all bracket calculations.
- Uses **Market Orders** at 09:45 EST for immediate entry. 5. **Hybrid Exit Strategy:**
- Recalculates SL/TP brackets based on the **Actual Fill Price** fetched from the portfolio. - **Broker-Side:** Physical **Stop Loss** order placed immediately for protection.
6. **Risk Management:** - **Bot-Side:** **Take Profit** monitored manually by polling current market price.
- **Position Sizing:** Risks **1% of account balance** per trade. - This bypasses ISA restrictions against multiple pending sell orders for the same shares.
- **Virtual Balance:** In demo mode, subtracts £4,750 from total value to simulate a realistic £250 starting point. 6. **Automatic Exit (11:00 EST):** Force close via Market Order and cleanup pending SL.
- **Targets:** 38.2% Fibonacci retracement level. Risk:Reward ratio of 1:2.
7. **Automatic Exit:** Force close any open positions at 11:00 EST via Market Order. ## Risk & Capital Management
* **Virtual Balance Simulation:** In demo mode, subtracts £4,750 from total equity to simulate a realistic £250 starting point.
* **1% Risk Rule:** Risks exactly 1% of the Virtual Balance per trade.
* **Capital Partitioning:** Divides total available capital (£250) and risk budget equally among all active ticker threads for the day (max 3).
* **Precision & Minimums:** Automatically detects "precision-mismatch" or "min-quantity-exceeded" errors from T212 and retries with corrected values.
## Technical Architecture ## Technical Architecture
* **API Client (`src/api/client.py`):** Handles REST Basic Auth calls to Trading212. * **`main.py`:** Daily orchestrator. Scan -> Backtest -> Select Top 3 -> Spawn Parallel Threads. Handles early API verification and unbuffered logging.
* **Strategy Engine (`src/strategy/touch_turn.py`):** Calculates setup, Fibonacci levels, and percentage-based targets. * **`src/api/client.py`:** REST wrapper with Basic Auth.
* **Execution Manager (`src/execution/manager.py`):** Handles ticker swapping for ISA mode, market order placement, protection bracketing, and status monitoring. * **`src/strategy/touch_turn.py`:** Setup logic, Fibonacci calculation, and timezone conversion (UTC -> Eastern).
* **Orchestrator (`main.py`):** Automates the morning routine: scanning, backtesting, and spawning parallel execution threads. * **`src/execution/manager.py`:** Handles ticker swapping (Inverse ETPs), market entries, hybrid brackets, and retry loops with jitter.
* **Data resilient:** Implements retry loops and random jitter to handle API delays and rate limits (429/403/404 errors). * **`src/strategy/inverse_mapping.py`:** Map of US stocks to 3x Short Inverse ETPs (GraniteShares/Leverage Shares).
## Getting Started ## Resilience Features
1. **Setup Environment:** * **API Backoff:** Random jitter (1-10s) and exponential retry on 429 errors.
```bash * **Order Tracking:** Uses portfolio checks to infer status if order IDs disappear (404).
pip install -r requirements.txt * **Unbuffered Logging:** Force-flushes logs to `logs/bot_*.log` immediately for real-time monitoring.
```
2. **Configuration:**
- Set credentials in your `.env` file.
- `ISA_MODE=True` enables Inverse ETP substitution.
3. **Operation:**
- Best deployed via a systemd timer at 09:30 America/New_York time.
## TODOs ## Operation
- [x] Document the strategy logic. 1. **Timer:** Service managed by `systemd` timer firing at 09:30 America/New_York.
- [x] Implement ATR calculation and Fibonacci targets. 2. **Tracking:** P&L recorded in `pnl_tracking.csv` (R-multiple based).
- [x] Implement 15m candle capture with timezone resilience. 3. **Verification:** Always run `./venv/bin/python3 test_api_connection.py` before live days.
- [x] Implement ISA-compliant shorting via Inverse ETP mapping.
- [x] Implement Risk-based position sizing (Virtual Balance logic).
- [x] Create a leaderboard-based backtesting engine.
- [x] Implement resilient execution (Retry loops, Jitter, Portfolio-checks).
- [x] Add daily logging and P&L tracking (CSV).