Commit Graph

125 Commits

Author SHA1 Message Date
rob e1d38f3df4 Remove debug logging from PythonGenerator
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-16 05:04:44 -03:00
rob 205305fe0e Fix math blocks and add backtest cancellation
- Fix all math block handlers (floor, ceil, min, max, round, sqrt, abs,
  power, modulo, log, ln, trig, mean, median, std_dev, random, clamp,
  factorial) to check inside 'inputs' wrapper for parameters
- Add math, random, statistics modules to strategy execution context
- Add backtest cancellation feature with cancel button in UI
- Fix balances_generators.js to unwrap dynamic_value structures

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-16 05:04:03 -03:00
rob 533a00dce7 Fix backtest performance: cache compilation and skip unnecessary DB writes
Performance optimizations for backtesting:
- Cache compiled strategy code instead of recompiling every iteration
- Skip save_context() for backtests (no DB persistence needed per tick)
- Check cache existence before recreating broker state caches
- Add margin position processing to backtest strategy

These fixes eliminate O(n) slowdown that caused backtests to progressively
slow to a crawl. Backtests now maintain consistent speed throughout.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-15 16:49:18 -03:00
rob b2d40d3d2f Add margin position editor and broker support 2026-03-13 15:41:29 -03:00
rob d3bbb36dc2 Fix live trade P/L bugs, improve UI refresh, add balance toggle
Key fixes:
- Add price validation to detect/correct doubled filled_price from broker
- Emit position_closed socket event to refresh UI after closing positions
- Fix statistics not updating when positions are closed
- Filter out zero-size positions from display
- Add USD/USDT toggle for balance display (click to switch)

Trade system improvements:
- Refactor Trade class P/L calculation with realized/unrealized tracking
- Add settle() method for proper position closing
- Improve trade_filled() to use current filled qty for averaging
- Add fallback to exchange balances when broker balance unavailable

Paper broker enhancements:
- Add exchange-qualified price storage for multi-exchange support
- Add price_source tracking for positions
- Improve state persistence

Tests:
- Add comprehensive tests for trade P/L calculations
- Add tests for paper broker price source tracking

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-12 12:15:56 -03:00
rob 5866319b5e Fix critical Phase 4 issues: wire SL/TP to broker, reconcile trades, fix schema
High priority fixes:
- Wire time_in_force, stop_loss, take_profit to broker.place_order()
  * Pass time_in_force from received_new_trade() to new_trade()
  * Pass SL/TP/TIF from new_trade() to broker.place_order()

- Reconcile Trade ledger when SL/TP triggers
  * Find all matching paper trades for symbol
  * Settle trades at trigger price
  * Move from active_trades to settled_trades
  * Save to database

- Fix fresh schema missing SL/TP columns
  * Add stop_loss and take_profit to CREATE TABLE statement
  * Ensures first-run trade persistence works

Medium priority fixes:
- Hide SL/TP fields for SELL orders (inventory-only model)
  * SL/TP only makes sense for BUY (opening positions)
  * SELL closes existing positions, no SL/TP needed
  * Added _updateSltpVisibility() method
  * Side change listener shows/hides SL/TP row
  * Removed SELL-side SL/TP validation

Tests:
- Added 2 integration tests for manual trading SL/TP path
- 353 tests pass (4 pre-existing failures unrelated)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-11 19:49:39 -03:00
rob 4bfa51f0b1 Fix UX mismatch and dead code in paper trading
- Hide exchange dropdown for paper trades (uses single synthetic market)
- Add _updateExchangeRowVisibility() to toggle exchange row visibility
- Call visibility update on target change and form open
- Remove stale 'binance' fallback in Trade constructor call
  (Trade.__init__ now handles exchange normalization for paper trades)

Addresses codex feedback:
- Medium: UX mismatch where exchange choice appeared relevant for paper
- Low: Dead code passing 'binance' for paper trades

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-11 19:40:03 -03:00
rob 2ae087a099 Add stop loss, take profit, and time-in-force support for manual trading
Phase 4: Advanced Order Management

