File size: 6,829 Bytes
d96a847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#


# file: agent_system/execution.py
from typing import List, Dict
import numpy as np
from core import Portfolio, Force

class ExecutionAgent:
    def __init__(self, portfolio: Portfolio):
        self.portfolio = portfolio

    def execute_rebalance(self, forces: List[Force], weights: np.ndarray, prices: Dict[str, float]):
        print(f"\n--- 🤖 EXECUTION: Rebalancing ---")
        
        # 1. Calculate Target USD exposure per asset
        target_exposure = {}
        equity = self.portfolio.total_value
        
        for i, force in enumerate(forces):
            w = weights[i]
            if w < 0.01: continue
            
            usd_allocation = equity * w
            for asset, asset_w in force.allocation.weights.items():
                target_exposure[asset] = target_exposure.get(asset, 0) + (usd_allocation * asset_w)

        # 2. Generate Orders
        for sym, price in prices.items():
            current_qty = self.portfolio.positions.get(sym, 0.0)
            current_usd = current_qty * price
            
            target_usd = target_exposure.get(sym, 0.0)
            diff_usd = target_usd - current_usd
            
            if abs(diff_usd) < 50.0: continue # Dust filter
            
            action = "BUY" if diff_usd > 0 else "SELL"
            qty = abs(diff_usd) / price
            
            print(f"ORDER: {action} {qty:.4f} {sym} (Value: ${abs(diff_usd):.2f})")
            
            # Update Internal State (Simulation)
            self.portfolio.cash -= diff_usd
            self.portfolio.positions[sym] = self.portfolio.positions.get(sym, 0) + (qty if action == "BUY" else -qty)
# file: agent_system/execution.py

"""class MPCExecutor:
    def __init__(self, fee_rate=0.002, min_gain=0.001):
        self.fee_rate = fee_rate
        self.min_gain = min_gain

    def rebalance(self, portfolio, forces, target_w, prices):
        current_total_val = portfolio.total_value
        
        # 1. Map Force weights to Asset Target USD values
        # We initialize ONLY for assets that are not the base cash (USDT)
        target_usd_assets = {symbol: 0.0 for symbol in prices.keys() if symbol != "USDT"}
        
        for i, force in enumerate(forces):
            force_weight = target_w[i]
            for asset_symbol, asset_alloc_weight in force.allocation.weights.items():
                if asset_symbol in target_usd_assets:
                    # Target Value = Total Portfolio * Force Weight * Asset's weight in that Force
                    target_usd_assets[asset_symbol] += (current_total_val * force_weight * asset_alloc_weight)

        # 2. Execute Asset Trades
        for asset, t_usd in target_usd_assets.items():
            price = prices[asset]
            # Use .get() with a default of 0.0 to prevent KeyError
            current_qty = portfolio.positions.get(asset, 0.0)
            current_usd_val = current_qty * price
            
            diff_usd = t_usd - current_usd_val
            
            # MPC Friction Filter: Only trade if move is significant
            if abs(diff_usd) > (current_total_val * self.min_gain):
                execution_fee = abs(diff_usd) * self.fee_rate
                
                # Update Cash (USDT)
                portfolio.cash -= (diff_usd + execution_fee)
                
                # Update Asset Position
                portfolio.positions[asset] = current_qty + (diff_usd / price)
                
                action = "BUY" if diff_usd > 0 else "SELL"
                print(f"  [MPC] {action} {asset}: ${abs(diff_usd):.2f} | Fee: ${execution_fee:.2f}")

        # 3. Final Portfolio Sync
        portfolio.update(prices)"""
        
"""class MPCExecutor:
    def __init__(self, fee_rate=0.002, min_gain=0.001):
        self.fee_rate = fee_rate
        self.min_gain = min_gain

    def rebalance(self, portfolio, forces, target_w, prices):
        current_total = portfolio.total_value
        target_usd_assets = {sym: 0.0 for sym in prices.keys() if sym != "USDT"}
        
        for i, force in enumerate(forces):
            f_weight = target_w[i]
            for asset, a_weight in force.allocation.weights.items():
                if asset in target_usd_assets:
                    target_usd_assets[asset] += (current_total * f_weight * a_weight)

        for asset, t_usd in target_usd_assets.items():
            price = prices[asset]
            current_qty = portfolio.positions.get(asset, 0.0)
            current_usd = current_qty * price
            diff = t_usd - current_usd
            
            if abs(diff) > (current_total * self.min_gain):
                fee = abs(diff) * self.fee_rate
                portfolio.cash -= (diff + fee)
                portfolio.positions[asset] = current_qty + (diff / price)
        
        portfolio.update(prices)"""

# file: agent_system/executor.py

class MPCExecutor:
    def __init__(self, fee_rate=0.002, min_gain_threshold=0.01):
        """
        :param fee_rate: Trading fee (e.g., 0.002 = 0.2%)
        :param min_gain_threshold: The 'Safety Buffer'. 
               Only trade if the position change > 1% of total portfolio.
        """
        self.fee_rate = fee_rate
        self.min_gain = min_gain_threshold

    def rebalance(self, portfolio, forces, target_w, prices):
        current_total = portfolio.total_value
        target_usd_assets = {sym: 0.0 for sym in prices.keys() if sym != "USDT"}
        
        # 1. Map Force Weights -> Asset Weights (Target State)
        for i, force in enumerate(forces):
            f_weight = target_w[i]
            for asset, a_weight in force.allocation.weights.items():
                if asset in target_usd_assets:
                    target_usd_assets[asset] += (current_total * f_weight * a_weight)

        # 2. Threshold Execution (The Safety Buffer)
        for asset, t_usd in target_usd_assets.items():
            price = prices[asset]
            current_qty = portfolio.positions.get(asset, 0.0)
            current_usd = current_qty * price
            
            # Calculate the absolute difference in USD
            diff_usd = t_usd - current_usd
            
            # --- THE SAFETY CHECK ---
            # If the trade size is less than 1% of our total money, IGNORE IT.
            # This stops 'micro-trading' and saves massive fees.
            if abs(diff_usd) < (current_total * self.min_gain):
                continue # Skip this trade
            
            # 3. Apply Fees and Execute
            fee = abs(diff_usd) * self.fee_rate
            portfolio.cash -= (diff_usd + fee)
            portfolio.positions[asset] = current_qty + (diff_usd / price)
            
            print(f"⚖️ Rebalanced {asset}: Moved ${diff_usd:,.2f} (Fee: ${fee:,.2f})")
        
        portfolio.update(prices)