File size: 6,276 Bytes
96e0cc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import os
from dotenv import load_dotenv
from pybit.unified_trading import HTTP

load_dotenv()

def test_public_endpoints():
    print("Testing public API endpoints...")
    try:
        session = HTTP(testnet=True)

        server_time = session.get_server_time()
        print(f"βœ… Server time: {server_time['result']['timeSecond']}")

        ticker = session.get_tickers(category="linear", symbol="BTCUSDT")
        if ticker['result']['list']:
            price = ticker['result']['list'][0]['lastPrice']
            print(f"βœ… BTCUSDT price: ${price}")

        kline = session.get_kline(
            category="linear",
            symbol="BTCUSDT",
            interval="1",
            limit=1
        )
        if kline['result']['list']:
            print("βœ… Kline data retrieved successfully")

        instruments = session.get_instruments_info(category="linear", symbol="BTCUSDT")
        if instruments['result']['list']:
            print("βœ… Instrument info retrieved successfully")

        return True
    except Exception as e:
        print(f"❌ Public API test failed: {e}")
        return False

def test_private_endpoints():
    print("\nTesting private API endpoints...")

    API_KEY = os.getenv("BYBIT_API_KEY")
    API_SECRET = os.getenv("BYBIT_API_SECRET")
    TESTNET = os.getenv("BYBIT_TESTNET", "true").lower() == "true"

    print(f"API Key configured: {'Yes' if API_KEY else 'No'}")
    print(f"API Secret configured: {'Yes' if API_SECRET else 'No'}")
    print(f"Using {'TESTNET' if TESTNET else 'MAINNET'}")

    if not API_KEY or not API_SECRET:
        print("❌ ERROR: API credentials not found in .env file")
        print("Please set BYBIT_API_KEY and BYBIT_API_SECRET in your .env file")
        return False

    if API_KEY == "your_api_key_here" or API_SECRET == "your_api_secret_here":
        print("❌ ERROR: API credentials are still set to default placeholder values")
        print("Please update .env with your actual Bybit API credentials")
        return False

    try:
        session = HTTP(
            api_key=API_KEY,
            api_secret=API_SECRET,
            testnet=TESTNET
        )

        print("βœ… HTTP client initialized with API credentials")

        balance_success = False
        positions_success = False
        orders_success = False

        try:
            balance = session.get_wallet_balance(accountType="UNIFIED")
            print(f"βœ… Account balance retrieved: {len(balance['result']['list'])} coins")

            for coin in balance['result']['list']:
                if coin['coin'] == 'USDT':
                    print(f"   USDT Balance: {coin.get('walletBalance', '0')}")

            balance_success = True

        except Exception as e:
            print(f"❌ Balance check failed: {e}")
            print("   Trying CONTRACT account type...")

            try:
                balance = session.get_wallet_balance(accountType="CONTRACT")
                print(f"βœ… Contract account balance retrieved: {len(balance['result']['list'])} coins")
                balance_success = True
            except Exception as e2:
                print(f"❌ Contract balance also failed: {e2}")
                print("   Common causes:")
                print("   - API key lacks balance viewing permissions")
                print("   - Invalid API credentials")
                print("   - Account not funded on testnet")
                print("   - Check API key permissions in Bybit dashboard")

        try:
            positions = session.get_positions(category="linear")
            print(f"βœ… Positions retrieved: {len(positions['result']['list'])} positions")
            positions_success = True
        except Exception as e:
            print(f"❌ Positions check failed: {e}")
            print("   This requires 'View Positions' permission")

        try:
            orders = session.get_open_orders(category="linear")
            print(f"βœ… Open orders retrieved: {len(orders['result']['list'])} orders")
            orders_success = True
        except Exception as e:
            print(f"❌ Orders check failed: {e}")
            print("   This requires 'View Orders' permission")

        if balance_success and positions_success and orders_success:
            print("πŸŽ‰ All private API endpoints working!")
            return True
        else:
            print("⚠️  Some private API endpoints failed")
            print("   For trading bot to work, you need:")
            print("   - Valid API credentials")
            print("   - API key with permissions: View Account Balance, View Positions, View Orders")
            print("   - API key with permissions: Trade (for placing orders)")
            print("   - Funded testnet account (if using testnet)")
            return False

    except Exception as e:
        print(f"❌ Private API connection failed: {e}")
        return False

def main():
    print("πŸ” Bybit API Connection Test")
    print("=" * 40)

    public_ok = test_public_endpoints()
    private_ok = test_private_endpoints()

    print("\n" + "=" * 40)
    print("πŸ“Š Test Results:")

    if public_ok:
        print("βœ… Public API: Working")
    else:
        print("❌ Public API: Failed")

    if private_ok:
        print("βœ… Private API: Working")
        print("πŸŽ‰ All API tests passed! Ready for trading.")
        return True
    else:
        print("❌ Private API: Failed")
        print("\nπŸ”§ To fix private API issues:")
        print("1. Go to Bybit account > API Management")
        print("2. Ensure your API key has these permissions:")
        print("   - 'Unified Trading Account' - Read & Trade")
        print("   - 'USDC Derivatives' - Read & Trade (if using USDC)")
        print("   - 'Spot' - Read & Trade (if using spot)")
        print("3. Make sure your account is upgraded to Unified Trading Account")
        print("4. Fund your testnet account with USDT:")
        print("   - Go to Bybit testnet faucet or transfer from mainnet")
        print("   - Minimum 10 USDT recommended for testing")
        print("5. Verify API credentials in .env file are correct")
        return False

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