Skip to content

Natural-language trading calculator with AI-powered signal rating. Parse trades in plain English, get instant position sizing, and rate signal confidence with real-time market data.

License

Notifications You must be signed in to change notification settings

Monkeyattack/tradecalc

Repository files navigation

TradeCalc

Natural-Language Trading Calculator with AI-Powered Signal Rating

A mobile-first trading calculator that parses natural language queries (e.g., "buy gold at 2350 with 1% risk, TP 50 pips, SL 30 pips") and calculates precise position sizing, risk/reward ratios, and order levels. Now includes AI-powered signal confidence scoring with real-time market data and sentiment analysis.


🎯 Features

Core Calculator

  • Natural Language Parsing: Describe trades in plain English
  • Instant Position Sizing: Calculate lot sizes based on account risk
  • Risk/Reward Analysis: Automatic R:R calculations with pip distances
  • Multi-Instrument Support: Forex (EURUSD, GBPUSD), Gold (XAUUSD), Crypto (BTCUSD, ETHUSD)
  • Flexible Targets: Support for percentage, pips, or absolute price targets

AI Signal Rating (New) πŸš€

  • Real-Time Confidence Scoring: ML-powered analysis of trade setups
  • Gold Sentiment Analysis: ETF short interest tracking for XAUUSD
  • Market Data Integration: Live prices from Polygon.io
  • Risk Assessment: Automatic stop loss and take profit evaluation
  • Momentum Analysis: Price trend confirmation

Technical Indicators

  • Premium Data: 15-minute aggregates from Polygon.io
  • Pure Python Implementations: SMA, EMA, RSI, ATR
  • Trend Analysis: Real-time market regime detection

πŸ“± Architecture

TradeCalc
β”œβ”€β”€ Backend (Python/FastAPI)
β”‚   β”œβ”€β”€ Natural Language Parser
β”‚   β”œβ”€β”€ Position Calculator Engine
β”‚   β”œβ”€β”€ Signal Rating Service
β”‚   β”œβ”€β”€ Gold Sentiment Analyzer
β”‚   └── Polygon.io Integration
β”‚
└── Mobile App (React Native/Expo)
    β”œβ”€β”€ Calculator Screen
    β”œβ”€β”€ Signal Rating Screen
    └── Market Insights Screen

Tech Stack

Backend:

  • Python 3.10+
  • FastAPI (REST API)
  • Pydantic (data validation)
  • httpx (HTTP client)
  • Polygon.io API

Mobile:

  • React Native
  • Expo
  • TypeScript
  • React Navigation
  • Axios

Infrastructure:

  • PM2 (process management)
  • HashiCorp Vault (secrets)
  • Log rotation & monitoring

πŸš€ Quick Start

Backend Setup

# Clone repository
git clone https://github.com/yourusername/tradecalc.git
cd tradecalc

# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate  # Linux/Mac
# .venv\Scripts\activate   # Windows

# Install dependencies
pip install -e ".[dev]"

# Configure environment
cp .env.example .env
# Edit .env with your Polygon API key

# Start development server
uvicorn tradecalc.services.api:app --host 127.0.0.1 --port 8100 --reload

# Or use PM2 (production)
pm2 start ecosystem.mobile_calc.config.js

Mobile App Setup

cd mobile

# Install dependencies
npm install

# Configure API endpoint (mobile/app.json)
{
  "extra": {
    "apiBaseUrl": "http://localhost:8100",
    "premiumEnabled": true
  }
}

# Start Expo dev server
npm run start

# Run on device/emulator
npm run android  # or npm run ios

πŸ“– API Documentation

Health Check

GET http://localhost:8100/health

Response:

{
  "status": "ok"
}

Interpret Order

Parse natural language and calculate position.

POST http://localhost:8100/interpret
Content-Type: application/json

{
  "query": "buy gold at 2350 with 1% risk, TP 50 pips, SL 30 pips",
  "account_size": 25000,
  "risk_per_trade_percent": 1.0
}

