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>
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>
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>
- 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>
- 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>
- 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>
- 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>
- 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>
- 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>
- 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>
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>
- 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>
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>
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>
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>
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>
- 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>
Signals System Refactor:
- Migrated from config.yml to DataCache/SQLite storage
- Added user ownership (creator field) and public/private visibility
- Implemented full CRUD operations with tbl_key identifiers
- Auto-creates signals table in database on init
- Card-based UI with 100x100 icons and hover detail panels
- State visualization: green pulsing border (TRUE), red (FALSE)
- Edit support via popup form with Create/Edit buttons
Alerts System Implementation:
- Connected frontend Alerts.js to SocketIO communications
- Alerts triggered by signal state changes (s_updates)
- Support for strategy events, trades, errors, notifications
- Color-coded alerts with icons and timestamps
- Clear button and max 50 alerts limit (ephemeral, not persisted)
Backend changes:
- BrighterTrades.py: Updated signal handlers with user_id
- Added received_edit_signal() and permission checks
- Signal filtering by user ownership
Frontend changes:
- signals.js: Three-manager pattern (SigUIManager, SigDataManager, Signals)
- Alerts.js: Event handlers for updates and strategy_events
- general.js: Initialize signals and alerts with comms
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Check if exchange supports fetchPositions before calling it
- Handle PermissionDenied (error -2015) gracefully with debug log instead of error
- Handle NotSupported exception for exchanges that don't support positions
- Use ccxt standard field names (contracts, entryPrice) with fallbacks
- Skip positions with zero size
- Add documentation noting this is a futures/derivatives feature
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add utils.py with sanitize_for_json() function to convert numpy types
(int64, float64, bool_, ndarray) to native Python types
- Handle inf/nan values by converting to None
- Update backtesting.py to use shared sanitize_for_json utility
- Update app.py strategy_events emit to sanitize data before sending
- Remove empty root BrighterTrading.db and add *.db to gitignore
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Show loading state while connecting to exchange
- Display success/error messages in the form
- Prevent double-submission with disabled button
- Add 30-second timeout with error message
- Register handler for Exchange_connection_result message
- Reload page after successful connection (with delay to show message)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Added proper mocking for all BrighterTrades dependencies (DataCache,
ExchangeInterface, Users, Strategies, Candles, Indicators, Trades)
- Pass mock socketio instance to BrighterTrades constructor
- Fixed patch paths to use correct module path (src.BrighterTrades.*)
- All 5 tests now pass
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Key fixes:
- ExchangeInterface: Remove stale entries before creating new exchange connections
- LiveBroker: Optimize get_total_equity() to price only top 10 assets (was hanging on 462 testnet assets)
- LiveBroker: Add fiat currency skip list to avoid failed price lookups
- PythonGenerator: Fix market symbol regex to handle 2-5 char symbols (BTC/USDT)
New features:
- LiveStrategyInstance: Full live trading strategy execution
- Circuit breaker and position limits for live trading safety
- Restart-safe order reconciliation via client order IDs
Verified working:
- Live strategy starts on Binance testnet
- Orders placed and filled successfully
- Execution loop runs with active strategies
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1. Paper equity calculation (High):
- get_balance() now correctly includes position value (size * current_price)
- Previously only added unrealized_pnl, missing position principal
2. Buy affordability checks (High):
- place_order() now uses execution price including slippage for market orders
- Uses limit price for limit orders instead of current price
- Prevents orders that would drive cash negative
3. ExchangeInterface price stubs (High):
- get_trade_executed_price() now handles order_price=0.0 (market orders)
- Falls back to current price or entry price when order_price is zero
4. Determinism hash strengthening (Medium):
- Hash now includes full trade sequence with individual trade details
- Added test for different trade sequences with same totals
5. Live mode consistency (Medium):
- Factory now falls back to paper trading with warning instead of raising
- Consistent behavior between factory.py and Strategies.py
Added test: test_paper_broker_equity_calculation to verify fix#1
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Phase 5 - Live Trading (stub implementation):
- Create LiveBroker stub with NotImplementedError for all methods
- Document required exchange API integration points
- Add testnet flag for safety
Phase 6 - Observability:
- Add structured logging with StructuredFormatter and ColoredFormatter
- Create TradingLogger for trading-specific log entries
- Implement health check system with HealthCheck class
- Add default health checks for database, exchange, memory
- Create health_endpoint() for monitoring integration
The LiveBroker is a stub that needs exchange API integration
for production use. All other trading modes (backtest, paper)
are fully functional.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Create PaperStrategyInstance extending StrategyInstance
- Integrate PaperBroker for simulated order execution
- Add trade_order() method translating Blockly calls to broker
- Add mode selection in Strategies.create_strategy_instance()
- Update execute_strategy() to support paper/backtest/live modes
- Include comprehensive tests for paper trading functionality
Paper trading now works with:
- Market and limit orders
- Position tracking with P&L
- Balance management
- Trade history
- Reset functionality
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Fix deprecated datetime.utcfromtimestamp() in shared_utilities.py
- Create BacktestResult schema with locked structure
- Add TradeResult and BacktestMetrics dataclasses
- Implement determinism hash for verifying reproducible results
- Add comprehensive tests for result schema and determinism
The BacktestResult schema ensures consistent output format and
provides methods to verify that same inputs produce same results.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Create brokers package with unified trading interface
- BaseBroker: Abstract base class defining broker contract
- BacktestBroker: Wraps Backtrader for backtesting mode
- PaperBroker: Simulated order execution for paper trading
- Factory function to create broker based on trading mode
- Comprehensive test suite for broker functionality
The broker abstraction enables strategies to work identically
across backtest, paper, and live trading modes.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Fix set_new_candle() to update cached candle instead of raising
- Fix trades.update() type mismatch: pass {symbol: price} dict
- Fix StrategyInstance.trades collision: rename list to trade_history
- Add missing ExchangeInterface methods for trade status/qty/price
- Add get_user_balance stub for paper trading
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Security: Move API keys to environment variables in config.py
- Portability: Use cross-platform path resolution for DB_FILE
- Add config.example.py template for developers
- Fix Windows path in ExchangeInterface.get_public_exchanges()
- Add cached_last_candle attribute to Candles class
- Add pytest configuration (pytest.ini, conftest.py)
- Fix test imports for DataCache_v3
- Include identity compatibility layer (user_name/user_id resolution)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>