- Add stop_loss and take_profit fields to Trade class with DB persistence
- Add SL/TP form fields in new trade popup with validation
- Implement SL/TP evaluation in PaperBroker.update()
- Auto-close positions when SL/TP thresholds are crossed
- Emit sltp_triggered events to frontend with notifications
- Add Time-in-Force dropdown (GTC, IOC, FOK) to trade form
- Add persistence for position_sltp tracking across state save/load
- Add unit tests for SL/TP functionality (5 new tests)
- Add Trade class SL/TP field tests (2 new tests)

Also includes Phase 3 manual trading broker hardening:
- Fix broker UI not wired on startup
- Fix cancelled orders vanishing from history
- Fix positions not live-updating P/L
- Fix paper pricing exchange-ambiguity
- Simplify paper trades to single synthetic market

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-11 19:35:52 -03:00
rob 2dccabfac3 Add chart analysis feature with candlestick pattern detection
- Add /api/detect_patterns endpoint to detect CDL_* patterns in time range
- Add ChartAnalysis class with hover-based pattern detection mode
- Add Analyze dropdown button in header with pattern detection option
- Style dropdown and pattern detection UI with gradient theme
- Add AGENTS.md with repository guidelines for AI agents
- Update gitignore to exclude test screenshots and artifacts

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-11 15:26:49 -03:00
rob 9a389d20d2 Fix chart sync, indicators popup z-index, and volume height
- Rewrite chart binding to use single unified sync handler per chart
  instead of cumulative handlers that conflicted with each other
- Use v5 API unsubscribeVisibleTimeRangeChange for cleanup
- Add _isSyncing flag to prevent recursive sync loops
- Raise indicators popup z-index from 99 to 150 (above formation
  overlay at 100) to prevent formations from triggering mouseleave
- Reduce volume indicator height from 30% to 15% of chart
- Remove obsolete v2 scaleMargins call on Volume series
- Add better candlestick init logging for debugging

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-11 02:03:56 -03:00
rob 5874f1cc7a Keep strategy dialog open on save failure
Previously the dialog closed immediately after submitting, before
knowing if the save succeeded. If there was an error (e.g., duplicate
name), users had to recreate their entire strategy.

Now the dialog only closes on success, and shows a helpful error
message on failure so users can fix the issue without losing work.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-11 00:59:37 -03:00
rob d2f31e7111 Add Blockly integration for chart formations in strategies
- Add formation_blocks.js with dynamic block generation per formation
- Add handle_formation() to PythonGenerator for code generation
- Add process_formation() to StrategyInstance for runtime execution
- Inject formations manager into paper/backtest strategy instances
- Add get_current_candle_time() override for backtest bar timestamps
- Add Formations category to Blockly toolbox
- Fix scope property names in formations.js (exchange_name, interval)

Formations can now be referenced in strategy logic by their line properties
(line, upper, lower, midline) and values are calculated at candle time.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-11 00:51:56 -03:00
rob 18d773320c Fix draft formation not preserving drag changes on save
When dragging a draft formation's anchors, the changes were being
stored in dragFormation and renderedFormations, but not synced
back to draftFormation. When completeDrawing() was called to save,
it used draftFormation.lines_json which still had the original
horizontal line data.

Now _endDrag() checks if the dragged formation is the draft
(tbl_key === draftTblKey) and syncs lines_json back to draftFormation.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 23:06:18 -03:00
rob ee199022fa Fix anchor positioning when outside visible time range
- Add _getAnchorPixelPosition method that handles anchors outside
  the visible time range by calculating their position along the line
- Update _createAnchor to use robust position calculation
- Update _updateFormationPositionsInPlace to use new method

Previously, anchors would not update when their time coordinate was
outside the visible range (because _chartToPixel returns null).
Lines would update correctly via _getInfiniteLineEndpoints, but anchors
would stay at stale positions.

Now anchors are positioned at the viewport edge when their actual
time coordinate is outside the visible range, keeping them on the line.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 22:48:03 -03:00
rob d7398569a8 Fix formation overlay sync to update on every RAF frame
- Remove hasViewChanged check from RAF loop
- Update formations on every animation frame for smooth chart sync
- This ensures formations stay positioned correctly when:
  - Time scale changes (horizontal scroll/zoom)
  - Price scale changes (vertical scroll/zoom)
- Simplify _hasViewChanged method (kept for potential future optimization)
- Clean up debug logging

