File size: 10,925 Bytes
da0ce7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/env python3
"""

Verify that the margin trading system is properly integrated in the main Orca loop.

Tests that:

1. Margin penny trader is callable from main loop

2. Real profit calculations account for all fees

3. Position monitoring works correctly

4. Real metrics are accessible

"""

import json
import time
from pathlib import Path
from datetime import datetime

def check_state_file():
    """Check the current margin trading state."""
    print("\n" + "="*80)
    print("πŸ“Š MARGIN TRADING STATE FILE CHECK")
    print("="*80)

    repo = Path(__file__).resolve().parents[2]
    state_file = repo / "kraken_margin_army_state.json"

    if not state_file.exists():
        print("❌ State file not found!")
        return False

    with open(state_file) as f:
        state = json.load(f)

    # Check active trades
    active_long = state.get('active_long')
    active_short = state.get('active_short')

    print(f"\nβœ… State file exists (last updated: {state.get('last_updated')})")

    if active_long:
        print(f"\nπŸ”΅ ACTIVE LONG POSITION:")
        print(f"   Pair: {active_long.get('pair')}")
        print(f"   Volume: {active_long.get('volume'):.8f}")
        print(f"   Entry: ${active_long.get('entry_price'):.4f}")
        print(f"   Leverage: {active_long.get('leverage')}x")
        print(f"   Entry Fee: ${active_long.get('entry_fee'):.4f}")
        print(f"   Order ID: {active_long.get('order_id')}")
    else:
        print("\nπŸ”΅ No active long position")

    if active_short:
        print(f"\nπŸ”΄ ACTIVE SHORT POSITION:")
        print(f"   Pair: {active_short.get('pair')}")
        print(f"   Volume: {active_short.get('volume'):.8f}")
        print(f"   Entry: ${active_short.get('entry_price'):.4f}")
        print(f"   Leverage: {active_short.get('leverage')}x")
        print(f"   Entry Fee: ${active_short.get('entry_fee'):.4f}")
        print(f"   Order ID: {active_short.get('order_id')}")
    else:
        print("\nπŸ”΄ No active short position")

    # Stats
    print(f"\nπŸ“ˆ TRADING STATISTICS:")
    print(f"   Total Trades: {state.get('total_trades')}")
    print(f"   Winning Trades: {state.get('winning_trades')}")
    print(f"   Total P&L: ${state.get('total_profit'):.2f}")

    return bool(active_long or active_short)

def check_profit_monitor():
    """Verify real_profit_monitor is available and works."""
    print("\n" + "="*80)
    print("πŸ’° REAL PROFIT MONITOR INTEGRATION CHECK")
    print("="*80)

    try:
        from real_profit_monitor import RealProfitMonitor

        monitor = RealProfitMonitor()
        print("βœ… RealProfitMonitor imported successfully")

        # Test with a sample trade
        test_trade = {
            'pair': 'DASHUSD',
            'side': 'buy',
            'volume': 10.0,
            'entry_price': 36.0,
            'current_price': 36.5,
            'leverage': 3,
            'entry_time': time.time()
        }

        result = monitor.calculate_real_profit(test_trade)

        print("\nβœ… Real Profit Calculation Test:")
        print(f"   Entry Price: ${result['entry_price']:.4f}")
        print(f"   Current Price: ${result['current_price']:.4f}")
        print(f"   Gross P&L: ${result['gross_pnl']:+.4f}")
        print(f"   Total Fees: ${result['fees']['total']:+.4f}")
        print(f"   NET P&L: ${result['net_pnl']:+.4f}")
        print(f"   Is Profitable: {result['is_profitable']}")
        print(f"   Fee Burden: {result['fee_burden_pct']:.2f}%")

        return True
    except Exception as e:
        print(f"❌ Error testing RealProfitMonitor: {e}")
        return False

def check_margin_trader():
    """Verify margin penny trader is properly integrated."""
    print("\n" + "="*80)
    print("πŸ€– MARGIN PENNY TRADER INTEGRATION CHECK")
    print("="*80)

    try:
        from kraken_margin_penny_trader import KrakenMarginArmyTrader

        trader = KrakenMarginArmyTrader()
        print("βœ… KrakenMarginPennyTrader imported successfully")

        # Check if monitor_position method exists
        if hasattr(trader, 'monitor_position'):
            print("βœ… monitor_position() method available")
        else:
            print("❌ monitor_position() method NOT found")
            return False

        # Check key attributes
        print("\nβœ… Key Components:")
        print(f"   Active Trade: {bool(trader.active_trade)}")
        print(f"   Market Data: {bool(trader.market)}")
        print(f"   Intelligence: {bool(trader.intel)}")
        print(f"   Stream: {bool(trader.stream)}")

        # Check PROFIT_TARGET_USD is set
        from kraken_margin_penny_trader import PROFIT_TARGET_USD
        print(f"   Profit Target: ${PROFIT_TARGET_USD}")

        return True
    except Exception as e:
        print(f"❌ Error testing KrakenMarginArmyTrader: {e}")
        import traceback
        traceback.print_exc()
        return False

