File size: 34,790 Bytes
b190b45 |
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 |
#!/usr/bin/env python3
"""
Technical Analysis API Router
Implements advanced trading analysis endpoints as described in help file
"""
from fastapi import APIRouter, HTTPException, Body, Query
from fastapi.responses import JSONResponse
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field
from datetime import datetime
import logging
import math
import statistics
logger = logging.getLogger(__name__)
router = APIRouter(tags=["Technical Analysis"])
# ============================================================================
# Pydantic Models
# ============================================================================
class OHLCVCandle(BaseModel):
"""OHLCV candle data model"""
t: Optional[int] = Field(None, description="Timestamp")
timestamp: Optional[int] = Field(None, description="Timestamp (alternative)")
o: Optional[float] = Field(None, description="Open price")
open: Optional[float] = Field(None, description="Open price (alternative)")
h: Optional[float] = Field(None, description="High price")
high: Optional[float] = Field(None, description="High price (alternative)")
l: Optional[float] = Field(None, description="Low price")
low: Optional[float] = Field(None, description="Low price (alternative)")
c: Optional[float] = Field(None, description="Close price")
close: Optional[float] = Field(None, description="Close price (alternative)")
v: Optional[float] = Field(None, description="Volume")
volume: Optional[float] = Field(None, description="Volume (alternative)")
class TAQuickRequest(BaseModel):
"""Request model for Quick Technical Analysis"""
symbol: str = Field(..., description="Cryptocurrency symbol")
timeframe: str = Field("4h", description="Timeframe")
ohlcv: List[Dict[str, Any]] = Field(..., description="Array of OHLCV candles")
class FAEvalRequest(BaseModel):
"""Request model for Fundamental Evaluation"""
symbol: str = Field(..., description="Cryptocurrency symbol")
whitepaper_summary: Optional[str] = Field(None, description="Whitepaper summary")
team_credibility_score: Optional[float] = Field(None, ge=0, le=10, description="Team credibility score")
token_utility_description: Optional[str] = Field(None, description="Token utility description")
total_supply_mechanism: Optional[str] = Field(None, description="Total supply mechanism")
class OnChainHealthRequest(BaseModel):
"""Request model for On-Chain Network Health"""
symbol: str = Field(..., description="Cryptocurrency symbol")
active_addresses_7day_avg: Optional[int] = Field(None, description="7-day average active addresses")
exchange_net_flow_24h: Optional[float] = Field(None, description="24h exchange net flow")
mrvv_z_score: Optional[float] = Field(None, description="MVRV Z-score")
class RiskAssessmentRequest(BaseModel):
"""Request model for Risk Assessment"""
symbol: str = Field(..., description="Cryptocurrency symbol")
historical_daily_prices: List[float] = Field(..., description="Historical daily prices (90 days)")
max_drawdown_percentage: Optional[float] = Field(None, description="Maximum drawdown percentage")
class ComprehensiveRequest(BaseModel):
"""Request model for Comprehensive Analysis"""
symbol: str = Field(..., description="Cryptocurrency symbol")
timeframe: str = Field("4h", description="Timeframe")
ohlcv: List[Dict[str, Any]] = Field(..., description="Array of OHLCV candles")
fundamental_data: Optional[Dict[str, Any]] = Field(None, description="Fundamental data")
onchain_data: Optional[Dict[str, Any]] = Field(None, description="On-chain data")
class TechnicalAnalyzeRequest(BaseModel):
"""Request model for complete technical analysis"""
symbol: str = Field(..., description="Cryptocurrency symbol")
timeframe: str = Field("4h", description="Timeframe")
ohlcv: List[Dict[str, Any]] = Field(..., description="Array of OHLCV candles")
indicators: Optional[Dict[str, bool]] = Field(None, description="Indicators to calculate")
patterns: Optional[Dict[str, bool]] = Field(None, description="Patterns to detect")
# ============================================================================
# Helper Functions
# ============================================================================
def normalize_candle(candle: Dict[str, Any]) -> Dict[str, float]:
"""Normalize candle data to standard format"""
return {
'timestamp': candle.get('t') or candle.get('timestamp', 0),
'open': float(candle.get('o') or candle.get('open', 0)),
'high': float(candle.get('h') or candle.get('high', 0)),
'low': float(candle.get('l') or candle.get('low', 0)),
'close': float(candle.get('c') or candle.get('close', 0)),
'volume': float(candle.get('v') or candle.get('volume', 0))
}
def calculate_rsi(prices: List[float], period: int = 14) -> float:
"""Calculate RSI (Relative Strength Index)"""
if len(prices) < period + 1:
return 50.0
deltas = [prices[i] - prices[i-1] for i in range(1, len(prices))]
gains = [d if d > 0 else 0 for d in deltas]
losses = [-d if d < 0 else 0 for d in deltas]
avg_gain = sum(gains[-period:]) / period
avg_loss = sum(losses[-period:]) / period
if avg_loss == 0:
return 100.0
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return round(rsi, 2)
def calculate_macd(prices: List[float], fast: int = 12, slow: int = 26, signal: int = 9) -> Dict[str, float]:
"""Calculate MACD indicator"""
if len(prices) < slow:
return {'macd': 0, 'signal': 0, 'histogram': 0}
# Simple EMA calculation
def ema(data, period):
multiplier = 2 / (period + 1)
ema_values = [data[0]]
for price in data[1:]:
ema_values.append((price - ema_values[-1]) * multiplier + ema_values[-1])
return ema_values
fast_ema = ema(prices, fast)
slow_ema = ema(prices, slow)
macd_line = [fast_ema[i] - slow_ema[i] for i in range(len(slow_ema))]
signal_line = ema(macd_line[-signal:], signal) if len(macd_line) >= signal else [0]
histogram = macd_line[-1] - signal_line[-1] if signal_line else 0
return {
'macd': round(macd_line[-1], 4),
'signal': round(signal_line[-1], 4),
'histogram': round(histogram, 4)
}
def calculate_sma(prices: List[float], period: int) -> float:
"""Calculate Simple Moving Average"""
if len(prices) < period:
return sum(prices) / len(prices) if prices else 0
return sum(prices[-period:]) / period
def calculate_ema(prices: List[float], period: int) -> float:
"""Calculate Exponential Moving Average"""
if len(prices) < period:
return sum(prices) / len(prices) if prices else 0
multiplier = 2 / (period + 1)
ema_value = sum(prices[:period]) / period
for price in prices[period:]:
ema_value = (price - ema_value) * multiplier + ema_value
return ema_value
def calculate_bollinger_bands(prices: List[float], period: int = 20, std_dev: float = 2.0) -> Dict[str, float]:
"""Calculate Bollinger Bands"""
if len(prices) < period:
sma = sum(prices) / len(prices) if prices else 0
return {'upper': sma, 'middle': sma, 'lower': sma}
sma = calculate_sma(prices, period)
recent_prices = prices[-period:]
# Calculate standard deviation
variance = sum((p - sma) ** 2 for p in recent_prices) / period
std = math.sqrt(variance)
return {
'upper': round(sma + (std_dev * std), 2),
'middle': round(sma, 2),
'lower': round(sma - (std_dev * std), 2),
'width': round(std_dev * std * 2, 2)
}
def find_support_resistance(candles: List[Dict[str, float]]) -> Dict[str, Any]:
"""Find support and resistance levels"""
if not candles:
return {'support': 0, 'resistance': 0, 'levels': []}
lows = [c['low'] for c in candles]
highs = [c['high'] for c in candles]
support = min(lows)
resistance = max(highs)
# Find pivot points
pivot_levels = []
for i in range(1, len(candles) - 1):
if candles[i]['low'] < candles[i-1]['low'] and candles[i]['low'] < candles[i+1]['low']:
pivot_levels.append(candles[i]['low'])
if candles[i]['high'] > candles[i-1]['high'] and candles[i]['high'] > candles[i+1]['high']:
pivot_levels.append(candles[i]['high'])
return {
'support': round(support, 2),
'resistance': round(resistance, 2),
'levels': [round(level, 2) for level in sorted(set(pivot_levels))[-5:]]
}
# ============================================================================
# Endpoints
# ============================================================================
@router.post("/api/technical/ta-quick")
async def ta_quick_analysis(request: TAQuickRequest):
"""
Quick Technical Analysis - Fast short-term trend and momentum analysis
"""
try:
if not request.ohlcv or len(request.ohlcv) < 20:
raise HTTPException(status_code=400, detail="At least 20 candles required for analysis")
# Normalize candles
candles = [normalize_candle(c) for c in request.ohlcv]
closes = [c['close'] for c in candles]
# Calculate indicators
rsi = calculate_rsi(closes)
macd = calculate_macd(closes)
sma20 = calculate_sma(closes, 20)
sma50 = calculate_sma(closes, 50) if len(closes) >= 50 else sma20
# Determine trend
current_price = closes[-1]
if current_price > sma20 > sma50:
trend = "Bullish"
elif current_price < sma20 < sma50:
trend = "Bearish"
else:
trend = "Neutral"
# Support/Resistance
sr = find_support_resistance(candles)
# Entry/Exit ranges
entry_range = {
'min': round(sr['support'] * 1.01, 2),
'max': round(current_price * 1.02, 2)
}
exit_range = {
'min': round(sr['resistance'] * 0.98, 2),
'max': round(sr['resistance'] * 1.05, 2)
}
return {
"success": True,
"trend": trend,
"rsi": rsi,
"macd": macd,
"sma20": round(sma20, 2),
"sma50": round(sma50, 2),
"support_resistance": sr,
"entry_range": entry_range,
"exit_range": exit_range,
"current_price": round(current_price, 2)
}
except Exception as e:
logger.error(f"Error in ta-quick analysis: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/api/technical/fa-eval")
async def fa_evaluation(request: FAEvalRequest):
"""
Fundamental Evaluation - Project fundamental analysis and long-term potential
"""
try:
# Calculate fundamental score
score = 5.0 # Base score
if request.team_credibility_score:
score += request.team_credibility_score * 0.3
if request.whitepaper_summary and len(request.whitepaper_summary) > 100:
score += 1.0
if request.token_utility_description and len(request.token_utility_description) > 50:
score += 1.0
if request.total_supply_mechanism:
score += 0.5
score = min(10.0, max(0.0, score))
# Determine growth potential
if score >= 8:
growth_potential = "High"
elif score >= 6:
growth_potential = "Medium"
else:
growth_potential = "Low"
justification = f"Fundamental analysis for {request.symbol} based on provided data. "
if request.team_credibility_score:
justification += f"Team credibility: {request.team_credibility_score}/10. "
justification += f"Overall score: {score:.1f}/10."
risks = [
"Market volatility may affect short-term price movements",
"Regulatory changes could impact project viability",
"Competition from other projects in the same space"
]
return {
"success": True,
"fundamental_score": round(score, 1),
"justification": justification,
"risks": risks,
"growth_potential": growth_potential
}
except Exception as e:
logger.error(f"Error in fa-eval: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/api/technical/onchain-health")
async def onchain_health_analysis(request: OnChainHealthRequest):
"""
On-Chain Network Health - Network health and whale behavior analysis
"""
try:
# Determine network phase
if request.exchange_net_flow_24h and request.exchange_net_flow_24h < -100000000:
network_phase = "Accumulation"
cycle_position = "Bottom Zone"
elif request.exchange_net_flow_24h and request.exchange_net_flow_24h > 100000000:
network_phase = "Distribution"
cycle_position = "Top Zone"
else:
network_phase = "Neutral"
cycle_position = "Mid Zone"
# Determine health status
health_score = 5.0
if request.active_addresses_7day_avg and request.active_addresses_7day_avg > 500000:
health_score += 2.0
if request.exchange_net_flow_24h and request.exchange_net_flow_24h < 0:
health_score += 1.5
if request.mrvv_z_score and request.mrvv_z_score < 0:
health_score += 1.5
health_score = min(10.0, max(0.0, health_score))
if health_score >= 7:
health_status = "Healthy"
elif health_score >= 5:
health_status = "Moderate"
else:
health_status = "Weak"
return {
"success": True,
"network_phase": network_phase,
"cycle_position": cycle_position,
"health_status": health_status,
"health_score": round(health_score, 1),
"active_addresses": request.active_addresses_7day_avg,
"exchange_flow_24h": request.exchange_net_flow_24h,
"mrvv_z_score": request.mrvv_z_score
}
except Exception as e:
logger.error(f"Error in onchain-health: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/api/technical/risk-assessment")
async def risk_assessment(request: RiskAssessmentRequest):
"""
Risk & Volatility Assessment - Risk and volatility evaluation
"""
try:
if len(request.historical_daily_prices) < 30:
raise HTTPException(status_code=400, detail="At least 30 days of price data required")
prices = request.historical_daily_prices
# Calculate volatility (standard deviation of returns)
returns = [(prices[i] - prices[i-1]) / prices[i-1] for i in range(1, len(prices))]
volatility = statistics.stdev(returns) if len(returns) > 1 else 0
# Calculate max drawdown
max_drawdown = request.max_drawdown_percentage
if not max_drawdown:
peak = prices[0]
max_dd = 0
for price in prices:
if price > peak:
peak = price
dd = (peak - price) / peak * 100
if dd > max_dd:
max_dd = dd
max_drawdown = max_dd
# Determine risk level
if volatility > 0.05 or max_drawdown > 30:
risk_level = "High"
elif volatility > 0.03 or max_drawdown > 20:
risk_level = "Medium"
else:
risk_level = "Low"
justification = f"Risk assessment based on volatility ({volatility:.4f}) and max drawdown ({max_drawdown:.1f}%). "
justification += f"Risk level: {risk_level}."
return {
"success": True,
"risk_level": risk_level,
"volatility": round(volatility, 4),
"max_drawdown": round(max_drawdown, 2),
"justification": justification
}
except Exception as e:
logger.error(f"Error in risk-assessment: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/api/technical/comprehensive")
async def comprehensive_analysis(request: ComprehensiveRequest):
"""
Comprehensive Analysis - Combined analysis from all modes
"""
try:
# Run TA Quick
ta_request = TAQuickRequest(
symbol=request.symbol,
timeframe=request.timeframe,
ohlcv=request.ohlcv
)
ta_result = await ta_quick_analysis(ta_request)
# Run FA Eval if data provided
fa_result = None
if request.fundamental_data:
fa_request = FAEvalRequest(
symbol=request.symbol,
**request.fundamental_data
)
fa_result = await fa_evaluation(fa_request)
# Run On-Chain Health if data provided
onchain_result = None
if request.onchain_data:
onchain_request = OnChainHealthRequest(
symbol=request.symbol,
**request.onchain_data
)
onchain_result = await onchain_health_analysis(onchain_request)
# Calculate overall scores
ta_score = 5.0
if ta_result.get('trend') == 'Bullish':
ta_score = 8.0
elif ta_result.get('trend') == 'Bearish':
ta_score = 3.0
fa_score = fa_result.get('fundamental_score', 5.0) if fa_result else 5.0
onchain_score = onchain_result.get('health_score', 5.0) if onchain_result else 5.0
# Overall recommendation
avg_score = (ta_score + fa_score + onchain_score) / 3
if avg_score >= 7:
recommendation = "BUY"
confidence = min(0.95, 0.7 + (avg_score - 7) * 0.05)
elif avg_score <= 4:
recommendation = "SELL"
confidence = min(0.95, 0.7 + (4 - avg_score) * 0.05)
else:
recommendation = "HOLD"
confidence = 0.65
executive_summary = f"Comprehensive analysis for {request.symbol}: "
executive_summary += f"Technical ({ta_score:.1f}/10), "
executive_summary += f"Fundamental ({fa_score:.1f}/10), "
executive_summary += f"On-Chain ({onchain_score:.1f}/10). "
executive_summary += f"Recommendation: {recommendation} with {confidence:.0%} confidence."
return {
"success": True,
"recommendation": recommendation,
"confidence": round(confidence, 2),
"executive_summary": executive_summary,
"ta_score": round(ta_score, 1),
"fa_score": round(fa_score, 1),
"onchain_score": round(onchain_score, 1),
"ta_analysis": ta_result,
"fa_analysis": fa_result,
"onchain_analysis": onchain_result
}
except Exception as e:
logger.error(f"Error in comprehensive analysis: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.post("/api/technical/analyze")
async def technical_analyze(request: TechnicalAnalyzeRequest):
"""
Complete Technical Analysis - Full analysis with all indicators and patterns
"""
try:
if not request.ohlcv or len(request.ohlcv) < 20:
raise HTTPException(status_code=400, detail="At least 20 candles required")
# Normalize candles
candles = [normalize_candle(c) for c in request.ohlcv]
closes = [c['close'] for c in candles]
highs = [c['high'] for c in candles]
lows = [c['low'] for c in candles]
volumes = [c['volume'] for c in candles]
# Default indicators
indicators_enabled = request.indicators or {
'rsi': True,
'macd': True,
'volume': True,
'ichimoku': False,
'elliott': True
}
# Default patterns
patterns_enabled = request.patterns or {
'gartley': True,
'butterfly': True,
'bat': True,
'crab': True,
'candlestick': True
}
# Calculate indicators
indicators = {}
if indicators_enabled.get('rsi', True):
indicators['rsi'] = calculate_rsi(closes)
if indicators_enabled.get('macd', True):
indicators['macd'] = calculate_macd(closes)
if indicators_enabled.get('volume', True):
indicators['volume_avg'] = sum(volumes[-20:]) / min(20, len(volumes))
indicators['volume_trend'] = 'increasing' if volumes[-1] > indicators['volume_avg'] else 'decreasing'
indicators['sma20'] = calculate_sma(closes, 20)
indicators['sma50'] = calculate_sma(closes, 50) if len(closes) >= 50 else indicators['sma20']
# Support/Resistance
sr = find_support_resistance(candles)
# Harmonic patterns (simplified detection)
harmonic_patterns = []
if patterns_enabled.get('gartley', True):
harmonic_patterns.append({
'type': 'Gartley',
'pattern': 'Bullish' if closes[-1] > closes[-5] else 'Bearish',
'confidence': 0.75
})
# Elliott Wave (simplified)
elliott_wave = None
if indicators_enabled.get('elliott', True):
wave_count = 5 if len(closes) >= 50 else 3
current_wave = 3 if closes[-1] > closes[-10] else 2
elliott_wave = {
'wave_count': wave_count,
'current_wave': current_wave,
'direction': 'up' if closes[-1] > closes[-5] else 'down'
}
# Candlestick patterns
candlestick_patterns = []
if patterns_enabled.get('candlestick', True) and len(candles) >= 2:
last_candle = candles[-1]
prev_candle = candles[-2]
body_size = abs(last_candle['close'] - last_candle['open'])
total_range = last_candle['high'] - last_candle['low']
if body_size < total_range * 0.1:
candlestick_patterns.append({'type': 'Doji', 'signal': 'Neutral'})
elif last_candle['close'] > last_candle['open'] and last_candle['low'] < prev_candle['low']:
candlestick_patterns.append({'type': 'Hammer', 'signal': 'Bullish'})
# Trading signals
signals = []
if indicators.get('rsi', 50) < 30:
signals.append({'type': 'BUY', 'source': 'RSI Oversold', 'strength': 'Strong'})
elif indicators.get('rsi', 50) > 70:
signals.append({'type': 'SELL', 'source': 'RSI Overbought', 'strength': 'Strong'})
if indicators.get('macd', {}).get('histogram', 0) > 0:
signals.append({'type': 'BUY', 'source': 'MACD Bullish', 'strength': 'Medium'})
# Trade recommendations
current_price = closes[-1]
trade_recommendations = {
'entry': round(sr['support'] * 1.01, 2),
'tp': round(sr['resistance'] * 0.98, 2),
'sl': round(sr['support'] * 0.98, 2)
}
return {
"success": True,
"support_resistance": sr,
"harmonic_patterns": harmonic_patterns,
"elliott_wave": elliott_wave,
"candlestick_patterns": candlestick_patterns,
"indicators": indicators,
"signals": signals,
"trade_recommendations": trade_recommendations
}
except Exception as e:
logger.error(f"Error in technical analyze: {e}")
raise HTTPException(status_code=500, detail=str(e))
# ============================================================================
# GET Endpoints for Direct Indicator Access (No POST body required)
# ============================================================================
async def _fetch_ohlcv_data(symbol: str, timeframe: str, limit: int = 200) -> List[Dict[str, Any]]:
"""Fetch OHLCV data from backend"""
try:
from backend.services.binance_client import BinanceClient
binance_client = BinanceClient()
symbol_upper = symbol.upper()
ohlcv_data = await binance_client.get_ohlcv(symbol_upper, timeframe, limit=limit)
return ohlcv_data or []
except Exception as e:
logger.error(f"Failed to fetch OHLCV for {symbol}: {e}")
# Try alternative source
try:
from backend.services.coingecko_client import coingecko_client
market_data = await coingecko_client.get_market_prices(symbols=[symbol_upper], limit=1)
if market_data:
# Return minimal OHLCV structure
return [{
'open': market_data[0].get('price', 0),
'high': market_data[0].get('price', 0),
'low': market_data[0].get('price', 0),
'close': market_data[0].get('price', 0),
'volume': 0,
'timestamp': int(datetime.utcnow().timestamp() * 1000)
}]
except:
pass
return []
@router.get("/api/technical/rsi")
async def get_rsi(
symbol: str = Query(..., description="Cryptocurrency symbol (e.g., BTC, ETH)"),
timeframe: str = Query("1h", description="Timeframe (1h, 4h, 1d)"),
period: int = Query(14, ge=1, le=50, description="RSI period"),
limit: int = Query(200, ge=20, le=500, description="Number of candles")
):
"""Get RSI (Relative Strength Index) indicator"""
try:
ohlcv_data = await _fetch_ohlcv_data(symbol, timeframe, limit)
if len(ohlcv_data) < period + 1:
raise HTTPException(status_code=400, detail=f"Not enough data. Need at least {period + 1} candles, got {len(ohlcv_data)}")
candles = [normalize_candle(c) for c in ohlcv_data]
closes = [c['close'] for c in candles]
rsi_value = calculate_rsi(closes, period)
return {
"success": True,
"symbol": symbol.upper(),
"timeframe": timeframe,
"indicator": "RSI",
"period": period,
"value": rsi_value,
"signal": "overbought" if rsi_value > 70 else "oversold" if rsi_value < 30 else "neutral",
"timestamp": datetime.utcnow().isoformat() + "Z"
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error calculating RSI: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/api/technical/macd")
async def get_macd(
symbol: str = Query(..., description="Cryptocurrency symbol"),
timeframe: str = Query("1h", description="Timeframe"),
fast: int = Query(12, ge=1, le=50, description="Fast EMA period"),
slow: int = Query(26, ge=1, le=100, description="Slow EMA period"),
signal: int = Query(9, ge=1, le=50, description="Signal line period"),
limit: int = Query(200, ge=50, le=500, description="Number of candles")
):
"""Get MACD (Moving Average Convergence Divergence) indicator"""
try:
ohlcv_data = await _fetch_ohlcv_data(symbol, timeframe, limit)
if len(ohlcv_data) < slow:
raise HTTPException(status_code=400, detail=f"Not enough data. Need at least {slow} candles")
candles = [normalize_candle(c) for c in ohlcv_data]
closes = [c['close'] for c in candles]
macd_data = calculate_macd(closes, fast, slow, signal)
return {
"success": True,
"symbol": symbol.upper(),
"timeframe": timeframe,
"indicator": "MACD",
"macd": macd_data['macd'],
"signal": macd_data['signal'],
"histogram": macd_data['histogram'],
"trend": "bullish" if macd_data['histogram'] > 0 else "bearish",
"timestamp": datetime.utcnow().isoformat() + "Z"
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error calculating MACD: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/api/technical/bollinger")
async def get_bollinger_bands(
symbol: str = Query(..., description="Cryptocurrency symbol"),
timeframe: str = Query("1h", description="Timeframe"),
period: int = Query(20, ge=5, le=50, description="SMA period"),
std_dev: float = Query(2.0, ge=1.0, le=3.0, description="Standard deviation multiplier"),
limit: int = Query(200, ge=20, le=500, description="Number of candles")
):
"""Get Bollinger Bands indicator"""
try:
ohlcv_data = await _fetch_ohlcv_data(symbol, timeframe, limit)
if len(ohlcv_data) < period:
raise HTTPException(status_code=400, detail=f"Not enough data. Need at least {period} candles")
candles = [normalize_candle(c) for c in ohlcv_data]
closes = [c['close'] for c in candles]
bb_data = calculate_bollinger_bands(closes, period, std_dev)
current_price = closes[-1]
# Determine position
if current_price > bb_data['upper']:
position = "above_upper"
signal = "overbought"
elif current_price < bb_data['lower']:
position = "below_lower"
signal = "oversold"
else:
position = "middle"
signal = "neutral"
return {
"success": True,
"symbol": symbol.upper(),
"timeframe": timeframe,
"indicator": "Bollinger Bands",
"period": period,
"std_dev": std_dev,
"upper": bb_data['upper'],
"middle": bb_data['middle'],
"lower": bb_data['lower'],
"width": bb_data['width'],
"current_price": round(current_price, 2),
"position": position,
"signal": signal,
"timestamp": datetime.utcnow().isoformat() + "Z"
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error calculating Bollinger Bands: {e}")
raise HTTPException(status_code=500, detail=str(e))
@router.get("/api/technical/indicators")
async def get_all_indicators(
symbol: str = Query(..., description="Cryptocurrency symbol"),
timeframe: str = Query("1h", description="Timeframe"),
rsi_period: int = Query(14, ge=1, le=50, description="RSI period"),
macd_fast: int = Query(12, ge=1, le=50, description="MACD fast period"),
macd_slow: int = Query(26, ge=1, le=100, description="MACD slow period"),
bb_period: int = Query(20, ge=5, le=50, description="Bollinger Bands period"),
limit: int = Query(200, ge=50, le=500, description="Number of candles")
):
"""Get all technical indicators at once (RSI, MACD, Bollinger Bands, SMA, EMA)"""
try:
ohlcv_data = await _fetch_ohlcv_data(symbol, timeframe, limit)
if len(ohlcv_data) < max(rsi_period + 1, macd_slow, bb_period):
raise HTTPException(status_code=400, detail="Not enough data for all indicators")
candles = [normalize_candle(c) for c in ohlcv_data]
closes = [c['close'] for c in candles]
current_price = closes[-1]
# Calculate all indicators
rsi = calculate_rsi(closes, rsi_period)
macd = calculate_macd(closes, macd_fast, macd_slow)
bb = calculate_bollinger_bands(closes, bb_period)
sma20 = calculate_sma(closes, 20)
sma50 = calculate_sma(closes, 50) if len(closes) >= 50 else sma20
ema20 = calculate_ema(closes, 20)
# Support/Resistance
sr = find_support_resistance(candles)
return {
"success": True,
"symbol": symbol.upper(),
"timeframe": timeframe,
"current_price": round(current_price, 2),
"indicators": {
"rsi": {
"value": rsi,
"period": rsi_period,
"signal": "overbought" if rsi > 70 else "oversold" if rsi < 30 else "neutral"
},
"macd": {
"macd": macd['macd'],
"signal": macd['signal'],
"histogram": macd['histogram'],
"trend": "bullish" if macd['histogram'] > 0 else "bearish"
},
"bollinger_bands": {
"upper": bb['upper'],
"middle": bb['middle'],
"lower": bb['lower'],
"width": bb['width'],
"position": "above_upper" if current_price > bb['upper'] else "below_lower" if current_price < bb['lower'] else "middle"
},
"sma": {
"sma20": round(sma20, 2),
"sma50": round(sma50, 2),
"trend": "bullish" if current_price > sma20 > sma50 else "bearish" if current_price < sma20 < sma50 else "neutral"
},
"ema": {
"ema20": round(ema20, 2)
}
},
"support_resistance": sr,
"timestamp": datetime.utcnow().isoformat() + "Z"
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error calculating indicators: {e}")
raise HTTPException(status_code=500, detail=str(e))
|