The previous implementation only updated when time range changed,
causing formations to drift when the price scale was modified.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 22:38:16 -03:00
rob 2d01ee07eb Fix formation line rendering for points outside visible range
The _getInfiniteLineEndpoints method was returning null when anchor
points were outside the visible time range, causing lines to not
render. Fixed by calculating line intersections with viewport edges
in chart coordinates first, then converting to pixels.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 21:55:06 -03:00
rob d7c8d42905 Add channel drawing UX with parallel line placement
Channel drawing now works like line drawing:
- First click places primary horizontal line (3 anchors)
- Mouse move shows dotted parallel preview line
- Second click places parallel line (1 center anchor)

Channel anchor behavior:
- Primary line center anchor: moves both lines together
- Primary line end anchors: pivots both lines (stays parallel)
- Secondary line center anchor: adjusts distance to primary

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 21:41:15 -03:00
rob 53797c2f39 Improve line drawing UX with single-click placement and 3-anchor control
- Single click places a solid horizontal line with 3 anchors
- Center anchor (green): drag to move entire line without changing angle
- End anchors (blue): drag to pivot from opposite end, changing angle
- Hovering over any part of the line shows all anchors
- Name input appears immediately after line is placed
- Line can be adjusted before saving

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 21:17:12 -03:00
rob ac4c085acd Improve formations drawing UX with step-by-step flow
Changed UX flow from confusing to clear:
1. Click Line/Channel -> Shows instructions + points counter
2. Click points on chart -> Updates counter (Points: 1/2)
3. After enough points -> Shows name input + Save button
4. Enter name + Save -> Formation created

formations_hud.html:
- Add instructions panel with Cancel button
- Add points status display
- Separate name input controls (shown after points placed)

formations.js:
- Add showDrawingInstructions() with type-specific text
- Add updatePointsStatus() for live counter
- Add showNameInput() after drawing complete
- Add hideAllDrawingUI() for cleanup

formation_overlay.js:
- Add onPointsChangedCallback for UI updates
- Store _pointsNeeded per drawing session
- Stop accepting clicks after enough points
- Change cursor back to default when complete

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 20:00:47 -03:00
rob fceb040ef0 Fix formations stability and socket reliability issues
formation_overlay.js:
- Fix Map mutation during iteration causing infinite loops
- Use array snapshots for _updateAllFormations and clearAllFormations
- Add guards to skip unnecessary RAF work when no formations exist
- Simplify range change detection with primitive comparison

Formations.py:
- Fix DataCache method names to match actual API
- Use insert_row_into_datacache, modify_datacache_item,
  remove_row_from_datacache

communication.js:
- Enable persistent reconnection (Infinity attempts)
- Add bounded queue (250 max) to prevent memory growth
- Coalesce candle_data messages (keep latest only)
- Prioritize control/CRUD messages in queue flush

formations.js:
- Add user feedback alert when deleting while offline

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 19:39:29 -03:00
rob 5717ac6a81 Implement chart formations MVP with Line and Channel support
Add formations feature for drawing trendlines and channels on charts:

Backend (Formations.py):
- CRUD operations with DataCache integration
- Database table with scope-based indexing
- Line value calculation with infinite extension
- Property value lookup for strategy integration

Frontend (formations.js, formation_overlay.js):
- Three-class pattern: UIManager, DataManager, Controller
- SVG overlay for drawing with RAF sync loop
- Click-to-draw interface with temp line preview
- Anchor dragging for line adjustment
- Coordinate conversion using v5 API

UI Integration:
- HUD panel with Line/Channel buttons
- Formation cards with hover details
- Drawing controls (name input, save/cancel)

