Skip to content

Latest commit

 

History

History
394 lines (325 loc) · 11.1 KB

File metadata and controls

394 lines (325 loc) · 11.1 KB

Signal Rating Integration

Overview

Added gold sentiment analysis and comprehensive signal rating functionality to the TradeCalc mobile app, bringing the same AI-powered confidence scoring from meta-trader-hub to TradeCalc.

What Was Added

Backend Services (Python)

1. /src/tradecalc/services/polygon_price.py (179 lines)

Purpose: Enhanced Polygon.io price service with comprehensive market data

Key Features:

  • Real-time bid/ask/mid prices
  • Daily OHLC data (open, high, low, close)
  • Price changes and percentages
  • Volume data
  • Correct symbol format mapping (e.g., XAUUSDC:XAUUSD)
  • Automatic forex/crypto market fallback

Critical Fix: Uses correct Polygon.io symbol format without hyphens for gold (C:XAUUSD, not C:XAU-USD)

Usage:

from tradecalc.services.polygon_price import get_polygon_price_service

price_service = get_polygon_price_service()
price_data = price_service.get_current_price('XAUUSD')
# Returns: bid, ask, mid, day_high, day_low, change_pct, etc.

2. /src/tradecalc/services/gold_sentiment.py (193 lines)

Purpose: Gold market sentiment analyzer using ETF proxy short interest

Proxy Strategy:

  • Gold Miner ETFs (GDX, GDXJ): 50% weight
  • Physical Gold ETFs (GLD, IAU): 30% weight
  • Leveraged Miner ETFs (NUGT, JNUG): 20% weight

Sentiment Calculation:

  • High short interest (>60%) → bullish (potential squeeze)
  • Moderate short interest (40-60%) → neutral_bullish
  • Low short interest (25-40%) → neutral
  • Very low short interest (<25%) → bearish

Usage:

from tradecalc.services.gold_sentiment import get_gold_sentiment_analyzer

analyzer = get_gold_sentiment_analyzer()
sentiment = analyzer.analyze_gold_sentiment('XAUUSD')
# Returns: sentiment, confidence, reason, weighted_squeeze, proxy_data

Note: Polygon.io may not provide short interest data for ETFs (data source limitation). The architecture is correct and will work when data becomes available or alternative sources are integrated.

3. /src/tradecalc/services/api.py - New Endpoint

Endpoint: POST /rate-signal

Request Model:

{
  "symbol": "XAUUSD",
  "action": "BUY",
  "entry_price": 4110.0,  // optional, uses current price if omitted
  "stop_loss": 4100.0,     // optional
  "take_profit": 4150.0    // optional
}

Response Model:

{
  "symbol": "XAUUSD",
  "action": "BUY",
  "current_price": 4110.48,
  "confidence": 0.65,
  "recommendation": "buy",
  "reason": "Gold sentiment boost: +7.5% (High short interest in gold proxies suggests potential rally); Good risk/reward ratio (5.0:1): +10%",
  "sentiment": {
    "sentiment": "bullish",
    "confidence": 0.5,
    "reason": "High short interest in gold proxies suggests potential rally",
    "weighted_squeeze": 0.52,
    "data_coverage": 0.67,
    "analyzed_at": "2025-10-13T..."
  },
  "market_data": {
    "bid": 4110.25,
    "ask": 4110.71,
    "mid": 4110.48,
    "day_open": 4095.30,
    "day_high": 4122.15,
    "day_low": 4088.42,
    "day_close": 4110.48,
    "change_pct": 0.37
  },
  "entry_price": 4110.0,
  "stop_loss": 4100.0,
  "take_profit": 4150.0
}

Confidence Enhancement Logic:

  1. Base Confidence: Starts at 50% (neutral)

  2. Gold Sentiment Boost (XAUUSD only):

    • BUY + bullish sentiment: +15% × sentiment_confidence
    • SELL + bullish sentiment: -10% (warning)
    • SELL + bearish sentiment: +12% × sentiment_confidence
  3. Stop Loss Analysis:

    • Very tight (<0.5%): -10%
    • Very wide (>5%): -15%
  4. Risk/Reward Ratio:

    • R:R ≥ 2.0: +10%
    • R:R < 1.0: -10%
  5. Price Momentum:

    • BUY + positive change (>0.5%): +5%
    • SELL + negative change (<-0.5%): +5%
  6. Final Confidence: Capped at 0-95%

