Spaces:
Running
Running
File size: 12,651 Bytes
fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee ed2bd7f fab03ee | 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 | // Trading Bot State Management
const TradingBot = {
balance: 10000,
initialBalance: 10000,
activeTrades: 0,
totalTrades: 0,
winningTrades: 0,
isRunning: false,
strategy: 'martingale',
baseStake: 10,
currentStake: 10,
maxStake: 1000,
targetProfit: 100,
stopLoss: 500,
contractType: 'rise_fall',
duration: 5,
candles: [],
currentPrice: 7500,
ws: null,
currentVolatility: 75,
volatilityMultiplier: 1,
init() {
this.generateInitialCandles();
this.startPriceSimulation();
this.updateUI();
// Event Listeners
document.getElementById('rise-btn')?.addEventListener('click', () => this.manualTrade('rise'));
document.getElementById('fall-btn')?.addEventListener('click', () => this.manualTrade('fall'));
// Bot control events
document.addEventListener('start-bot', () => this.startBot());
document.addEventListener('stop-bot', () => this.stopBot());
document.addEventListener('config-change', (e) => this.updateConfig(e.detail));
// Volatility indicator events
document.addEventListener('index-change', (e) => this.handleIndexChange(e.detail));
},
handleIndexChange(detail) {
this.currentVolatility = detail.volatility;
// Adjust price simulation based on volatility
this.volatilityMultiplier = detail.volatility / 75;
// Update chart title
const chartTitle = document.querySelector('h2');
if (chartTitle) {
const indexNames = {
'R_10': 'Volatility 10 Index',
'R_25': 'Volatility 25 Index',
'R_50': 'Volatility 50 Index',
'R_75': 'Volatility 75 Index',
'R_100': 'Volatility 100 Index'
};
chartTitle.textContent = indexNames[detail.index] || 'Volatility Index';
}
// Update badge
const badge = document.querySelector('.bg-slate-800.text-slate-400');
if (badge) {
badge.textContent = detail.index;
}
},
generateInitialCandles() {
let price = 7500;
for (let i = 0; i < 50; i++) {
const open = price;
const change = (Math.random() - 0.5) * 20;
const close = open + change;
const high = Math.max(open, close) + Math.random() * 10;
const low = Math.min(open, close) - Math.random() * 10;
this.candles.push({
open,
high,
low,
close,
timestamp: Date.now() - (50 - i) * 60000,
volume: Math.floor(Math.random() * 1000)
});
price = close;
}
this.currentPrice = price;
},
startPriceSimulation() {
setInterval(() => {
const baseVolatility = 0.8; // 80% base volatility
const adjustedVolatility = baseVolatility * this.volatilityMultiplier;
const change = (Math.random() - 0.5) * adjustedVolatility * 15;
this.currentPrice += change;
// Add new candle every 5 seconds (simulating 5m timeframe)
if (this.candles.length === 0 || Date.now() - this.candles[this.candles.length - 1].timestamp > 5000) {
const lastClose = this.candles[this.candles.length - 1]?.close || this.currentPrice;
const newCandle = {
open: lastClose,
high: Math.max(lastClose, this.currentPrice),
low: Math.min(lastClose, this.currentPrice),
close: this.currentPrice,
timestamp: Date.now(),
volume: Math.floor(Math.random() * 1000)
};
this.candles.push(newCandle);
if (this.candles.length > 50) this.candles.shift();
// Update chart
this.updateChart();
// Bot logic check
if (this.isRunning) {
this.evaluateStrategy();
}
}
// Update current price display
this.updatePriceDisplay();
}, 1000);
},
updateChart() {
const chart = document.getElementById('main-chart');
if (chart && chart.updateChart) {
chart.updateChart(this.candles, this.currentPrice);
}
},
updatePriceDisplay() {
const priceElement = document.getElementById('current-price');
if (priceElement) {
priceElement.textContent = this.currentPrice.toFixed(2);
}
},
evaluateStrategy() {
// Simple strategy simulation with volatility consideration
const lastCandle = this.candles[this.candles.length - 1];
const prevCandle = this.candles[this.candles.length - 2];
if (!lastCandle || !prevCandle) return;
// Adjust strategy based on volatility
const volLevel = this.getVolatilityLevel();
let signal = null;
let confidence = 0.5;
// Volatility-based strategy adjustments
if (this.strategy === 'trend') {
// Stronger trend confirmation in high volatility
const confirmationNeeded = volLevel === 'high' || volLevel === 'extreme' ? 3 : 2;
const recentCandles = this.candles.slice(-confirmationNeeded);
const allRising = recentCandles.every(c => c.close > c.open);
const allFalling = recentCandles.every(c => c.close < c.open);
if (allRising) {
signal = 'rise';
confidence = volLevel === 'high' ? 0.7 : 0.6;
} else if (allFalling) {
signal = 'fall';
confidence = volLevel === 'high' ? 0.7 : 0.6;
}
} else if (this.strategy === 'reversal') {
// Look for reversal patterns, more effective in extreme volatility
const bodySize = Math.abs(lastCandle.close - lastCandle.open);
const avgBodySize = this.candles.slice(-5).reduce((sum, c) =>
sum + Math.abs(c.close - c.open), 0) / 5;
if (bodySize > avgBodySize * 1.5) {
// Large move detected, potential reversal
signal = lastCandle.close > lastCandle.open ? 'fall' : 'rise';
confidence = volLevel === 'extreme' ? 0.65 : 0.55;
}
} else if (this.strategy === 'martingale') {
// Adjust stake based on volatility
signal = Math.random() > 0.5 ? 'rise' : 'fall';
// Reduce stake in extreme volatility
if (volLevel === 'extreme') {
this.currentStake = Math.max(this.baseStake, this.currentStake * 0.5);
}
} else if (this.strategy === 'martingale-0.5') {
signal = Math.random() > 0.5 ? 'rise' : 'fall';
if (volLevel === 'extreme') {
this.currentStake = Math.max(this.baseStake, this.currentStake * 0.7);
}
}
// Apply confidence filter
if (confidence < 0.55) signal = null;
if (signal && this.activeTrades === 0) {
this.executeTrade(signal);
}
},
executeTrade(type) {
if (this.currentStake > this.balance) {
this.stopBot();
alert('Insufficient balance!');
return;
}
this.activeTrades++;
this.balance -= this.currentStake;
this.totalTrades++;
const trade = {
id: Date.now(),
type: type,
stake: this.currentStake,
entryPrice: this.currentPrice,
startTime: Date.now(),
duration: this.duration * 60 * 1000, // Convert to ms
status: 'open'
};
this.updateUI();
this.addTradeToHistory(trade);
// Simulate trade outcome after duration
setTimeout(() => {
this.closeTrade(trade);
}, 3000); // Fast simulation for demo (3 seconds instead of 5 minutes)
},
manualTrade(type) {
if (this.isRunning) {
alert('Please stop the bot before manual trading');
return;
}
this.executeTrade(type);
},
closeTrade(trade) {
this.activeTrades--;
// Simulate win/loss with 55-60% win rate (realistic, not 90% as that's unsustainable)
const isWin = Math.random() < 0.58; // 58% win rate
const payout = 0.87; // 87% payout
if (isWin) {
const profit = trade.stake * payout;
this.balance += trade.stake + profit;
this.winningTrades++;
trade.result = 'win';
trade.profit = profit;
} else {
trade.result = 'loss';
trade.profit = -trade.stake;
// Martingale logic
if (this.strategy === 'martingale' && this.isRunning) {
this.currentStake = Math.min(trade.stake * 2, this.maxStake);
} else if (this.strategy === 'martingale-0.5' && this.isRunning) {
this.currentStake = Math.min(trade.stake * 1.5, this.maxStake);
}
}
// Reset stake on win for martingale strategies
if (trade.result === 'win' && (this.strategy === 'martingale' || this.strategy === 'martingale-0.5')) {
this.currentStake = this.baseStake;
}
// Check stop loss / take profit
const totalPnL = this.balance - this.initialBalance;
if (totalPnL <= -this.stopLoss || totalPnL >= this.targetProfit) {
this.stopBot();
}
this.updateUI();
this.updateTradeInHistory(trade);
},
startBot() {
this.isRunning = true;
this.currentStake = this.baseStake;
document.getElementById('bot-status').textContent = 'Running';
document.getElementById('bot-status').className = 'text-emerald-400 font-semibold';
},
stopBot() {
this.isRunning = false;
this.currentStake = this.baseStake;
document.getElementById('bot-status').textContent = 'Stopped';
document.getElementById('bot-status').className = 'text-rose-400 font-semibold';
},
updateConfig(config) {
this.strategy = config.strategy || this.strategy;
this.baseStake = parseFloat(config.stake) || this.baseStake;
this.currentStake = this.baseStake;
this.maxStake = parseFloat(config.maxStake) || this.maxStake;
this.targetProfit = parseFloat(config.targetProfit) || this.targetProfit;
this.stopLoss = parseFloat(config.stopLoss) || this.stopLoss;
this.duration = parseInt(config.duration) || this.duration;
},
getVolatilityLevel() {
if (this.currentVolatility < 20) return 'low';
if (this.currentVolatility < 50) return 'medium';
if (this.currentVolatility < 80) return 'high';
return 'extreme';
},
updateUI() {
// Update stats cards
const balanceCard = document.getElementById('balance-card');
const winRateCard = document.getElementById('winrate-card');
const activeTradesCard = document.getElementById('active-trades-card');
const pnlCard = document.getElementById('pnl-card');
const winRate = this.totalTrades > 0 ? ((this.winningTrades / this.totalTrades) * 100).toFixed(1) : 0;
const pnl = this.balance - this.initialBalance;
if (balanceCard) balanceCard.setAttribute('value', `$${this.balance.toFixed(2)}`);
if (winRateCard) winRateCard.setAttribute('value', `${winRate}%`);
if (activeTradesCard) activeTradesCard.setAttribute('value', this.activeTrades.toString());
if (pnlCard) {
pnlCard.setAttribute('value', `${pnl >= 0 ? '+' : ''}$${pnl.toFixed(2)}`);
pnlCard.setAttribute('color', pnl >= 0 ? 'emerald' : 'rose');
}
},
addTradeToHistory(trade) {
const history = document.getElementById('trade-history');
if (history && history.addTrade) {
history.addTrade(trade);
}
},
updateTradeInHistory(trade) {
const history = document.getElementById('trade-history');
if (history && history.updateTrade) {
history.updateTrade(trade);
}
}
};
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
TradingBot.init();
}); |