Files
trading_bot_v4/backtester/calculate_leverage_pnl.py
mindesbunister 96d1667ae6 feat: Complete pyramiding/position stacking implementation (ALL 7 phases)
Phase 1: Configuration
- Added pyramiding config to trading.ts interface and defaults
- Added 6 ENV variables: ENABLE_PYRAMIDING, BASE_LEVERAGE, STACK_LEVERAGE,
  MAX_LEVERAGE_TOTAL, MAX_PYRAMID_LEVELS, STACKING_WINDOW_MINUTES

Phase 2: Database Schema
- Added 5 Trade fields: pyramidLevel, parentTradeId, stackedAt,
  totalLeverageAtEntry, isStackedPosition
- Added index on parentTradeId for pyramid group queries

Phase 3: Execute Endpoint
- Added findExistingPyramidBase() - finds active base trade within window
- Added canAddPyramidLevel() - validates pyramid conditions
- Stores pyramid metadata on new trades

Phase 4: Position Manager Core
- Added pyramidGroups Map for trade ID grouping
- Added addToPyramidGroup() - groups stacked trades by parent
- Added closeAllPyramidLevels() - unified exit for all levels
- Added getTotalPyramidLeverage() - calculates combined leverage
- All exit triggers now close entire pyramid group

Phase 5: Telegram Notifications
- Added sendPyramidStackNotification() - notifies on stack entry
- Added sendPyramidCloseNotification() - notifies on unified exit

Phase 6: Testing (25 tests, ALL PASSING)
- Pyramid Detection: 5 tests
- Pyramid Group Tracking: 4 tests
- Unified Exit: 4 tests
- Leverage Calculation: 4 tests
- Notification Context: 2 tests
- Edge Cases: 6 tests

Phase 7: Documentation
- Updated .github/copilot-instructions.md with full implementation details
- Updated docs/PYRAMIDING_IMPLEMENTATION_PLAN.md status to COMPLETE

Parameters: 4h window, 7x base/stack leverage, 14x max total, 2 max levels
Data-driven: 100% win rate for signals ≤72 bars apart in backtesting
2026-01-09 13:53:05 +01:00

150 lines
4.4 KiB
Python