Recommendation Mapping:

  • ≥75%: strong_buy / strong_sell
  • ≥60%: buy / sell
  • ≥45%: neutral
  • ≥30%: sell / buy (opposite)
  • <30%: strong_sell / strong_buy (opposite)

Mobile App (React Native)

4. /mobile/src/services/api.ts - API Types

Added TypeScript types and API function:

  • RateSignalRequest type
  • SignalRating response type
  • rateSignal() function

5. /mobile/src/screens/SignalRatingScreen.tsx (456 lines)

Purpose: Full-featured signal rating UI with real-time analysis

Key Features:

  • Symbol selection chips (XAUUSD, BTCUSD, ETHUSD, EURUSD, GBPUSD)
  • BUY/SELL action toggle
  • Optional entry price, stop loss, take profit inputs
  • Real-time confidence scoring
  • Visual confidence bar with color coding
  • Detailed analysis breakdown
  • Gold sentiment display (when available)
  • Market data snapshot (bid/ask, high/low, change %)

UI Design:

  • Dark gradient background (#050C1A#0B172D)
  • Color-coded recommendations:
    • Strong Buy: #10B981 (green)
    • Buy: #34D399 (light green)
    • Neutral: #FBBF24 (yellow)
    • Sell: #F87171 (light red)
    • Strong Sell: #EF4444 (red)

6. /mobile/App.tsx - Navigation

  • Added SignalRating screen to navigation stack
  • Added deep linking: /signal-rating
  • Updated RootStackParamList type

7. /mobile/src/screens/CalculatorScreen.tsx - Navigation Link

  • Added "Rate Signal" link in header alongside "Insights"
  • Users can navigate to signal rating from calculator screen

How It Works

User Flow:

  1. User opens TradeCalc mobile app
  2. Navigates to "Rate Signal" from header
  3. Selects symbol (e.g., XAUUSD)
  4. Chooses action (BUY or SELL)
  5. Optionally enters entry price, SL, TP
  6. Taps "Rate Signal"
  7. Backend fetches:
    • Current market price from Polygon.io
    • Gold sentiment (if XAUUSD)
    • Calculates confidence using enhancement logic
  8. App displays:
    • Confidence score (0-100%)
    • Recommendation badge (strong buy/buy/neutral/sell/strong sell)
    • Analysis breakdown
    • Gold sentiment details (if applicable)
    • Market data snapshot

Technical Flow:

Mobile App (React Native)
    ↓ POST /rate-signal
FastAPI Backend
    ↓ get_current_price()
Polygon Price Service → Polygon.io API
    ↓
    ↓ analyze_gold_sentiment() [if XAUUSD]
Gold Sentiment Analyzer → Polygon.io API (ETF data)
    ↓
Confidence Enhancement Logic
    ↓
SignalRating Response
    ↓
Mobile App UI Display

Deployment Instructions

Backend Deployment:

  1. Ensure Polygon API Key in Vault:

    vault kv get secret/polygon
    # Should return: api_key=your_key_here
  2. Restart TradeCalc Service:

    pm2 restart mobile_calc-api
    pm2 logs mobile_calc-api --lines 50
  3. Verify Health:

    curl http://localhost:8100/health
    # Should return: {"status": "ok"}
  4. Test Rate-Signal Endpoint:

    curl -X POST http://localhost:8100/rate-signal \
      -H "Content-Type: application/json" \
      -d '{
        "symbol": "XAUUSD",
        "action": "BUY",
        "stop_loss": 4100.0,
        "take_profit": 4150.0
      }'

Mobile App Deployment:

  1. Install Dependencies (if needed):

    cd /home/claude-dev/repos/tradecalc/mobile
    npm install
  2. Configure API Base URL (in mobile/app.json):

    {
      "extra": {
        "apiBaseUrl": "http://localhost:8100",
        "premiumEnabled": true
      }
    }
  3. Start Dev Server:

    npm run start
  4. Run on Device/Emulator:

    npm run android  # or npm run ios

