Spaces:
Running
Running
File size: 4,120 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 | #!/usr/bin/env python3
"""Diagnose Binance API key issues and check permissions."""
from aureon_baton_link import link_system as _baton_link; _baton_link(__name__)
import os, requests, time, hmac, hashlib
try:
from dotenv import load_dotenv
load_dotenv()
except:
pass
api_key = os.getenv("BINANCE_API_KEY") or os.getenv("BINANCE_KEY")
api_secret = os.getenv("BINANCE_API_SECRET") or os.getenv("BINANCE_SECRET")
base_url = "https://api.binance.com"
print("\n" + "="*80)
print("BINANCE API KEY DIAGNOSTICS")
print("="*80)
print(f"API Key: {api_key[:10]}...{api_key[-10:] if api_key else 'MISSING'}")
print(f"Secret: {'SET' if api_secret else 'MISSING'}")
print("="*80 + "\n")
if not api_key or not api_secret:
print("β Missing credentials in .env")
exit(1)
# Test 1: Public endpoint (no auth)
print("1οΈβ£ Testing public endpoint (no auth required)...")
try:
r = requests.get(f"{base_url}/api/v3/ping", timeout=5)
print(f" β
Binance API reachable: {r.status_code}")
except Exception as e:
print(f" β Failed: {e}")
# Test 2: Server time
print("\n2οΈβ£ Testing server time...")
try:
r = requests.get(f"{base_url}/api/v3/time")
server_time = r.json()['serverTime']
local_time = int(time.time() * 1000)
drift = abs(server_time - local_time)
print(f" Server: {server_time}, Local: {local_time}, Drift: {drift}ms")
if drift > 5000:
print(f" β οΈ Time drift > 5s may cause signature issues")
else:
print(f" β
Time sync OK")
except Exception as e:
print(f" β Failed: {e}")
# Test 3: API key permissions (simple call)
print("\n3οΈβ£ Testing API key with signed request (account endpoint)...")
try:
timestamp = int(time.time() * 1000)
params = f"timestamp={timestamp}"
signature = hmac.new(api_secret.encode(), params.encode(), hashlib.sha256).hexdigest()
headers = {"X-MBX-APIKEY": api_key}
url = f"{base_url}/api/v3/account?{params}&signature={signature}"
r = requests.get(url, headers=headers)
if r.status_code == 200:
data = r.json()
print(f" β
API key valid and authorized")
print(f" Can Trade: {data.get('canTrade')}")
print(f" Can Withdraw: {data.get('canWithdraw')}")
print(f" Can Deposit: {data.get('canDeposit')}")
# Show balances
balances = [b for b in data.get('balances', []) if float(b['free']) > 0 or float(b['locked']) > 0]
print(f"\n π° Assets with balance: {len(balances)}")
for bal in balances[:10]:
free = float(bal['free'])
locked = float(bal['locked'])
total = free + locked
print(f" {bal['asset']:<10} Free: {free:<15.8f} Locked: {locked:<15.8f} Total: {total:<15.8f}")
if len(balances) > 10:
print(f" ... and {len(balances) - 10} more")
elif r.status_code == 401:
error = r.json()
code = error.get('code')
msg = error.get('msg')
print(f" β Authentication failed (401)")
print(f" Code: {code}")
print(f" Message: {msg}")
if code == -2015:
print("\n π§ LIKELY CAUSES:")
print(" 1. IP restriction - your IP not whitelisted")
print(" 2. API key permissions insufficient")
print(" 3. API key disabled or deleted")
print("\n π‘ SOLUTIONS:")
print(" 1. Binance.com β Account β API Management")
print(" 2. Edit your API key β Add current IP to whitelist")
print(" 3. Or unrestrict IP (less secure but easier)")
print(" 4. Ensure 'Enable Spot & Margin Trading' is checked")
else:
print(f" β Unexpected status: {r.status_code}")
print(f" Response: {r.text}")
except Exception as e:
print(f" β Request failed: {e}")
print("\n" + "="*80)
print("DIAGNOSIS COMPLETE")
print("="*80 + "\n")
|