Commit Graph

241 Commits

Author SHA1 Message Date
mindesbunister
0ed2e89c7e feat: implement per-symbol cooldown period
CRITICAL: Cooldown was global across ALL symbols, causing missed opportunities
Example: ETH trade at 10:00 blocked SOL trade at 10:04 (5min cooldown)

Changes:
- Added getLastTradeTimeForSymbol() function to query last trade per symbol
- Updated check-risk endpoint to use symbol-specific cooldown
- Each coin (SOL/ETH/BTC) now has independent cooldown timer
- Cooldown message shows symbol: 'Must wait X min before next SOL-PERP trade'

Result: Can trade ETH and SOL simultaneously without interference
Example: ETH LONG at 10:00, SOL SHORT at 10:01 = both allowed
2025-11-03 08:01:30 +01:00
mindesbunister
0ea8773bdc fix: detect exit reason using trade state flags instead of current price
CRITICAL BUG: Position Manager was using current price to determine exit reason,
but on-chain orders filled at a DIFFERENT price in the past!

Example: LONG entry $184.55, TP1 filled at $184.66, but when Position Manager
checked later (price dropped), it saw currentPrice < TP1 and defaulted to 'SL'

Result: Profitable trades incorrectly labeled as SL exits in database

Fix:
- Use trade.tp1Hit and trade.tp2Hit flags to determine exit reason
- If no TP flags set, use realized P&L to distinguish:
  - Profit >0.5% = TP1 filled
  - Negative P&L = SL filled
- Remove duplicate P&L calculation

This ensures exit reasons match actual on-chain order fills
2025-11-03 00:02:19 +01:00
mindesbunister
da960330f4 fix(n8n): pass quality score from Check Risk to Execute Trade
- Added qualityScore field to Execute Trade node JSON body
- Pulls value from Check Risk response: .item.json.qualityScore
- This enables quality score to be saved in database and displayed on analytics dashboard
2025-11-02 23:51:50 +01:00
mindesbunister
d4aeeb4f99 fix: add MAE/MFE fields to all ActiveTrade initializations
Updated execute, test, and test-db endpoints to include:
- maxFavorableExcursion: 0
- maxAdverseExcursion: 0
- maxFavorablePrice: entryPrice
- maxAdversePrice: entryPrice

Required for TypeScript compilation after adding MAE/MFE tracking
2025-11-02 23:04:02 +01:00
mindesbunister
ee7558b47c fix: remove duplicate line from MAE/MFE implementation 2025-11-02 23:01:34 +01:00
mindesbunister
12d874ff93 feat: implement MAE/MFE tracking for trade optimization
Added Maximum Favorable/Adverse Excursion tracking:
- Track maxFavorableExcursion: best profit % reached during trade
- Track maxAdverseExcursion: worst loss % reached during trade
- Track maxFavorablePrice and maxAdversePrice
- Update every price check (2s interval)
- Save to database on trade exit for optimization analysis

Benefits:
- Identify if TP levels are too conservative (MFE consistently higher)
- Determine if SL is too tight (MAE < SL but trade recovers)
- Optimize runner size based on how often MFE >> TP2
- Data-driven exit strategy tuning after collecting 10-20 trades

Display in monitoring logs: Shows MFE/MAE % every 20 seconds
2025-11-02 23:00:21 +01:00
mindesbunister
7c18e81164 fix: update on-chain SL orders after TP1 hits
CRITICAL: After TP1 closes 75%, the on-chain stop loss orders were NOT being updated
- Position Manager was tracking new SL price internally but not updating Drift orders
- Old SL orders (e.g., $181.69) remained active even after TP1 at $185.28
- This prevented the 'move SL to breakeven after TP1' logic from working

Fix:
- After TP1 hits, cancel ALL old orders on-chain
- Place new SL orders at updated price (breakeven + configured %)
- Place remaining TP2 order for the 25% runner position
- Maintains dual-stop system if enabled