#!/usr/bin/env python3
"""
Calculate real P&L for ML v11.2 Long Strategy with proper leverage
Starting Capital: $1,400
Leverage: 10x
Commission: 0.05% per trade (0.1% round trip)
"""
# Trade data from CSV (Entry Price, Exit Price, Price Change %)
trades = [
# Trade #, Entry, Exit, PnL%
(1, 127.26, 123.69, -2.81),
(2, 139.45, 141.85, 1.72),
(3, 139.77, 141.85, 1.49),
(4, 144.09, 140.05, -2.80),
(5, 130.99, 133.09, 1.60),
(6, 133.64, 135.78, 1.60),
(7, 133.90, 135.67, 1.32),
(8, 133.15, 135.67, 1.89),
(9, 139.24, 141.41, 1.56),
(10, 139.12, 141.41, 1.65),
(11, 131.41, 133.79, 1.81),
(12, 131.95, 133.79, 1.39),
(13, 132.82, 129.07, -2.82),
(14, 132.76, 129.07, -2.78),
(15, 130.96, 133.06, 1.60),
(16, 125.93, 127.95, 1.60),
(17, 126.71, 128.74, 1.60),
(18, 128.70, 130.24, 1.20),
(19, 127.67, 130.24, 2.01),
(20, 123.58, 125.56, 1.60),
(21, 126.22, 128.11, 1.50),
(22, 125.96, 128.11, 1.71),
(23, 126.06, 128.21, 1.71),
(24, 126.32, 128.21, 1.50),
(25, 126.10, 121.98, -3.27),
(26, 124.89, 121.98, -2.33),
(27, 122.07, 124.04, 1.61),
(28, 122.09, 124.04, 1.60),
(29, 123.03, 125.00, 1.60),
(30, 123.34, 125.69, 1.91),
(31, 124.08, 125.69, 1.30),
(32, 123.82, 125.81, 1.61),
(33, 124.72, 126.72, 1.60),
(34, 124.90, 126.91, 1.61),
(35, 124.92, 126.91, 1.59),
(36, 128.81, 130.88, 1.61),
(37, 131.33, 133.34, 1.53),
(38, 131.14, 133.34, 1.68),
(39, 134.23, 136.57, 1.74),
(40, 134.60, 136.57, 1.46),
(41, 138.24, 140.46, 1.61),
(42, 138.89, 141.12, 1.61),
(43, 140.00, 136.08, -2.80),
(44, 135.09, 137.26, 1.61),
]
# Configuration
STARTING_CAPITAL = 1400.0
LEVERAGE = 10
COMMISSION_RATE = 0.0005 # 0.05% per trade (entry + exit = 0.1%)
print("=" * 70)
print("ML v11.2 LONG STRATEGY - REAL P&L CALCULATION")
print("=" * 70)
print(f"Starting Capital: ${STARTING_CAPITAL:,.2f}")
print(f"Leverage: {LEVERAGE}x")
print(f"Commission: {COMMISSION_RATE * 100:.2f}% per trade (0.1% round trip)")
print(f"Total Trades: {len(trades)}")
print("=" * 70)
# Calculate with compounding
equity = STARTING_CAPITAL
max_equity = STARTING_CAPITAL
max_drawdown = 0
max_drawdown_pct = 0
wins = 0
losses = 0
total_commission = 0
print("\n📊 TRADE-BY-TRADE BREAKDOWN (with 10x leverage):")
print("-" * 70)
for trade_num, entry, exit_price, pnl_pct in trades:
# Position size = equity * leverage
notional = equity * LEVERAGE
# Commission on entry and exit (0.05% each way)
commission = notional * COMMISSION_RATE * 2 # Round trip
total_commission += commission
# Gross P&L at 10x leverage
gross_pnl = notional * (pnl_pct / 100)
# Net P&L after commission
net_pnl = gross_pnl - commission
# Update equity
old_equity = equity
equity += net_pnl
# Track wins/losses
if net_pnl > 0:
wins += 1
else:
losses += 1
# Track drawdown
if equity > max_equity:
max_equity = equity
drawdown = max_equity - equity
drawdown_pct = (drawdown / max_equity) * 100
if drawdown > max_drawdown:
max_drawdown = drawdown
max_drawdown_pct = drawdown_pct
# Print every trade
emoji = "" if net_pnl > 0 else ""
print(f"Trade {trade_num:2d}: {emoji} Entry ${entry:.2f} → Exit ${exit_price:.2f} | "
f"Notional ${notional:,.0f} | Net P&L: ${net_pnl:+,.2f} | Equity: ${equity:,.2f}")
print("-" * 70)
# Final stats
total_profit = equity - STARTING_CAPITAL
roi = (total_profit / STARTING_CAPITAL) * 100
win_rate = (wins / len(trades)) * 100
print("\n" + "=" * 70)
print("📈 FINAL RESULTS WITH 10x LEVERAGE")
print("=" * 70)
print(f"Starting Capital: ${STARTING_CAPITAL:,.2f}")
print(f"Final Equity: ${equity:,.2f}")
print(f"Total Profit: ${total_profit:+,.2f}")
print(f"ROI: {roi:+.2f}%")
print(f"Total Commission: ${total_commission:,.2f}")
print("=" * 70)
print(f"Wins: {wins}")
print(f"Losses: {losses}")
print(f"Win Rate: {win_rate:.2f}%")
print(f"Max Drawdown: ${max_drawdown:,.2f} ({max_drawdown_pct:.2f}%)")
print("=" * 70)
# Compare to TradingView results
tv_pnl = 657.95
print(f"\n📊 COMPARISON TO TRADINGVIEW BACKTEST:")
print(f"TradingView (1x): ${tv_pnl:+,.2f} (+47.00%)")
print(f"With 10x Leverage: ${total_profit:+,.2f} ({roi:+.2f}%)")
print(f"Multiplier Effect: {total_profit/tv_pnl:.1f}x")