Socket handlers for real-time sync:
- request_formations, new_formation
- edit_formation, delete_formation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 16:22:08 -03:00
rob ba7b6e79ff Address second round of Codex review feedback on formations plan
Fixes:
1. Class signature consistency - reference __init__ from 1.1, don't redefine
2. Dynamic chart ID - use this.data.chart1_id instead of hardcoded 'chart1'
3. Comms wiring - use this.comms.on() pattern like signals.js
4. RAF loop guards - add pause conditions, destroy() teardown hook
5. Drag null guards - validate chartCoords before mutating formation data
6. Test organization - split MVP tests from Phase C target tests

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 16:03:33 -03:00
rob a46d2006f3 Update formations plan for Lightweight Charts v5 compatibility
Addresses Codex review feedback:
- Use series-based coordinate conversion (series.priceToCoordinate)
- Add infinite line extension math (_getInfiniteLineEndpoints)
- Fix message pattern: use sendToApp() not emit('message')
- Remove wall clock fallback in get_current_candle_time()
- Clarify architecture: socket handlers in BrighterTrades, not app.py
- Clarify UX: shape appears at center, drag to adjust (no click-to-place)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 15:57:38 -03:00
rob 5c37fb00b6 Upgrade Lightweight Charts from v2.1.0 to v5.1.0
- Update series creation to v5 API (addSeries with type parameter)
- Migrate watermarks to createTextWatermark plugin
- Migrate markers to createSeriesMarkers primitive
- Replace getBarSpacing() with timeScale().options().barSpacing
- Update crosshair handler: seriesPrices → seriesData
- Move scaleMargins from series options to price scale
- Fix chart sync infinite loop with time-based debounce (50ms)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 15:47:18 -03:00
rob 6a7a1c2b45 Fix indicator update callbacks and card display after refactor
- Bind indicators.update callback to correct this context in general.js
- Update updateDisplay to fall back to card elements when old chart elements don't exist
- Add _formatDisplayValue helper for consistent value formatting
- Remove verbose debug console.log statements
- Add FORMATIONS_PLAN.md documenting SVG overlay approach for chart formations

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-10 15:01:55 -03:00
rob c8c51841cf Redesign indicator and backtest displays with icon cards
- Replace indicator table with icon card grid display
- Add edit indicator popup dialog for modifying indicator settings
- Display indicator type, value, and emoji symbols on cards
- Add visibility toggle and delete buttons on hover
- Redesign backtest items with CSS-based icons and status indicators
- Unify dialog styling across external indicator, signal type, and public strategies
- Make edit indicator dialog draggable
- Fix button text: "+ Add Public" -> "Add Public"
- Remove dark theme from signal_type_popup for consistency

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-09 23:22:15 -03:00
rob c9cc0487fe Align signals and strategies buttons with grid layout
- Use 2-column grid for signal buttons (matches indicators layout)
- Use 2-column grid for strategy buttons (matches indicators layout)
- Remove background color from External Source button

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-09 21:41:39 -03:00
rob 51601b7f93 Document ExternalSources and ExternalIndicators modules
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-09 21:35:33 -03:00
rob b4bf6c5c8e Add external data sources and indicators for backtesting
External Sources:
- New ExternalSources.py module for real-time API data fetching
- Configurable refresh intervals, JSONPath extraction, and auth headers
- External sources can be used in signals for live strategy conditions

External Indicators:
- New ExternalIndicators.py module for historical API data
- Supports backtesting by fetching and caching historical data points
- Timestamps are matched to candle times during backtest execution
- Fear & Greed index and similar APIs now work in backtests

Signal System Enhancements:
- Added signal Blockly blocks for use in strategy builder
- New signal_blocks.js for dynamic signal block generation
- Signals category added to strategy toolbox
- PythonGenerator updated to handle signal_* block types
- process_signal() method added to StrategyInstance classes

notify_user Block Enhancement:
- Now supports dynamic values (variables, indicators, expressions)
- Can display indicator values and calculations in notifications

Bug Fixes:
- Fixed Socket.IO parse error causing strategies not to load on refresh
- Enhanced sanitize_for_json to handle pandas, datetime, bytes types
- Fixed external indicator name matching (underscore/space conversion)
- Fixed PRAGMA query missing fetch_all=True in ExternalIndicators