Result: SL will now actually move up on Drift UI after TP1 fires
2025-11-02 22:41:06 +01:00
mindesbunister
9572b54775 fix(drift): calculate realizedPnL with leverage on USD notional, not base asset
- Old calculation: (closePrice - entryPrice) * sizeInBaseAsset = tiny P&L in dollars
- New calculation: profitPercent * leverage * notionalUSD / 100 = correct leveraged P&L
- Example: -0.13% price move * 10x leverage * $540 notional = -$7.02 (not -$0.38)
- Fixes trades showing -$0.10 to -$0.77 losses when they should be -$5 to -$40
- Applied to both DRY_RUN and real execution paths
2025-11-02 20:45:57 +01:00
mindesbunister
bcd1cd0c76 fix(position-manager): correctly handle partial close size conversions to USD
- Convert closePosition.closedSize (base asset) to USD when updating trade.currentSize
- Fix conversion when position.size detected from Drift: set currentSize = position.size * currentPrice
- Prevent trade.currentSize from being reduced to tiny values due to unit mismatch
2025-11-02 20:34:59 +01:00
mindesbunister
202c44e4bc fix: remove qualityScore from Execute Trade body (causes syntax error)
- Execute Trade node was trying to access qualityScore from Check Risk node
- This caused syntax error in n8n when Check Risk blocks the trade
- Backend API calculates qualityScore from the provided metrics (atr, adx, rsi, etc.)
- No need to pass it explicitly in the request body
2025-11-02 16:47:10 +01:00
mindesbunister
32e88c3823 fix: improve signal quality scoring for volume breakouts
- Lower ATR threshold from 0.6% to 0.15% (allows low volatility breakouts)
- Increase volume bonus: +15 for very strong volume (1.5x+), was +10 for 1.2x+
- Add volume breakout logic: High volume (1.4x+) at 95%+ range gets +5 instead of -15 penalty
- Add volume compensation: +10 bonus when volume >1.8x and ATR <0.6%
- Example: SOL signal with 0.18% ATR, 1.74x volume at 95.6% range now scores 70/100 (PASS) instead of 25/100 (BLOCK)
- This signal moved +0.97% and would have hit TP1 (+1.5%) - proves quality scoring was too conservative
- Changes apply globally to all symbols (SOL, ETH, BTC) using same scoring algorithm
2025-11-02 09:10:03 +01:00
mindesbunister
466c0c8001 fix: runner tracking bug - detect TP fills by size reduction
- Position Manager now detects TP1/TP2 fills by monitoring position size reductions instead of entry price mismatches
- When position size reduces by ~75%, marks TP1 as filled and updates currentSize
- When position size reduces by ~95%, marks TP2 as filled and activates trailing stop for 5% runner
- Entry price mismatch check now skipped after TP fills (Drift shows weighted average entry price after partial closes)
- Fixes bug where runners were incorrectly closed after TP1/TP2 fired on-chain
- Adds grace period for new trades (<30s) to avoid false positives during blockchain propagation delays
- This unblocks Phase 1 data collection for signal quality optimization (need 10+ trades with MAE/MFE data)
2025-11-01 20:06:14 +01:00
mindesbunister
056440bf8f feat: add quality score display and timezone fixes
- Add qualityScore to ExecuteTradeResponse interface and response object
- Update analytics page to always show Signal Quality card (N/A if unavailable)
- Fix n8n workflow to pass context metrics and qualityScore to execute endpoint
- Fix timezone in Telegram notifications (Europe/Berlin)
- Fix symbol normalization in /api/trading/close endpoint
- Update Drift ETH-PERP minimum order size (0.002 ETH not 0.01)
- Add transaction confirmation to closePosition() to prevent phantom closes
- Add 30-second grace period for new trades in Position Manager
- Fix execution order: database save before Position Manager.addTrade()
- Update copilot instructions with transaction confirmation pattern
2025-11-01 17:00:37 +01:00
mindesbunister
7788327a4e Update Parse Signal Enhanced for new alert format
- Changed regex from /\.P\s+(\d+)/ to /\b(buy|sell)\s+(\d+|D|W|M)\b/i
- Matches new format: 'ETH buy 15' instead of 'SOL buy .P 15'
- Supports all timeframes: 5, 15, 60, D (daily), W (weekly), M (monthly)
- Updated comment to reflect new format example
2025-11-01 11:12:38 +01:00
mindesbunister
eb2fea7bc0 Clean up alert format - remove .P notation
- Changed 'SOL buy .P 15' to 'SOL buy 15' (cleaner format)
- timeframe.period is already dynamic (no conversion needed)
- Works for any timeframe: 5, 15, 60, 240, D, etc.
- Format: 'ETH buy 15' or 'BTC sell 5' or 'SOL buy 60'
2025-11-01 11:09:37 +01:00
mindesbunister
fe0496121c Fix hardcoded SOL symbol in Pine Script alerts
- Use syminfo.ticker to dynamically get symbol name
- Strip USD/USDT/PERP suffixes to get base currency
- Works for ETH, SOL, BTC, and any other symbol
- Alerts now correctly show 'ETH buy' for Ethereum, 'BTC buy' for Bitcoin, etc.

