File size: 14,086 Bytes
fc115d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
"""
Client-side Binance Testnet Integration
Makes API calls from user's browser to bypass HuggingFace geo-restrictions
"""

import streamlit as st
import streamlit.components.v1 as components


def render_testnet_tab(api_key: str, api_secret: str):
    """
    Render testnet tab with client-side JavaScript API calls.

    This bypasses HuggingFace's geo-restrictions by making API calls
    from the user's browser instead of the server.
    """

    # JavaScript/HTML component for client-side API calls
    html_code = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/crypto-js.js"></script>
        <style>
            body {{
                font-family: 'Source Sans Pro', sans-serif;
                padding: 20px;
                background-color: #0E1117;
                color: #FAFAFA;
            }}
            .portfolio-card {{
                background-color: #262730;
                border-radius: 8px;
                padding: 20px;
                margin: 10px 0;
                border: 1px solid #464646;
            }}
            .metric {{
                text-align: center;
                padding: 15px;
            }}
            .metric-label {{
                font-size: 14px;
                color: #A0A0A0;
                margin-bottom: 5px;
            }}
            .metric-value {{
                font-size: 28px;
                font-weight: bold;
                color: #FAFAFA;
            }}
            .metric-delta {{
                font-size: 14px;
                margin-top: 5px;
            }}
            .positive {{ color: #00D26A; }}
            .negative {{ color: #FF4B4B; }}
            .button {{
                padding: 10px 20px;
                margin: 5px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 16px;
                font-weight: bold;
            }}
            .buy-btn {{
                background-color: #00D26A;
                color: white;
            }}
            .sell-btn {{
                background-color: #FF4B4B;
                color: white;
            }}
            .info-btn {{
                background-color: #4A4A4A;
                color: white;
            }}
            #status {{
                padding: 10px;
                margin: 10px 0;
                border-radius: 4px;
                display: none;
            }}
            .status-success {{
                background-color: #00D26A20;
                border: 1px solid #00D26A;
                color: #00D26A;
            }}
            .status-error {{
                background-color: #FF4B4B20;
                border: 1px solid #FF4B4B;
                color: #FF4B4B;
            }}
            .loading {{
                text-align: center;
                padding: 20px;
                color: #A0A0A0;
            }}
        </style>
    </head>
    <body>
        <div id="status"></div>
        <div id="loading" class="loading">Loading testnet data...</div>

        <div id="portfolio" style="display:none;">
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                <div class="portfolio-card metric">
                    <div class="metric-label">๐Ÿ’ฐ Portfolio Value</div>
                    <div class="metric-value" id="portfolioValue">$0.00</div>
                    <div class="metric-delta" id="portfolioDelta"></div>
                </div>
                <div class="portfolio-card metric">
                    <div class="metric-label">๐Ÿ’ต USDT Balance</div>
                    <div class="metric-value" id="usdtBalance">$0.00</div>
                </div>
                <div class="portfolio-card metric">
                    <div class="metric-label">๐Ÿ“Š Total P&L %</div>
                    <div class="metric-value" id="totalPnl">+0.00%</div>
                    <div class="metric-delta" id="pnlDelta"></div>
                </div>
            </div>

            <div class="portfolio-card" style="margin-top: 20px;">
                <h3>๐Ÿ“Š Current Positions</h3>
                <div id="positions"></div>
            </div>

            <div class="portfolio-card" style="margin-top: 20px;">
                <h3>๐ŸŽฎ Trading Controls</h3>
                <select id="symbol" style="padding: 10px; margin: 10px 0; width: 200px;">
                    <option value="BTCUSDT">BTC/USDT</option>
                    <option value="ETHUSDT">ETH/USDT</option>
                    <option value="SOLUSDT">SOL/USDT</option>
                    <option value="XRPUSDT">XRP/USDT</option>
                </select>
                <input type="number" id="amount" placeholder="Amount (USDT)" value="100" style="padding: 10px; margin: 10px; width: 200px;">
                <br>
                <button class="button buy-btn" onclick="placeBuyOrder()">๐ŸŸข BUY (Market)</button>
                <button class="button sell-btn" onclick="placeSellOrder()">๐Ÿ”ด SELL (Market)</button>
                <button class="button info-btn" onclick="refreshData()">๐Ÿ”„ Refresh</button>
            </div>
        </div>

        <script>
            const API_KEY = '{api_key}';
            const API_SECRET = '{api_secret}';
            const BASE_URL = 'https://testnet.binance.vision';

            // Generate HMAC SHA256 signature
            function generateSignature(queryString) {{
                return CryptoJS.HmacSHA256(queryString, API_SECRET).toString();
            }}

            // Make authenticated API request
            async function binanceRequest(endpoint, params = {{}}, method = 'GET') {{
                const timestamp = Date.now();
                params.timestamp = timestamp;
                params.recvWindow = 10000;

                const queryString = Object.keys(params)
                    .map(key => `${{key}}=${{params[key]}}`)
                    .join('&');

                const signature = generateSignature(queryString);
                const url = `${{BASE_URL}}${{endpoint}}?${{queryString}}&signature=${{signature}}`;

                const response = await fetch(url, {{
                    method: method,
                    headers: {{
                        'X-MBX-APIKEY': API_KEY
                    }}
                }});

                if (!response.ok) {{
                    const error = await response.json();
                    throw new Error(error.msg || 'API request failed');
                }}

                return response.json();
            }}

            // Show status message
            function showStatus(message, isError = false) {{
                const status = document.getElementById('status');
                status.textContent = message;
                status.className = isError ? 'status-error' : 'status-success';
                status.style.display = 'block';
                setTimeout(() => {{ status.style.display = 'none'; }}, 5000);
            }}

            // Fetch account balance
            async function fetchBalance() {{
                try {{
                    const account = await binanceRequest('/api/v3/account');
                    return account.balances.filter(b => parseFloat(b.free) > 0 || parseFloat(b.locked) > 0);
                }} catch (error) {{
                    console.error('Error fetching balance:', error);
                    throw error;
                }}
            }}

            // Fetch ticker price
            async function fetchPrice(symbol) {{
                try {{
                    const response = await fetch(`${{BASE_URL}}/api/v3/ticker/24hr?symbol=${{symbol}}`);
                    const ticker = await response.json();
                    return parseFloat(ticker.lastPrice);
                }} catch (error) {{
                    console.error('Error fetching price:', error);
                    return 0;
                }}
            }}

            // Update portfolio display
            async function updatePortfolio() {{
                try {{
                    const balances = await fetchBalance();
                    let totalValue = 0;
                    let positions = [];

                    for (const balance of balances) {{
                        const free = parseFloat(balance.free);
                        const locked = parseFloat(balance.locked);
                        const total = free + locked;

                        if (total > 0) {{
                            if (balance.asset === 'USDT') {{
                                totalValue += total;
                                document.getElementById('usdtBalance').textContent = `$${{total.toFixed(2)}}`;
                            }} else {{
                                const price = await fetchPrice(balance.asset + 'USDT');
                                const value = total * price;
                                totalValue += value;

                                positions.push({{
                                    asset: balance.asset,
                                    amount: total.toFixed(6),
                                    price: price.toFixed(2),
                                    value: value.toFixed(2)
                                }});
                            }}
                        }}
                    }}

                    // Update portfolio metrics
                    document.getElementById('portfolioValue').textContent = `$${{totalValue.toFixed(2)}}`;

                    document.getElementById('totalPnl').textContent = 'N/A';
                    document.getElementById('totalPnl').className = 'metric-value';

                    document.getElementById('portfolioDelta').textContent = '';
                    document.getElementById('portfolioDelta').className = 'metric-delta';

                    document.getElementById('pnlDelta').textContent = '';
                    document.getElementById('pnlDelta').className = 'metric-delta';

                    // Update positions table
                    const positionsDiv = document.getElementById('positions');
                    if (positions.length === 0) {{
                        positionsDiv.innerHTML = '<p style="color: #A0A0A0;">No open positions. Portfolio is 100% USDT</p>';
                    }} else {{
                        let html = '<table style="width: 100%; border-collapse: collapse;">';
                        html += '<tr><th>Asset</th><th>Amount</th><th>Price</th><th>Value (USDT)</th></tr>';
                        positions.forEach(p => {{
                            html += `<tr><td>${{p.asset}}</td><td>${{p.amount}}</td><td>$${{p.price}}</td><td>$${{p.value}}</td></tr>`;
                        }});
                        html += '</table>';
                        positionsDiv.innerHTML = html;
                    }}

                    document.getElementById('loading').style.display = 'none';
                    document.getElementById('portfolio').style.display = 'block';

                }} catch (error) {{
                    document.getElementById('loading').textContent = 'โŒ Error: ' + error.message;
                    showStatus('Error loading portfolio: ' + error.message, true);
                }}
            }}

            // Place buy order
            async function placeBuyOrder() {{
                try {{
                    const symbol = document.getElementById('symbol').value;
                    const amountUSDT = parseFloat(document.getElementById('amount').value);

                    const price = await fetchPrice(symbol);
                    const quantity = (amountUSDT / price).toFixed(6);

                    await binanceRequest('/api/v3/order', {{
                        symbol: symbol,
                        side: 'BUY',
                        type: 'MARKET',
                        quantity: quantity
                    }}, 'POST');

                    showStatus(`โœ… BUY order placed: ${{quantity}} ${{symbol.replace('USDT', '')}} @ $${{price.toFixed(2)}}`);
                    setTimeout(updatePortfolio, 1000);
                }} catch (error) {{
                    showStatus('โŒ Order failed: ' + error.message, true);
                }}
            }}

            // Place sell order
            async function placeSellOrder() {{
                try {{
                    const symbol = document.getElementById('symbol').value;
                    const balances = await fetchBalance();
                    const asset = symbol.replace('USDT', '');
                    const balance = balances.find(b => b.asset === asset);

                    if (!balance || parseFloat(balance.free) === 0) {{
                        showStatus(`โŒ No ${{asset}} to sell`, true);
                        return;
                    }}

                    const quantity = parseFloat(balance.free).toFixed(6);

                    await binanceRequest('/api/v3/order', {{
                        symbol: symbol,
                        side: 'SELL',
                        type: 'MARKET',
                        quantity: quantity
                    }}, 'POST');

                    showStatus(`โœ… SELL order placed: ${{quantity}} ${{asset}}`);
                    setTimeout(updatePortfolio, 1000);
                }} catch (error) {{
                    showStatus('โŒ Order failed: ' + error.message, true);
                }}
            }}

            // Refresh data
            function refreshData() {{
                document.getElementById('loading').style.display = 'block';
                document.getElementById('portfolio').style.display = 'none';
                updatePortfolio();
            }}

            // Initialize on load
            updatePortfolio();

            // Auto-refresh every 30 seconds
            setInterval(updatePortfolio, 30000);
        </script>
    </body>
    </html>
    """

    # Render the component
    components.html(html_code, height=800, scrolling=True)