Testing Checklist

  • Backend API responds to /rate-signal POST requests
  • Polygon price service fetches accurate gold price
  • Gold sentiment analyzer returns sentiment data
  • Confidence enhancement logic applies correctly
  • Mobile app navigates to Signal Rating screen
  • Form inputs work (symbol, action, prices)
  • "Rate Signal" button triggers API call
  • Loading indicator appears during API call
  • Error messages display on failure
  • Results panel shows confidence score
  • Recommendation badge has correct color
  • Gold sentiment section appears for XAUUSD
  • Market data displays correctly
  • Navigation back to Calculator works

Known Limitations

1. ETF Short Interest Data

Issue: Polygon.io may not provide short interest data for ETFs (GLD, GDX, GDXJ, etc.)

Workaround Options:

  • Use individual gold mining stocks instead of ETFs (e.g., NEM, GOLD, AEM)
  • Integrate CFTC COT (Commitment of Traders) data for gold futures positioning
  • Consider paid data sources for ETF short interest (IEX, NYSE)

Architecture Status: ✅ Code is correct and ready; just needs data source integration

2. Symbol Support

Current: XAUUSD gets full gold sentiment analysis Other Symbols: BTCUSD, ETHUSD, EURUSD, GBPUSD get basic price-based analysis only

Future: Extend crypto sentiment (already implemented in meta-trader-hub) to TradeCalc

3. Cache Strategy

Current: No caching implemented Future: Add Redis caching for:

  • Polygon price data (5-minute cache)
  • Gold sentiment analysis (24-hour cache)
  • Short interest data (bi-monthly refresh)

Comparison: meta-trader-hub vs TradeCalc

Feature meta-trader-hub TradeCalc
Gold Sentiment ✅ Implemented ✅ Implemented
Crypto Short Squeeze ✅ Implemented ❌ Not yet
TradingView Indicators ✅ Integrated ❌ Not yet
ML Confidence ✅ XGBoost model ❌ Not yet
Signal Rating UI ❌ Terminal only ✅ Mobile UI
Natural Language Parser ❌ Not applicable ✅ Core feature

Future Enhancements

Phase 2: Crypto Sentiment

  • Copy CryptoShortAnalyzer from meta-trader-hub
  • Apply to BTCUSD, ETHUSD, SOLUSD
  • Use equity proxies: MSTR, COIN, MARA, RIOT

Phase 3: TradingView Integration

  • Copy TradingViewScanner from meta-trader-hub
  • Add RSI, MACD, ADX analysis
  • Apply to all symbols

Phase 4: ML Confidence

  • Copy MLModelPredictor from meta-trader-hub
  • Train models on TradeCalc signal history
  • Combine with sentiment analysis

Phase 5: Caching & Performance

  • Implement Redis caching
  • Add rate limiting
  • Optimize API response times

Related Documentation

  • /home/claude-dev/repos/meta-trader-hub/backend/GOLD_SENTIMENT_ENHANCEMENT.md - Original implementation
  • /home/claude-dev/repos/meta-trader-hub/backend/services/data/gold_sentiment_analyzer.py - Source code
  • /home/claude-dev/repos/tradecalc/CLAUDE.md - TradeCalc architecture guide

API Integration Examples

Example 1: Rate Gold BUY Signal

curl -X POST http://localhost:8100/rate-signal \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "XAUUSD",
    "action": "BUY",
    "entry_price": 4110.0,
    "stop_loss": 4100.0,
    "take_profit": 4150.0
  }'

Example 2: Rate Crypto Signal (No Entry Price)

curl -X POST http://localhost:8100/rate-signal \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "BTCUSD",
    "action": "SELL",
    "stop_loss": 62000.0,
    "take_profit": 58000.0
  }'

Example 3: Quick Rating (Minimal Params)

curl -X POST http://localhost:8100/rate-signal \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "EURUSD",
    "action": "BUY"
  }'

Created: 2025-10-13 Status: ✅ Implementation Complete Next Steps: Deploy and test end-to-end