This fixes the bug where ETH triggers sent 'SOL buy' alerts.
2025-11-01 11:06:14 +01:00
mindesbunister
8f0aa7223d Fix Format Risk node data references
- Updated to Set node v3.4 with proper assignments format
- Explicitly reference Parse Signal Enhanced for rawMessage
- Use $json for Check Risk output (reason, details, score, reasons)
- Properly formatted message with all data fields populated
- Added seconds to timestamp for better tracking
2025-11-01 11:00:13 +01:00
mindesbunister
c70fe45b15 Fix Format Risk message - clean readable format
- Removed ugly escaped syntax with $('Parse Signal').item.json references
- Use $json directly (cleaner and works correctly)
- Issues now display as bullet points instead of comma-separated
- Proper line breaks and formatting
- Professional looking blocked trade notifications
2025-11-01 10:54:30 +01:00
mindesbunister
49a09ef04e Add 'Clear Manual Closes' button to analytics
- New button in analytics page to clear orphaned trades
- API endpoint /api/trading/clear-manual-closes
- Intelligently checks Drift positions before deleting
- Only removes trades with no matching position or mismatched entry price
- Safe operation: keeps trades on error (false positives better than deletions)
- User-friendly confirmation dialog
2025-11-01 02:41:26 +01:00
mindesbunister
c82da51bdc CRITICAL FIX: Add transaction confirmation to detect failed orders
- Added getConnection() method to DriftService
- Added proper transaction confirmation in openPosition()
- Check confirmation.value.err to detect on-chain failures
- Return error if transaction fails instead of assuming success
- Prevents phantom trades that never actually execute

This fixes the issue where bot was recording trades with transaction
signatures that don't exist on-chain (like 2gqrPxnvGzdRp56...).
2025-11-01 02:26:47 +01:00
mindesbunister
a6005b6a5b Add configurable minimum quality score setting
- Added minQualityScore to TradingConfig (default: 60)
- Updated settings UI with slider control (0-100, step 5)
- Updated check-risk endpoint to use config value
- Made scoreSignalQuality function accept minScore parameter
- Updated API to read/write MIN_QUALITY_SCORE env variable
- Allows users to adjust quality threshold from settings page
2025-11-01 01:59:08 +01:00
mindesbunister
553c1f105a fix: increase ETH position size to 0 to meet Drift minimum (0.01 ETH) 2025-10-31 16:40:57 +01:00
mindesbunister
6f1c7bd5e3 fix: update test endpoint to use symbol-specific position sizing 2025-10-31 16:34:25 +01:00
mindesbunister
26f70c6426 feat: implement symbol-specific position sizing for multi-asset trading
- Extended MarketConfig with optional positionSize and leverage fields
- Configured ETH-PERP at  @ 1x leverage for minimal-risk data collection
- Created getPositionSizeForSymbol() helper function in config/trading.ts
- Integrated symbol-specific sizing into execute endpoint
- Added comprehensive guide in docs/guides/SYMBOL_SPECIFIC_SIZING.md