Dependencies:
- Added jsonpath-ng for JSONPath extraction from API responses

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-09 21:25:36 -03:00
rob a4422dc556 Unify dialog styling with consistent gradient headers
- Add .dialog-header CSS class with blue gradient (#3E3AF2 → #6366f1)
- Add .dialog-close-btn for consistent close buttons in headers
- Update all 12 dialog templates to use unified header styling
- Add close buttons to all dialogs (positioned in header)
- Fix trade_details and login popups (add proper header structure)
- Update public strategy browser modal to match dialog style
- Update indicator popup styling to match app theme
- Add null checks to initializeResizablePopup for robustness
- Update CLAUDE.md with wallet module documentation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-09 14:57:14 -03:00
rob 7e77f55837 Add Bitcoin wallet system with configurable strategy fees
Features:
- Two-address custody model (Fee Address + Sweep Address)
- Credits ledger for instant, reliable strategy fee transactions
- Configurable fee percentage (1-100% of exchange commission)
- Background jobs for auto-sweep, deposit detection, withdrawal processing
- Account settings dialog accessible via username click
- $50 balance cap with auto-sweep to user's sweep address

Security improvements:
- Atomic withdrawal reservation prevents partial state
- Fee accumulation cleanup on strategy startup failure
- Deposit monitoring includes disabled wallets for recovery
- Null tx hash checks prevent silent failures
- Key export disabled by default

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-09 12:45:25 -03:00
rob cd9a69f1d4 Add exchange validation, fix indicators bug, and improve balance display
- Add exchange_validation.py module for validating exchange requirements
  before running strategies (backtest, paper, live modes)
- Fix AttributeError in Signals.py: 'Indicators' object has no attribute
  'indicators' - created IndicatorWrapper class for proper data access
- Fix testnet balance issue: explicitly pass testnet=False to all
  connect_exchange calls to prevent pickle corruption from old testnet
  Exchange objects
- Add balance exchange selector: display one exchange at a time with
  dropdown to switch between connected exchanges (defaults to chart view)
- Add unique tbl_key generation for exchange_data to prevent duplicate
  entries (format: user:exchange)
- Fix DataCache balance serialization for list types
- Update frontend error handling for exchange validation errors

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-08 19:41:41 -03:00
rob ee16023b6b Add public strategy subscription system
Implement a subscription system for public strategies:

Security & Auth:
- Bind WebSocket user identity at connect time (prevents spoofing)
- Add server-side ownership verification for all destructive operations
- Invalidate socket connections on logout
- Add XSS protection with HTML/JS escaping in frontend

Database:
- Add strategy_subscriptions table with proper indexes
- Fix get_all_rows_from_datacache to fall back to DB when cache empty

Backend:
- Add subscribe/unsubscribe endpoints with authorization checks
- Add get_user_strategies (owned + subscribed) and get_public_strategies_catalog
- Propagate indicator_owner_id through strategy instances for subscribed strategies
- Redact strategy internals (code, workspace) for non-owners

Frontend:
- Add "Add Public" button to browse and subscribe to public strategies
- Show subscribed strategies with creator badge and unsubscribe button
- Prevent editing of subscribed strategies (show info modal instead)
- Add public strategy browser modal

Tests:
- Update authorization tests for new subscription-required model

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-08 16:59:52 -03:00
rob 11c1310f49 Register all 61 candlestick patterns in frontend indicatorMap
The new patterns were only added to the backend (indicators.py) but
not registered in the frontend (indicators.js), causing "Unknown
indicator type" errors when trying to display them on charts.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-08 13:33:43 -03:00
rob 1e203a1159 Add SVG diagrams for all 61 candlestick patterns
Each pattern now has a visual representation showing the characteristic
candlestick formations. SVGs include:
- Single candle patterns (Doji, Hammer, Marubozu, etc.)
- Two candle patterns (Engulfing, Harami, Kicking, etc.)
- Three+ candle patterns (Morning/Evening Star, Three Soldiers, etc.)

Visual elements use green (#00C853) for bullish candles, red (#FF5252)
for bearish candles, and gray (#888) for neutral/indecision candles.
Dashed lines indicate key price levels where relevant.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-08 12:15:53 -03:00
rob e98861a7fb Add all 61 TA-Lib candlestick pattern indicators
Extends the initial 15 patterns to include all 61 TA-Lib candlestick
pattern functions. Adds pattern descriptions and categories for the
indicator dropdown UI.

New patterns include: Abandoned Baby, Advance Block, Belt Hold,
Breakaway, Closing Marubozu, Concealing Baby Swallow, Counterattack,
Dragonfly Doji, Gravestone Doji, Hanging Man, Hikkake, Homing Pigeon,
Identical Three Crows, In Neck, Kicking, Ladder Bottom, Long Legged
Doji, Long Line, Mat Hold, Matching Low, Rise/Fall Three Methods,
Rickshaw Man, Separating Lines, Short Line, Stalled Pattern, Stick
Sandwich, Takuri, Tasuki Gap, Thrusting, Tristar, Two Crows, Unique
Three River, Upside/Downside Gap Three Methods, and more.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-08 12:10:14 -03:00
rob 8f362a1379 Add categorized indicator dropdown with expandable Patterns submenu
- Group candlestick patterns under expandable "Patterns" category
- Regular indicators shown directly in dropdown
- Patterns submenu expands on hover with all CDL_* indicators
- Fixed submenu positioning outside scrollable container
- Tooltip shows pattern description and SVG when hovering items

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-08 11:55:43 -03:00
rob 4ab7a5023d Add candlestick pattern indicators with TA-Lib integration
- Add 15 candlestick pattern indicators (Doji, Hammer, Engulfing, etc.)
- Create dedicated Patterns chart pane for pattern visualization
- Add hover tooltips with descriptions and SVG diagrams in indicator selector
- Fix color picker compatibility by using hex format instead of RGBA
- Fix chart positioning and timestamp synchronization for pattern chart

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-08 05:45:51 -03:00
rob 7b796c51c8 Fix indicator toggle functionality and add loading feedback
- Fix JSON parsing bug: JavaScript FormData sends indicator list as
  JSON string inside a list, now properly parsed on backend
- Move form event listener setup to _setupIndicatorForm() called from
  addToCharts() so it's always attached regardless of indicator data
- Add immediate visual feedback: popup hides instantly on submit and
  button shows "Updating..." text

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-08 03:33:45 -03:00
rob 24fcb56c38 Improve backtest time handling and indicator warmup
- Add UTC time formatter to charts for consistent time display
- Show both local and UTC times in backtest trades table
- Add indicator warmup period calculation to fetch extra candles
- Append 'Z' suffix to trade/alert timestamps to indicate UTC
- Add get_available_balance to strategy execution context

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-08 00:38:22 -04:00
rob 307f251576 Add backtest debugging features: timestamps, chart markers, and alerts
- Add Open/Close Time columns to Trades Executed table
- Display trade markers (buy/sell arrows) automatically on chart
- Clear markers when closing results dialog or running new test
- Collect notify_user alerts with timestamps during backtesting
- Display Strategy Alerts section in backtest results
- Fix timestamp conversion: use unit='s' for EDM timestamps (not 'ms')
- Fix trade datetime extraction using data feed's datetime method

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-06 23:34:55 -04:00
rob 3e6463e4b3 Add Bollinger %B indicator and fix credential handling
- Add BollingerPercentB indicator class in backend (BOL%B)
  - Calculates %B = (Close - Lower) / (Upper - Lower)
  - Shows where price is relative to Bollinger Bands
  - Values: 1.0 = upper band, 0.5 = middle, 0.0 = lower
- Add BollingerPercentB JavaScript class for frontend display
  - Creates its own chart (chart4) like RSI/MACD
  - Includes chart binding for synchronized scrolling
- Add chart4 HTML container and data plumbing
- Fix credential update when reconnecting with changed API keys
- Add TESTNET_MODE config setting for live trading mode control

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-06 06:31:31 -04:00
rob 21d449d877 Fix KuCoin balance fetching and add balance refresh functionality
- Add KuCoin-specific balance fetching with type='trade' parameter
- Reinitialize ccxt client in refresh_balances() to fix pickle corruption
- Force reconnection when exchange is restored from database cache
- Add balance refresh button and socket handler in frontend
- Fix template null check for balances display
- Clean up DataCache and candles imports

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-06 06:10:31 -04:00
rob 91f51cd71f Fix set_flag blocks being dropped after trade_action
Bug: trade_order_generators.js set skipAdditionalParsing=true which
caused json_base_generator.js to return early before processing <next>
sibling blocks. This meant set_flag and other blocks connected after
trade_action were silently dropped from the JSON.

Fix: Removed the unnecessary skipAdditionalParsing flag. The code path
it was meant to protect was already in an else branch, so the flag
served no purpose and broke <next> block handling.

Also includes minor fixes to Strategies.js and backtesting.js from
earlier session work.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-06 02:28:50 -04:00
rob 3976fc8366 Fix backtest data source and chart view detection bugs
- Fix market/symbol key mismatch in PythonGenerator.py (6 locations)
  causing backtest to use wrong trading pair (BTC/USD vs BTC/USDT)
- Fix backtesting.py to always use default_source for backtest data
- Fix exchange/exchange_name key mismatch in app.py and BrighterTrades.py
  causing strategy dialog to show wrong current chart exchange
- Add favicon links to standalone HTML templates
- Add AI strategy dialog template
- Update tests and documentation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-06 00:05:31 -04:00
rob 0e481e653e Integrate EDM for candle data and improve UI dialogs
EDM Integration:
- Add edm_client module for REST/WebSocket communication with exchange-data-manager
- Refactor candles.py to fetch data exclusively from EDM
- Add EDM session management for authenticated exchange access
- Update backtesting to use EDM for historical data
- Pass edm_client through to all strategy instances
- Add /api/edm-config, /api/chart-view, /health/edm endpoints
- Remove legacy candle-fetching code from DataCache_v3 and Exchange

UI Improvements:
- Make all popup dialogs draggable and resizable (exchange config, indicator, signal, trade)
- Add default trading source (exchange, symbol, timeframe) to strategy dialog
- Convert symbol fields to dropdowns with smart prioritization (popular pairs first)
- Fix signal dialog property dropdown initialization

Bug Fixes:
- Fix PythonGenerator regex to handle symbols starting with numbers (e.g., 0G/USDT)
- Fix EDM client date format (use Unix timestamps instead of ISO strings)
- Fix strategy default_source database migration

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-04 11:42:06 -04:00
rob 33de4affb4 Fix auth UX, exchange config, and trade validation
Auth/Login improvements:
- Add dedicated login page (login_page.html)
- Redirect to /app after successful login/signup instead of welcome
- Add flash message categories to prevent cross-page message pollution
- Filter flash messages by category in templates

Exchange configuration fixes:
- Fix JS discarding API keys for public exchanges (now optional, not cleared)
- Add explicit key/secret validation in backend before saving
- Properly update configured_exchanges when keys provided

Trade dialog enhancements:
- Add exchange selector populated from connected exchanges
- Add testnet checkbox with exchange support detection
- Add production trading confirmation dialog
- Show TESTNET/LIVE badges on trade cards
- Validate exchange is configured before creating live trades

Bug fixes:
- Add try/except around get_user_data in is_logged_in()
- Fix DataFrame index access for user data retrieval

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-02 20:59:07 -04:00
rob 45395c86c5 Implement fee fetching from exchange via ccxt
Exchange.py:
- Add get_trading_fees(symbol) - fetches fees from market data
  - Tries user-specific fees for authenticated users (fetch_trading_fees)
  - Falls back to market data (public)
  - Returns maker/taker rates with source indicator
- Add get_margin_info(symbol) - returns margin trading availability

ExchangeInterface.py:
- Add get_trading_fees() - routes to appropriate exchange
- Add get_margin_info() - routes to appropriate exchange
- Both methods handle user/exchange lookup with fallback to defaults

trade.py:
- Update new_trade() to fetch actual fees from exchange
- Uses taker fee for market orders, maker fee for limit orders
- Falls back to exchange_fees defaults if fetch fails

Fees now come from actual exchange data (0.1% for Binance spot)
instead of hardcoded defaults.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-02 16:30:19 -04:00
rob b9730b3a1d Upgrade ccxt from 4.4.8 to 4.5.40
Key improvements:
- 80-190% performance gains in utility functions
- New margin/futures WebSocket support for Binance
- Better liquidation and position tracking
- coincurve library for faster ECDSA signing
- New exchange support (Aster)

All Exchange methods verified working with new version.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-02 16:19:08 -04:00
rob f603728080 Fix paper trade P/L updates and fee calculations
- Fix default fee from 0.1 (10%) to 0.001 (0.1%) in Trade class
- Add real-time trade updates via WebSocket trade_update events
- Fetch current market price for market orders instead of using cached price
- Add trade persistence to database with proper schema
- Add execution loop to update trades even without active strategies
- Add frontend handler for trade_update events in communication.js
- Add handleTradeUpdate method in trade.js for live P/L updates
- Add debug file logging for trade update debugging
- Update statistics dashboard and trading HUD templates

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-02 16:05:53 -04:00