File size: 6,536 Bytes
b1f38ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""
Test Script: Simulated Portfolio Per-User Initialization
Demonstrates that each user gets 10k USDT and balances update with trades
"""
import requests
import time

BASE_URL = "http://127.0.0.1:8000"

def register_user(email, password, name="Test User"):
    """Register a new user"""
    response = requests.post(
        f"{BASE_URL}/api/register",
        json={
            "email": email,
            "password": password,
            "name": name
        }
    )
    print(f"\nπŸ“ Registering user: {email}")
    if response.status_code == 200:
        print(f"   βœ… Registration successful")
        return response.json()
    else:
        print(f"   ⚠️  {response.json().get('detail', 'Registration failed')}")
        return None

def login_user(email, password):
    """Login and get auth token"""
    response = requests.post(
        f"{BASE_URL}/api/login",
        json={
            "email": email,
            "password": password
        }
    )
    print(f"\nπŸ” Logging in: {email}")
    if response.status_code == 200:
        data = response.json()
        token = data.get('access_token')
        print(f"   βœ… Login successful")
        return token
    else:
        print(f"   ❌ Login failed")
        return None

def get_portfolio(token):
    """Get simulated portfolio"""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(
        f"{BASE_URL}/api/simulated/portfolio",
        headers=headers
    )
    print(f"\nπŸ’° Fetching portfolio...")
    if response.status_code == 200:
        data = response.json()
        print(f"   Total Value: ${data['total_value_usdt']:,.2f}")
        print(f"   Assets:")
        for asset in data['assets']:
            print(f"      - {asset['symbol']}: {asset['balance']:,.8f} (${asset['value_usdt']:,.2f})")
        return data
    else:
        print(f"   ❌ Failed to fetch portfolio")
        return None

def start_trading_session(token, symbol="BTCUSDT", trade_amount=100, duration=5):
    """Start a simulated trading session"""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.post(
        f"{BASE_URL}/api/simulated/start",
        headers=headers,
        json={
            "strategy": "HMM Regime Filter",
            "symbol": symbol,
            "trade_amount": trade_amount,
            "duration": duration,
            "duration_unit": "minutes",
            "short_window": 10,
            "long_window": 50,
            "n_states": 2,
            "window": 30,
            "threshold": 1.0,
            "interval": "1m"
        }
    )
    print(f"\nπŸš€ Starting trading session: {symbol}")
    if response.status_code == 200:
        data = response.json()
        print(f"   βœ… Session started: {data['session_id']}")
        print(f"   Duration: {duration} minutes")
        print(f"   Trade Amount: ${trade_amount}")
        return data
    else:
        print(f"   ❌ Failed to start session: {response.text}")
        return None

def main():
    print("=" * 60)
    print("πŸ§ͺ Testing Simulated Portfolio - Per User Initialization")
    print("=" * 60)
    
    # Test User 1
    print("\n" + "=" * 60)
    print("TEST 1: New User Gets 10k USDT")
    print("=" * 60)
    
    user1_email = f"testuser1_{int(time.time())}@example.com"
    register_user(user1_email, "password123", "Test User 1")
    token1 = login_user(user1_email, "password123")
    
    if token1:
        portfolio1_before = get_portfolio(token1)
        
        # Verify starting balance
        if portfolio1_before and portfolio1_before['total_value_usdt'] == 10000.0:
            print("\n   βœ… PASS: User 1 started with exactly 10,000 USDT")
        else:
            print("\n   ❌ FAIL: User 1 did not get 10,000 USDT")
    
    # Test User 2
    print("\n" + "=" * 60)
    print("TEST 2: Second User Also Gets 10k USDT")
    print("=" * 60)
    
    user2_email = f"testuser2_{int(time.time())}@example.com"
    register_user(user2_email, "password123", "Test User 2")
    token2 = login_user(user2_email, "password123")
    
    if token2:
        portfolio2_before = get_portfolio(token2)
        
        if portfolio2_before and portfolio2_before['total_value_usdt'] == 10000.0:
            print("\n   βœ… PASS: User 2 also started with exactly 10,000 USDT")
        else:
            print("\n   ❌ FAIL: User 2 did not get 10,000 USDT")
    
    # Test Trading Session
    print("\n" + "=" * 60)
    print("TEST 3: Balance Changes After Trading Session")
    print("=" * 60)
    
    if token1:
        print("\n⏳ Starting trading session for User 1...")
        session = start_trading_session(token1, symbol="BTCUSDT", trade_amount=100, duration=1)
        
        if session:
            print("\n   Waiting 15 seconds for trades to execute...")
            time.sleep(15)
            
            portfolio1_after = get_portfolio(token1)
            
            if portfolio1_after:
                if portfolio1_after['total_value_usdt'] != 10000.0:
                    print(f"\n   βœ… PASS: Balance changed from $10,000 to ${portfolio1_after['total_value_usdt']:,.2f}")
                    print("   πŸ’‘ Portfolio is actively trading and updating!")
                else:
                    print("\n   ⚠️  Balance hasn't changed yet (may need more time)")
    
    # Test Persistence
    print("\n" + "=" * 60)
    print("TEST 4: User 1 Portfolio Persists After Re-login")
    print("=" * 60)
    
    if token1:
        # Re-login as User 1
        new_token1 = login_user(user1_email, "password123")
        if new_token1:
            portfolio1_relogin = get_portfolio(new_token1)
            
            if portfolio1_relogin and portfolio1_after:
                if portfolio1_relogin['total_value_usdt'] == portfolio1_after['total_value_usdt']:
                    print("\n   βœ… PASS: Portfolio balance persisted after re-login")
                else:
                    print(f"\n   ⚠️  Balance changed (trading may still be active)")
    
    print("\n" + "=" * 60)
    print("βœ… All Tests Complete!")
    print("=" * 60)
    print("\nπŸ“‹ Summary:")
    print("   β€’ Each new user automatically gets 10,000 USDT")
    print("   β€’ Balances are tracked per user (isolated portfolios)")
    print("   β€’ Trading sessions update balances in real-time")
    print("   β€’ Portfolios persist across logins/restarts")
    print("   β€’ Every 10 seconds, strategy runs and may execute trades")
    print("\n")

if __name__ == "__main__":
    main()