Purpose: Enable ETH trading for faster signal quality data collection
         while preserving SOL's profit-generation sizing (0 @ 10x)

Next: Create ETH alert in TradingView and restart bot
2025-10-31 16:16:03 +01:00
mindesbunister
a2d7cbcc4c Add detailed blocking reasons to risk check notifications
Enhanced 'Format Risk' node in n8n workflow to display:
- Specific blocking reason (duplicate, drawdown, cooldown, quality, etc.)
- Details about what triggered the block
- Quality score if low quality was the reason
- Quality issues breakdown (ATR too low, weak ADX, etc.)

Example output:
 TRADE BLOCKED
SHORT | ATR:0.30 | ADX:19.1 | RSI:46

 Issues: ATR too low (0.30% - dead market), Moderate trend (ADX 19.1), RSI supports short (46.0)
14:23
2025-10-31 14:34:49 +01:00
mindesbunister
d3f385deac Add ATR-based position scaling guide
Comprehensive guide covering:
- How ATR is captured and stored (entry value frozen)
- Static ATR approach (Phases 1-3): Use entry ATR for entire trade
- Dynamic ATR approach (Phase 5+): Real-time updates via TradingView or bot calculation
- Use cases: Dynamic TP/SL, trailing stops, scaling in/out decisions
- Implementation path: Start simple with entry ATR, add real-time later if data supports
- Code examples for all approaches
- Troubleshooting common ATR issues
- Database schema considerations

Explains why waiting for data is critical before implementing advanced ATR features.
2025-10-31 13:34:18 +01:00
mindesbunister
27c6a06d31 Update copilot-instructions.md with latest system features
Major additions:
- Exit strategy details: 3-tier scaling (TP1 75%, TP2 80% of remaining, 5% runner with trailing stop)
- Signal quality system: 5 metrics scored 0-100, filters trades at 60+ threshold
- Runner implementation: Trailing stop activation after TP2, peakPrice tracking
- Database fields: signalQualityScore, MAE/MFE, configSnapshot for state persistence
- New API endpoints: /check-risk, /analytics/last-trade, /restart
- Updated workflows with quality score validation and runner management
- Common pitfalls: Quality score duplication, runner configuration confusion
- Development roadmap: Link to POSITION_SCALING_ROADMAP.md with 6 phases

Critical corrections:
- Position Manager singleton: getPositionManager() → getInitializedPositionManager()
- Updated monitoring loop details with external closure detection and state saving
2025-10-31 12:04:20 +01:00
mindesbunister
1e858cd25d Fix roadmap: Runner already implemented, need to optimize size & trailing stop
Corrections:
- Runner system already exists (5% with 0.3% trailing stop)
- Current +41% trade is the runner in action!
- Phase 5 reframed: Optimize runner size (5% → 10-25% for high quality) and make trailing stop ATR-based
- Updated current state and trade example to reflect actual implementation
2025-10-31 11:59:29 +01:00
mindesbunister
9989f75955 Add position scaling & exit optimization roadmap
- 6-phase development plan: data collection → ATR-based → quality tiers → direction bias → runners → ML
- Each phase has clear prerequisites, implementation tasks, and success criteria
- Decision gates based on data validation (20+ trades for Phase 2, 30+ for Phase 3, etc.)
- Includes SQL queries for analysis and performance validation
- Documents current +41% trade as motivation for runner implementation
- Estimated 3-4 months timeline to complete Phases 1-5
2025-10-31 11:55:34 +01:00
mindesbunister
3c79ecbe55 Display signal quality score on analytics dashboard
- Add signalQualityScore to LastTrade interface
- Display quality score badge in last trade section (0-100)
- Color-coded: green (80+), yellow (70-79), orange (60-69)
- Shows 'Excellent', 'Good', or 'Marginal' label
- Gracefully handles null values (old trades without scores)
- Better layout when quality score is present
2025-10-31 11:34:46 +01:00
mindesbunister
090b79a07f Store signal quality score in database for future analysis
- Add signalQualityScore field to Trade model (0-100)
- Calculate quality score in execute endpoint using same logic as check-risk
- Save score with every trade for correlation analysis
- Create database migration for new field
- Enables future analysis: score vs win rate, P&L, etc.

