Skip to content

Conversation

@birdbathd
Copy link
Contributor

@birdbathd birdbathd commented Nov 24, 2025

Summary

Implements a comprehensive protective orders system with trailing take profit, break-even protection, and two-phase activation logic.

Key Features

  • ✅ Trailing take profit with activation threshold
  • ✅ Two-phase activation (wait for activation distance, then track profit)
  • ✅ 0.5% minimum profit buffer before activation
  • ✅ Break-even stop loss protection
  • ✅ Per-symbol protective order configuration
  • ✅ Real-time protective order monitoring UI
  • ✅ Expanded on Tranche management system integration

Bug Fixes

  • Fixed duplicate variable declarations causing bot crash on startup
  • Fixed service initialization checks in API routes
  • Removed redundant per-symbol config (now centralized)

Technical Details

  • Service: src/lib/services/protectiveOrderService.ts with two-phase activation
  • UI: Protective order status display with real-time updates
  • Logging: Comprehensive logging for debugging and monitoring

Dependencies

  • Depends on: #tradingview-charts (base TradingView integration)

Screenshots

image

Testing -TBA

  • Bot starts without errors
  • Protective orders activate correctly
  • Trailing TP tracks profit with minimum buffer
  • Break-even protection engages properly

CryptoGnome and others added 30 commits October 12, 2025 17:14
- Treat default "admin" password as unauthenticated access
- Update password check logic in both auth API and login page to exclude "admin" from requiring authentication
- Remove minLength constraint from password input field
- Add clarifying comments about default password handling

This change improves user experience by allowing immediate access when using the default password, while still requiring authentication for custom passwords.
Features:
- Interactive TradingView charts with 7-day kline caching
- Manual and auto-refresh (60s intervals) with optimized updates
- Liquidation markers grouped by configurable time intervals
- Position lines and VWAP indicator
- Recent orders overlay on chart
- Compact, modern chart controls UI

Database Management:
- Configurable liquidation data retention (default: 90 days)
- Automated cleanup scheduler with configurable intervals
- UI controls for database retention settings
- Statistics tracking for stored liquidations

Performance:
- Smart caching system prevents redundant API calls
- Only updates chart when data actually changes
- Efficient incremental updates for new candles
- Optimized state management to prevent unnecessary re-renders
- Automatically loads older candles when scrolling back in time
- Monitors visible time range and loads 500 candles at a time
- Adds endTime parameter support to klines API
- Tracks earliest loaded candle timestamp in cache
- Shows 'Loading history...' indicator during fetch
- Prepends historical data without disrupting current view
- No more 7-day limit - can view unlimited historical data
- Use ref for loadHistoricalData to avoid scope issues
- Remove klineData.length from chart init dependencies to prevent re-initialization
- Chart now initializes correctly and loads historical data on scroll
- Track user interactions (scrolling/zooming) with chart
- Only reset to 2/3 position on initial load
- Maintain view position during auto-refresh and historical data loading
- Reset interaction state when symbol or timeframe changes
- Improves UX by not disrupting user's chosen view
- Add ping/pong keepalive every 30 seconds to detect silent disconnections
- Add inactivity monitor: auto-reconnect if no liquidations received for 5 minutes
- Add proper cleanup of keepalive and inactivity timers on disconnect/stop
- Log warnings when stream becomes inactive
- Broadcast inactivity warnings to UI for visibility

