Skip to content

Conversation

@konard
Copy link
Member

@konard konard commented Sep 12, 2025

🎯 Trading Portfolio Auto Balance Algorithm

This pull request implements a portfolio auto-balance algorithm that uses Deep (associative data storage) to maintain target asset allocations.

📋 Issue Reference

Fixes #138

✨ Features Implemented

  • Portfolio Balance Algorithm: Automatically rebalances portfolio based on configurable target allocations (e.g., 25% Gold, 25% USD, 50% TCS Group stocks)
  • Deep Storage Integration: Uses Platform.Data.Doublets for associative data storage of portfolio state and decisions
  • Configurable Thresholds: Set rebalance triggers and check intervals via configuration
  • Multi-Asset Support: Handles ETFs, Shares, and Cash positions
  • Exact Arithmetic: Uses rational numbers for precise portfolio calculations

🏗️ Architecture

Core Components Added:

  • PortfolioBalanceAlgorithm.cs: Main algorithm for analyzing and rebalancing portfolios
  • PortfolioBalanceSettings.cs: Configuration model for asset allocations
  • PortfolioBalanceAlgorithmTests.cs: Unit tests for algorithm validation
  • Extended FinancialStorage.cs: Added portfolio-specific Deep storage types
  • Extended TradingService.cs: Integrated portfolio balancing into main trading loop

Deep Storage Schema:

The algorithm stores portfolio relationships using associative data:

  • Asset ↔ Target Allocation Percentage (stored as rational numbers)
  • Asset ↔ Current Allocation Percentage
  • Asset ↔ Rebalance Actions and Amounts
  • Portfolio metadata and type classifications

🔧 Configuration Example

{
  "TradingSettings": {
    "PortfolioBalance": {
      "Enabled": true,
      "RebalanceThresholdPercent": 5.0,
      "RebalanceCheckInterval": "00:10:00",
      "AssetAllocations": [
        {
          "AssetType": "Gold",
          "Ticker": "TGLD", 
          "TargetPercent": 25.0,
          "Instrument": "Etf"
        },
        {
          "AssetType": "USD",
          "Ticker": "FXMM",
          "TargetPercent": 25.0,
          "Instrument": "Etf"
        },
        {
          "AssetType": "TCS Group stocks", 
          "Ticker": "TCSG",
          "TargetPercent": 50.0,
          "Instrument": "Shares"
        }
      ]
    }
  }
}

🔄 Algorithm Flow

  1. Portfolio Analysis: Retrieves current positions and calculates allocation percentages
  2. Deviation Detection: Compares current vs. target allocations
  3. Threshold Check: Identifies assets exceeding rebalance thresholds
  4. Action Generation: Creates buy/sell actions to restore target balance
  5. Deep Storage: Stores all analysis results and decisions in associative format
  6. Execution: Coordinates rebalancing across trading instances

📊 Example Output

[10:00:00] Starting portfolio balance analysis
[10:00:01] Asset TGLD: Current 15.2%, Target 25.0%, Deviation 9.8%
[10:00:01] Asset FXMM: Current 28.5%, Target 25.0%, Deviation 3.5%
[10:00:01] Asset TCSG: Current 56.3%, Target 50.0%, Deviation 6.3%
[10:00:02] Rebalance needed for TGLD: Buy 9800.00 RUB
[10:00:02] Rebalance needed for TCSG: Sell 6300.00 RUB
[10:00:02] Portfolio analysis complete. 2 rebalance actions identified

🧪 Testing

  • Unit tests for portfolio calculations and threshold logic
  • Deep storage integration tests for data persistence
  • Rebalance action generation validation
  • Run tests with: dotnet run --test

📚 Documentation

  • Comprehensive documentation in PORTFOLIO_BALANCE.md
  • Configuration examples and troubleshooting guide
  • Architecture overview and Deep storage schema explanation

🎖️ Reward Claim

This implementation fulfills the requirements for issue #138:

  • ✅ Portfolio auto balance algorithm implemented
  • ✅ Uses Deep (associative data storage) for portfolio state
  • ✅ Configurable asset allocation percentages (25% Gold, 25% USD, 50% stocks example)
  • ✅ Integrated with existing TraderBot architecture
  • ✅ Comprehensive testing and documentation

🎯 1000 RUB reward can be claimed upon review and acceptance.


🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com

Adding CLAUDE.md with task information for AI processing.
This file will be removed when the task is complete.

Issue: #138
@konard konard self-assigned this Sep 12, 2025
@konard konard changed the title [WIP] Trader: Trading portfolio auto balance algorithm, that uses, that uses Deep (associative data storage) Trader: Trading portfolio auto balance algorithm using Deep (associative data storage) Sep 12, 2025
- Add PortfolioBalanceAlgorithm with configurable asset allocations (e.g. 25% Gold, 25% USD, 50% TCS stocks)
- Integrate Deep (associative data storage) for portfolio state persistence using rational numbers
- Add portfolio balance settings and configuration support
- Extend FinancialStorage with portfolio-specific types and relationships
- Integrate portfolio balancing into main TradingService loop
- Add comprehensive unit tests for algorithm validation
- Include example configuration and detailed documentation

Features:
- Automatic portfolio analysis and rebalancing
- Configurable deviation thresholds and check intervals
- Multi-asset support (ETFs, Shares, Cash)
- Deep storage for exact arithmetic and state persistence
- Risk management with balance validation

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@konard konard marked this pull request as ready for review September 12, 2025 21:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Trader: Trading portfolio auto balance algorithm, that uses, that uses Deep (associative data storage)

2 participants