def check_orca_integration():
    """Verify margin trader is called from main Orca loop."""
    print("\n" + "="*80)
    print("πŸ‹ ORCA KILL CYCLE INTEGRATION CHECK")
    print("="*80)

    try:
        repo = Path(__file__).resolve().parents[2]
        orca_candidates = (
            repo / "aureon_radar" / "bots" / "orca_complete_kill_cycle.py",
            repo / "aureon" / "bots" / "orca_complete_kill_cycle.py",
        )
        orca_file = next((path for path in orca_candidates if path.is_file()), orca_candidates[0])
        if not orca_file.exists():
            print("❌ Orca file not found")
            return False

        content = orca_file.read_text()

        # Check for margin_penny_trader.tick() call
        if 'self.margin_penny_trader.tick()' in content:
            print("βœ… margin_penny_trader.tick() found in main loop")
        else:
            print("❌ margin_penny_trader.tick() NOT found in main loop")
            return False

        # Check for session_stats aggregation
        if '_hive_all_closed' in content:
            print("βœ… Closed trades aggregation found (session_stats)")
        else:
            print("❌ Closed trades aggregation NOT found")
            return False

        # Check for margin interval setting
        if 'kraken_margin_interval' in content:
            print("βœ… Margin trading interval configured")
        else:
            print("❌ Margin trading interval NOT configured")

        # Find the tick interval
        import re
        match = re.search(r'kraken_margin_interval\s*=\s*([\d.]+)', content)
        if match:
            interval = float(match.group(1))
            print(f"   Tick Interval: {interval}s (every {interval}s the margin trader runs)")

        return True
    except Exception as e:
        print(f"❌ Error checking Orca integration: {e}")
        return False

def check_fee_constants():
    """Verify all fee constants are properly set."""
    print("\n" + "="*80)
    print("πŸ’³ FEE CONSTANTS VERIFICATION")
    print("="*80)

    try:
        from kraken_margin_penny_trader import (
            KRAKEN_OPEN_FEE,
            KRAKEN_CLOSE_FEE,
            KRAKEN_ROLLOVER_RATE,
            KRAKEN_ROLLOVER_INTERVAL,
            PROFIT_TARGET_USD
        )
        from real_profit_monitor import (
            KRAKEN_OPEN_FEE as RPM_OPEN_FEE,
            KRAKEN_CLOSE_FEE as RPM_CLOSE_FEE,
            KRAKEN_ROLLOVER_RATE as RPM_ROLLOVER_RATE,
            KRAKEN_ROLLOVER_INTERVAL as RPM_ROLLOVER_INTERVAL
        )

        print("βœ… Kraken Margin Trader Fees:")
        print(f"   Open Fee: {KRAKEN_OPEN_FEE*100:.3f}%")
        print(f"   Close Fee: {KRAKEN_CLOSE_FEE*100:.3f}%")
        print(f"   Rollover Rate: {KRAKEN_ROLLOVER_RATE*100:.3f}% per {KRAKEN_ROLLOVER_INTERVAL/3600:.0f}h")
        print(f"   Profit Target: ${PROFIT_TARGET_USD:.2f}")

        print("\nβœ… Real Profit Monitor Fees (should match):")
        print(f"   Open Fee: {RPM_OPEN_FEE*100:.3f}%")
        print(f"   Close Fee: {RPM_CLOSE_FEE*100:.3f}%")
        print(f"   Rollover Rate: {RPM_ROLLOVER_RATE*100:.3f}% per {RPM_ROLLOVER_INTERVAL/3600:.0f}h")

        # Verify they match
        if (KRAKEN_OPEN_FEE == RPM_OPEN_FEE and
            KRAKEN_CLOSE_FEE == RPM_CLOSE_FEE and
            KRAKEN_ROLLOVER_RATE == RPM_ROLLOVER_RATE):
            print("\nβœ… Fee constants are synchronized across modules")
        else:
            print("\n⚠️  Fee constants DO NOT match - inconsistency detected!")
            return False

        return True
    except Exception as e:
        print(f"❌ Error checking fees: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """Run all verification checks."""
    print("\n" + "β–ˆ"*80)
    print("β–ˆ" + " "*78 + "β–ˆ")
    print("β–ˆ" + "  MARGIN TRADING SYSTEM INTEGRATION VERIFICATION".center(78) + "β–ˆ")
    print("β–ˆ" + " "*78 + "β–ˆ")
    print("β–ˆ"*80)

    checks = [
        ("State File", check_state_file),
        ("Real Profit Monitor", check_profit_monitor),
        ("Margin Penny Trader", check_margin_trader),
        ("Fee Constants", check_fee_constants),
        ("Orca Integration", check_orca_integration),
    ]

    results = []
    for name, check_func in checks:
        try:
            result = check_func()
            results.append((name, result))
        except Exception as e:
            print(f"\n❌ CRITICAL ERROR in {name}: {e}")
            import traceback
            traceback.print_exc()
            results.append((name, False))

    # Summary
    print("\n" + "="*80)
    print("πŸ“‹ VERIFICATION SUMMARY")
    print("="*80)

    for name, result in results:
        status = "βœ… PASS" if result else "❌ FAIL"
        print(f"{status} | {name}")

    all_pass = all(r for _, r in results)

    print("\n" + "="*80)
    if all_pass:
        print("🎯 ALL CHECKS PASSED - System is properly integrated!")
        print("\nThe margin trading system is:")
        print("  βœ… Properly integrated into the main Orca autonomous loop")
        print("  βœ… Monitoring positions every 5 seconds via margin_penny_trader.tick()")
        print("  βœ… Calculating REAL profit (accounting for ALL fees)")
        print("  βœ… Auto-closing positions when profit target met")
        print("  βœ… Real metrics accessible via real_profit_monitor.py")
        print("\nTo run the system with live metrics:")
        print("  python run_unified_orca.py --autonomous --open-dashboard")
    else:
        print("⚠️  SOME CHECKS FAILED - See details above")
    print("="*80 + "\n")

    return all_pass

if __name__ == '__main__':
    success = main()
    exit(0 if success else 1)