|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async function example1_basicStrategy() {
|
|
|
|
|
|
const { analyzeWithStrategy, HYBRID_STRATEGIES } = await import('./trading-strategies.js');
|
|
|
|
|
|
|
|
|
const marketData = {
|
|
|
price: 43250,
|
|
|
volume: 1000000,
|
|
|
high24h: 44000,
|
|
|
low24h: 42500
|
|
|
};
|
|
|
|
|
|
|
|
|
const result = analyzeWithStrategy('BTC', 'trend-rsi-macd', marketData);
|
|
|
|
|
|
console.log('Strategy:', result.strategy);
|
|
|
console.log('Signal:', result.signal);
|
|
|
console.log('Confidence:', result.confidence);
|
|
|
console.log('Entry:', result.levels);
|
|
|
console.log('Stop Loss:', result.stopLoss);
|
|
|
console.log('Take Profits:', result.takeProfitLevels);
|
|
|
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
|
|
|
async function example2_htsEngine() {
|
|
|
|
|
|
const HTSEngine = (await import('./hts-engine.js')).default;
|
|
|
|
|
|
|
|
|
const hts = new HTSEngine();
|
|
|
|
|
|
|
|
|
const ohlcvData = [
|
|
|
{ timestamp: 1234567890, open: 43000, high: 43500, low: 42800, close: 43250, volume: 1000000 },
|
|
|
{ timestamp: 1234567950, open: 43250, high: 43800, low: 43100, close: 43650, volume: 1200000 },
|
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
const analysis = await hts.analyze(ohlcvData, 'BTC');
|
|
|
|
|
|
console.log('Final Signal:', analysis.signal);
|
|
|
console.log('Final Score:', analysis.score);
|
|
|
console.log('Confidence:', analysis.confidence);
|
|
|
console.log('Market Regime:', analysis.regime);
|
|
|
console.log('Component Scores:', analysis.components);
|
|
|
console.log('Dynamic Weights:', analysis.weights);
|
|
|
|
|
|
return analysis;
|
|
|
}
|
|
|
|
|
|
|
|
|
async function example3_regimeDetection() {
|
|
|
|
|
|
const { AdaptiveRegimeDetector } = await import('./adaptive-regime-detector.js');
|
|
|
|
|
|
|
|
|
const detector = new AdaptiveRegimeDetector();
|
|
|
|
|
|
|
|
|
const regime = detector.detectRegime(ohlcvData);
|
|
|
|
|
|
console.log('Market Regime:', regime.regime);
|
|
|
console.log('Characteristics:', regime.characteristics);
|
|
|
console.log('Best Strategies:', regime.bestStrategies);
|
|
|
console.log('Confidence:', regime.confidence);
|
|
|
|
|
|
return regime;
|
|
|
}
|
|
|
|
|
|
|
|
|
async function example4_advancedStrategies() {
|
|
|
|
|
|
const { analyzeWithAdvancedStrategy, ADVANCED_STRATEGIES_V2 } = await import('./advanced-strategies-v2.js');
|
|
|
|
|
|
|
|
|
const result = analyzeWithAdvancedStrategy('BTC', 'ict-market-structure', ohlcvData);
|
|
|
|
|
|
console.log('Strategy:', result.strategy);
|
|
|
console.log('Signal:', result.signal);
|
|
|
console.log('Win Rate:', result.winRate);
|
|
|
console.log('Risk/Reward:', result.avgRR);
|
|
|
console.log('Entry/Stop/Target:', result.riskReward);
|
|
|
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async function comprehensiveAnalysis(symbol, ohlcvData, currentPrice) {
|
|
|
try {
|
|
|
console.log(`[Comprehensive Analysis] Starting for ${symbol}...`);
|
|
|
|
|
|
|
|
|
const { AdaptiveRegimeDetector } = await import('./adaptive-regime-detector.js');
|
|
|
const detector = new AdaptiveRegimeDetector();
|
|
|
const regime = detector.detectRegime(ohlcvData);
|
|
|
console.log(`✅ Regime detected: ${regime.regime}`);
|
|
|
|
|
|
|
|
|
const recommendedStrategies = regime.bestStrategies || ['trend-rsi-macd'];
|
|
|
|
|
|
|
|
|
const HTSEngine = (await import('./hts-engine.js')).default;
|
|
|
const hts = new HTSEngine();
|
|
|
const htsAnalysis = await hts.analyze(ohlcvData, symbol);
|
|
|
console.log(`✅ HTS Analysis complete: ${htsAnalysis.signal} (score: ${htsAnalysis.score})`);
|
|
|
|
|
|
|
|
|
const { analyzeWithStrategy } = await import('./trading-strategies.js');
|
|
|
const marketData = {
|
|
|
price: currentPrice,
|
|
|
volume: ohlcvData[ohlcvData.length - 1].volume,
|
|
|
high24h: Math.max(...ohlcvData.slice(-24).map(c => c.high)),
|
|
|
low24h: Math.min(...ohlcvData.slice(-24).map(c => c.low))
|
|
|
};
|
|
|
const strategyResult = analyzeWithStrategy(symbol, recommendedStrategies[0], marketData);
|
|
|
console.log(`✅ Strategy Analysis: ${strategyResult.signal} (confidence: ${strategyResult.confidence}%)`);
|
|
|
|
|
|
|
|
|
let advancedResult = null;
|
|
|
if (regime.regime.includes('volatile') || regime.regime.includes('breakout')) {
|
|
|
const { analyzeWithAdvancedStrategy } = await import('./advanced-strategies-v2.js');
|
|
|
advancedResult = analyzeWithAdvancedStrategy(symbol, 'liquidity-sweep-reversal', ohlcvData);
|
|
|
console.log(`✅ Advanced Strategy: ${advancedResult.signal}`);
|
|
|
}
|
|
|
|
|
|
|
|
|
const signals = [
|
|
|
{ signal: htsAnalysis.signal, weight: 0.40, confidence: htsAnalysis.confidence },
|
|
|
{ signal: strategyResult.signal, weight: 0.35, confidence: strategyResult.confidence },
|
|
|
];
|
|
|
|
|
|
if (advancedResult) {
|
|
|
signals.push({ signal: advancedResult.signal, weight: 0.25, confidence: advancedResult.confidence });
|
|
|
}
|
|
|
|
|
|
|
|
|
let buyScore = 0;
|
|
|
let sellScore = 0;
|
|
|
let totalConfidence = 0;
|
|
|
|
|
|
signals.forEach(s => {
|
|
|
const weightedConfidence = (s.confidence / 100) * s.weight;
|
|
|
if (s.signal === 'buy') {
|
|
|
buyScore += weightedConfidence;
|
|
|
} else if (s.signal === 'sell') {
|
|
|
sellScore += weightedConfidence;
|
|
|
}
|
|
|
totalConfidence += weightedConfidence;
|
|
|
});
|
|
|
|
|
|
let finalSignal = 'hold';
|
|
|
let finalConfidence = 50;
|
|
|
|
|
|
if (buyScore > sellScore && buyScore > 0.30) {
|
|
|
finalSignal = 'buy';
|
|
|
finalConfidence = Math.round((buyScore / totalConfidence) * 100);
|
|
|
} else if (sellScore > buyScore && sellScore > 0.30) {
|
|
|
finalSignal = 'sell';
|
|
|
finalConfidence = Math.round((sellScore / totalConfidence) * 100);
|
|
|
}
|
|
|
|
|
|
|
|
|
const atr = htsAnalysis.components.rsiMacd.details?.atr || (currentPrice * 0.02);
|
|
|
let entryPrice = currentPrice;
|
|
|
let stopLoss = 0;
|
|
|
let takeProfits = [];
|
|
|
|
|
|
if (finalSignal === 'buy') {
|
|
|
stopLoss = currentPrice - (atr * 1.5);
|
|
|
takeProfits = [
|
|
|
{ level: currentPrice + (atr * 2), type: 'TP1', percentage: 40 },
|
|
|
{ level: currentPrice + (atr * 3), type: 'TP2', percentage: 35 },
|
|
|
{ level: currentPrice + (atr * 5), type: 'TP3', percentage: 25 }
|
|
|
];
|
|
|
} else if (finalSignal === 'sell') {
|
|
|
stopLoss = currentPrice + (atr * 1.5);
|
|
|
takeProfits = [
|
|
|
{ level: currentPrice - (atr * 2), type: 'TP1', percentage: 40 },
|
|
|
{ level: currentPrice - (atr * 3), type: 'TP2', percentage: 35 },
|
|
|
{ level: currentPrice - (atr * 5), type: 'TP3', percentage: 25 }
|
|
|
];
|
|
|
}
|
|
|
|
|
|
|
|
|
const comprehensiveResult = {
|
|
|
symbol,
|
|
|
timestamp: new Date().toISOString(),
|
|
|
|
|
|
|
|
|
signal: finalSignal,
|
|
|
confidence: finalConfidence,
|
|
|
strength: finalConfidence > 80 ? 'very-strong' : finalConfidence > 65 ? 'strong' : finalConfidence > 50 ? 'medium' : 'weak',
|
|
|
|
|
|
|
|
|
regime: regime.regime,
|
|
|
regimeCharacteristics: regime.characteristics,
|
|
|
|
|
|
|
|
|
entryPrice,
|
|
|
stopLoss,
|
|
|
takeProfits,
|
|
|
riskRewardRatio: `1:${((takeProfits[takeProfits.length - 1]?.level || entryPrice) - entryPrice) / Math.abs(stopLoss - entryPrice) || 2}`,
|
|
|
|
|
|
|
|
|
htsAnalysis: {
|
|
|
signal: htsAnalysis.signal,
|
|
|
score: htsAnalysis.score,
|
|
|
confidence: htsAnalysis.confidence,
|
|
|
weights: htsAnalysis.weights
|
|
|
},
|
|
|
strategyAnalysis: {
|
|
|
strategy: strategyResult.strategy,
|
|
|
signal: strategyResult.signal,
|
|
|
confidence: strategyResult.confidence,
|
|
|
indicators: strategyResult.indicators
|
|
|
},
|
|
|
advancedAnalysis: advancedResult ? {
|
|
|
strategy: advancedResult.strategy,
|
|
|
signal: advancedResult.signal,
|
|
|
confidence: advancedResult.confidence
|
|
|
} : null,
|
|
|
|
|
|
|
|
|
voting: {
|
|
|
buyScore: Math.round(buyScore * 100),
|
|
|
sellScore: Math.round(sellScore * 100),
|
|
|
signals: signals.map(s => ({ signal: s.signal, weight: s.weight, confidence: s.confidence }))
|
|
|
},
|
|
|
|
|
|
|
|
|
recommendedStrategies: recommendedStrategies,
|
|
|
recommendation: generateRecommendation(finalSignal, finalConfidence, regime.regime)
|
|
|
};
|
|
|
|
|
|
console.log('✅ Comprehensive analysis complete');
|
|
|
return comprehensiveResult;
|
|
|
|
|
|
} catch (error) {
|
|
|
console.error('[Comprehensive Analysis] Error:', error);
|
|
|
return {
|
|
|
symbol,
|
|
|
signal: 'hold',
|
|
|
confidence: 0,
|
|
|
error: error.message,
|
|
|
timestamp: new Date().toISOString()
|
|
|
};
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function generateRecommendation(signal, confidence, regime) {
|
|
|
if (signal === 'buy' && confidence > 80) {
|
|
|
return `Strong BUY signal in ${regime} market. High probability setup with ${confidence}% confidence. Consider entering position with proper risk management.`;
|
|
|
} else if (signal === 'buy' && confidence > 60) {
|
|
|
return `BUY signal detected in ${regime} market. Moderate confidence (${confidence}%). Wait for confirmation or use smaller position size.`;
|
|
|
} else if (signal === 'sell' && confidence > 80) {
|
|
|
return `Strong SELL signal in ${regime} market. High probability setup with ${confidence}% confidence. Consider shorting or taking profits.`;
|
|
|
} else if (signal === 'sell' && confidence > 60) {
|
|
|
return `SELL signal detected in ${regime} market. Moderate confidence (${confidence}%). Wait for confirmation or use smaller position size.`;
|
|
|
} else {
|
|
|
return `HOLD position in ${regime} market. Mixed signals or low confidence (${confidence}%). Wait for clearer setup.`;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TradingMonitor {
|
|
|
constructor(symbols = ['BTC', 'ETH'], interval = 60000) {
|
|
|
this.symbols = symbols;
|
|
|
this.interval = interval;
|
|
|
this.isRunning = false;
|
|
|
this.results = new Map();
|
|
|
}
|
|
|
|
|
|
async start() {
|
|
|
this.isRunning = true;
|
|
|
console.log('[Trading Monitor] Starting...');
|
|
|
|
|
|
while (this.isRunning) {
|
|
|
for (const symbol of this.symbols) {
|
|
|
try {
|
|
|
|
|
|
const ohlcvData = await this.fetchOHLCVData(symbol);
|
|
|
const currentPrice = ohlcvData[ohlcvData.length - 1].close;
|
|
|
|
|
|
|
|
|
const analysis = await comprehensiveAnalysis(symbol, ohlcvData, currentPrice);
|
|
|
|
|
|
|
|
|
this.results.set(symbol, analysis);
|
|
|
|
|
|
|
|
|
if (analysis.confidence > 75 && analysis.signal !== 'hold') {
|
|
|
console.log(`🚨 HIGH CONFIDENCE SIGNAL: ${symbol} ${analysis.signal.toUpperCase()} (${analysis.confidence}%)`);
|
|
|
console.log(`Entry: ${analysis.entryPrice}, Stop: ${analysis.stopLoss}`);
|
|
|
console.log(`Targets: ${analysis.takeProfits.map(tp => tp.level).join(', ')}`);
|
|
|
}
|
|
|
} catch (error) {
|
|
|
console.error(`[Trading Monitor] Error analyzing ${symbol}:`, error);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
await new Promise(resolve => setTimeout(resolve, this.interval));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
stop() {
|
|
|
this.isRunning = false;
|
|
|
console.log('[Trading Monitor] Stopped');
|
|
|
}
|
|
|
|
|
|
getResults() {
|
|
|
return Object.fromEntries(this.results);
|
|
|
}
|
|
|
|
|
|
async fetchOHLCVData(symbol) {
|
|
|
|
|
|
|
|
|
const response = await fetch(`/api/ohlcv/${symbol}?interval=1h&limit=100`);
|
|
|
const data = await response.json();
|
|
|
return data.data || data.ohlcv || data;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async function integrateWithTradingAssistant() {
|
|
|
|
|
|
document.getElementById('get-signals-btn').addEventListener('click', async () => {
|
|
|
const selectedSymbol = getSelectedSymbol();
|
|
|
const selectedStrategy = getSelectedStrategy();
|
|
|
|
|
|
try {
|
|
|
|
|
|
const ohlcvData = await fetchOHLCVData(selectedSymbol);
|
|
|
const currentPrice = await fetchCurrentPrice(selectedSymbol);
|
|
|
|
|
|
|
|
|
const analysis = await comprehensiveAnalysis(selectedSymbol, ohlcvData, currentPrice);
|
|
|
|
|
|
|
|
|
displaySignalCard(analysis);
|
|
|
|
|
|
|
|
|
addToSignalHistory(analysis);
|
|
|
|
|
|
} catch (error) {
|
|
|
console.error('Analysis error:', error);
|
|
|
showToast('Analysis failed: ' + error.message, 'error');
|
|
|
}
|
|
|
});
|
|
|
|
|
|
|
|
|
const monitor = new TradingMonitor(['BTC', 'ETH', 'BNB'], 300000);
|
|
|
|
|
|
document.getElementById('toggle-monitor-btn').addEventListener('click', () => {
|
|
|
if (monitor.isRunning) {
|
|
|
monitor.stop();
|
|
|
} else {
|
|
|
monitor.start();
|
|
|
}
|
|
|
});
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export {
|
|
|
example1_basicStrategy,
|
|
|
example2_htsEngine,
|
|
|
example3_regimeDetection,
|
|
|
example4_advancedStrategies,
|
|
|
comprehensiveAnalysis,
|
|
|
TradingMonitor,
|
|
|
integrateWithTradingAssistant
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log('[Integration Guide] Loaded successfully ✅');
|
|
|
|
|
|
|