-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
989 lines (855 loc) · 35.8 KB
/
Copy pathindex.js
File metadata and controls
989 lines (855 loc) · 35.8 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
// BinanceAI Pro — OpenClaw Skill Implementation
// Author: BinanceAI Pro Team
// For Binance OpenClaw AI Competition #AIBinance
const GROQ_API = "https://api.groq.com/openai/v1/chat/completions";
const BINANCE_BASE = "https://api.binance.com";
const SQUARE_API = "https://www.binance.com/bapi/composite/v1/public/pgc/openApi/content/add";
const CRYPTOPANIC_API = "https://cryptopanic.com/api/free/v1/posts/?auth_token=public&public=true&kind=news";
// ─── State ─────────────────────────────────────────────────────────────────
let state = {
binanceKey: null,
binanceSecret: null,
squareKey: null,
groqKey: null,
whaleAlertKey: null,
watchlist: ["BTCUSDT", "ETHUSDT", "BNBUSDT"],
signals: [],
botActive: false,
maxTradeUSDT: 10,
maxOpenTrades: 3,
monitorIntervals: {},
};
// ─── HMAC SHA256 Signing ────────────────────────────────────────────────────
async function signQuery(queryString, secret) {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw", encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" }, false, ["sign"]
);
const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(queryString));
return Array.from(new Uint8Array(sig)).map(b => b.toString(16).padStart(2, "0")).join("");
}
// ─── Binance Authenticated Request (via Server Proxy) ──────────────────────
async function binanceRequest(method, path, params = {}, auth = false) {
if (auth && (!state.binanceKey || !state.binanceSecret)) {
return { error: "❌ API keys not configured. Run /setup first" };
}
try {
// Use the local Node.js proxy server
const url = new URL("http://localhost:3000/api/binance");
url.searchParams.set("path", path);
url.searchParams.set("method", method);
url.searchParams.set("params", JSON.stringify(params));
if (auth) {
url.searchParams.set("apiKey", state.binanceKey);
url.searchParams.set("apiSecret", state.binanceSecret);
}
const res = await fetch(url.toString());
const data = await res.json();
if (data.error) {
console.error("Binance API Error:", data.error);
return { error: data.error };
}
return data;
} catch (e) {
console.error("Request failed:", e.message);
return { error: `Request failed: ${e.message}` };
}
}
// ─── Groq AI Call ───────────────────────────────────────────────────────────
async function askGroq(systemPrompt, userMessage, json = false) {
const res = await fetch(GROQ_API, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${state.groqKey}`
},
body: JSON.stringify({
model: "llama-3.3-70b-versatile",
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userMessage }
],
temperature: 0.7,
max_tokens: 1024,
response_format: json ? { type: "json_object" } : undefined
})
});
const data = await res.json();
return data.choices?.[0]?.message?.content || "";
}
// ─── Post to Square ─────────────────────────────────────────────────────────
async function postToSquare(text) {
const res = await fetch(SQUARE_API, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Square-OpenAPI-Key": state.squareKey,
"clienttype": "binanceSkill"
},
body: JSON.stringify({ bodyTextOnly: text })
});
const data = await res.json();
if (data.code === "000000") {
return { success: true, url: `https://www.binance.com/square/post/${data.data.id}` };
}
return { success: false, error: data.message || data.code };
}
// ─── Technical Analysis ─────────────────────────────────────────────────────
function calcEMA(closes, period) {
const k = 2 / (period + 1);
let ema = closes[0];
for (let i = 1; i < closes.length; i++) ema = closes[i] * k + ema * (1 - k);
return ema;
}
function calcRSI(closes, period = 14) {
let gains = 0, losses = 0;
for (let i = 1; i <= period; i++) {
const diff = closes[i] - closes[i - 1];
if (diff > 0) gains += diff; else losses -= diff;
}
let avgGain = gains / period, avgLoss = losses / period;
for (let i = period + 1; i < closes.length; i++) {
const diff = closes[i] - closes[i - 1];
avgGain = (avgGain * (period - 1) + Math.max(diff, 0)) / period;
avgLoss = (avgLoss * (period - 1) + Math.max(-diff, 0)) / period;
}
const rs = avgGain / (avgLoss || 0.0001);
return 100 - 100 / (1 + rs);
}
function analyzeKlines(klines) {
const closes = klines.map(k => parseFloat(k[4]));
const volumes = klines.map(k => parseFloat(k[5]));
const highs = klines.map(k => parseFloat(k[2]));
const lows = klines.map(k => parseFloat(k[3]));
const ema20 = calcEMA(closes.slice(-20), 20);
const ema50 = calcEMA(closes.slice(-50), 50);
const rsi = calcRSI(closes.slice(-29));
const currentPrice = closes[closes.length - 1];
const avgVol = volumes.slice(-20).reduce((a, b) => a + b) / 20;
const currentVol = volumes[volumes.length - 1];
const volSpike = currentVol / avgVol;
const recent = closes.slice(-20);
const resistance = Math.max(...highs.slice(-20));
const support = Math.min(...lows.slice(-20));
return { currentPrice, ema20, ema50, rsi, volSpike, resistance, support, closes };
}
// ─── SECTION 1: Personal Assistant ─────────────────────────────────────────
async function handleChat(userMessage) {
const msg = userMessage.toLowerCase();
// Balance check
if (msg.includes("balance") || msg.includes("holdings") || msg.includes("portfolio") || msg.includes("account")) {
return await getAccountBalance();
}
// Real-time price with CoinGecko
if (msg.includes("price of") || msg.includes("btc price") || msg.includes("eth price")) {
const match = userMessage.match(/price\s+(?:of\s+)?(\w+)/i);
if (match) {
const coin = match[1];
return await getRealTimePriceAnalysis(coin);
}
}
// Post to Square
if (msg.includes("post to square") || msg.includes("square post") || msg.includes("binance pe post")) {
return await assistantPost(userMessage);
}
// Place trade
const buyMatch = msg.match(/buy (\w+usdt|\w+btc) \$?(\d+)/);
if (buyMatch) return await placeTrade("BUY", buyMatch[1].toUpperCase(), parseFloat(buyMatch[2]));
const sellMatch = msg.match(/sell (\w+usdt|\w+btc) \$?(\d+)/);
if (sellMatch) return await placeTrade("SELL", sellMatch[1].toUpperCase(), parseFloat(sellMatch[2]));
// Cancel orders
const closeMatch = msg.match(/close (\w+usdt|\w+btc)/);
if (closeMatch) return await cancelOrders(closeMatch[1].toUpperCase());
// Open trades
if (msg.includes("open trades") || msg.includes("my trades") || msg.includes("chalti trade")) {
return await getOpenOrders();
}
// News post
if (msg.includes("news") && msg.includes("post")) {
return await newsPost();
}
// Generic AI chat
const reply = await askGroq(
"You are BinanceAI Pro, a helpful crypto trading assistant. Be concise, use emojis. Always mention #AIBinance when relevant.",
userMessage
);
return reply;
}
async function assistantPost(userMessage) {
// Fetch BTC news for context
const newsRes = await fetch(CRYPTOPANIC_API + "¤cies=BTC,ETH,BNB");
const newsData = await newsRes.json();
const headlines = newsData.results?.slice(0, 5).map(n => n.title).join("\n") || "No recent news";
const post = await askGroq(
`You are a crypto content creator for Binance Square. Create an engaging post based on user request and current news.
Always include #AIBinance hashtag. Keep under 300 chars. Use emojis. Be insightful and engaging.`,
`User request: ${userMessage}\n\nRecent headlines:\n${headlines}`
);
return { type: "post_preview", content: post, action: "post_to_square" };
}
async function placeTrade(side, symbol, amountUSDT) {
const price = await binanceRequest("GET", "/api/v3/ticker/price", { symbol });
const currentPrice = parseFloat(price.price);
return {
type: "trade_confirm",
message: `⚠️ Confirm ${side} trade:\n\n📊 ${symbol}\n💵 Amount: $${amountUSDT}\n💲 Price: $${currentPrice.toFixed(4)}\n\nType CONFIRM to proceed.`,
onConfirm: async () => {
const order = await binanceRequest("POST", "/api/v3/order", {
symbol,
side,
type: "MARKET",
quoteOrderQty: amountUSDT,
newClientOrderId: `agent-${Date.now()}`
}, true);
if (order.orderId) {
return `✅ Order placed!\n📋 Order ID: ${order.orderId}\n💹 ${side} ${symbol}\n💵 $${amountUSDT}`;
}
return `❌ Order failed: ${order.msg}`;
}
};
}
async function cancelOrders(symbol) {
return {
type: "trade_confirm",
message: `⚠️ Cancel ALL open orders for ${symbol}?\n\nType CONFIRM to proceed.`,
onConfirm: async () => {
const result = await binanceRequest("DELETE", "/api/v3/openOrders", { symbol }, true);
return `✅ Cancelled ${result.length || 0} orders for ${symbol}`;
}
};
}
async function getOpenOrders() {
const orders = await binanceRequest("GET", "/api/v3/openOrders", {}, true);
if (!orders.length) return "📭 No open orders right now.";
const list = orders.map(o =>
`• ${o.symbol}: ${o.side} ${o.type} @ $${parseFloat(o.price).toFixed(4)} (qty: ${o.origQty})`
).join("\n");
return `📋 Open Orders (${orders.length}):\n${list}`;
}
// ─── SECTION 2: Signal Generator ───────────────────────────────────────────
async function generateSignal(symbol) {
const normalSymbol = symbol.toUpperCase().includes("USDT") ? symbol.toUpperCase() : symbol.toUpperCase() + "USDT";
// Get kline data
const klines = await binanceRequest("GET", "/api/v3/klines", {
symbol: normalSymbol, interval: "4h", limit: 100
});
if (!klines || klines.code) return `❌ Could not fetch data for ${normalSymbol}`;
const ta = analyzeKlines(klines);
const taData = JSON.stringify({
symbol: normalSymbol,
currentPrice: ta.currentPrice,
ema20: ta.ema20.toFixed(4),
ema50: ta.ema50.toFixed(4),
rsi: ta.rsi.toFixed(2),
volumeSpike: ta.volSpike.toFixed(2) + "x",
resistance: ta.resistance.toFixed(4),
support: ta.support.toFixed(4),
trend: ta.ema20 > ta.ema50 ? "BULLISH" : "BEARISH"
});
const signalJSON = await askGroq(
`You are an expert crypto technical analyst. Analyze the data and return ONLY valid JSON with this exact structure:
{
"direction": "LONG or SHORT or NEUTRAL",
"confidence": 1-10,
"entry": number,
"tp1": number,
"tp2": number,
"sl": number,
"reasoning": "2-3 sentence explanation",
"post_text": "engaging Square post under 280 chars with #AIBinance emoji"
}`,
`Technical Analysis Data:\n${taData}`,
true
);
let signal;
try {
signal = JSON.parse(signalJSON);
} catch (e) {
return "❌ Signal generation failed. Try again.";
}
// Save to signals DB
const signalRecord = {
id: Date.now(),
symbol: normalSymbol,
timestamp: new Date().toISOString(),
entry: signal.entry,
tp1: signal.tp1,
tp2: signal.tp2,
sl: signal.sl,
direction: signal.direction,
confidence: signal.confidence,
status: "ACTIVE",
posted: false,
post_url: null
};
state.signals.push(signalRecord);
// Start monitoring
startSignalMonitor(signalRecord);
return { type: "signal", signal, record: signalRecord };
}
// Monitor signal for TP/SL hit
function startSignalMonitor(record) {
const intervalId = setInterval(async () => {
try {
const price = await binanceRequest("GET", "/api/v3/ticker/price", { symbol: record.symbol });
const current = parseFloat(price.price);
let hitType = null;
if (record.direction === "LONG") {
if (current >= record.tp1) hitType = "TP1";
if (current >= record.tp2) hitType = "TP2";
if (current <= record.sl) hitType = "SL";
} else if (record.direction === "SHORT") {
if (current <= record.tp1) hitType = "TP1";
if (current <= record.tp2) hitType = "TP2";
if (current >= record.sl) hitType = "SL";
}
if (hitType) {
clearInterval(intervalId);
record.status = hitType;
// Generate fresh AI post
const updatePost = await askGroq(
"You are a crypto signal tracker. Generate an exciting update post for Binance Square. Include emoji and #AIBinance. Under 280 chars.",
`Signal Update: ${record.symbol} ${record.direction} signal ${hitType === "SL" ? "STOPPED OUT ❌" : "TARGET HIT ✅"}!
Original entry: $${record.entry}, Current price: $${current}
${hitType === "TP1" ? "TP1" : hitType === "TP2" ? "TP2 🎯🎯" : "Stop Loss"} hit at $${current}`
);
if (state.squareKey) {
const result = await postToSquare(updatePost);
record.post_url = result.url;
}
// Notify via OpenClaw
return updatePost;
}
} catch (e) {
// Silent fail, retry next interval
}
}, 5 * 60 * 1000); // Every 5 minutes
state.monitorIntervals[record.id] = intervalId;
}
// ─── SECTION 3: Whale Alerts ────────────────────────────────────────────────
async function getWhaleAlerts(minAmount = 1000000) {
let transactions = [];
try {
if (state.whaleAlertKey) {
const res = await fetch(
`https://api.whale-alert.io/v1/transactions?api_key=${state.whaleAlertKey}&min_value=${minAmount}&limit=20`
);
const data = await res.json();
transactions = data.transactions || [];
} else {
// Fallback: CryptoCompare large trades
const res = await fetch("https://min-api.cryptocompare.com/data/top/totalvolfull?limit=10&tsym=USD");
const data = await res.json();
// Simulate whale data from volume leaders
transactions = (data.Data || []).slice(0, 10).map(coin => ({
symbol: coin.CoinInfo?.Name,
amount_usd: coin.RAW?.USD?.TOTALVOLUME24HTO || 0,
transaction_type: "exchange",
from: { owner_type: "unknown" },
to: { owner_type: "unknown" },
hash: "N/A"
}));
}
} catch (e) {
return { error: "Could not fetch whale data. Please add Whale Alert API key." };
}
return { type: "whale_alerts", transactions };
}
async function analyzeWhaleImpact(transaction) {
const analysis = await askGroq(
`You are a crypto market analyst. Analyze whale transaction impact in 2-3 sentences.
Be specific about potential price impact. Format: direction emoji + analysis + suggested action.`,
`Transaction: ${JSON.stringify(transaction)}`
);
return { type: "whale_analysis", analysis, transaction };
}
async function postWhaleAlert(transaction, analysis) {
const post = await askGroq(
"Create a Binance Square post about this whale movement. Be engaging, include data, add #AIBinance #WhaleAlert. Under 280 chars.",
`Transaction: ${JSON.stringify(transaction)}\nAnalysis: ${analysis}`
);
return { type: "post_preview", content: post, action: "post_to_square" };
}
// ─── SECTION 4: News Alerts ─────────────────────────────────────────────────
async function getNewsAlerts(filter = null) {
let url = CRYPTOPANIC_API;
if (filter) url += `¤cies=${filter}`;
const res = await fetch(url);
const data = await res.json();
const articles = data.results?.slice(0, 15) || [];
return { type: "news", articles };
}
async function analyzeAndPostNews(article) {
const analysis = await askGroq(
`You are a crypto news analyst for Binance Square.
1. Analyze the news impact (Bullish/Bearish/Neutral)
2. Generate an engaging Square post
Format response as JSON: {"impact": "BULLISH|BEARISH|NEUTRAL", "explanation": "...", "post_text": "...#AIBinance..."}`,
`News Title: ${article.title}\nSource: ${article.domain}\nURL: ${article.url}`,
true
);
try {
const result = JSON.parse(analysis);
return { type: "news_analysis", ...result, article };
} catch {
return { type: "news_analysis", impact: "NEUTRAL", explanation: analysis, post_text: analysis };
}
}
// ─── SECTION 5: Trading Bot ─────────────────────────────────────────────────
async function startTradingBot(config = {}) {
state.botActive = true;
state.maxTradeUSDT = config.maxTradeUSDT || 10;
state.watchlist = config.watchlist || state.watchlist;
const runBot = async () => {
if (!state.botActive) return;
const openOrders = await binanceRequest("GET", "/api/v3/openOrders", {}, true);
if (openOrders.length >= state.maxOpenTrades) return;
for (const symbol of state.watchlist) {
try {
const klines = await binanceRequest("GET", "/api/v3/klines", {
symbol, interval: "1h", limit: 60
});
const ta = analyzeKlines(klines);
const rsi = ta.rsi;
const bullish = ta.ema20 > ta.ema50;
const oversold = rsi < 35;
const notOverbought = rsi < 65;
const volSpike = ta.volSpike > 1.3;
// Check 1h volatility (safety)
const priceChange = Math.abs(ta.closes[ta.closes.length - 1] - ta.closes[ta.closes.length - 4]) / ta.closes[ta.closes.length - 4] * 100;
if (priceChange > 5) continue; // Too volatile
if (bullish && oversold && notOverbought && volSpike) {
// Strong BUY signal — needs first-trade confirmation
const alreadyHolding = openOrders.some(o => o.symbol === symbol);
if (alreadyHolding) continue;
return {
type: "bot_trade_signal",
symbol,
confidence: Math.round((10 - rsi / 10 + ta.volSpike) * 0.8),
rsi: rsi.toFixed(1),
message: `🤖 Bot found opportunity: ${symbol}\nRSI: ${rsi.toFixed(1)} | Vol spike: ${ta.volSpike.toFixed(1)}x\n\nType CONFIRM to allow bot to trade, or SKIP.`
};
}
} catch (e) {
// Skip this coin
}
}
};
// Run every 15 minutes
state.botInterval = setInterval(runBot, 15 * 60 * 1000);
return { type: "bot_started", message: `🤖 Trading bot started!\nWatchlist: ${state.watchlist.join(", ")}\nMax per trade: $${state.maxTradeUSDT}` };
}
function stopTradingBot() {
state.botActive = false;
if (state.botInterval) clearInterval(state.botInterval);
return "🛑 Trading bot stopped.";
}
// ─── CoinGecko API Integration ────────────────────────────────────────────────
const COINGECKO_API = "https://api.coingecko.com/api/v3";
async function getCoinDataFromCoinGecko(coinId) {
try {
const res = await fetch(`${COINGECKO_API}/simple/price?ids=${coinId}&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true`);
return await res.json();
} catch (e) {
console.error("CoinGecko error:", e);
return null;
}
}
async function getMultipleCoinsFromCoinGecko(coinIds) {
try {
const res = await fetch(`${COINGECKO_API}/simple/price?ids=${coinIds.join(",")}&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true`);
return await res.json();
} catch (e) {
console.error("CoinGecko error:", e);
return {};
}
}
// Get real-time price with Groq analysis
async function getRealTimePriceAnalysis(symbol) {
const coin = symbol.replace("USDT", "").toLowerCase();
const coinGeckoData = await getCoinDataFromCoinGecko(coin);
if (!coinGeckoData || !coinGeckoData[coin]) {
// Fallback to Binance
const price = await binanceRequest("GET", "/api/v3/ticker/price", { symbol: symbol.toUpperCase().includes("USDT") ? symbol.toUpperCase() : symbol.toUpperCase() + "USDT" });
return { price: price.price, source: "Binance" };
}
const data = coinGeckoData[coin];
const priceUSD = data.usd;
const change24h = data.usd_24h_change || 0;
const marketCap = data.usd_market_cap || 0;
const volume24h = data.usd_24h_vol || 0;
// Use Groq to analyze
const analysis = await askGroq(
`You are a real-time crypto price analyst. Analyze this coin and provide a brief assessment.
Format: emoji + price + 24h change + trend assessment. Keep it under 150 chars.`,
`${coin.toUpperCase()} Price Analysis:
- Current Price: $${priceUSD}
- 24h Change: ${change24h.toFixed(2)}%
- Market Cap: $${marketCap.toLocaleString()}
- 24h Volume: $${volume24h.toLocaleString()}
Provide a concise market assessment.`
);
return {
symbol: coin.toUpperCase(),
price: priceUSD,
change24h: change24h.toFixed(2) + "%",
marketCap: marketCap,
volume24h: volume24h,
analysis: analysis,
source: "CoinGecko + Groq AI"
};
}
// ─── Account Balance ──────────────────────────────────────────────────────────
async function getAccountBalance() {
if (!state.binanceKey || !state.binanceSecret) {
return { error: "❌ API keys not configured. Run setup first!" };
}
const account = await binanceRequest("GET", "/api/v3/account", { omitZeroBalances: true }, true);
if (account.error) {
return { error: `❌ Error fetching account: ${account.error}` };
}
if (account.code) {
return { error: `❌ Binance API Error: ${account.msg}` };
}
const balances = account.balances?.filter(b => {
const total = parseFloat(b.free) + parseFloat(b.locked);
return total > 0;
}) || [];
if (balances.length === 0) {
return { message: "📭 No holdings found", balances: [] };
}
// Get all prices at once from CoinGecko
const coins = balances.filter(b => b.asset !== "USDT" && b.asset !== "BUSD" && b.asset !== "USDC").map(b => b.asset.toLowerCase());
const coinGeckoData = coins.length > 0 ? await getMultipleCoinsFromCoinGecko(coins) : {};
let totalUSDT = 0;
const balanceDetails = balances.map(b => {
const free = parseFloat(b.free);
const locked = parseFloat(b.locked);
const total = free + locked;
if (b.asset === "USDT" || b.asset === "BUSD" || b.asset === "USDC") {
totalUSDT += total;
return { asset: b.asset, free: free.toFixed(8), locked: locked.toFixed(8), total: total.toFixed(2), valueUSDT: total.toFixed(2) };
} else {
const coinData = coinGeckoData[b.asset.toLowerCase()];
const price = coinData?.usd || 0;
const valueUSDT = total * price;
totalUSDT += valueUSDT;
return {
asset: b.asset,
free: free.toFixed(8),
locked: locked.toFixed(8),
total: total.toFixed(8),
price: "$" + price.toFixed(2),
valueUSDT: valueUSDT.toFixed(2)
};
}
});
return {
type: "balance",
totalUSDT: totalUSDT.toFixed(2),
balances: balanceDetails,
count: balanceDetails.length
};
}
// ─── SECTION 6: Portfolio Manager ──────────────────────────────────────────
async function analyzePortfolio() {
const account = await binanceRequest("GET", "/api/v3/account", { omitZeroBalances: true }, true);
if (account.code) return `❌ Could not fetch portfolio: ${account.msg}`;
const balances = account.balances?.filter(b => parseFloat(b.free) > 0 || parseFloat(b.locked) > 0) || [];
// Get prices for all non-stable holdings
const holdings = [];
let totalUSDT = 0;
for (const b of balances) {
const amount = parseFloat(b.free) + parseFloat(b.locked);
if (b.asset === "USDT" || b.asset === "BUSD" || b.asset === "USDC") {
holdings.push({ asset: b.asset, amount, valueUSDT: amount, type: "stable" });
totalUSDT += amount;
} else {
try {
const price = await binanceRequest("GET", "/api/v3/ticker/price", { symbol: b.asset + "USDT" });
const valueUSDT = amount * parseFloat(price.price);
holdings.push({ asset: b.asset, amount, price: parseFloat(price.price), valueUSDT, type: "crypto" });
totalUSDT += valueUSDT;
} catch {
holdings.push({ asset: b.asset, amount, valueUSDT: 0, type: "unknown" });
}
}
}
// Calculate allocations
const portfolioData = holdings.map(h => ({
...h,
allocation: ((h.valueUSDT / totalUSDT) * 100).toFixed(1) + "%"
}));
// AI Analysis
const aiAnalysis = await askGroq(
`You are a professional crypto portfolio advisor. Analyze this portfolio and provide:
1. Overall health score (0-100)
2. Risk level: Low/Medium/High
3. Top 3 specific actionable recommendations
4. Diversification assessment
5. One key risk to watch
Be specific, data-driven, and concise. Use emojis for readability.`,
`Portfolio Data (Total: $${totalUSDT.toFixed(2)} USDT):\n${JSON.stringify(portfolioData, null, 2)}`
);
return {
type: "portfolio",
holdings: portfolioData,
totalUSDT,
analysis: aiAnalysis
};
}
// ─── Setup / Onboarding ─────────────────────────────────────────────────────
async function setupKeys(keys) {
if (keys.binanceKey) state.binanceKey = keys.binanceKey;
if (keys.binanceSecret) state.binanceSecret = keys.binanceSecret;
if (keys.squareKey) state.squareKey = keys.squareKey;
if (keys.groqKey) state.groqKey = keys.groqKey;
if (keys.whaleAlertKey) state.whaleAlertKey = keys.whaleAlertKey;
// Test Binance connection
const ping = await binanceRequest("GET", "/api/v3/ping");
if (ping && Object.keys(ping).length === 0) {
return "✅ All keys saved! Binance connection successful.\n\n🚀 BinanceAI Pro is ready! Try:\n• 'signal for BTC'\n• 'my portfolio'\n• 'crypto news'\n• 'buy BTCUSDT $5'";
}
return "⚠️ Keys saved but Binance connection test failed. Check your API keys.";
}
function getState() {
return {
connected: !!(state.binanceKey && state.squareKey && state.groqKey),
botActive: state.botActive,
activeSignals: state.signals.filter(s => s.status === "ACTIVE").length,
watchlist: state.watchlist
};
}
// ─── UI Functions (Missing from HTML) ────────────────────────────────────────
async function sendChat() {
const input = document.getElementById("chatInput");
const msg = input.value.trim();
if (!msg) return;
const messages = document.getElementById("chatMessages");
// User message
const userDiv = document.createElement("div");
userDiv.className = "msg user";
userDiv.innerHTML = `<div class="msg-bubble">${msg}</div>`;
messages.appendChild(userDiv);
input.value = "";
// Loading
const loadDiv = document.createElement("div");
loadDiv.className = "msg bot";
loadDiv.innerHTML = `<div class="msg-avatar bot">🦞</div><div class="msg-bubble" style="display:flex;gap:8px"><div class="spinner"></div> Processing...</div>`;
messages.appendChild(loadDiv);
messages.scrollTop = messages.scrollHeight;
try {
const response = await handleChat(msg);
loadDiv.remove();
const botDiv = document.createElement("div");
botDiv.className = "msg bot";
botDiv.innerHTML = `<div class="msg-avatar bot">🦞</div><div class="msg-bubble">${JSON.stringify(response)}</div>`;
messages.appendChild(botDiv);
} catch (e) {
loadDiv.remove();
const errDiv = document.createElement("div");
errDiv.className = "msg bot";
errDiv.innerHTML = `<div class="msg-avatar bot">🦞</div><div class="msg-bubble" style="color:var(--red)">❌ Error: ${e.message}</div>`;
messages.appendChild(errDiv);
}
messages.scrollTop = messages.scrollHeight;
}
async function generateSignalUI() {
const coin = document.getElementById("signalCoin").value.trim();
if (!coin) {
alert("Coin name enter karo bhai!");
return;
}
const resultsDiv = document.getElementById("signalResults");
resultsDiv.innerHTML = '<div class="loading-overlay"><div class="spinner"></div> Analyzing...</div>';
try {
const result = await generateSignal(coin);
if (result.type === "signal") {
const sig = result.signal;
const conf = (sig.confidence / 10) * 100;
resultsDiv.innerHTML = `
<div class="signal-card">
<div class="signal-header">
<div><span class="signal-coin">${sig.symbol}</span></div>
<span class="signal-direction direction-${sig.direction.toLowerCase()}">${sig.direction}</span>
</div>
<div class="signal-grid">
<div class="sig-item"><div class="sig-lbl">Entry</div><div class="sig-val">$${sig.entry.toFixed(2)}</div></div>
<div class="sig-item"><div class="sig-lbl">TP1</div><div class="sig-val">$${sig.tp1.toFixed(2)}</div></div>
<div class="sig-item"><div class="sig-lbl">TP2</div><div class="sig-val">$${sig.tp2.toFixed(2)}</div></div>
<div class="sig-item"><div class="sig-lbl">SL</div><div class="sig-val">$${sig.sl.toFixed(2)}</div></div>
</div>
<div style="font-size:12px;color:var(--muted2);margin:10px 0">${sig.reasoning}</div>
<div class="confidence-bar"><div class="confidence-fill" style="width:${conf}%"></div></div>
<div style="font-size:11px;color:var(--muted);margin-top:4px">Confidence: ${sig.confidence}/10</div>
<div class="signal-actions">
<button class="btn-post" onclick="postSignal('${sig.symbol}', '${sig.post_text.replace(/'/g, "\\'")}')">Post to Square</button>
</div>
</div>
`;
} else {
resultsDiv.innerHTML = `<div style="color:var(--red);padding:20px">${result}</div>`;
}
} catch (e) {
resultsDiv.innerHTML = `<div style="color:var(--red);padding:20px">❌ ${e.message}</div>`;
}
}
async function postSignal(symbol, text) {
if (!state.squareKey) {
alert("Square API key set karo first!");
return;
}
const preview = document.createElement("div");
preview.className = "post-preview-modal show";
preview.innerHTML = `
<div class="post-preview-box">
<div class="post-preview-title">Preview - Binance Square Post</div>
<div class="post-text">${text}</div>
<div class="post-actions">
<button class="btn-secondary" style="flex:1" onclick="this.parentElement.parentElement.parentElement.remove()">Cancel</button>
<button class="btn-primary" style="flex:1" onclick="confirmPost('${text.replace(/'/g, "\\'")}')" >Post Now</button>
</div>
</div>
`;
document.body.appendChild(preview);
}
async function confirmPost(text) {
try {
const result = await postToSquare(text);
if (result.success) {
alert(`✅ Posted! URL: ${result.url}`);
document.querySelectorAll(".post-preview-modal").forEach(el => el.remove());
} else {
alert(`❌ Post failed: ${result.error}`);
}
} catch(e) {
alert(`❌ Error: ${e.message}`);
}
}
function openSetup() {
const modal = document.getElementById("setupModal");
modal.classList.add("show");
}
function closeSetup() {
const modal = document.getElementById("setupModal");
modal.classList.remove("show");
}
async function saveKeys() {
const binanceKey = document.getElementById("keyBinanceAPI").value;
const binanceSecret = document.getElementById("keyBinanceSecret").value;
const groqKey = document.getElementById("keyGroq").value;
const squareKey = document.getElementById("keySquare").value;
const whaleKey = document.getElementById("keyWhale").value;
if (!binanceKey || !binanceSecret || !groqKey || !squareKey) {
alert("Sab keys required hain!");
return;
}
const res = await setupKeys({ binanceKey, binanceSecret, groqKey, squareKey, whaleAlertKey: whaleKey });
alert(res);
if (res.includes("✅")) {
closeSetup();
updateStatus();
}
}
function updateStatus() {
const st = getState();
const dot = document.getElementById("statusDot");
const txt = document.getElementById("statusText");
if (st.connected) {
dot.style.background = "var(--green)";
dot.style.boxShadow = "0 0 8px var(--green)";
txt.textContent = "Connected";
txt.style.color = "var(--green)";
} else {
dot.style.background = "var(--muted)";
dot.style.boxShadow = "none";
txt.textContent = "Not Connected";
txt.style.color = "var(--muted)";
}
document.getElementById("statSignals").textContent = st.activeSignals;
document.getElementById("statBot").textContent = st.botActive ? "🟢 Active" : "⚫ Idle";
}
async function startBot() {
const res = await startTradingBot();
alert(res.message);
updateStatus();
}
async function stopBot() {
const res = stopTradingBot();
alert(res);
updateStatus();
}
async function loadNews() {
const div = document.getElementById("newsList");
div.innerHTML = '<div class="loading-overlay"><div class="spinner"></div> Loading...</div>';
try {
const res = await getNewsAlerts("BTC,ETH,BNB");
if (res.articles && res.articles.length > 0) {
div.innerHTML = res.articles.map(a => `
<div class="news-item" onclick="analyzeNews('${a.title.replace(/'/g, "\\'")}')">
<div class="news-title">${a.title}</div>
<div class="news-meta">
<span class="news-source">${a.domain}</span>
<span class="news-tag">${new Date(a.published_at).toLocaleDateString()}</span>
</div>
</div>
`).join("");
}
} catch (e) {
div.innerHTML = `<div style="color:var(--red);padding:20px">❌ ${e.message}</div>`;
}
}
async function analyzeNews(title) {
alert("News analysis: " + title);
}
async function loadPortfolio() {
const div = document.getElementById("portfolioContent");
div.innerHTML = '<div class="loading-overlay"><div class="spinner"></div> Loading...</div>';
try {
const res = await analyzePortfolio();
if (res.type === "portfolio") {
const holdings = res.holdings.map(h => `
<div class="holding-row">
<div class="holding-left">
<div class="holding-icon">${h.asset.substring(0, 2)}</div>
<div>
<div class="holding-name">${h.asset}</div>
<div class="holding-amount">${h.amount.toFixed(4)}</div>
</div>
</div>
<div class="holding-right">
<div class="holding-value">$${h.valueUSDT.toFixed(2)}</div>
<div class="holding-pct">${h.allocation}</div>
</div>
</div>
`).join("");
div.innerHTML = `
<div class="portfolio-total">
<div class="portfolio-total-val">$${res.totalUSDT.toFixed(2)}</div>
<div class="portfolio-total-lbl">Total Value</div>
</div>
<div class="holdings-list">${holdings}</div>
<div class="ai-suggestion">${res.analysis}</div>
`;
}
} catch (e) {
div.innerHTML = `<div style="color:var(--red);padding:20px">❌ ${e.message}</div>`;
}
}
async function updatePrices() {
try {
const btc = await binanceRequest("GET", "/api/v3/ticker/price", { symbol: "BTCUSDT" });
const ethPrice = await binanceRequest("GET", "/api/v3/ticker/price", { symbol: "ETHUSDT" });
document.getElementById("statBTC").textContent = "$" + parseFloat(btc.price).toFixed(2);
document.getElementById("statBTCChange").textContent = "Live";
} catch (e) {
console.error("Price update failed:", e);
}
}
// Init on load
window.addEventListener("load", () => {
updateStatus();
updatePrices();
setInterval(updatePrices, 30000); // Every 30 sec
});