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.
- 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
- 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
- Premium Data: 15-minute aggregates from Polygon.io
- Pure Python Implementations: SMA, EMA, RSI, ATR
- Trend Analysis: Real-time market regime detection
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
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
# 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
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
GET http://localhost:8100/health
Response:
{
"status": "ok"
}
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"]
}
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
}
}
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"}
]
}
# 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"
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
}'
The AI rating system analyzes multiple 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%
- β₯75%: Strong Buy/Sell
- β₯60%: Buy/Sell
- β₯45%: Neutral
- β₯30%: Opposite recommendation
- <30%: Strong opposite
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
# 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
cd mobile
# Run tests
npm test
# Type checking
npm run typecheck
# Linting
npm run lint
# 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
- API keys stored in
.env
(not committed) - HashiCorp Vault support for production
- PM2 auto-loads environment from
.env
# 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
- SIGNAL_RATING_INTEGRATION.md - AI signal rating feature
- PM2_SETUP.md - Production deployment guide
- CLAUDE.md - Architecture & development guide
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Run tests and linting
- Commit changes (
git commit -m 'Add amazing feature'
) - Push to branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Python:
- Follow PEP 8
- Use type hints
- 100-char line length
- Run
ruff check
andruff format
TypeScript:
- ESLint Universe config
- Explicit types (avoid
any
) - camelCase for internal, snake_case for API
This project is licensed under the MIT License - see the LICENSE file for details.
- Polygon.io - Real-time market data
- Expo - Mobile development framework
- FastAPI - High-performance Python API framework
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