-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
384 lines (328 loc) · 14.1 KB
/
popup.js
File metadata and controls
384 lines (328 loc) · 14.1 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
/**
* SmartTradeAI Popup - ML Edition v2.0
* Modern UI with enhanced visualization
*/
let currentTradingPair = 'BTCUSDT';
// apiClient is already created in api-client.js
document.addEventListener('DOMContentLoaded', async function () {
// Initialize API connection status
await updateAPIStatus();
// Button event listeners
document.getElementById("analyze").addEventListener("click", analyzeCurrentMarket);
document.getElementById("ai-predict").addEventListener("click", runAIPrediction);
document.getElementById("simulate").addEventListener("click", simulateTrading);
// Footer links
document.getElementById("settings").addEventListener("click", function (e) {
e.preventDefault();
chrome.runtime.openOptionsPage();
});
document.getElementById("open-dashboard").addEventListener("click", function (e) {
e.preventDefault();
chrome.runtime.openOptionsPage();
});
// Extract trading pair from Binance URL
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs.length > 0) {
const url = tabs[0].url;
if (url.includes('binance.com') && (url.includes('/trade/') || url.includes('/futures/'))) {
const pathParts = url.split('/');
const pair = pathParts[pathParts.length - 1].split('?')[0];
if (pair && pair.includes('USDT')) {
currentTradingPair = pair;
}
} else {
document.getElementById("status").textContent = "⚠️ Open Binance trading page";
disableAllButtons(true);
}
}
});
});
function disableAllButtons(disabled) {
const analyze = document.getElementById("analyze");
const predict = document.getElementById("ai-predict");
const simulate = document.getElementById("simulate");
if (analyze) analyze.disabled = disabled;
if (predict) predict.disabled = disabled;
if (simulate) simulate.disabled = disabled;
}
/**
* Update API connection status
*/
async function updateAPIStatus() {
const indicator = document.getElementById("api-indicator");
const statusText = document.getElementById("api-status-text");
if (!indicator || !statusText) {
console.log("Status elements not found - popup may not be loaded");
return;
}
try {
const isConnected = await apiClient.checkConnection();
if (isConnected) {
indicator.classList.add("connected");
statusText.textContent = "✅ Connected & Ready";
disableAllButtons(false);
} else {
indicator.classList.remove("connected");
statusText.textContent = "⚠️ API Available (Models Loading)";
disableAllButtons(false);
}
} catch (error) {
if (indicator) indicator.classList.remove("connected");
if (statusText) statusText.textContent = "❌ Backend Offline";
disableAllButtons(true);
console.error("API Error:", error);
}
}
/**
* Analyze current market
*/
async function analyzeCurrentMarket() {
const btn = document.getElementById("analyze");
const status = document.getElementById("status");
const mlResults = document.getElementById("ml-results");
if (!btn || !status || !mlResults) {
console.error("Required popup elements not found");
return;
}
try {
btn.disabled = true;
status.classList.add("loading");
status.textContent = "🔄 Analyzing with 10 strategies (1H timeframe)...";
mlResults.classList.remove("show");
const analysis = await apiClient.analyzeMarket(currentTradingPair, '1h', 100);
if (!analysis || !analysis.primary_signal) {
throw new Error("Invalid analysis data");
}
status.classList.remove("loading");
status.textContent = "✅ 1H Analysis Complete!";
// Update UI with results
const primary = analysis.primary_signal;
const confidence = Math.round(primary.confidence);
// Primary Strategy - with null checks
const detectedStrategy = document.getElementById("detected-strategy");
const strategyConf = document.getElementById("strategy-confidence");
if (detectedStrategy) detectedStrategy.textContent = primary.strategy.replace(/_/g, ' ');
if (strategyConf) {
strategyConf.textContent = `${confidence}%`;
strategyConf.className = "badge";
}
// Price Action - with null checks
const priceAction = document.getElementById("price-action");
const priceConf = document.getElementById("price-confidence");
if (priceAction) priceAction.textContent = primary.action;
if (priceConf) {
priceConf.textContent = `${confidence}%`;
priceConf.className = `badge ${primary.action.toLowerCase()}`;
}
// Risk Management - with null checks
const risk = analysis.risk_management;
const entryPrice = document.getElementById("entry-price");
const stopLoss = document.getElementById("stop-loss");
const takeProfit = document.getElementById("take-profit");
const posSize = document.getElementById("position-size");
if (entryPrice) entryPrice.textContent = `$${risk.entry.toFixed(2)}`;
if (stopLoss) stopLoss.textContent = `$${risk.stop_loss.toFixed(2)}`;
if (takeProfit) takeProfit.textContent = `$${risk.take_profit.toFixed(2)}`;
if (posSize) posSize.textContent = risk.position_size;
// Show results
mlResults.classList.add("show");
// Display individual strategy analysis
displayIndividualStrategies(analysis.strategy_analyses || analysis.all_strategies);
// Notify
chrome.runtime.sendMessage({
type: "showNotification",
message: `${primary.action} Signal (1H): ${primary.strategy}`,
notificationType: primary.action === 'BUY' ? 'info' : 'warning'
}).catch(() => { });
} catch (error) {
if (status) {
status.classList.remove("loading");
status.textContent = `❌ ${error.message}`;
}
console.error("Analysis Error:", error);
} finally {
if (btn) btn.disabled = false;
}
}
/**
* Display individual strategy analysis
*/
function displayIndividualStrategies(strategies) {
const container = document.getElementById("strategies-list");
const section = document.getElementById("individual-strategies");
if (!container || !section) return;
container.innerHTML = "";
// Strategy icons
const icons = {
'EMA_CROSSOVER': '🔀',
'SUPERTREND': '📈',
'RSI_MACD': '📊',
'BOLLINGER_RSI': '📏',
'FIBONACCI': '🔢',
'VWAP': '💧',
'ICHIMOKU': '☁️',
'PARABOLIC_SAR': '🎯',
'ORB': '🏗️',
'WHEEL': '♻️'
};
Object.entries(strategies).forEach(([key, data]) => {
const icon = icons[key] || '📍';
const name = (data.name || key).replace(/_/g, ' ');
const signal = data.signal || data.action || 'HOLD';
const confidence = Math.round((data.confidence || 0) * 100);
const signalClass = signal === 'BUY' ? 'buy' : signal === 'SELL' ? 'sell' : 'hold';
// Create expandable strategy item
const strategyItem = document.createElement('div');
strategyItem.className = 'strategy-item';
strategyItem.innerHTML = `
<div class="strategy-item-header">
<div style="display: flex; align-items: center; gap: 8px; flex: 1;">
<span>${icon}</span>
<div class="strategy-item-title">${name}</div>
</div>
<div class="strategy-item-signal">
<span class="badge ${signalClass}">${signal}</span>
<span class="badge" style="background: rgba(102, 126, 234, 0.6);">${confidence}%</span>
<span class="expand-icon">▼</span>
</div>
</div>
<div class="strategy-item-details">
<div class="detail-row">
<span>Signal:</span>
<span class="detail-value">${signal}</span>
</div>
<div class="detail-row">
<span>Confidence:</span>
<span class="detail-value">${confidence}%</span>
</div>
${data.parameters ? `
<div class="detail-row" style="flex-direction: column; align-items: flex-start;">
<span>Parameters:</span>
${Object.entries(data.parameters).map(([k, v]) => `
<div style="font-size: 10px; margin-left: 8px; margin-top: 2px;">
${k}: <span class="detail-value">${typeof v === 'number' ? v.toFixed(2) : v}</span>
</div>
`).join('')}
</div>
` : ''}
${data.details ? `
<div class="detail-row" style="margin-top: 8px;">
<span style="color: #51cf66; font-weight: 600;">${data.details}</span>
</div>
` : ''}
</div>
`;
// Add click listener for expansion
const header = strategyItem.querySelector('.strategy-item-header');
header.addEventListener('click', function () {
strategyItem.classList.toggle('expanded');
});
container.appendChild(strategyItem);
});
section.classList.add("show");
}
/**
* Run AI multi-timeframe prediction
*/
async function runAIPrediction() {
const btn = document.getElementById("ai-predict");
const status = document.getElementById("status");
const mlResults = document.getElementById("ml-results");
if (!btn || !status) {
console.error("Required elements not found");
return;
}
try {
btn.disabled = true;
status.classList.add("loading");
status.textContent = "🤖 ML Predicting all timeframes...";
const [pred5, pred15, pred30, pred1h] = await Promise.all([
apiClient.predict5Min(currentTradingPair),
apiClient.predict15Min(currentTradingPair),
apiClient.predict30Min(currentTradingPair),
apiClient.predict1H(currentTradingPair)
]);
const predictions = {
'5m': pred5.probability_up,
'15m': pred15.probability_up,
'30m': pred30.probability_up,
'1h': pred1h.probability_up
};
// Calculate overall sentiment
const avgProb = (predictions['5m'] + predictions['15m'] + predictions['30m'] + predictions['1h']) / 4;
const isUp = avgProb > 0.55;
const confidence = Math.round(Math.abs(avgProb - 0.5) * 200);
status.classList.remove("loading");
status.innerHTML = `
<div style="text-align: left; font-size: 12px;">
<strong>📊 Prediction Summary:</strong><br/>
<div style="background: rgba(0, 0, 0, 0.2); padding: 8px; border-radius: 4px; margin-top: 6px; font-family: monospace;">
<div>5-Min: <strong style="color: #51cf66;">${(predictions['5m'] * 100).toFixed(0)}%</strong> ↑</div>
<div>15-Min: <strong style="color: #51cf66;">${(predictions['15m'] * 100).toFixed(0)}%</strong> ↑</div>
<div>30-Min: <strong style="color: #51cf66;">${(predictions['30m'] * 100).toFixed(0)}%</strong> ↑</div>
<div>1-Hour: <strong style="color: #51cf66;">${(predictions['1h'] * 100).toFixed(0)}%</strong> ↑</div>
</div>
<div style="margin-top: 8px; color: #a0a0c0; font-size: 11px;">
Overall: ${isUp ? '📈 BULLISH TREND' : '📉 BEARISH TREND'} (${confidence}% confidence)
</div>
</div>
`;
// Update signal box
const priceAction = document.getElementById("price-action");
const priceConf = document.getElementById("price-confidence");
if (priceAction) priceAction.textContent = isUp ? '📈 BULLISH' : '📉 BEARISH';
if (priceConf) {
priceConf.textContent = `${confidence}%`;
priceConf.className = `badge ${isUp ? 'buy' : 'sell'}`;
}
if (mlResults) mlResults.classList.add("show");
chrome.runtime.sendMessage({
type: "showNotification",
message: `Prediction: ${isUp ? '📈 BULLISH' : '📉 BEARISH'} (${confidence}% confidence)`,
notificationType: "info"
}).catch(() => { });
} catch (error) {
if (status) {
status.classList.remove("loading");
status.textContent = `❌ Prediction Error: ${error.message}`;
}
console.error("Prediction Error:", error);
} finally {
if (btn) btn.disabled = false;
}
}
/**
* Simulate trading
*/
async function simulateTrading() {
const btn = document.getElementById("simulate");
const status = document.getElementById("status");
if (!btn || !status) {
console.error("Required elements not found");
return;
}
try {
btn.disabled = true;
status.classList.add("loading");
status.textContent = "📈 Starting simulation...";
const analysis = await apiClient.analyzeMarket(currentTradingPair);
const primary = analysis.primary_signal;
const risk = analysis.risk_management;
status.classList.remove("loading");
status.textContent = `✅ Simulating ${primary.action} @ $${risk.entry.toFixed(2)}`;
chrome.runtime.sendMessage({
type: "showNotification",
message: `Simulating ${primary.action} trade at $${risk.entry.toFixed(2)}`,
notificationType: "success"
}).catch(() => { });
} catch (error) {
if (status) {
status.classList.remove("loading");
status.textContent = `❌ Simulation Error: ${error.message}`;
}
console.error("Simulation Error:", error);
} finally {
if (btn) btn.disabled = false;
}
}
// Refresh API status every 30 seconds