Response:

{
  "symbol": "XAUUSD",
  "side": "buy",
  "entry_price": 2350.0,
  "take_profit": {
    "price": 2355.0,
    "distance_pips": 50,
    "distance_percent": 0.21
  },
  "stop_loss": {
    "price": 2347.0,
    "distance_pips": 30,
    "distance_percent": 0.13
  },
  "suggested_lot": {
    "lots": 0.083,
    "notional_value": 19517.5,
    "risk_amount": 250.0
  },
  "expected_reward_amount": 416.5,
  "expected_risk_amount": 250.0,
  "notes": ["Risk/reward ratio: 1.67:1"]
}

Rate Signal (New) πŸ”₯

AI-powered signal confidence rating.

POST http://localhost:8100/rate-signal
Content-Type: application/json

{
  "symbol": "XAUUSD",
  "action": "BUY",
  "entry_price": 4110.0,
  "stop_loss": 4100.0,
  "take_profit": 4150.0
}

Response:

{
  "symbol": "XAUUSD",
  "action": "BUY",
  "current_price": 4110.66,
  "confidence": 0.65,
  "recommendation": "buy",
  "reason": "Gold sentiment boost: +7.5% (High short interest suggests rally); Good risk/reward ratio (5.0:1): +10%; Positive momentum (+1.8%): +5%",
  "sentiment": {
    "sentiment": "bullish",
    "confidence": 0.5,
    "reason": "High short interest in gold proxies suggests potential rally",
    "weighted_squeeze": 0.52
  },
  "market_data": {
    "bid": 4110.47,
    "ask": 4110.84,
    "mid": 4110.66,
    "day_high": 4116.66,
    "day_low": 4024.38,
    "change_pct": 1.84
  }
}

Market Insights

GET http://localhost:8100/insights/XAUUSD

Response:

{
  "symbol": "XAUUSD",
  "trendLabel": "Bullish Momentum",
  "updatedAt": "2025-10-13T12:00:00Z",
  "indicators": [
    {"label": "SMA(20)", "value": "2345.23"},
    {"label": "EMA(20)", "value": "2348.15"},
    {"label": "RSI(14)", "value": "65.4"},
    {"label": "ATR(14)", "value": "12.8"}
  ]
}

🎨 Usage Examples

Natural Language Queries

# Basic query
"buy EURUSD at 1.0850"

# With risk management
"sell gold at 2350 risk 2% of my 50k account"

# With targets in pips
"buy GBPUSD at 1.2700 TP 100 pips SL 50 pips"

# With percentage targets
"sell BTCUSD at 62000 TP 3% SL 1.5%"

# With explicit prices
"buy XAUUSD at 2350 TP at 2400 SL at 2330"

# With lot size override
"sell EURUSD size 0.5 lots"

AI Signal Rating

Rate a Gold Buy Signal:

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
  }'

Rate a Crypto Sell Signal:

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

πŸ“Š Signal Confidence Scoring

The AI rating system analyzes multiple factors:

Base Confidence: 50% (neutral)

Enhancement Factors:

Gold Sentiment (XAUUSD only):

  • BUY + bullish sentiment: +15% Γ— sentiment confidence
  • SELL + bullish sentiment: -10% (warning)
  • SELL + bearish sentiment: +12% Γ— sentiment confidence

Stop Loss Analysis:

  • Very tight (<0.5%): -10%
  • Very wide (>5%): -15%

Risk/Reward Ratio:

  • R:R β‰₯ 2.0: +10%
  • R:R < 1.0: -10%

Price Momentum:

  • BUY + positive trend (>0.5%): +5%
  • SELL + negative trend (<-0.5%): +5%

Final Confidence: Capped at 0-95%

Recommendation Mapping:

  • β‰₯75%: Strong Buy/Sell
  • β‰₯60%: Buy/Sell
  • β‰₯45%: Neutral
  • β‰₯30%: Opposite recommendation
  • <30%: Strong opposite