This allows data-driven decisions on dynamic position sizing
2025-10-31 11:12:07 +01:00
mindesbunister
aecdc108f6 Add last trade details to analytics dashboard
- Add getLastTrade() function to database service
- Create /api/analytics/last-trade endpoint
- Display last trade with full details on analytics page
- Show entry/exit prices, P&L, position size, targets
- Visual indicators for trade direction and exit reason
- Helps quickly diagnose where trades went (TP1, TP2, or SL)
2025-10-31 10:47:19 +01:00
mindesbunister
8a17c2cf90 Fix Position Manager bug: prevent cancelling orders when tracking old trades
Bug: Position Manager was comparing ANY position on the symbol to the trade being
tracked, without verifying entry price match. When a new position opened, it would
think the old tracked trade 'closed externally' and cancel ALL orders - including
the new position's exit orders.

Fix: Added entry price verification (0.5% tolerance). If position entry price doesn't
match the tracked trade, mark the old trade as 'lost tracking' and remove from
monitoring WITHOUT cancelling orders (they belong to the new position).

This prevents the catastrophic scenario where exit orders are repeatedly cancelled,
leaving positions unprotected.
2025-10-31 09:34:48 +01:00
mindesbunister
37ce94d8f1 Restore context metrics in execute endpoint and clean up test files 2025-10-31 09:09:26 +01:00
mindesbunister
c88d94d14d Add n8n nodes with signal quality scoring - ready for import 2025-10-30 19:45:24 +01:00
mindesbunister
15ae57b303 Add signal quality scoring test results - all tests passed 2025-10-30 19:40:55 +01:00
mindesbunister
171c5ed1b7 Add comprehensive signal quality scoring setup guide 2025-10-30 19:38:27 +01:00
mindesbunister
830468d524 Implement signal quality scoring system
- Updated execute endpoint to store context metrics in database
- Updated CreateTradeParams interface with 5 context metrics
- Updated Prisma schema with rsiAtEntry and pricePositionAtEntry
- Ran migration: add_rsi_and_price_position_metrics
- Complete flow: TradingView → n8n → check-risk (scores) → execute (stores)
2025-10-30 19:31:32 +01:00
mindesbunister
781b88f803 Enhance TradingView indicator with context metrics for signal quality
Added 5 context metrics to alert messages:
- ATR% (volatility as % of price)
- ADX (trend strength)
- RSI (momentum)
- VOL (volume ratio vs 20-bar MA)
- POS (price position in 20-bar range 0-100%)

Changes to Pine Script:
- Always calculate ADX (needed for context even if filter disabled)
- Extract ta.rma() calls outside ternary operators (Pine Script requirement)
- Use alert() instead of alertcondition() for dynamic message support
- Changed to single-line string concatenation for compatibility

Alert message format:
OLD: 'Buy SOL 15 | Profile=Hours ATR=10 Mult=3.0'
NEW: 'SOL buy .P 15 | ATR:1.85 | ADX:28.3 | RSI:62.5 | VOL:1.45 | POS:75.3'

Next: Update n8n to parse these metrics, implement signal quality scoring in bot
2025-10-30 15:53:48 +01:00
mindesbunister
7c4adff4e4 Implement risk checks: cooldown, hourly limit, and daily drawdown
Implemented 3 critical risk checks in /api/trading/check-risk:

1. Daily Drawdown Check
   - Blocks trades if today's P&L < maxDailyDrawdown
   - Prevents catastrophic daily losses
   - Currently: -0 limit (configurable via MAX_DAILY_DRAWDOWN)

2. Hourly Trade Limit
   - Blocks trades if tradesInLastHour >= maxTradesPerHour
   - Prevents overtrading / algorithm malfunction
   - Currently: 20 trades/hour (configurable via MAX_TRADES_PER_HOUR)

3. Cooldown Period
   - Blocks trades if timeSinceLastTrade < minTimeBetweenTrades
   - Enforces breathing room between trades
   - Uses minutes (not seconds) thanks to previous commit
   - Currently: 0 min = disabled (configurable via MIN_TIME_BETWEEN_TRADES)

Added database helper functions:
- getLastTradeTime() - Returns timestamp of most recent trade
- getTradesInLastHour() - Counts trades in last 60 minutes
- getTodayPnL() - Sums realized P&L since midnight

All checks include detailed logging with values and thresholds.
Risk check called by n8n workflow before every trade execution.
2025-10-30 10:50:08 +01:00
mindesbunister
b7b0fb9bb2 Change cooldown unit from seconds to minutes
- Updated minTimeBetweenTrades config to use minutes instead of seconds
- Changed default from 600 seconds to 10 minutes
- Updated Settings UI label from 'seconds' to 'minutes' and adjusted range (0-60 min)
- Updated .env comments to reflect new unit
- No functional change since cooldown enforcement not yet implemented (TODO in check-risk route)
2025-10-30 10:35:47 +01:00
mindesbunister
25d31ff75a Fix: Save MAE/MFE values when trades exit
Bug: MAE/MFE was tracked in memory during trades but not saved to database on exit
Cause: updateTradeExit() wasn't receiving or saving MAE/MFE parameters

Changes:
- Added MAE/MFE fields to UpdateTradeExitParams interface
- Modified updateTradeExit() to save maxFavorableExcursion, maxAdverseExcursion, maxFavorablePrice, maxAdversePrice
- Updated both updateTradeExit() calls in Position Manager to pass MAE/MFE values
- Enhanced exit logging to show final MAE/MFE percentages

Impact: Future trades will now properly save MAE/MFE data for analytics
Note: Past 2 trades (from before this fix) don't have MAE/MFE saved
2025-10-30 07:37:10 +01:00
mindesbunister
6e87fc8749 Phase 4: TP/SL Optimization Visual Dashboard
- Created /analytics/optimization page with comprehensive UI
- Displays MAE/MFE analysis with percentiles
- Shows current TP/SL performance with hit rate bars
- Visualizes optimal recommendations vs current levels
- Projects impact of optimization (win rate, profit factor, P&L improvement)
- Provides reasoning for each recommended level
- Added navigation link from main analytics page

Dashboard features:
- Overview stats: total trades, win rate, profit factor, money left on table
- MAE analysis: avg, median, 25th/75th percentile, worst
- MFE analysis: avg, median, 25th/75th percentile, best
- Current config: TP1/TP2/SL hit rates with progress bars
- Recommendations: optimal levels with color-coded cards
- Reasoning cards: explanation for each recommendation
- Projected impact: win rate change, profit factor change, profit improvement
- Direct link to Settings page to apply recommendations

Access at: http://localhost:3001/analytics/optimization

Phase 1-4 Complete! System now tracks MAE/MFE, captures market context,
analyzes performance, and provides data-driven TP/SL recommendations.
2025-10-29 21:19:52 +01:00
mindesbunister
da72b5de04 Phase 3: TP/SL Optimization Analytics API
- Created /api/analytics/tp-sl-optimization endpoint
- Analyzes historical trades using MAE/MFE data
- Calculates optimal TP1/TP2/SL levels based on percentiles
- Provides win rate, profit factor, and hit rate analysis
- Shows money left on table (MFE - realized P&L)
- Projects impact of optimal levels on future performance

Analytics calculated:
- MAE analysis: avg, median, percentiles, worst
- MFE analysis: avg, median, percentiles, best
- Current level performance: TP1/TP2/SL hit rates
- Optimal recommendations: TP1=50% of avg MFE, TP2=80%, SL=70% of avg MAE
- Projected improvements: win rate change, profit factor, total P&L

Requires 10+ closed trades with MAE/MFE data to generate recommendations
Test script: scripts/test-analytics.sh

Next: Phase 4 (visual dashboard) or wait for trades with MAE/MFE data
2025-10-29 21:11:23 +01:00
mindesbunister
e068c5f2e6 Phase 2: Market context capture at entry
- Added getFundingRate() method to DriftService
- Capture expectedEntryPrice from oracle before order execution
- Capture fundingRateAtEntry from Drift Protocol
- Save market context fields to database (expectedEntryPrice, fundingRateAtEntry)
- Calculate entry slippage percentage in createTrade()
- Fixed template literal syntax errors in execute endpoint

Database fields populated:
- expectedEntryPrice: Oracle price before order
- entrySlippagePct: Calculated from entrySlippage
- fundingRateAtEntry: Current funding rate from Drift

Next: Phase 3 (analytics API) or test market context on next trade
2025-10-29 20:51:46 +01:00
mindesbunister
65e6a8efed Phase 1: Add MAE/MFE tracking and analytics schema
- Added 20+ analytics fields to Trade model (MAE/MFE, fill tracking, timing, market context, slippage)
- Implemented real-time MAE/MFE tracking in Position Manager (updates every 5s)
- Enhanced database schema with comprehensive trade analytics
- Updated all API endpoints to initialize MAE/MFE fields
- Modified updateTradeState() to persist MAE/MFE in configSnapshot

Database changes:
- maxFavorableExcursion/maxAdverseExcursion track best/worst profit %
- maxFavorablePrice/maxAdversePrice track exact price levels
- Fill tracking: tp1Filled, tp2Filled, softSlFilled, hardSlFilled
- Timing metrics: timeToTp1, timeToTp2, timeToSl
- Market context: atrAtEntry, adxAtEntry, volumeAtEntry, fundingRateAtEntry, basisAtEntry
- Slippage tracking: expectedEntryPrice, entrySlippagePct, expectedExitPrice, exitSlippagePct

Position Manager changes:
- Track MAE/MFE on every price check (2s interval)
- Throttled database updates (5s interval) via updateTradeMetrics()
- Persist MAE/MFE in trade state snapshots for recovery

Next: Phase 2 (market context capture) or Phase 3 (analytics API)
2025-10-29 20:34:03 +01:00
mindesbunister
d4d2883af6 Fix: Prevent Position Manager from closing runner after on-chain TP2
- Detect on-chain TP2 fills in size mismatch logic and set tp2Hit flag
- Position size thresholds: <30% = TP1, <10% = TP2 (prevents runner from being closed)
- Ensures runner (5-20%) trails properly instead of being market-closed immediately
2025-10-29 20:04:33 +01:00
mindesbunister
797e80b56a CRITICAL FIX: TP/SL orders using wrong size calculation
**ROOT CAUSE:** placeExitOrders() calculated position size using TP/SL prices instead of entry price

**Problem:**
- TP1 order size: 85 / TP1_price (00.746) = 2.914 SOL
- Actual position: 80 / entry_price (99.946) = 3.901 SOL
- TP1 should close: 3.901 * 75% = 2.926 SOL
- But it only closed: 2.914 SOL = 74.7%  WRONG!

**Result:** TP1 closed ~25% instead of 75%, no runner left

**Fix:**
- Changed usdToBase() to use entryPrice for ALL size calculations
- Added entryPrice param to PlaceExitOrdersOptions interface
- Updated all API routes to pass entryPrice

**Testing:** Next trade will have correctly sized TP/SL orders
2025-10-29 17:34:10 +01:00
mindesbunister
f7cf9ec63b Fix database race condition and Drift initialization errors
- Remove saveTradeState() call from addTrade() to avoid P2025 error
- Add initialization check in checkTradeConditions() to skip when Drift not ready
- Silence 'not initialized' errors during startup (expected behavior)
- Trade state is now saved only by API endpoint after DB record created
2025-10-29 16:00:06 +01:00
mindesbunister
344a79a753 Fix runner activation and order cancellation
- Change takeProfit2SizePercent from 100% to 80% to leave 5% runner
- Fix cancelAllOrders() to detect trigger orders using orderId > 0
- Trigger orders (TRIGGER_MARKET, TRIGGER_LIMIT) now properly canceled
- Trailing stop will now activate on 5% runner position
2025-10-29 15:38:47 +01:00