Commit Graph

32 Commits

Author SHA1 Message Date
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 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 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 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 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
rob da9d1fc5ee Fix test_BrighterTrades.py socketio mock issue
- 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>
2026-03-01 17:31:20 -04:00
rob 639043b261 Live trading infrastructure functional on testnet
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>
2026-03-01 15:23:34 -04:00
rob 6821f821e1 Implement execution loop, paper persistence, and CI pipeline
Strategy Execution Loop:
- Add tick() method to StrategyInstance for price-driven execution
- Add update() method to Strategies for iterating active instances
- Enable execution loop in received_cdata() to process candle updates
- Add PaperStrategyInstance.tick() with broker price updates

Paper Trading Persistence:
- Add Position.to_dict()/from_dict() for serialization
- Add PaperBroker state persistence (save_state/load_state)
- Add _ensure_persistence_cache() with DB schema migration
- Auto-load/save broker state in PaperStrategyInstance

Runtime Fixes (from Codex review):
- Fix get_user_info() signature mismatch in start_strategy
- Fix live/paper mode handling for stop operations
- Normalize fill event payload (filled_qty/filled_price keys)
- Remove double broker update path (delegate to tick)
- Prevent runtime events from polluting strategy list in UI

CI Pipeline:
- Add GitHub Actions workflow (.github/workflows/test.yml)
- Python 3.12 with TA-Lib dependency
- Syntax checks and 5 critical test suites

Tests: 85 passed
- test_strategy_execution.py (16 tests)
- test_execution_loop.py (17 tests)
- test_paper_persistence.py (19 tests)
- test_backtest_determinism.py (13 tests)
- test_brokers.py (18 tests)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-28 19:48:50 -04:00
rob b555f6e004 Fix high-severity issues identified by Codex
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>
2026-02-28 17:23:58 -04:00
rob 51ec74175d Phase 4: Paper trading implementation
- 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>
2026-02-28 17:07:34 -04:00
rob 1bb224b15d Phase 3: Backtest determinism
- 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>
2026-02-28 17:02:54 -04:00
rob f1182d4e0c Phase 2: Broker abstraction foundation
- 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>
2026-02-28 17:00:43 -04:00
rob 34637df478 Phase 0: Stabilize baseline
- 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>
2026-02-28 16:44:11 -04:00
Rob f1d0f2a4b1 Indicators are fixed after last update. 2024-09-18 13:47:07 -03:00
Rob 1ff21b56dd Made a lot of changes to DataCache indicator data is not being saved to the database. 2024-09-15 14:05:08 -03:00
Rob b666ec22af Extended DataCache with indicator caching functionality. All DataCache tests pass. 2024-09-07 19:51:01 -03:00
Rob a16cc542d2 Refactored DataCache, again. Implemented more advance cache management. All DataCache tests pass. 2024-08-25 10:25:08 -03:00
Rob 8361efd965 Refactored DataCache, Database and Users. All db interactions are now all inside Database. All data request from Users now go through DataCache. Expanded DataCache test to include all methods. All DataCache tests pass. 2024-08-19 23:10:13 -03:00
Rob 439c852cf5 Fixed an issue where the client asked for too many records and was not receiving them. Also ensured that much of the code is dealing with timezones proactively. 2024-08-16 15:51:15 -03:00
Rob d288eebbec Re-wrote DataCache.py and Implemented tests and got them all passing. 2024-08-15 22:39:38 -03:00
Rob c398a423a3 implemented tests for Exchangeinterface.py 2024-08-04 02:06:23 -03:00
Rob 4130e0ca9a Completed unittests for Database and DataCache. 2024-08-03 16:56:13 -03:00
Rob e601f8c23e Completed unittests for Exchange. 2024-08-02 15:51:25 -03:00
Rob 0b1ad39476 Fixed query_uptodate function and added comprehensive test cases 2024-08-02 01:36:45 -03:00
Rob b699bd950e Updated project structure and staged modified files 2024-07-25 08:21:15 -03:00
Rob a9ad629647 Many improvements. 2023-05-14 17:33:13 -03:00
Rob 119ab270c0 implemented an exchange interface. Added support for multiple exchange connections. 2023-03-04 08:38:46 -04:00
Rob 79d2a9c597 Classes implemented in python and javascript. UML class diagram. Rough sequence uml. TODO: local file getting dirty from refresh. Signals implemented. Strategies implemented. Trades implemented but still needs some testing. 2023-02-17 22:47:13 -04:00