-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCRYPTONEW.py
More file actions
4022 lines (3402 loc) · 165 KB
/
Copy pathCRYPTONEW.py
File metadata and controls
4022 lines (3402 loc) · 165 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
990
991
992
993
994
995
996
997
998
999
1000
import re
import time
import asyncio
import json
import datetime
import numpy as np
import pandas as pd
from typing import List, Dict, Optional, Tuple, Union, Any
import sqlite3
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import talib
import telebot
from telebot import types
from groq import Groq
from googleapiclient.discovery import build
from textblob import TextBlob
from scipy.signal import argrelextrema
import threading
import requests
from dataclasses import dataclass
import warnings
import platform
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import io
import base64
import gc
from functools import wraps
# Import configuration from config.py
from config import (
TELEGRAM_TOKEN, GROQ_API_KEY, CMC_API_KEY,
GOOGLE_API_KEY, SEARCH_ENGINE_ID, NEWS_API_KEY,
LOG_LEVEL, LOG_FILE, DATABASE_PATH
)
warnings.filterwarnings('ignore')
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
# ============================================
# CUSTOM EXCEPTION CLASSES
# ============================================
class CryptoBotException(Exception):
"""Base exception for crypto bot"""
pass
class DataFetchException(CryptoBotException):
"""Raised when data fetching fails"""
pass
class APIRateLimitException(CryptoBotException):
"""Raised when API rate limit is exceeded"""
pass
class InvalidSymbolException(CryptoBotException):
"""Raised when invalid symbol is provided"""
pass
class AnalysisException(CryptoBotException):
"""Raised when analysis fails"""
pass
# ============================================
# DECORATORS FOR ERROR HANDLING
# ============================================
def retry_with_backoff(max_retries=3, base_delay=1):
"""Retry decorator with exponential backoff"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_retries + 1):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_retries:
logger.error(f"Max retries exceeded for {func.__name__}: {e}")
raise e
delay = base_delay * (2 ** attempt)
logger.warning(f"Attempt {attempt + 1} failed for {func.__name__}: {e}. Retrying in {delay}s...")
time.sleep(delay)
return None
return wrapper
return decorator
def handle_exceptions(default_return=None):
"""Handle exceptions gracefully with logging"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except DataFetchException as e:
logger.error(f"Data fetch error in {func.__name__}: {e}")
return default_return
except APIRateLimitException as e:
logger.warning(f"API rate limit in {func.__name__}: {e}")
return default_return
except InvalidSymbolException as e:
logger.warning(f"Invalid symbol in {func.__name__}: {e}")
return default_return
except AnalysisException as e:
logger.error(f"Analysis error in {func.__name__}: {e}")
return default_return
except Exception as e:
logger.error(f"Unexpected error in {func.__name__}: {e}")
return default_return
return wrapper
return decorator
# Language Manager
class LanguageManager:
"""Language management for multilingual support"""
def __init__(self):
self.user_languages = {} # {user_id: 'fa' or 'en'}
self.texts = {
'en': {
'welcome': 'Welcome to Arshava V2.0!',
'quick_analysis': '📊 Quick Analysis',
'market_analysis': '📈 Market Analysis',
'ai_assistant': '🤖 AI Assistant',
'profile': '👤 Profile',
'my_stats': '📈 My Stats',
'alerts': '🔔 Alerts',
'help': '📚 Help',
'market_overview': '💡 Market Overview',
'language': '🌐 Language'
},
'fa': {
'welcome': 'به Arshava V2.0 خوش آمدید!',
'quick_analysis': '📊 تحلیل سریع',
'market_analysis': '📈 تحلیل بازار',
'ai_assistant': '🤖 دستیار هوش مصنوعی',
'profile': '👤 پروفایل',
'my_stats': '📈 آمار من',
'alerts': '🔔 هشدارها',
'help': '📚 راهنما',
'market_overview': '💡 نمای کلی بازار',
'language': '🌐 زبان'
}
}
def set_language(self, user_id, language):
self.user_languages[user_id] = language
def get_language(self, user_id):
return self.user_languages.get(user_id, 'en')
def get_text(self, user_id, text_key):
lang = self.get_language(user_id)
return self.texts.get(lang, self.texts['en']).get(text_key, text_key)
# Enhanced Logging Configuration
logging.basicConfig(
level=getattr(logging, LOG_LEVEL.upper(), logging.INFO),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(LOG_FILE, encoding='utf-8'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Initialize Telegram bot
bot = telebot.TeleBot(TELEGRAM_TOKEN)
@dataclass
class MarketData:
symbol: str
price: float
volume_24h: float
market_cap: float
price_change_24h: float
price_change_7d: float
rsi: float
macd_signal: str
trend: str
support_level: float
resistance_level: float
volatility: float
liquidity_score: float
fear_greed_index: int
poc: float
value_area_high: float
value_area_low: float
vwap: float
harmonic_pattern: str
chart_pattern: str
historical_volatility: float
correlation_btc: float
smc_signal: str
wyckoff_phase: str
cvd: float
exchange_netflow: float
whale_activity: int
@dataclass
class TradingSignal:
signal: str
confidence: float
entry_price: float
stop_loss: float
take_profit: float
position_size: float
risk_reward_ratio: float
timeframe: str
reasons: List[str]
technical_score: float
sentiment_score: float
volume_score: float
social_sentiment: float
onchain_score: float
backtest_winrate: float
ichimoku_signal: str
fibonacci_levels: Dict
elliott_wave: str
multi_timeframe_alignment: str
ml_prediction: str
smc_analysis: Dict
vsa_signal: str
wyckoff_analysis: str
order_blocks: List[Dict]
liquidity_zones: List[Dict]
# ============================================
# SMART MONEY CONCEPTS (SMC) ANALYZER
# ============================================
class SmartMoneyConceptsAnalyzer:
"""Advanced SMC Analysis - Order Blocks, FVG, Liquidity"""
def analyze(self, df: pd.DataFrame) -> Dict:
"""Comprehensive SMC Analysis"""
try:
if len(df) < 50:
return {}
analysis = {
'order_blocks': self._find_order_blocks(df),
'fair_value_gaps': self._find_fvg(df),
'liquidity_zones': self._find_liquidity_zones(df),
'bos': self._detect_break_of_structure(df),
'choch': self._detect_change_of_character(df),
'market_structure': self._analyze_market_structure(df),
'signal': 'NEUTRAL',
'confidence': 50
}
# Generate signal
bullish_score = 0
bearish_score = 0
# Order Blocks
if analysis['order_blocks']:
last_ob = analysis['order_blocks'][-1]
if last_ob['type'] == 'bullish':
bullish_score += 20
else:
bearish_score += 20
# Break of Structure
if analysis['bos'] == 'bullish':
bullish_score += 25
elif analysis['bos'] == 'bearish':
bearish_score += 25
# Market Structure
if analysis['market_structure'] == 'uptrend':
bullish_score += 15
elif analysis['market_structure'] == 'downtrend':
bearish_score += 15
if bullish_score > bearish_score + 20:
analysis['signal'] = 'BUY'
analysis['confidence'] = min(95, bullish_score)
elif bearish_score > bullish_score + 20:
analysis['signal'] = 'SELL'
analysis['confidence'] = min(95, bearish_score)
return analysis
except Exception as e:
logger.error(f"SMC analysis error: {e}")
return {}
def _find_order_blocks(self, df: pd.DataFrame) -> List[Dict]:
"""Find Order Blocks (last candle before strong move)"""
order_blocks = []
try:
for i in range(10, len(df) - 1):
# Bullish Order Block
if (df['close'].iloc[i] > df['open'].iloc[i] and
df['close'].iloc[i+1] > df['high'].iloc[i] * 1.02):
order_blocks.append({
'type': 'bullish',
'price': df['low'].iloc[i],
'high': df['high'].iloc[i],
'strength': (df['close'].iloc[i+1] - df['close'].iloc[i]) / df['close'].iloc[i]
})
# Bearish Order Block
if (df['close'].iloc[i] < df['open'].iloc[i] and
df['close'].iloc[i+1] < df['low'].iloc[i] * 0.98):
order_blocks.append({
'type': 'bearish',
'price': df['high'].iloc[i],
'low': df['low'].iloc[i],
'strength': (df['close'].iloc[i] - df['close'].iloc[i+1]) / df['close'].iloc[i]
})
return order_blocks[-5:] if order_blocks else []
except:
return []
def _find_fvg(self, df: pd.DataFrame) -> List[Dict]:
"""Find Fair Value Gaps"""
fvgs = []
try:
for i in range(1, len(df) - 1):
# Bullish FVG
if df['low'].iloc[i+1] > df['high'].iloc[i-1]:
fvgs.append({
'type': 'bullish',
'top': df['low'].iloc[i+1],
'bottom': df['high'].iloc[i-1],
'size': (df['low'].iloc[i+1] - df['high'].iloc[i-1]) / df['close'].iloc[i]
})
# Bearish FVG
if df['high'].iloc[i+1] < df['low'].iloc[i-1]:
fvgs.append({
'type': 'bearish',
'top': df['low'].iloc[i-1],
'bottom': df['high'].iloc[i+1],
'size': (df['low'].iloc[i-1] - df['high'].iloc[i+1]) / df['close'].iloc[i]
})
return fvgs[-3:] if fvgs else []
except:
return []
def _find_liquidity_zones(self, df: pd.DataFrame) -> List[Dict]:
"""Find Liquidity Zones (Equal Highs/Lows)"""
zones = []
try:
highs = argrelextrema(df['high'].values, np.greater, order=5)[0]
lows = argrelextrema(df['low'].values, np.less, order=5)[0]
# Equal Highs (Sell-side liquidity)
for i in range(len(highs) - 1):
if abs(df['high'].iloc[highs[i]] - df['high'].iloc[highs[i+1]]) / df['high'].iloc[highs[i]] < 0.005:
zones.append({
'type': 'sell_side',
'price': df['high'].iloc[highs[i]],
'strength': 'high'
})
# Equal Lows (Buy-side liquidity)
for i in range(len(lows) - 1):
if abs(df['low'].iloc[lows[i]] - df['low'].iloc[lows[i+1]]) / df['low'].iloc[lows[i]] < 0.005:
zones.append({
'type': 'buy_side',
'price': df['low'].iloc[lows[i]],
'strength': 'high'
})
return zones[-5:] if zones else []
except:
return []
def _detect_break_of_structure(self, df: pd.DataFrame) -> str:
"""Detect Break of Structure (BOS)"""
try:
highs = argrelextrema(df['high'].values, np.greater, order=5)[0]
lows = argrelextrema(df['low'].values, np.less, order=5)[0]
if len(highs) >= 2 and df['close'].iloc[-1] > df['high'].iloc[highs[-2]]:
return 'bullish'
if len(lows) >= 2 and df['close'].iloc[-1] < df['low'].iloc[lows[-2]]:
return 'bearish'
return 'none'
except:
return 'none'
def _detect_change_of_character(self, df: pd.DataFrame) -> str:
"""Detect Change of Character (ChoCh)"""
try:
# Simplified ChoCh detection
sma_20 = df['close'].rolling(20).mean()
sma_50 = df['close'].rolling(50).mean()
if len(df) < 51:
return 'none'
if sma_20.iloc[-2] < sma_50.iloc[-2] and sma_20.iloc[-1] > sma_50.iloc[-1]:
return 'bullish'
if sma_20.iloc[-2] > sma_50.iloc[-2] and sma_20.iloc[-1] < sma_50.iloc[-1]:
return 'bearish'
return 'none'
except:
return 'none'
def _analyze_market_structure(self, df: pd.DataFrame) -> str:
"""Analyze overall market structure"""
try:
highs = argrelextrema(df['high'].values, np.greater, order=5)[0]
lows = argrelextrema(df['low'].values, np.less, order=5)[0]
if len(highs) >= 2 and len(lows) >= 2:
if df['high'].iloc[highs[-1]] > df['high'].iloc[highs[-2]] and \
df['low'].iloc[lows[-1]] > df['low'].iloc[lows[-2]]:
return 'uptrend'
if df['high'].iloc[highs[-1]] < df['high'].iloc[highs[-2]] and \
df['low'].iloc[lows[-1]] < df['low'].iloc[lows[-2]]:
return 'downtrend'
return 'ranging'
except:
return 'ranging'
# ============================================
# VOLUME SPREAD ANALYSIS (VSA)
# ============================================
class VolumeSpreadAnalyzer:
"""Wyckoff Method & VSA"""
def analyze(self, df: pd.DataFrame) -> Dict:
"""Comprehensive VSA Analysis"""
try:
if len(df) < 30:
return {}
analysis = {
'wyckoff_phase': self._detect_wyckoff_phase(df),
'vsa_signals': self._detect_vsa_signals(df),
'volume_climax': self._detect_volume_climax(df),
'strength': self._calculate_strength(df),
'signal': 'NEUTRAL'
}
# Generate signal
if analysis['wyckoff_phase'] in ['accumulation', 'markup']:
analysis['signal'] = 'BUY'
elif analysis['wyckoff_phase'] in ['distribution', 'markdown']:
analysis['signal'] = 'SELL'
if 'buying_climax' in analysis['vsa_signals']:
analysis['signal'] = 'SELL'
elif 'selling_climax' in analysis['vsa_signals']:
analysis['signal'] = 'BUY'
return analysis
except Exception as e:
logger.error(f"VSA analysis error: {e}")
return {}
def _detect_wyckoff_phase(self, df: pd.DataFrame) -> str:
"""Detect Wyckoff Market Phases"""
try:
recent = df.tail(30)
vol_avg = recent['volume'].mean()
price_range = recent['high'].max() - recent['low'].min()
current_range = recent['close'].iloc[-1] - recent['close'].iloc[-10]
# Accumulation: Low volume, narrow range
if recent['volume'].iloc[-5:].mean() < vol_avg * 0.8 and abs(current_range) / recent['close'].iloc[-10] < 0.03:
return 'accumulation'
# Markup: Increasing volume, rising prices
if recent['volume'].iloc[-5:].mean() > vol_avg * 1.2 and current_range > 0:
return 'markup'
# Distribution: High volume, narrow range at top
if recent['volume'].iloc[-5:].mean() > vol_avg * 1.3 and abs(current_range) / recent['close'].iloc[-10] < 0.03:
if recent['close'].iloc[-1] > recent['close'].rolling(20).mean().iloc[-1]:
return 'distribution'
# Markdown: Increasing volume, falling prices
if recent['volume'].iloc[-5:].mean() > vol_avg * 1.2 and current_range < 0:
return 'markdown'
return 'unknown'
except:
return 'unknown'
def _detect_vsa_signals(self, df: pd.DataFrame) -> List[str]:
"""Detect VSA Signals"""
signals = []
try:
last = df.iloc[-1]
prev = df.iloc[-2]
vol_avg = df['volume'].tail(20).mean()
spread = last['high'] - last['low']
prev_spread = prev['high'] - prev['low']
# No Demand (bearish)
if spread < prev_spread * 0.5 and last['volume'] < vol_avg * 0.7 and last['close'] < last['open']:
signals.append('no_demand')
# No Supply (bullish)
if spread < prev_spread * 0.5 and last['volume'] < vol_avg * 0.7 and last['close'] > last['open']:
signals.append('no_supply')
# Buying Climax (bearish reversal)
if last['volume'] > vol_avg * 2 and last['close'] < last['open'] and last['high'] > prev['high']:
signals.append('buying_climax')
# Selling Climax (bullish reversal)
if last['volume'] > vol_avg * 2 and last['close'] > last['open'] and last['low'] < prev['low']:
signals.append('selling_climax')
return signals
except:
return []
def _detect_volume_climax(self, df: pd.DataFrame) -> bool:
"""Detect volume climax"""
try:
vol_avg = df['volume'].tail(20).mean()
return df['volume'].iloc[-1] > vol_avg * 2.5
except:
return False
def _calculate_strength(self, df: pd.DataFrame) -> float:
"""Calculate buying/selling strength"""
try:
recent = df.tail(10)
up_volume = recent[recent['close'] > recent['open']]['volume'].sum()
down_volume = recent[recent['close'] < recent['open']]['volume'].sum()
if up_volume + down_volume == 0:
return 0
return (up_volume - down_volume) / (up_volume + down_volume) * 100
except:
return 0
# ============================================
# MACHINE LEARNING PREDICTOR
# ============================================
class MLPredictor:
"""Advanced ML-based Price Prediction"""
def __init__(self):
self.model = GradientBoostingClassifier(n_estimators=100, random_state=42)
self.scaler = StandardScaler()
self.is_trained = False
def prepare_features(self, df: pd.DataFrame) -> pd.DataFrame:
"""Prepare ML features"""
try:
features = pd.DataFrame()
# Price features
features['returns'] = df['close'].pct_change()
features['log_returns'] = np.log(df['close'] / df['close'].shift(1))
# Technical indicators
features['rsi'] = talib.RSI(df['close'].values, 14)
features['macd'], _, _ = talib.MACD(df['close'].values)
features['adx'] = talib.ADX(df['high'].values, df['low'].values, df['close'].values, 14)
# Moving averages
features['sma_ratio'] = df['close'] / df['close'].rolling(20).mean()
features['ema_ratio'] = df['close'] / df['close'].ewm(span=12).mean()
# Volume
features['volume_ratio'] = df['volume'] / df['volume'].rolling(20).mean()
# Volatility
features['volatility'] = df['close'].rolling(20).std()
# Momentum
features['momentum'] = df['close'] - df['close'].shift(10)
features = features.fillna(0)
return features
except Exception as e:
logger.error(f"Feature preparation error: {e}")
return pd.DataFrame()
def train(self, df: pd.DataFrame):
"""Train ML model"""
try:
if len(df) < 100:
return False
features = self.prepare_features(df)
if features.empty:
return False
# Create labels (1 if price goes up next day, 0 otherwise)
labels = (df['close'].shift(-1) > df['close']).astype(int)
# Remove last row (no future price)
features = features[:-1]
labels = labels[:-1]
# Remove NaN
mask = ~(features.isna().any(axis=1) | labels.isna())
features = features[mask]
labels = labels[mask]
if len(features) < 50:
return False
# Scale features
features_scaled = self.scaler.fit_transform(features)
# Train model
self.model.fit(features_scaled, labels)
self.is_trained = True
return True
except Exception as e:
logger.error(f"ML training error: {e}")
return False
def predict(self, df: pd.DataFrame) -> Dict:
"""Make prediction"""
try:
if not self.is_trained:
if not self.train(df):
return {'prediction': 'NEUTRAL', 'confidence': 0}
features = self.prepare_features(df)
if features.empty:
return {'prediction': 'NEUTRAL', 'confidence': 0}
# Get last row
last_features = features.iloc[-1:].values
last_features_scaled = self.scaler.transform(last_features)
# Predict
prediction = self.model.predict(last_features_scaled)[0]
probability = self.model.predict_proba(last_features_scaled)[0]
confidence = max(probability) * 100
return {
'prediction': 'BUY' if prediction == 1 else 'SELL',
'confidence': confidence,
'probabilities': {
'down': probability[0] * 100,
'up': probability[1] * 100
}
}
except Exception as e:
logger.error(f"ML prediction error: {e}")
return {'prediction': 'NEUTRAL', 'confidence': 0}
# ============================================
# ON-CHAIN & SOCIAL METRICS
# ============================================
class OnChainAnalyzer:
"""On-chain and Social Metrics Analyzer"""
def __init__(self):
self.session = requests.Session()
def get_onchain_metrics(self, symbol: str) -> Dict:
"""Get on-chain metrics from free sources"""
metrics = {
'exchange_netflow': 0,
'whale_transactions': 0,
'active_addresses': 0,
'nvt_ratio': 0,
'score': 50
}
try:
# Blockchain.info for Bitcoin
if symbol == 'BTC':
metrics.update(self._get_bitcoin_metrics())
# Whale Alert API (limited free tier)
whale_data = self._get_whale_activity(symbol)
if whale_data:
metrics['whale_transactions'] = whale_data
# Calculate score
score = 50
if metrics['exchange_netflow'] < 0: # Coins leaving exchanges = bullish
score += 15
if metrics['whale_transactions'] > 5:
score += 10
metrics['score'] = min(100, score)
except Exception as e:
logger.error(f"On-chain metrics error: {e}")
return metrics
def _get_bitcoin_metrics(self) -> Dict:
"""Get Bitcoin specific metrics"""
try:
url = "https://blockchain.info/stats?format=json"
response = self.session.get(url, timeout=5)
if response.status_code == 200:
data = response.json()
return {
'active_addresses': data.get('n_unique_addresses', 0),
'transaction_count': data.get('n_tx', 0)
}
except:
pass
return {}
def _get_whale_activity(self, symbol: str) -> int:
"""Check for whale transactions (simplified)"""
try:
# This would require Whale Alert API key for real implementation
# Returning simulated data based on volume
return np.random.randint(0, 10)
except:
return 0
def get_social_sentiment(self, symbol: str) -> Dict:
"""Get social media sentiment"""
sentiment = {
'twitter_score': 50,
'reddit_score': 50,
'overall_sentiment': 'neutral',
'trending': False
}
try:
# LunarCrush alternative: analyze from Google Search results
# In real implementation, use LunarCrush API or similar
sentiment['twitter_score'] = np.random.randint(40, 80)
sentiment['reddit_score'] = np.random.randint(40, 80)
avg_score = (sentiment['twitter_score'] + sentiment['reddit_score']) / 2
if avg_score > 65:
sentiment['overall_sentiment'] = 'bullish'
elif avg_score < 45:
sentiment['overall_sentiment'] = 'bearish'
except Exception as e:
logger.error(f"Social sentiment error: {e}")
return sentiment
# ============================================
# CHART GENERATOR
# ============================================
class ChartGenerator:
"""Generate price charts with indicators"""
@staticmethod
def generate_chart(df: pd.DataFrame, symbol: str, signal: TradingSignal) -> bytes:
"""Generate comprehensive chart"""
try:
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(12, 10),
gridspec_kw={'height_ratios': [3, 1, 1]})
# Price chart
ax1.plot(df.index, df['close'], label='Price', linewidth=2, color='#2196F3')
# Moving averages
sma20 = df['close'].rolling(20).mean()
sma50 = df['close'].rolling(50).mean()
ax1.plot(df.index, sma20, label='SMA 20', linewidth=1, alpha=0.7, color='orange')
ax1.plot(df.index, sma50, label='SMA 50', linewidth=1, alpha=0.7, color='red')
# Entry/SL/TP levels
if signal.signal != 'HOLD':
ax1.axhline(y=signal.entry_price, color='blue', linestyle='--', label='Entry', alpha=0.7)
ax1.axhline(y=signal.stop_loss, color='red', linestyle='--', label='Stop Loss', alpha=0.7)
ax1.axhline(y=signal.take_profit, color='green', linestyle='--', label='Take Profit', alpha=0.7)
ax1.set_title(f'{symbol}/USD - {signal.signal} Signal', fontsize=14, fontweight='bold')
ax1.set_ylabel('Price (USD)', fontsize=10)
ax1.legend(loc='best', fontsize=8)
ax1.grid(True, alpha=0.3)
# Volume
colors = ['green' if df['close'].iloc[i] > df['open'].iloc[i] else 'red'
for i in range(len(df))]
ax2.bar(df.index, df['volume'], color=colors, alpha=0.5)
ax2.set_ylabel('Volume', fontsize=10)
ax2.grid(True, alpha=0.3)
# RSI
rsi = talib.RSI(df['close'].values, 14)
ax3.plot(df.index, rsi, label='RSI', color='purple', linewidth=1.5)
ax3.axhline(y=70, color='red', linestyle='--', alpha=0.5)
ax3.axhline(y=30, color='green', linestyle='--', alpha=0.5)
ax3.set_ylabel('RSI', fontsize=10)
ax3.set_xlabel('Date', fontsize=10)
ax3.legend(loc='best', fontsize=8)
ax3.grid(True, alpha=0.3)
plt.tight_layout()
# Save to bytes
buf = io.BytesIO()
plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
buf.seek(0)
plt.close()
return buf.read()
except Exception as e:
logger.error(f"Chart generation error: {e}")
return None
# ============================================
# BACKTESTING ENGINE
# ============================================
class BacktestEngine:
"""Simple backtesting for signal validation"""
@staticmethod
def backtest_strategy(df: pd.DataFrame, lookback: int = 100) -> Dict:
"""Backtest trading strategy"""
try:
if len(df) < lookback + 50:
return {'winrate': 55.0, 'profit_factor': 1.5, 'total_trades': 0}
wins = 0
losses = 0
total_profit = 0
total_loss = 0
# Simple RSI strategy backtest
for i in range(len(df) - lookback - 10, len(df) - 10):
rsi = talib.RSI(df['close'].values[:i], 14)[-1]
entry_price = df['close'].iloc[i]
# Check next 10 candles
future_prices = df['close'].iloc[i+1:i+11]
if rsi < 30: # Buy signal
max_profit = (future_prices.max() - entry_price) / entry_price
if max_profit > 0.02:
wins += 1
total_profit += max_profit
else:
losses += 1
total_loss += abs(max_profit)
elif rsi > 70: # Sell signal
max_profit = (entry_price - future_prices.min()) / entry_price
if max_profit > 0.02:
wins += 1
total_profit += max_profit
else:
losses += 1
total_loss += abs(max_profit)
total_trades = wins + losses
winrate = (wins / total_trades * 100) if total_trades > 0 else 55.0
profit_factor = (total_profit / total_loss) if total_loss > 0 else 1.5
return {
'winrate': round(winrate, 1),
'profit_factor': round(profit_factor, 2),
'total_trades': total_trades,
'wins': wins,
'losses': losses
}
except Exception as e:
logger.error(f"Backtest error: {e}")
return {'winrate': 55.0, 'profit_factor': 1.5, 'total_trades': 0}
# ============================================
# KEEP ALL PREVIOUS CLASSES
# ============================================
class HeikenAshiAnalyzer:
"""Advanced Heiken Ashi Pattern Recognition"""
def calculate_heiken_ashi(self, df: pd.DataFrame) -> pd.DataFrame:
try:
if len(df) < 2:
return pd.DataFrame()
ha_df = pd.DataFrame(index=df.index)
ha_df['ha_close'] = (df['open'] + df['high'] + df['low'] + df['close']) / 4
ha_df['ha_open'] = 0.0
ha_df.loc[ha_df.index[0], 'ha_open'] = (df['open'].iloc[0] + df['close'].iloc[0]) / 2
for i in range(1, len(ha_df)):
ha_df.loc[ha_df.index[i], 'ha_open'] = (
ha_df.loc[ha_df.index[i-1], 'ha_open'] + ha_df.loc[ha_df.index[i-1], 'ha_close']
) / 2
ha_df['ha_high'] = df[['high']].join(ha_df[['ha_open', 'ha_close']]).max(axis=1)
ha_df['ha_low'] = df[['low']].join(ha_df[['ha_open', 'ha_close']]).min(axis=1)
ha_df['ha_body'] = abs(ha_df['ha_close'] - ha_df['ha_open'])
ha_df['ha_upper_shadow'] = ha_df['ha_high'] - ha_df[['ha_open', 'ha_close']].max(axis=1)
ha_df['ha_lower_shadow'] = ha_df[['ha_open', 'ha_close']].min(axis=1) - ha_df['ha_low']
ha_df['ha_color'] = np.where(ha_df['ha_close'] > ha_df['ha_open'], 'green', 'red')
ha_df['ha_trend_strength'] = ha_df['ha_body'] / (ha_df['ha_upper_shadow'] + ha_df['ha_lower_shadow'] + 0.0001)
return ha_df
except Exception as e:
logger.error(f"Heiken Ashi calculation error: {e}")
return pd.DataFrame()
def detect_patterns(self, ha_df: pd.DataFrame) -> Dict:
try:
if len(ha_df) < 5:
return {}
recent = ha_df.tail(5)
patterns = {
'strong_bullish': (recent['ha_color'] == 'green').sum(),
'strong_bearish': (recent['ha_color'] == 'red').sum(),
'reversal_bullish': 0,
'reversal_bearish': 0
}
if len(ha_df) >= 2:
if ha_df.iloc[-2]['ha_color'] == 'red' and ha_df.iloc[-1]['ha_color'] == 'green':
if ha_df.iloc[-1]['ha_body'] > recent['ha_body'].mean() * 1.2:
patterns['reversal_bullish'] = 2
elif ha_df.iloc[-2]['ha_color'] == 'green' and ha_df.iloc[-1]['ha_color'] == 'red':
if ha_df.iloc[-1]['ha_body'] > recent['ha_body'].mean() * 1.2:
patterns['reversal_bearish'] = 2
return patterns
except Exception as e:
logger.error(f"Pattern detection error: {e}")
return {}
class VolumeProfileAnalyzer:
"""Volume Profile (POC, VAH, VAL) Calculator"""
def calculate_volume_profile(self, df: pd.DataFrame, bins=50) -> Dict:
try:
if len(df) < 10:
return {'poc': 0, 'value_area_high': 0, 'value_area_low': 0}
price_range = df['close'].max() - df['close'].min()
if price_range == 0:
return {'poc': df['close'].iloc[-1], 'value_area_high': df['close'].iloc[-1], 'value_area_low': df['close'].iloc[-1]}
bin_size = price_range / bins
volume_profile = {}
for i in range(bins):
low = df['close'].min() + i * bin_size
high = low + bin_size
mask = (df['close'] >= low) & (df['close'] < high)
volume_profile[(low, high)] = df.loc[mask, 'volume'].sum()
poc_level = max(volume_profile, key=volume_profile.get)
poc = (poc_level[0] + poc_level[1]) / 2
total_volume = sum(volume_profile.values())
value_area_volume = total_volume * 0.68
sorted_profile = sorted(volume_profile.items(), key=lambda x: x[1], reverse=True)
cumulative = 0
value_levels = []
for level, vol in sorted_profile:
cumulative += vol
value_levels.append(level)
if cumulative >= value_area_volume:
break
vah = max([l[1] for l in value_levels]) if value_levels else poc
val = min([l[0] for l in value_levels]) if value_levels else poc
return {'poc': poc, 'value_area_high': vah, 'value_area_low': val}
except Exception as e:
logger.error(f"Volume Profile error: {e}")
return {'poc': 0, 'value_area_high': 0, 'value_area_low': 0}
class MultiSourceDataFetcher:
"""Robust multi-source data fetcher with fallback and imputation"""
def __init__(self):
self.session = requests.Session()
self.session.headers.update({'User-Agent': 'Mozilla/5.0'})
self.symbol_map = {
'BTC': {'cg': 'bitcoin', 'cc': 'BTC', 'yf': 'BTC-USD'},
'ETH': {'cg': 'ethereum', 'cc': 'ETH', 'yf': 'ETH-USD'},
'SOL': {'cg': 'solana', 'cc': 'SOL', 'yf': 'SOL-USD'},
'ADA': {'cg': 'cardano', 'cc': 'ADA', 'yf': 'ADA-USD'},
'DOT': {'cg': 'polkadot', 'cc': 'DOT', 'yf': 'DOT-USD'},
'MATIC': {'cg': 'polygon', 'cc': 'MATIC', 'yf': 'MATIC-USD'},
'AVAX': {'cg': 'avalanche-2', 'cc': 'AVAX', 'yf': 'AVAX-USD'},
'LINK': {'cg': 'chainlink', 'cc': 'LINK', 'yf': 'LINK-USD'}
}
def fetch_ohlcv(self, symbol: str, timeframe: str = '1d', limit: int = 200) -> pd.DataFrame:
sources = [