-
Notifications
You must be signed in to change notification settings - Fork 19
feat: Protective orders with trailing take profit #79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
birdbathd
wants to merge
31
commits into
CryptoGnome:dev
Choose a base branch
from
birdbathd:feature/protective-orders
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- 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.
This reverts commit 3aeb2a5.
- 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Implements a comprehensive protective orders system with trailing take profit, break-even protection, and two-phase activation logic.
Key Features
Bug Fixes
Technical Details
src/lib/services/protectiveOrderService.tswith two-phase activationDependencies
Screenshots
Testing -TBA