- Split QUALITY_LEVERAGE_THRESHOLD into separate LONG and SHORT variants
- Added /api/drift/account-health endpoint for real-time collateral data
- Updated settings UI to show separate controls for LONG/SHORT thresholds
- Position size calculations now use dynamic collateral from Drift account
- Updated .env and docker-compose.yml with new environment variables
- LONG threshold: 95, SHORT threshold: 90 (configurable independently)
Files changed:
- app/api/drift/account-health/route.ts (NEW) - Account health API endpoint
- app/settings/page.tsx - Added collateral state, separate threshold inputs
- app/api/settings/route.ts - GET/POST handlers for LONG/SHORT thresholds
- .env - Added QUALITY_LEVERAGE_THRESHOLD_LONG/SHORT variables
- docker-compose.yml - Added new env vars with fallback defaults
Impact:
- Users can now configure quality thresholds independently for LONG vs SHORT signals
- Position size display dynamically updates based on actual Drift account collateral
- More flexible risk management with direction-specific leverage tiers
Complete implementation of adaptive leverage configuration via web interface:
Frontend (app/settings/page.tsx):
- Added 4 fields to TradingSettings interface:
* USE_ADAPTIVE_LEVERAGE: boolean
* HIGH_QUALITY_LEVERAGE: number
* LOW_QUALITY_LEVERAGE: number
* QUALITY_LEVERAGE_THRESHOLD: number
- Added complete Adaptive Leverage section with:
* Purple-themed informational box explaining quality-based leverage
* Toggle switch for enabling/disabling (🎯 Enable Adaptive Leverage)
* Number inputs for high leverage (1-20), low leverage (1-20), threshold (80-100)
* Visual tier display showing leverage multipliers and position sizes
* Dynamic calculation based on $560 free collateral
Backend (app/api/settings/route.ts):
- GET handler: Load 4 adaptive leverage fields from environment variables
- POST handler: Save 4 adaptive leverage fields to .env file
- Proper type conversion (boolean from 'true', numbers from parseInt/parseFloat)
Visual Tier Display Example:
Below Threshold: Blocked (no trade)
Changes enable users to adjust leverage settings via web UI instead of
manually editing .env file and restarting container.
- Added MIN_SIGNAL_QUALITY_SCORE_LONG and _SHORT fields to Settings interface
- Replaced single quality score field with three fields:
1. Global Fallback (91) - for BTC and other symbols
2. LONG Signals (90) - based on 71.4% WR data analysis
3. SHORT Signals (95) - based on toxic 28.6% WR data, blocks low-quality shorts
- Updated app/api/settings/route.ts GET/POST handlers to support direction-specific fields
- Fixed field naming consistency (MIN_SIGNAL_QUALITY_SCORE vs MIN_QUALITY_SCORE)
- User can now adjust direction-specific thresholds via settings UI without .env editing
- Container deployed: 2025-11-23T14:25:34 UTC
- 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
- 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)
- 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
- 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
**UI Updates (settings page):**
Added new '📈 Position Scaling' section with:
- Enable/disable toggle (defaults to OFF)
- Min quality score slider (60-90, default 75)
- Min profit to scale (0-2%, default 0.4%)
- Scale size percent (10-100%, default 50%)
- Max position multiplier (1-3x, default 2.0x)
- Min ADX increase (0-15, default 5)
- Max price position for scale (50-90%, default 70%)
**Visual Feedback:**
- Purple-themed section with warning banner
- Real-time risk calculator showing:
* Original position size (SOL example)
* Scale addition amount
* Total after 1 scale
* Maximum possible position size
- Dynamic descriptions explain each parameter
- Warning: 'DISABLED by default' with red indicator
**API Updates:**
Extended /api/settings GET/POST to handle 7 new fields:
- ENABLE_POSITION_SCALING
- MIN_SCALE_QUALITY_SCORE
- MIN_PROFIT_FOR_SCALE
- MAX_SCALE_MULTIPLIER
- SCALE_SIZE_PERCENT
- MIN_ADX_INCREASE
- MAX_PRICE_POSITION_FOR_SCALE
**User Flow:**
1. Navigate to http://localhost:3001/settings
2. Scroll to '📈 Position Scaling' section
3. Toggle 'Enable Position Scaling' to 1
4. Adjust thresholds (defaults are conservative)
5. See live calculation of scaling impact
6. Click 'Save Settings'
7. Click 'Restart Bot' to apply
**Safety:**
- Feature OFF by default (requires explicit opt-in)
- Warning banner explains scaling behavior
- Risk calculator shows maximum exposure
- Conservative defaults prevent aggressive scaling
- All parameters adjustable via sliders
**Example:**
With defaults (SOL $210×10x = $2100):
- Scale adds: $1050 (50% of $2100)
- Total after 1 scale: $3150
- Max position (2x): $4200
User can now enable and configure position scaling without touching .env file!
- Add SymbolSettings interface with enabled/positionSize/leverage fields
- Implement per-symbol ENV variables (SOLANA_*, ETHEREUM_*)
- Add SOL and ETH sections to settings UI with enable/disable toggles
- Add symbol-specific test buttons (SOL LONG/SHORT, ETH LONG/SHORT)
- Update execute and test endpoints to check symbol enabled status
- Add real-time risk/reward calculator per symbol
- Rename 'Position Sizing' to 'Global Fallback' for clarity
- Fix position manager P&L calculation for externally closed positions
- Fix zero P&L bug affecting 12 historical trades
- Add SQL scripts for recalculating historical P&L data
- Move archive TypeScript files to .archive to fix build
Defaults:
- SOL: 10 base × 10x leverage = 100 notional (profit trading)
- ETH: base × 1x leverage = notional (data collection)
- Global: 10 × 10x for BTC and other symbols
Configuration priority: Per-symbol ENV > Market config > Global ENV > Defaults
- 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
- 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)
- Implemented trailing stop logic in Position Manager for remaining position after TP2
- Added new ActiveTrade fields: tp2Hit, trailingStopActive, peakPrice
- New config settings: useTrailingStop, trailingStopPercent, trailingStopActivation
- Added trailing stop UI section in settings page with explanations
- Fixed env file parsing regex to support numbers in variable names (A-Z0-9_)
- Settings now persist correctly across container restarts
- Added back arrow navigation on settings page
- Updated all API endpoints and test files with new fields
- Trailing stop activates when runner reaches configured profit level
- SL trails below peak price by configurable percentage
- Split test trade button into separate LONG and SHORT buttons
- Update testTrade function to accept direction parameter
- Add confirmation dialog showing the specific direction
- Green button for LONG, red button for SHORT
- Success message includes executed direction
- Add PostgreSQL database with Prisma ORM
- Trade model: tracks entry/exit, P&L, order signatures, config snapshots
- PriceUpdate model: tracks price movements for drawdown analysis
- SystemEvent model: logs errors and system events
- DailyStats model: aggregated performance metrics
- Implement dual stop loss system (enabled by default)
- Soft stop (TRIGGER_LIMIT) at -1.5% to avoid wicks
- Hard stop (TRIGGER_MARKET) at -2.5% to guarantee exit
- Configurable via USE_DUAL_STOPS, SOFT_STOP_PERCENT, HARD_STOP_PERCENT
- Backward compatible with single stop modes
- Add database service layer (lib/database/trades.ts)
- createTrade(): save new trades with all details
- updateTradeExit(): close trades with P&L calculations
- addPriceUpdate(): track price movements during trade
- getTradeStats(): calculate win rate, profit factor, avg win/loss
- logSystemEvent(): log errors and system events
- Update execute endpoint to use dual stops and save to database
- Calculate dual stop prices when enabled
- Pass dual stop parameters to placeExitOrders
- Save complete trade record to database after execution
- Add test trade button to settings page
- New /api/trading/test endpoint for executing test trades
- Displays detailed results including dual stop prices
- Confirmation dialog before execution
- Shows entry price, position size, stops, and TX signature
- Generate Prisma client in Docker build
- Update DATABASE_URL for container networking
**New Features:**
- Added TAKE_PROFIT_1_SIZE_PERCENT (default: 50%)
- Added TAKE_PROFIT_2_SIZE_PERCENT (default: 50%)
- Users can now control WHAT % to close at each TP level
- Risk calculator now shows actual TP sizes dynamically
**Bug Fixes:**
- Fixed settings save failure by mounting .env file to container
- Added .env volume mount in docker-compose.yml
- Fixed permission issues (.env must be chmod 666)
**UI Changes:**
- Split TP controls into Price % and Size %
- TP1 Price: When to exit first partial
- TP1 Size: What % of position to close (1-100%)
- TP2 Price: When to exit second partial
- TP2 Size: What % of remaining to close (1-100%)
- Risk calculator displays dynamic percentages
**Example:**
- TP1 at +1% price, close 60% of position
- TP2 at +2% price, close 40% of remaining (24% of original)
- Total exit: 84% of position at TP levels
- Added restart button to settings page
- Created /api/restart endpoint (file-flag based)
- Implemented watch-restart.sh daemon
- Added systemd service for restart watcher
- Updated README with restart setup instructions
- Container automatically restarts when settings changed
Settings flow:
1. User edits settings in web UI
2. Click 'Save Settings' to persist to .env
3. Click 'Restart Bot' to apply changes
4. Watcher detects flag and restarts container
5. New settings loaded automatically
Features:
- Autonomous trading system with Drift Protocol on Solana
- Real-time position monitoring with Pyth price feeds
- Dynamic stop-loss and take-profit management
- n8n workflow integration for TradingView signals
- Beautiful web UI for settings management
- REST API for trade execution and monitoring
- Next.js 15 with standalone output mode
- TypeScript with strict typing
- Docker containerization with multi-stage builds
- PostgreSQL database for trade history
- Singleton pattern for Drift client connection pooling
- BN.js for BigNumber handling (Drift SDK requirement)
- Configurable stop-loss and take-profit levels
- Breakeven trigger and profit locking
- Daily loss limits and trade cooldowns
- Slippage tolerance controls
- DRY_RUN mode for safe testing
- Real-time risk calculator
- Interactive sliders for all parameters
- Live preview of trade outcomes
- Position sizing and leverage controls
- Beautiful gradient design with Tailwind CSS
- POST /api/trading/execute - Execute trades
- POST /api/trading/close - Close positions
- GET /api/trading/positions - Monitor active trades
- GET /api/trading/check-risk - Validate trade signals
- GET /api/settings - View configuration
- POST /api/settings - Update configuration
- Fixed Borsh serialization errors (simplified order params)
- Resolved RPC rate limiting with singleton pattern
- Fixed BigInt vs BN type mismatches
- Corrected order execution flow
- Improved position state management
- Complete setup guides
- Docker deployment instructions
- n8n workflow configuration
- API reference documentation
- Risk management guidelines
- Runs on port 3001 (external), 3000 (internal)
- Uses Helius RPC for optimal performance
- Production-ready with error handling
- Health monitoring and logging