This fixes the issue where the liquidation stream would stop receiving data
without triggering any errors or reconnection attempts.
- Add 'TP/SL' toggle to show/hide position entry and TP/SL lines
- Move 'Liquidations' toggle next to 'Group' setting (they're related)
- Reorganize controls: [Auto-refresh, Orders, TP/SL, VWAP] | [Liquidations, Group] | [Timeframe]
- Fix position lines disappearing when changing chart settings
- Position lines now persist through timeframe/symbol/grouping changes
- Lines are only cleared when toggle is disabled or positions change

This improves chart control organization and fixes the issue where TP/SL
lines would disappear when adjusting chart settings.
Resolved merge conflicts:
- src/bot/index.ts: Added Tranche Manager initialization from dev
- src/lib/bot/hunter.ts: Added tranche creation on order placement
- src/components/SymbolConfigForm.tsx: Updated input handling to allow default values

Accepted new tranche management features from dev:
- Tranche Manager service and database
- Tranche UI components (breakdown, timeline, settings)
- Tranche page for multi-position tracking

Chart features remain independent and functional.
- Reuse Hunter instance instead of creating new one on bot restart
- Remove all event listeners before re-attaching to prevent duplicates
- Clean up thresholdMonitor listeners by event name
- Add detailed logging for liquidation sidebar API loading
- Fix: Hunter now calls removeAllListeners() on stop to clear handlers

This fixes the issue where liquidations would appear multiple times in the UI
due to event listeners accumulating across bot restarts and HMR cycles.
- Add UNIQUE constraint on (symbol, event_time) to liquidations table
- Change INSERT to INSERT OR IGNORE to silently skip duplicate events
- Addresses root cause at database level instead of UI-level workarounds

Testing in progress for duplicate issues and potential bugs.
…y revert

- Restored tranche docs and all related source files from dev branch
- Ensures TradingView feature branch does not remove unrelated tranche features
…unts

- Properly close and remove listeners from old WebSocket before creating new connection
- Add deduplication logic in thresholdMonitor based on eventTime, quantity, and price
- Prevents multiple WebSocket connections from processing the same liquidation event
- Fixes issue where single liquidations were being counted 50+ times due to duplicate events
…n loops

- Add shouldReconnect flag to control automatic reconnection behavior
- Prevent close handler from reconnecting when manually disconnecting
- Track reconnection timeouts to avoid scheduling multiple reconnections
- Temporarily disable auto-reconnect during intentional disconnects (inactivity, config changes)
- Prevents reconnection cascades that could cause duplicate connections
- Maintains deduplication safety mechanisms from previous commit
- Add tranche management fields to SymbolConfig type
- Import and render TrancheSettingsSection in symbol config form
- Add default tranche configuration values
- Allows configuring isolation threshold, max tranches, and recovery settings per symbol
- Add tranche configuration fields to SymbolConfig type
- Integrate TrancheSettingsSection into symbol config form
- Initialize tranche database tables on startup
- Add Tranches page to sidebar navigation with DashboardLayout
- Fix symbol dropdown to show configured symbols from config
- Fix onChange binding and null coalescing for trade size fields

Note: Tranche system is implemented but requires testing with live positions
Configuration:
- Add protective order fields to SymbolConfig type
- Create ProtectiveOrdersSection UI component
- Support breakeven trim with configurable offset
- Support multiple trim levels at different P&L targets

Backend Implementation:
- Create ProtectiveOrderService to manage protective orders
- Place LIMIT orders with 'po_' prefix to avoid TP/SL conflicts
- Integrate with PositionManager for automatic triggers
- Monitor positions and place orders when price levels hit
- Handle order fills and position closures
- Filter protective orders from orphaned order cleanup

Features:
- Breakeven protection: Trim X% when price returns to entry
- Multi-level trims: Set multiple profit/loss targets
- Non-interfering: Uses separate order IDs, won't conflict with TP/SL
- Auto-cleanup: Removes orders when positions close

Note: Untested - requires live position testing
- Fixed log parsing to include proper timestamps with milliseconds
- Generate unique log IDs for each entry
- Added ProtectiveOrderService initialization in bot startup
- Service now starts when any symbol has enableProtectiveOrders=true
- Both TrancheManager and ProtectiveOrderService log their startup status
- Logs now show HH:MM:SS.mmm format for easy reading
…tarts

- Removed enableProtectiveOrders, protectiveBreakeven, protectiveTrimLevels from SymbolConfig types
- Removed ProtectiveOrdersSection from symbol config UI
- Removed automatic protective order checking from PositionManager
- ProtectiveOrderService now starts once in on-demand mode (no monitoring interval)
- Added duplicate start protection to prevent log spam
- Commented out old config-based methods (kept helpers for per-position activation)
- Protective orders now exclusively activated via 'Protect' button on positions
- Use getProtectiveOrderService() instead of proxy export to avoid initialization errors
- Return 503 error if service not available instead of throwing exception
- Provides better error message when bot is not running
…on and disable default TP/SL option

Major Changes:
- Renamed all 'trailing stop' references to 'trailing take profit' (trailing TP)
- Implemented break-even protection: TP never goes below entry price for LONG (never above for SHORT)
- Added 'Disable Default TP/SL' option to scale out settings with intelligent warnings
- Added DCA flag to trailing TP (integrates with existing liq hunter)
- Fixed WebSocket connection error banner flashing on page load (5s grace period)

Trailing TP Enhancements:
- placeTrailingStop() → placeTrailingTakeProfit() with break-even enforcement
- Monitoring enforces Math.max(idealTpPrice, entryPrice) for LONG positions
- Monitoring enforces Math.min(idealTpPrice, entryPrice) for SHORT positions
- Tracking now stores: entryPrice, enableDCA flag alongside trail data
- Method names updated: startTrailingTakeProfitMonitoring(), checkAndAdjustTrailingTakeProfits()
- Log messages updated to reflect 'trailing TP' instead of 'trailing stop'
- UI description: 'Captures upside while protecting profits (exit never falls below break-even)'

Disable Default TP/SL Feature:
- New toggle in ScaleOutModal to disable bot's automatic TP/SL for specific positions
- ProtectiveOrderService tracks disabled positions in disabledDefaultTPSL Set
- Position Manager checks isDefaultTPSLDisabled() before placing/adjusting TP/SL
- Cancels existing default TP/SL orders when option is enabled
- Automatically resumes default TP/SL when scale out is deactivated
- Preserves robustness: only skips disabled positions, monitors all others normally

Smart Warning System:
- No warning when breakeven 100% or any trim level is 100% (full position exit)
- 'No exit protection' warning when no methods enabled
- 'No stop loss protection' warning when only trailing TP (no downside protection)
- 'Partial exit only' warning when no 100% trim levels configured
- Confirmation prompts on submit for risky configurations
- Prevents activating with disabled TP/SL and no exit methods

UI/UX Improvements:
- Added DCA toggle: 'DCA on Drop Below Entry' (continues liq hunting when enabled)
- WebSocket error banner now waits 5 seconds before showing (prevents flash on page load)
- Context-aware warnings based on configured exit methods
- Validation ensures at least one exit method when default TP/SL disabled

Technical Details:
- ScaleOutSettings interface: added disableDefaultTPSL flag
- ProtectiveOrder triggerType: 'trailing_stop' → 'trailing_tp'
- positionManager.adjustProtectiveOrders(): checks isDefaultTPSLDisabled() before managing TP/SL
- positionManager.placeProtectiveOrders(): checks isDefaultTPSLDisabled() before placing orders
- cancelDefaultTPSL() method filters TAKE_PROFIT_MARKET, STOP_MARKET orders (excludes po_ prefix)
- Cleanup on deactivation: removes from disabledDefaultTPSL Set to resume normal TP/SL management

Files Modified:
- src/lib/services/protectiveOrderService.ts (trailing TP transformation, disable TP/SL tracking)
- src/components/ScaleOutModal.tsx (UI updates, smart warnings, validation)
- src/lib/bot/positionManager.ts (skip disabled positions in TP/SL management)
- src/components/PersistentErrorBanner.tsx (5s delay for WebSocket errors)
- src/bot/index.ts (event handlers for scale out)
- src/app/api/positions/scale-out/*.ts (API routes)
- Fix bug where trailing TP placed order immediately at breakeven
- Implement two-phase activation: wait for profit threshold, then trail
- Add 0.5% minimum profit buffer to prevent loss from spread/fees
- Remove duplicate variable declarations causing bot crash
- Update monitoring loop to handle activation threshold properly
- Add activationPercent and activated state to tracking interface
@birdbathd birdbathd marked this pull request as ready for review November 24, 2025 02:14
@birdbathd birdbathd marked this pull request as draft November 24, 2025 08:55
@birdbathd birdbathd marked this pull request as ready for review November 24, 2025 14:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants