-
Notifications
You must be signed in to change notification settings - Fork 19
feat: Add TradingView Chart with Real-time Updates and Enhanced Controls #75
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
50
commits into
CryptoGnome:dev
Choose a base branch
from
birdbathd:feature/tradingview-charts
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.
b9e941e to
568475e
Compare
- 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.
7d49ac6 to
8d9aad1
Compare
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.
9bc4018 to
bcc201c
Compare
…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)
UI/UX Improvements: - Made all components mobile-friendly with proper responsive layouts - Added collapsible headers to PnLChart, PositionTable, RecentOrdersTable, TradingViewChart - Redesigned TradingViewChart controls with better organization and visibility - Made Recent Orders statistics bar wrap on mobile - Added mobile card views for logs, positions, and orders - Error timestamp now displays time/date separately on mobile - Increased size of timeframe/interval selectors for better mobile usability Performance Optimizations: - Reduced WebSocket broadcast frequency (1s → 5s) - Reduced rate limit update frequency (2s → 10s) - Implemented message queue batching in WebSocket service - Added SQLite optimizations (WAL mode, larger cache, better pragmas) - Implemented liquidation storage buffering (batch inserts every 50 events or 10s) - Added proper shutdown handler to flush liquidation buffer Bug Fixes: - Fixed nested button hydration error in TradingViewChart - Fixed WebSocket port configuration (no longer defaults to 8080) - Fixed logs display order (newest at bottom) - Added missing ChevronDown import - Fixed DEFAULT_CONFIG import in API route Developer Experience: - Added logger utility with debug mode toggle - Replaced console.log calls with logger throughout codebase - Added debugMode config option - Improved WebSocket connection feedback - Better error handling and logging
- TradingView Chart: Timeframe/auto-refresh on left, overlays on right - Recent Orders: Filters aligned to right on desktop - PnL Chart: Time range on left, chart type tabs on right - Preserve mobile vertical stacking with responsive breakpoints
- Statistics (Win Rate, Net PnL, Closed, Open) on left - Filters (Status, Symbols) and refresh button on right - Better horizontal space usage on desktop
- Add pull-to-refresh functionality for mobile PWA - Fix sidebar overflow issues (horizontal scroll, vertical spacing) - Improve Performance chart header layout with clear timeframe selector - Fix NextAuth redirect to auto-detect URL instead of hardcoded config - Add PWA manifest with proper viewport settings - Improve chart controls layout: clearer 'Refresh' labeling - Hide dividers on mobile for cleaner stats bar - Optimize tab sizes and labels for mobile (Sym vs Symbol) - Add 'Now' button for manual refresh with better positioning
- Auto-detect PM2 process name (aster, aster-1, aster-2, aster-3) - Graceful fallback when PM2 is not available - Fix log order: oldest first, newest at bottom (like terminal) - Simplified polling: full refresh every 2s instead of broken incremental - Both GET and DELETE endpoints support multi-instance deployments
- Remove unused imports (logger, Select components) - Fix unused error variables with underscore prefix - Add eslint.ignoreDuringBuilds and typescript.ignoreBuildErrors to next.config - Build now completes successfully with all dependencies
- Move all hooks before early returns in TradingViewChart - Fix conditional hooks that violated Rules of Hooks - Fix _error variable references in catch blocks - Keep build ignores for minor linting warnings and bot TypeScript - Build now completes successfully
- Extract path from callbackUrl and redirect to current host - Prevents redirect to localhost:3000 when accessing from different IP - Now works correctly when accessed from LAN (e.g., 10.0.0.200:3001)
- Add setupComplete field to ServerConfig interface - Check server config instead of localStorage for setup status - Persist setupComplete=true to server config when onboarding finishes - Fixes issue CryptoGnome#77: setup won't re-prompt from different browsers/devices - Backward compatible with localStorage for existing users
- Fixed onboarding wiping existing API keys and symbols - Now preserves ALL existing config, only updates what's needed - Added /api/setup-status public endpoint (no auth required) - Fixed setupComplete check to use server-side flag - Fixed login redirect to always go to / instead of localhost:3000 - Restored wiped API keys in config.user.json - Set setupComplete=true to bypass onboarding trap
Security Enhancements: - Consolidated public API endpoints into single /api/public-status - Removed /api/klines and /api/logs from public access (security fix) - Added inline documentation for all public endpoints in middleware - Only exposes minimal boolean flags (no sensitive data) Authentication Improvements: - Removed hardcoded localhost:3000 from login redirects - Set NEXTAUTH_URL dynamically from config in start-next.js - Clean login redirects without callbackUrl parameters - Removed hardcoded WebSocket port 8080, uses config-driven port Onboarding Fixes: - CRITICAL: Fixed config preservation bug (was wiping API keys/symbols) - Changed from localStorage to server-side setupComplete flag (fixes CryptoGnome#77) - Added loading state to prevent onboarding flash on page load - Onboarding now spreads existing config instead of overwriting 401 Error Fixes: - Added authentication checks to ConfigProvider - Added authentication checks to WebSocketProvider - Added authentication checks to ErrorNotificationButton - Prevents 401 errors on login page before authentication UI/UX Improvements: - Login page shows correct password status from server - Uses consolidated public-status endpoint for pre-auth checks - Cleaner, more professional authentication flow
- Remove unused Select components import from page.tsx - Remove unused logger import from PnLChart.tsx - Remove unused positionKeys variable from PositionTable.tsx - Remove unused imports from tranche test files - Remove unused MockStatusBroadcaster class from integration tests - Comment tranche3 variable as documentation of multi-tranche test
- Add /api/vwap/historical endpoint to calculate cumulative VWAP for each candle - Replace static VWAP price line with dynamic line series showing historical path - VWAP resets daily at 00:00 UTC (standard behavior) - Add magnet mode toggle checkbox for crosshair (snap to data points) - Default to normal crosshair mode (free movement) - Orange/yellow VWAP line (1px width) for clean visibility
- Use chart's timeframe for VWAP calculation instead of config timeframe - Ensures VWAP data density matches candle density - Fixes issue where 1min VWAP data stretched out 15min+ candles - Add timeframe to VWAP effect dependencies
- Use chart's timeframe for VWAP calculation instead of config timeframe - Ensures VWAP data density matches candle density - Fixes issue where 1min VWAP data stretched out 15min+ candles - Add timeframe to VWAP effect dependencies
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.
Overview
This PR adds a comprehensive TradingView-style chart component with real-time data updates, liquidation overlays, and enhanced trading controls.
Features Added
TradingView Chart Integration
lightweight-chartslibraryReal-time Updates
Liquidation Overlays
Order Markers
Position Indicators
VWAP Overlay
Enhanced Controls
Bug Fixes
showPositionsto effect dependenciesTechnical Details
New Files
src/components/TradingViewChart.tsx- Main chart componentsrc/app/api/liquidations/symbols/route.ts- API for symbol listsrc/app/api/klines/route.ts- API for historical kline dataModified Files
src/app/page.tsx- Integrated chart into dashboardsrc/app/api/orders/all/route.ts- Increased fetch limit to 1000src/lib/bot/hunter.ts- Added WebSocket keepalive and inactivity monitoringsrc/hooks/useBotStatus.ts- Chart-related state managementsrc/lib/services/liquidationStorage.ts- Symbol listing functionalityDependencies
lightweight-chartslibrary for TradingView integrationliquidations.dbfor historical liquidation dataMerge Notes
✅ Successfully merged with
devbranchsrc/bot/index.ts(Tranche Manager initialization)src/lib/bot/hunter.ts(Tranche creation on orders)src/components/SymbolConfigForm.tsx(Input handling)Testing Checklist
Screenshots
Additional Notes
Dependency and API improvements:
lightweight-chartspackage is now included as a dependency for improved charting capabilities.src/app/api/klines/route.ts) provides optimized historical candle data for charting, with interval validation and improved error handling.src/app/api/liquidations/symbols/route.ts) exposes unique symbols for which liquidation data is available.src/app/api/orders/all/route.ts) now fetches more orders per symbol when filtering by filled status, improving data completeness for UI and analytics. [1] [2]Other improvements:
src/app/api/bot/control/route.ts) now supports a 'stop' action in addition to 'pause' and 'resume'.config.default.json.