Commit Graph

150 Commits

Author SHA1 Message Date
mindesbunister
03e91fc18d feat: ATR-based trailing stop + rate limit monitoring
MAJOR FIXES:
- ATR-based trailing stop for runners (was fixed 0.3%, now adapts to volatility)
- Fixes runners with +7-9% MFE exiting for losses
- Typical improvement: 2.24x more room (0.3% → 0.67% at 0.45% ATR)
- Enhanced rate limit logging with database tracking
- New /api/analytics/rate-limits endpoint for monitoring

DETAILS:
- Position Manager: Calculate trailing as (atrAtEntry / price × 100) × multiplier
- Config: TRAILING_STOP_ATR_MULTIPLIER=1.5, MIN=0.25%, MAX=0.9%
- Settings UI: Added ATR multiplier controls
- Rate limits: Log hits/recoveries/exhaustions to SystemEvent table
- Documentation: ATR_TRAILING_STOP_FIX.md + RATE_LIMIT_MONITORING.md

IMPACT:
- Runners can now capture big moves (like morning's $172→$162 SOL drop)
- Rate limit visibility prevents silent failures
- Data-driven optimization for RPC endpoint health
2025-11-11 14:51:41 +01:00
mindesbunister
0700daf8ff feat: add indicator version tracking system
Database changes:
- Added indicatorVersion field to Trade table
- Added indicatorVersion field to BlockedSignal table
- Tracks which Pine Script version (v5, v6, etc.) generated each signal

Pine Script changes:
- v6 now includes '| IND:v6' in alert messages
- Enables differentiation between v5 and v6 signals in database

Documentation:
- Created INDICATOR_VERSION_TRACKING.md with full implementation guide
- Includes n8n workflow update instructions
- Includes SQL analysis queries for v5 vs v6 comparison
- Includes rollback plan if needed

Next steps (manual):
1. Update n8n workflow Parse Signal Enhanced node to extract IND field
2. Update n8n HTTP requests to pass indicatorVersion
3. Update API endpoints to accept and save indicatorVersion
4. Rebuild Docker container

Benefits:
- Compare v5 vs v6 Pine Script effectiveness
- Track which version generated winning/losing trades
- Validate that v6 price position filter reduces blocked signals
- Data-driven decisions on Pine Script improvements
2025-11-11 12:53:33 +01:00
mindesbunister
871d82a64a feat: add Pine Script v6 with improved signal quality filters
New v6 improvements:
- Fixed price position calculation: 100-bar range (was 20-bar)
- Added price position filter: prevents chasing extremes (85% max for longs, 15% min for shorts)
- Added volume filter: optional range check (0.7-3.0x average)
- Added RSI momentum filter: optional directional confirmation
- All new filters toggleable with sensible defaults

Key changes:
- Price position filter ENABLED by default (prevents flip-flop losses)
- Volume and RSI filters DISABLED by default (test incrementally)
- Aligns TradingView filtering with bot's 5-metric scoring system
- Reduces signals sent to bot that would be blocked anyway

Rationale:
Database analysis showed range extreme entries (9-94%) caused flip-flop losses.
V6 filters these at source instead of blocking in bot after webhook call.

Testing approach:
1. Phase 1: Price position filter only (test 5-10 signals)
2. Phase 2: Add volume filter if needed
3. Phase 3: Add RSI filter as last resort
2025-11-11 12:32:26 +01:00
mindesbunister
6ef5fea41a docs: add essential SQL queries to AI agent instructions
Added SQL Analysis Queries section with:
- Phase 1 monitoring queries (count, score distribution, recent signals)
- Phase 2 comparison queries (blocked vs executed trades)
- Pattern analysis queries (range extremes, ADX distribution)

Benefits:
- AI agents have immediate access to standard queries
- Consistent analysis approach each time
- No need to context-switch to separate docs
- Quick reference for common investigations

Includes usage pattern guidance and reference to full docs.
2025-11-11 12:02:22 +01:00
mindesbunister
356b4ed578 docs: update AI agent instructions with blocked signals tracking
- Added BlockedSignal to database models list
- Updated signalQualityVersion to v4 (current)
- Added blocked signals tracking functions to database section
- Updated check-risk endpoint description
- Added Signal Quality Optimization Roadmap reference
- Documented blocked signals analysis workflow
- Added reference to BLOCKED_SIGNALS_TRACKING.md

This ensures AI agents understand the new data collection system.
2025-11-11 11:52:24 +01:00
mindesbunister
ba13c20c60 feat: implement blocked signals tracking system
- Add BlockedSignal table with 25 fields for comprehensive signal analysis
- Track all blocked signals with metrics (ATR, ADX, RSI, volume, price position)
- Store quality scores, block reasons, and detailed breakdowns
- Include future fields for automated price analysis (priceAfter1/5/15/30Min)
- Restore signalQualityVersion field to Trade table

Database changes:
- New table: BlockedSignal with indexes on symbol, createdAt, score, blockReason
- Fixed schema drift from manual changes

API changes:
- Modified check-risk endpoint to save blocked signals automatically
- Fixed hasContextMetrics variable scope (moved to line 209)
- Save blocks for: quality score too low, cooldown period, hourly limit
- Use config.minSignalQualityScore instead of hardcoded 60

Database helpers:
- Added createBlockedSignal() function with try/catch safety
- Added getRecentBlockedSignals(limit) for queries
- Added getBlockedSignalsForAnalysis(olderThanMinutes) for automation

Documentation:
- Created BLOCKED_SIGNALS_TRACKING.md with SQL queries and analysis workflow
- Created SIGNAL_QUALITY_OPTIMIZATION_ROADMAP.md with 5-phase plan
- Documented data-first approach: collect 10-20 signals before optimization

Rationale:
Only 2 historical trades scored 60-64 (insufficient sample size for threshold decision).
Building data collection infrastructure before making premature optimizations.

Phase 1 (current): Collect blocked signals for 1-2 weeks
Phase 2 (next): Analyze patterns and make data-driven threshold decision
Phase 3-5 (future): Automation and ML optimization
2025-11-11 11:49:21 +01:00
mindesbunister
ee89d15b8b Use percentage aware sizing in execute endpoint 2025-11-10 20:27:52 +01:00
mindesbunister
43b688d9f2 Fix test trade endpoint to honor TP2 runner configuration 2025-11-10 19:55:24 +01:00
mindesbunister
c3a053df63 CRITICAL FIX: Use ?? instead of || for tp2SizePercent to allow 0 value
BUG FOUND:
Line 558: tp2SizePercent: config.takeProfit2SizePercent || 100

When config.takeProfit2SizePercent = 0 (TP2-as-runner system), JavaScript's ||
operator treats 0 as falsy and falls back to 100, causing TP2 to close 100%
of remaining position instead of activating trailing stop.

IMPACT:
- On-chain orders placed correctly (line 481 uses ?? correctly)
- Position Manager reads from DB and expects TP2 to close position
- Result: User sees TWO take-profit orders instead of runner system

FIX:
Changed both tp1SizePercent and tp2SizePercent to use ?? operator:
- tp1SizePercent: config.takeProfit1SizePercent ?? 75
- tp2SizePercent: config.takeProfit2SizePercent ?? 0

This allows 0 value to be saved correctly for TP2-as-runner system.

VERIFICATION NEEDED:
Current open SHORT position in database has tp2SizePercent=100 from before
this fix. Next trade will use correct runner system.
2025-11-10 19:46:03 +01:00
mindesbunister
089308a07e Add Position Sync feature for recovering tracking after partial fills
- New /api/trading/sync-positions endpoint (no auth)
- Fetches actual Drift positions and compares with Position Manager
- Removes stale tracking, adds missing positions with calculated TP/SL
- Settings UI: Orange 'Sync Positions' button added
- CLI script: scripts/sync-positions.sh for terminal access
- Full documentation in docs/guides/POSITION_SYNC_GUIDE.md
- Quick reference: POSITION_SYNC_QUICK_REF.md
- Updated AI instructions with pitfall #23

Problem solved: Manual Telegram trades with partial fills can cause
Position Manager to lose tracking, leaving positions without software-
based stop loss protection. This feature restores dual-layer protection.

Note: Docker build not picking up route yet (cache issue), needs investigation
2025-11-10 17:05:32 +01:00
mindesbunister
2e47731e8e Update AI instructions with latest fixes
Added sections:
- Recent Critical Fixes (2024-11-10): Runner system + anti-chop filter V2
- JavaScript || vs ?? operator gotcha (#21)
- Range-bound chop detection details (#22)
- Updated anti-chop filter description with backtest results
2025-11-10 15:43:48 +01:00
mindesbunister
988fdb9ea4 Fix runner system + strengthen anti-chop filter
Three critical bugs fixed:
1. P&L calculation (65x inflation) - now uses collateralUSD not notional
2. handlePostTp1Adjustments() - checks tp2SizePercent===0 for runner mode
3. JavaScript || operator bug - changed to ?? for proper 0 handling

Signal quality improvements:
- Added anti-chop filter: price position <40% + ADX <25 = -25 points
- Prevents range-bound flip-flops (caught all 3 today)
- Backtest: 43.8% → 55.6% win rate, +86% profit per trade

Changes:
- lib/trading/signal-quality.ts: RANGE-BOUND CHOP penalty
- lib/drift/orders.ts: Fixed P&L calculation + transaction confirmation
- lib/trading/position-manager.ts: Runner system logic
- app/api/trading/execute/route.ts: || to ?? for tp2SizePercent
- app/api/trading/test/route.ts: || to ?? for tp1/tp2SizePercent
- prisma/schema.prisma: Added collateralUSD field
- scripts/fix_pnl_calculations.sql: Historical P&L correction
2025-11-10 15:36:51 +01:00
mindesbunister
e31a3f8433 fix: Update settings UI to show % instead of USD when percentage mode active
- Add SOLANA_USE_PERCENTAGE_SIZE and ETHEREUM_USE_PERCENTAGE_SIZE to TradingSettings interface
- Make SOL/ETH Position Size labels dynamic based on percentage mode
- Adjust max value (100 for %, 10000 for USD) based on mode
- Update descriptions to match mode (% of collateral vs fixed capital)
2025-11-10 13:40:28 +01:00
mindesbunister
6f0a1bb49b feat: Implement percentage-based position sizing
- Add usePercentageSize flag to SymbolSettings and TradingConfig
- Add calculateActualPositionSize() and getActualPositionSizeForSymbol() helpers
- Update execute and test endpoints to calculate position size from free collateral
- Add SOLANA_USE_PERCENTAGE_SIZE, ETHEREUM_USE_PERCENTAGE_SIZE, USE_PERCENTAGE_SIZE env vars
- Configure SOL to use 100% of portfolio (auto-adjusts to available balance)
- Fix TypeScript errors: replace fillNotionalUSD with actualSizeUSD
- Remove signalQualityVersion and fullyClosed references (not in interfaces)
- Add comprehensive documentation in PERCENTAGE_SIZING_FEATURE.md

Benefits:
- Prevents insufficient collateral errors by using available balance
- Auto-scales positions as account grows/shrinks
- Maintains risk proportional to capital
- Flexible per-symbol configuration (SOL percentage, ETH fixed)
2025-11-10 13:35:10 +01:00
mindesbunister
d20190c5b0 docs: Update copilot-instructions.md with configurable quality score threshold
- Updated Signal Quality System to reflect MIN_SIGNAL_QUALITY_SCORE is configurable (default: 65)
- Added critical pitfall #7: Never use hardcoded config values in endpoints
- Emphasized settings page can modify minSignalQualityScore dynamically
- Renumbered remaining pitfalls for clarity
2025-11-10 13:00:40 +01:00
mindesbunister
d2fbd125a0 fix: Make minSignalQualityScore configurable via settings + anti-chop improvements
CRITICAL BUG FIX:
- Settings page saved MIN_SIGNAL_QUALITY_SCORE to .env but check-risk had hardcoded value
- Now reads from config.minSignalQualityScore (defaults to 65, editable via /settings)
- Prevents settings changes from being ignored after restart

ANTI-CHOP FILTER FIXES:
- Fixed volume breakout bonus conflicting with anti-chop filter
- Volume breakout now requires ADX > 18 (trending market)
- Prevents high volume + low ADX from getting rewarded instead of penalized
- Anti-chop filter now properly blocks whipsaw traps at score 60

TESTING INFRASTRUCTURE:
- Added backtest script showing +17.1% P&L improvement (saved $242 in losses)
- Added test-signals.sh for comprehensive signal quality validation
- Added test-recent-signals.sh for analyzing actual trading session signals
- All tests passing: timeframe awareness, anti-chop, score thresholds

CHANGES:
- config/trading.ts: Added minSignalQualityScore to interface and defaults
- app/api/trading/check-risk/route.ts: Use config value instead of hardcoded 65
- lib/trading/signal-quality.ts: Fixed volume breakout bonus logic
- .env: Added MIN_SIGNAL_QUALITY_SCORE=65
- scripts/: Added comprehensive testing tools

BACKTEST RESULTS (Last 30 trades):
- Old system (score ≥60): $1,412.79 P&L
- New system (score ≥65 + anti-chop): $1,654.79 P&L
- Improvement: +$242.00 (+17.1%)
- Blocked 5 losing trades, missed 0 winners
2025-11-10 11:22:52 +01:00
mindesbunister
60a0035f56 Add anti-chop filter: Penalize high volume during weak trend
PROBLEM ANALYSIS:
Signal that lost -$32: ADX 14.8, VOL 2.29x → scored 70-90 (PASSED)
Signal that won +3%: ADX 15.7, VOL 1.18x → scored 45-65 (got BLOCKED before fix)

Key insight: High volume during choppy conditions (ADX < 16) indicates
whipsaw/trap, not genuine breakout. Our volume bonus (+15 pts for >1.5x)
was rewarding flip-flop signals instead of real moves.

FIX:
Add anti-chop filter in volume scoring:
- If ADX < 16 AND volume > 1.5x → -15 points (whipsaw trap)
- Overrides the normal +15 bonus for high volume
- Protects against false signals during consolidation

IMPACT ON RECENT SIGNALS:
1. 00:40 SHORT (ADX 17.2, VOL 0.98): 55→75  Still passes
2. 00:55 LONG (ADX 15, VOL 0.47): 35→55  Still blocked (correct, weak vol)
3. 01:05 SHORT (ADX 14.8, VOL 2.29): 70→60 ⚠️ Now flagged as whipsaw trap
4. 01:10 LONG (ADX 15.7, VOL 1.18): 45→65  Catches the +3% runup

Result: Loser signal now barely passes (60) with warning flag,
winner signal passes cleanly (65). Better risk/reward profile.
2025-11-10 07:46:46 +01:00
mindesbunister
4b11186d16 Fix: Add timeframe-aware signal quality scoring for 5min charts
PROBLEM:
- Long signal (ADX 15.7, ATR 0.35%) blocked with score 45/100
- Missed major +3% runup, lost -2 on short that didn't flip
- Scoring logic treated all timeframes identically (daily chart thresholds)

ROOT CAUSE:
- ADX < 18 always scored -15 points regardless of timeframe
- 5min charts naturally have lower ADX (12-22 healthy range)
- copilot-instructions mentioned timeframe awareness but wasn't implemented

FIX:
- Add timeframe parameter to RiskCheckRequest interface
- Update scoreSignalQuality() with timeframe-aware ADX thresholds:
  * 5min/15min: ADX 12-22 healthy (+5), <12 weak (-15), >22 strong (+15)
  * Higher TF: ADX 18-25 healthy (+5), <18 weak (-15), >25 strong (+15)
- Pass timeframe from n8n workflow through check-risk and execute
- Update both Check Risk nodes in Money Machine workflow

IMPACT:
Your blocked signal (ADX 15.7 on 5min) now scores:
- Was: 50 + 5 - 15 + 0 + 0 + 5 = 45 (BLOCKED)
- Now: 50 + 5 + 5 + 0 + 0 + 5 = 65 (PASSES)

This 20-point improvement from timeframe awareness would have caught the runup.
2025-11-10 07:34:21 +01:00
mindesbunister
14cd1a85ba Update copilot-instructions with critical Drift SDK insights
- Document Drift SDK position.size returns USD, not token quantity
- Add Solana RPC rate limiting retry pattern with exponential backoff
- Document /api/trading/cancel-orders endpoint for ghost order cleanup
- Clarify symbol normalization requirement for manual close endpoint
- Captures lessons learned from TP1 detection and P&L calculation debugging
2025-11-09 18:04:43 +01:00
mindesbunister
22195ed34c Fix P&L calculation and signal flip detection
- Fix external closure P&L using tp1Hit flag instead of currentSize
- Add direction change detection to prevent false TP1 on signal flips
- Signal flips now recorded with accurate P&L as 'manual' exits
- Add retry logic with exponential backoff for Solana RPC rate limits
- Create /api/trading/cancel-orders endpoint for manual cleanup
- Improves data integrity for win/loss statistics
2025-11-09 17:59:50 +01:00
mindesbunister
4d533ccb53 fix: Remove obsolete fields from test-db ActiveTrade object
- Remove atrAtEntry and runnerTrailingPercent fields
- These don't exist in ActiveTrade interface
- Fixes TypeScript build error
2025-11-08 11:05:19 +01:00
mindesbunister
2f80c2133c fix: Remove fallback that breaks TP2-as-runner system
- Change tp2SizePercent fallback from || 100 to ?? 0
- Allows 0 value to pass through (means 'activate trailing stop, don't close')
- Fixes bug where TP2 was closing 100% of remaining position
- Now correctly leaves 25% runner after TP1 closes 75%
- Applied to both execute and test endpoints
2025-11-08 10:59:58 +01:00
mindesbunister
9b767342dc feat: Implement re-entry analytics system with fresh TradingView data
- Add market data cache service (5min expiry) for storing TradingView metrics
- Create /api/trading/market-data webhook endpoint for continuous data updates
- Add /api/analytics/reentry-check endpoint for validating manual trades
- Update execute endpoint to auto-cache metrics from incoming signals
- Enhance Telegram bot with pre-execution analytics validation
- Support --force flag to override analytics blocks
- Use fresh ADX/ATR/RSI data when available, fallback to historical
- Apply performance modifiers: -20 for losing streaks, +10 for winning
- Minimum re-entry score 55 (vs 60 for new signals)
- Fail-open design: proceeds if analytics unavailable
- Show data freshness and source in Telegram responses
- Add comprehensive setup guide in docs/guides/REENTRY_ANALYTICS_QUICKSTART.md

Phase 1 implementation for smart manual trade validation.
2025-11-07 20:40:07 +01:00
mindesbunister
6d5991172a feat: Implement ATR-based dynamic TP2 system and fix P&L calculation
- Add ATR-based dynamic TP2 scaling from 0.7% to 3.0% based on volatility
- New config options: useAtrBasedTargets, atrMultiplierForTp2, minTp2Percent, maxTp2Percent
- Enhanced settings UI with ATR controls and updated risk calculator
- Fix external closure P&L calculation using unrealized P&L instead of volatile current price
- Update execute and test endpoints to use calculateDynamicTp2() function
- Maintain 25% runner system for capturing extended moves (4-5% targets)
- Add environment variables for ATR-based configuration
- Better P&L accuracy for manual position closures
2025-11-07 17:01:22 +01:00
mindesbunister
5acc61cf66 Fix P&L calculation and update Copilot instructions
- Fix P&L calculation in Position Manager to use actual entry vs exit price instead of SDK's potentially incorrect realizedPnL
- Calculate actual profit percentage and apply to closed position size for accurate dollar amounts
- Update database record for last trade from incorrect 6.58 to actual .66 P&L
- Update .github/copilot-instructions.md to reflect TP2-as-runner system changes
- Document 25% runner system (5x larger than old 5%) with ATR-based trailing
- Add critical P&L calculation pattern to common pitfalls section
- Mark Phase 5 complete in development roadmap
2025-11-07 16:24:43 +01:00
mindesbunister
0c644ccabe Make TP2 the runner - no more partial closes
CHANGE: TP2 now activates trailing stop on full 25% remaining instead
of closing 80% and leaving 5% runner.

Benefits:
- 5x larger runner (25% vs 5%) = 25 vs 05 on 100 position
- Eliminates Drift minimum size issues completely
- Simplifies logic - no more canUseRunner() viability checks
- Better R:R on extended moves

New flow:
- TP1 (+0.4%): Close 75%, keep 25%
- TP2 (+0.7%): Skip close, activate trailing stop on full 25%
- Runner: 25% with ATR-based trailing (0.25-0.9%)

Config change: takeProfit2SizePercent: 80 → 0
Position Manager: Remove canUseRunner logic, activate trailing at TP2 hit
2025-11-07 15:29:50 +01:00
mindesbunister
36ba3809a1 Fix runner system by checking minimum position size viability
PROBLEM: Runner never activated because Drift force-closes positions below
minimum size. TP2 would close 80% leaving 5% runner (~$105), but Drift
automatically closed the entire position.

SOLUTION:
1. Created runner-calculator.ts with canUseRunner() to check if remaining
   size would be above Drift minimums BEFORE executing TP2 close
2. If runner not viable: Skip TP2 close entirely, activate trailing stop
   on full 25% remaining (from TP1)
3. If runner viable: Execute TP2 as normal, activate trailing on 5%

Benefits:
- Runner system will now actually work for viable position sizes
- Positions that are too small won't try to force-close below minimums
- Better logs showing why runner did/didn't activate
- Trailing stop works on larger % if runner not viable (better R:R)

Example: $2100 position → $525 after TP1 → $105 runner = VIABLE
         $4 ETH position → $1 after TP1 → $0.20 runner = NOT VIABLE

Runner will trail with ATR-based dynamic % (0.25-0.9%) below peak price.
2025-11-07 15:10:01 +01:00
mindesbunister
309cad8108 Add SQL script to fix SHORT position P&L in database
Corrects all historical SHORT trades affected by the P&L calculation bug.

Results:
- 44 SHORT trades corrected
- Total P&L improved from -$388.82 to -$72.98 (+$315.84 recovered)
- SHORT win rate revealed to be 60.5% (not 39% as incorrectly shown)

Script creates backup table before making changes and includes rollback instructions.
2025-11-07 14:55:13 +01:00
mindesbunister
4996bc2aad Fix SHORT position P&L calculation bug
CRITICAL BUG FIX: SHORT positions were calculating P&L with inverted logic,
causing profits to be recorded as losses and vice versa.

Problem Example:
- SHORT at $156.58, exit at $154.66 (price dropped $1.92)
- Should be +~$25 profit
- Was recorded as -$499.23 LOSS

Root Cause:
Old formula: profitPercent = (exit - entry) / entry * (side === 'long' ? 1 : -1)
This multiplied the LONG formula by -1 for shorts, but then applied it to
full notional instead of properly accounting for direction.

Fix:
- LONG: priceDiff = (exit - entry) → profit when price rises
- SHORT: priceDiff = (entry - exit) → profit when price falls
- profitPercent = priceDiff / entry * 100
- Proper leverage calculation: realizedPnL = collateral * profitPercent * leverage

This fixes both dry-run and live close position calculations in lib/drift/orders.ts

Impact: All SHORT trades since bot launch have incorrect P&L in database.
Future trades will calculate correctly.
2025-11-07 14:53:03 +01:00
mindesbunister
a8de1c9d37 Update copilot instructions with signal quality versioning
- Added signalQualityVersion field documentation (v1/v2/v3 tracking)
- Documented /api/analytics/version-comparison endpoint
- Added Prisma Decimal type handling pitfall (#18)
- Added signal quality version tracking section to Development Roadmap
- References SQL analysis file for version comparison queries

Enables AI agents to understand the version tracking system for
data-driven algorithm optimization.
2025-11-07 13:38:56 +01:00
mindesbunister
6983f37a59 Fix Prisma Decimal type handling in version comparison API
- Changed numeric fields from typed as number to 'any' in raw query results
- Properly convert Prisma Decimal/BigInt types to JavaScript numbers
- Fixes TypeError: e.totalPnL.toFixed is not a function
- All numeric values (totalPnL, avgPnL, avgADX, etc.) now converted with Number()

Issue: Prisma returns Decimal objects from aggregation queries which don't have
toFixed() method. Frontend expects plain numbers for .toFixed(2) formatting.
2025-11-07 13:11:04 +01:00
mindesbunister
711ff9aaf4 Add signal quality version comparison to analytics dashboard
- Created /api/analytics/version-comparison endpoint
- Shows performance metrics for v1, v2, v3 scoring logic
- Compares: trade count, win rate, P&L, quality scores, MFE/MAE
- Special focus on extreme positions (< 15% or > 85% range)
- Tracks weak ADX count (< 18) for each version
- Visual indicators for current version (v3)
- Data collection progress notice for v3 (need 20+ trades)
- Legend explaining MFE, MAE, extreme positions, weak ADX

Enables data-driven optimization by comparing algorithm performance
with clean, version-tagged datasets.
2025-11-07 13:05:48 +01:00
mindesbunister
625dc44c59 Add signal quality version tracking to database
- Added signalQualityVersion field to Trade model
- Tracks which scoring logic version was used for each trade
- v1: Original logic (price position < 5% threshold)
- v2: Added volume compensation for low ADX
- v3: CURRENT - Stricter logic requiring ADX > 18 for extreme positions (< 15%)

This enables future analysis to:
- Compare performance between logic versions
- Filter trades by scoring algorithm
- Data-driven improvements based on clean datasets

All new trades will be marked as v3. Old trades remain null/v1 for comparison.
2025-11-07 12:56:35 +01:00
mindesbunister
3c9da22a8a Add ADX > 18 requirement for extreme price positions
- Shorts/longs at < 15% range require ADX > 18 AND volume > 1.2x
- OR RSI < 35 for shorts, RSI > 60 for longs
- Increased penalty from -10 to -15 when conditions not met
- Changed threshold from < 5% to < 15% to catch more edge cases

Test results:
- Big loser (01:35): ADX 16.1, price 9.3% → Score 60 (was 90) → BLOCKED
- Today's signal (10:05): ADX 17.3, price 0.9% → Score 55 (was 85) → BLOCKED

Rationale: False breakdowns in choppy ranges (ADX < 18) cause losses.
Tradeoff: May block some profitable breakdowns, but prevents chop losses.
2025-11-07 12:19:41 +01:00
mindesbunister
db907d8074 Improve signal quality scoring for breakdowns/breakouts
- Allow shorts at range bottom (<5%) with volume >1.2x OR RSI <40
- Allow longs at range bottom with volume >1.2x OR RSI >60
- Reduce ADX penalty from -15 to -5 when strong volume (>1.2x) present
- Reduce price position penalties from -15 to -10 (less harsh)
- Volume compensation recognizes breakdowns start before ADX strengthens

Test case (blocked signal that would have profited):
- OLD: ATR 0.32, ADX 17.3, RSI 32.5, Vol 1.27x, Price 0.9% → Score 45 (blocked)
- NEW: Same metrics → Score 85 (executes)

Rationale: Breakdowns continue lower, volume confirms conviction, ADX lags price action
2025-11-07 10:58:47 +01:00
mindesbunister
0365560c5b Add timeframe-aware signal quality scoring for 5min charts
- Lower ADX/ATR thresholds for 5min timeframe (ADX 12-22, ATR 0.2-0.7%)
- Add anti-chop filter: -20 points for extreme sideways (ADX<10, ATR<0.25, Vol<0.9)
- Pass timeframe parameter through check-risk and execute endpoints
- Fixes flip-flop losses from overly strict 5min filters
- Higher timeframes unchanged (still use ADX 18+, ATR 0.4+)

5min scoring now:
- ADX 12-15: moderate trend (+5)
- ADX 22+: strong trend (+15)
- ATR 0.2-0.35: acceptable (+5)
- ATR 0.35+: healthy (+10)
- Extreme chop penalty prevents whipsaw trades
2025-11-07 08:56:19 +01:00
mindesbunister
b52a980138 Add manual long/short commands via Telegram plain text
- Extended telegram_command_bot.py with MessageHandler for plain text messages
- Supports 'long sol/eth/btc' and 'short sol/eth/btc' syntax
- Calls /api/trading/execute directly with preset healthy metrics
- Increased timeout to 60s for on-chain transaction completion
- No changes to webhook flow or existing commands
2025-11-06 13:48:38 +01:00
mindesbunister
6c7eaf5f04 Add TP1/SL consistency check on trade restore 2025-11-06 12:18:31 +01:00
mindesbunister
7c888282ec Adjust TP detection logic for partial fills 2025-11-05 23:49:41 +01:00
mindesbunister
5241920d44 Prevent repeated TP2 cleanup loops 2025-11-05 16:14:17 +01:00
mindesbunister
a100945864 Enhance trailing stop with ATR-based sizing 2025-11-05 15:28:12 +01:00
mindesbunister
149294084e fix: auto-clean leftovers after stop hits 2025-11-05 11:42:22 +01:00
mindesbunister
b58e08778e fix: correct MFE/MAE tracking after partial exits 2025-11-05 10:29:32 +01:00
mindesbunister
18e3e73e83 feat: refresh exit orders after TP1 and add dry-run harness 2025-11-05 10:00:39 +01:00
mindesbunister
cbb6592153 fix: correct PnL math and add health probe 2025-11-05 07:58:27 +01:00
mindesbunister
02193b7dce fix(critical): Unify quality score calculation across check-risk and execute
PROBLEM:
- check-risk calculated quality score: 60, 70 (PASSED)
- execute calculated quality score: 35, 45 (should have BLOCKED)
- Two different functions with different logic caused trades to bypass validation

ROOT CAUSE:
Two separate scoring functions existed:
1. scoreSignalQuality() in check-risk (detailed, 95% price threshold)
2. calculateQualityScore() in execute (simpler, 90% price threshold)

Example with pricePosition=96.4%, volumeRatio=0.9:
- check-risk: Checks >95, volumeRatio>1.4 failed → -15 + bonuses = 60  PASSED
- execute: Checks >90 → -15 + bonuses = 35  Should block but already opened

SOLUTION:
1. Created lib/trading/signal-quality.ts with unified scoreSignalQuality()
2. Both endpoints now import and use SAME function
3. Consistent scoring logic: 95% price threshold, volume breakout bonus
4. Returns detailed reasons for debugging

IMPACT:
- Quality scores now MATCH between check-risk and execute
- No more trades bypassing validation due to calculation differences
- Better debugging with quality reasons logged

Files changed:
- NEW: lib/trading/signal-quality.ts (unified scoring function)
- MODIFIED: app/api/trading/check-risk/route.ts (import shared function)
- MODIFIED: app/api/trading/execute/route.ts (import shared function)
- REMOVED: Duplicate calculateQualityScore() from execute
- REMOVED: Duplicate scoreSignalQuality() from check-risk
2025-11-04 11:40:25 +01:00
mindesbunister
fdbb474e68 fix(n8n): CRITICAL - Add quality score validation to old workflow path
PROBLEM:
- Trades with quality score 35 and 45 were executed (threshold: 60)
- Position opened without risk management after signal flips
- "Parse Signal" node didn't extract ATR/ADX/RSI/volumeRatio/pricePosition
- "Check Risk" node only sent symbol+direction, skipped quality validation
- "Execute Trade" node didn't forward metrics to backend

ROOT CAUSE:
n8n workflow had TWO paths:
1. NEW: Parse Signal Enhanced → Check Risk1 → Execute Trade1 (working)
2. OLD: Parse Signal → Check Risk → Execute Trade (broken)

Old path bypassed quality check because check-risk endpoint saw
hasContextMetrics=false and allowed trade without validation.

FIX:
1. Changed "Parse Signal" from 'set' to 'code' node with metric extraction
2. Updated "Check Risk" to send atr/adx/rsi/volumeRatio/pricePosition
3. Updated "Execute Trade" to forward all metrics to backend

IMPACT:
- All trades now validated against quality score threshold (60)
- Low-quality signals properly blocked before execution
- Prevents positions opening without proper risk management

Evidence from database showed 3 trades in 2 hours with scores <60:
- 10:00:31 SOL LONG - Score 35 (phantom detected)
- 09:55:30 SOL SHORT - Score 35 (executed)
- 09:35:14 SOL LONG - Score 45 (executed)

All three should have been blocked. Fix prevents future bypasses.
2025-11-04 11:18:57 +01:00
mindesbunister
8bc08955cc feat: Add phantom trade detection and database tracking
- Detect position size mismatches (>50% variance) after opening
- Save phantom trades to database with expectedSizeUSD, actualSizeUSD, phantomReason
- Return error from execute endpoint to prevent Position Manager tracking
- Add comprehensive documentation of phantom trade issue and solution
- Enable data collection for pattern analysis and future optimization

Fixes oracle price lag issue during volatile markets where transactions
confirm but positions don't actually open at expected size.
2025-11-04 10:34:38 +01:00
mindesbunister
f682b93a1e Fix: Signal flip race condition - properly coordinate Position Manager during opposite signal closure
- Remove trade from Position Manager BEFORE closing Drift position (prevents race condition)
- Explicitly save closure to database with proper P&L calculation
- Mark flipped positions as 'manual' exit reason
- Increase delay from 1s to 2s for better on-chain confirmation
- Preserve MAE/MFE data in closure records

Fixes issue where SHORT signal would close LONG but not properly track the new SHORT position.
Database now correctly records both old position closure and new position opening.
2025-11-03 20:23:42 +01:00
mindesbunister
1426a9ec2f CRITICAL FIX: P&L calculation using wrong position size for phantom trades
- Position Manager was calculating P&L using tracked size instead of actual on-chain size
- Example: Tracked 100, actual 0.04 SOL () = -99.63% false loss instead of -0.32%
- Fixed external closure detection to use position.size * currentPrice as lastKnownSize
- Manually corrected phantom trade P&L from -092.25 to /bin/bash
- Total P&L corrected: -013.92 → +8.33 (accurate)
- Prevents all future phantom/mismatch trades from wildly incorrect P&L

Modified:
- lib/trading/position-manager.ts lines 421-445 (external closure P&L calculation)
2025-11-03 16:57:53 +01:00