πŸ—οΈ Project Structure

tradecalc/
β”œβ”€β”€ src/tradecalc/               # Python backend
β”‚   β”œβ”€β”€ data/
β”‚   β”‚   └── instruments.py       # Instrument specifications
β”‚   β”œβ”€β”€ engines/
β”‚   β”‚   └── calculator.py        # Position sizing engine
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ intent.py            # OrderIntent model
β”‚   β”‚   β”œβ”€β”€ results.py           # OrderCalculation model
β”‚   β”‚   └── ...
β”‚   └── services/
β”‚       β”œβ”€β”€ api.py               # FastAPI application
β”‚       β”œβ”€β”€ parser.py            # NLP parser
β”‚       β”œβ”€β”€ polygon_price.py     # Real-time prices
β”‚       β”œβ”€β”€ gold_sentiment.py    # Gold ETF analysis
β”‚       └── indicators.py        # Technical indicators
β”‚
β”œβ”€β”€ mobile/                      # React Native app
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ screens/
β”‚   β”‚   β”‚   β”œβ”€β”€ CalculatorScreen.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ SignalRatingScreen.tsx
β”‚   β”‚   β”‚   └── InsightsScreen.tsx
β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   └── api.ts           # API client
β”‚   β”‚   └── components/
β”‚   └── app.json
β”‚
β”œβ”€β”€ tests/                       # Python tests
β”œβ”€β”€ docs/                        # Documentation
β”œβ”€β”€ ecosystem.mobile_calc.config.js  # PM2 config
β”œβ”€β”€ pyproject.toml               # Python dependencies
└── README.md

πŸ§ͺ Testing

Python Backend

# Run all tests
pytest

# Run specific test
pytest tests/test_calculator.py -v

# Run with coverage
pytest --cov=tradecalc --cov-report=term

# Linting & formatting
ruff check src tests
ruff format src tests

Mobile App

cd mobile

# Run tests
npm test

# Type checking
npm run typecheck

# Linting
npm run lint

πŸ” Security & Configuration

Environment Variables

# Required
POLYGON_API_KEY=your_api_key_here

# Optional
TRADECALC_FORCE_STATIC_QUOTES=false
ENVIRONMENT=production

# Vault (optional)
VAULT_ADDR=https://vault.example.com:8200
VAULT_TOKEN=your_vault_token
VAULT_CACERT=/path/to/cert.pem

Secrets Management

  • API keys stored in .env (not committed)
  • HashiCorp Vault support for production
  • PM2 auto-loads environment from .env

πŸ“ˆ Production Deployment

Using PM2

# Start service
pm2 start ecosystem.mobile_calc.config.js

# Monitor
pm2 status mobile_calc-api
pm2 logs mobile_calc-api
pm2 monit

# Restart
pm2 restart mobile_calc-api

# Save configuration
pm2 save

Service Configuration:

  • Port: 8100 (localhost)
  • Workers: 2 Uvicorn processes
  • Memory limit: 512MB
  • Log rotation: 50MB files, 5 retained
  • Auto-restart on crash

πŸ“š Documentation


🀝 Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Run tests and linting
  4. Commit changes (git commit -m 'Add amazing feature')
  5. Push to branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

Code Style

Python:

  • Follow PEP 8
  • Use type hints
  • 100-char line length
  • Run ruff check and ruff format

TypeScript:

  • ESLint Universe config
  • Explicit types (avoid any)
  • camelCase for internal, snake_case for API

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • Polygon.io - Real-time market data
  • Expo - Mobile development framework
  • FastAPI - High-performance Python API framework

πŸ“ž Support

For issues, questions, or feature requests:

  • Open an issue on GitHub
  • Check CLAUDE.md for architecture details
  • Review PM2_SETUP.md for deployment help

Built with ❀️ for traders who want precision without complexity

About

Natural-language trading calculator with AI-powered signal rating. Parse trades in plain English, get instant position sizing, and rate signal confidence with real-time market data.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •