AI Signal Blueprint

How I Engineered an 79% Win-Rate Trading Algorithm

By Charl Van Zyl | RABITAI Trading Signals

JOIN THE COMMUNITY
Built for precision. Driven by Data.

Introduction

I set out to build a data-driven, adaptive trading system. Over 18 months, RabitAI evolved into an institutional-grade AI engine, delivering 2–5 actionable signals daily with up to 87% win rates across equities, crypto, forex and commodities.

  • No more gut feeling—pure logic and data
  • Multi-timeframe, multi-asset adaptability
  • Combines technicals, news, and AI reasoning

This blueprint reveals the exact process, from architecture to execution, so you can understand and replicate high-conviction AI trading signals.

System Architecture

Data Flow
  1. Ingest price data (Capital.com, yFinance fallback)
  2. Extract technical indicators (15m, 30m, 1H, 4H)
  3. Compute features: trend, momentum, volatility, sentiment
  4. Score trades with calculate_trade_probability()
  5. Validate with GPT & news sentiment
  6. Generate HTML report & chart, send via email
Core Technologies
  • tradingview_ta – technical indicators
  • openai – GPT-4 for reasoning & sentiment
  • pandas, numpy, scipy – data & modeling
  • scikit-learn – regression & scaling
  • arch – volatility modeling
  • feedparser, vaderSentiment, newsapi – news & sentiment
  • smtplib, MIME – email delivery
Modular Design
  • signals.py – main runtime
  • feature_engineering.py – feature construction
  • sentiment.py – sentiment analysis
  • charting.py – chart generation
  • email_report.py – HTML/email output
  • execution.py – trading API (optional)

Feature Engineering

80% of the system's edge comes from robust feature engineering. RabitAI fuses technical, volatility, and structure features across multiple timeframes.

Technical Indicators (per timeframe)
  • RSI, Stochastic RSI
  • EMA(9), EMA(21)
  • MACD Histogram
  • ADX, +DI / -DI
  • CCI, Bollinger %B, MFI, OBV
Volatility & Structure
  • ATR (Average True Range)
  • Shannon entropy (20-period log returns)
  • Bollinger Band width
  • Realized Volatility vs ATR
  • Trend strength (normalized ADX)
  • Slope angle (linear regression)
Sample Feature Extraction
def extract_features(df):
    features = {}
    # ...calculate indicators...
    features['ema_gap'] = df['ema9'].iloc[-1] - df['ema21'].iloc[-1]
    features['rsi'] = df['rsi'].iloc[-1]
    features['adx'] = df['adx'].iloc[-1]
    features['atr'] = df['atr'].iloc[-1]
    features['cci'] = df['cci'].iloc[-1]
    return features

All features are normalized (Z-score or min-max) before being passed to the probability model.

Market Regime Detection

RabitAI adapts to trending and mean-reverting markets by classifying regimes using entropy, ADX, and volatility relationships.

Detection Logic
  • Low entropy + high ADX → Momentum
  • High entropy + low ADX → Mean-Reverting
  • Volatility divergence → Unstable
Strategy Switching
  • Momentum: Breakouts, longer holds, wider TP
  • Mean-Reverting: Short trades, tighter SL, or skip
def detect_regime(features):
    if features['entropy'] < 1.0 and features['adx'] > 25:
        return 'momentum'
    elif features['entropy'] > 1.7 and features['adx'] < 20:
        return 'mean-reverting'
    return 'neutral'

Probability Scoring

Each signal is scored for confidence using a logistic model, trend scaling, entropy filtering, and sentiment alignment. Only high-confidence trades are sent.

def calculate_trade_probability(features):
    base = 0.0
    base += 0.3 * (features['ema_gap'])
    base += 0.25 * (features['rsi'] - 50)/50
    base += 0.2 * (features['adx'] / 50)
    base -= 0.15 * features['entropy']
    prob = 1 / (1 + math.exp(-base))
    return prob * 100
Signals below 60% confidence are filtered out. Above 80%, trades may be auto-executed or prioritized.

News & Sentiment Filtering

RabitAI integrates news headlines, client sentiment, VADER, and GPT-based summaries to avoid trading against major news flow.

  1. Pull latest headlines per ticker
  2. Score with VADER & keyword filters
  3. Pass to GPT with indicator context
  4. Compare GPT’s direction with signal
  5. Penalize probability if mismatch
sentiment_score = analyzer.polarity_scores(news_text)['compound']
if sentiment_score < -0.3 and signal == 'BUY':
    confidence *= 0.8
Bearish news overrides bullish signals, reducing risk of false positives.

TP/SL Prediction

Take Profit and Stop Loss levels are set dynamically based on volatility and market regime, not static percentages.

def calculate_tp_sl(current_price, atr, regime):
    if regime == 'momentum':
        sl = current_price - atr * 1.2
        tp = current_price + atr * 2.5
    elif regime == 'mean-reverting':
        sl = current_price - atr * 1.0
        tp = current_price + atr * 1.5
    else:
        sl = current_price - atr * 1.1
        tp = current_price + atr * 2.0
    return round(tp, 2), round(sl, 2)

Signal Reasoning with GPT

Every trade is reviewed by GPT-4, which analyzes technicals, sentiment, price structure, and volatility, then provides a rationale.

prompt = f"""
Analyze the following trade setup:
Symbol: {{symbol}}
Direction: {{direction}}
Timeframes: 15m, 30m, 1H, 4H
Indicators: {{indicator_summary}}
News Headlines: {{headline_summary}}
Entropy: {{entropy}}
ATR: {{atr}}

Should this trade be executed? If yes, why? What risk factors are present?
"""
Only signals with alignment across technicals, sentiment, and GPT summary are sent to users or execution queues.

Trade Report Output

Qualified signals are packaged into a polished HTML report, sent via email or Discord. Each report includes:

Symbol TSLA
Direction BUY
Entry $176.20
TP $182.60
SL $172.80
Confidence 84%
Chart Rendering (Python)
fig, ax = plt.subplots()
ax.plot(df['close'], label='Price')
ax.axhline(tp, color='green', linestyle='--', label='TP')
ax.axhline(sl, color='red', linestyle='--', label='SL')
# ...
img_buf = io.BytesIO()
plt.savefig(img_buf, format='png')
img_base64 = base64.b64encode(img_buf.getvalue()).decode()

Portfolio Integration & Risk

RabitAI manages risk at the portfolio level, adjusting position size and filtering overlapping or correlated trades.

def determine_position_size(probability, atr, account_balance):
    risk_pct = min(0.02, probability / 100 * 0.03)
    dollar_risk = account_balance * risk_pct
    position_size = dollar_risk / atr
    return round(position_size, 2)
Sample Portfolio Summary
{
  "date": "2025-05-26",
  "total_signals": 4,
  "executed": 2,
  "capital_allocated": "$4,000",
  "estimated_risk": "$120",
  "expected_return": "$360"
}

Lessons Learned

Simplicity Beats Complexity: Focus on high-impact features, not dozens of indicators.
GPT Adds Value—If Scoped: Strict prompts yield reliable trade justifications.
Filtering > Forecasting: Skipping bad setups is more important than perfect entries.
Portfolio Logic Early: Exposure rules and volatility caps improve outcomes.
Users Want Narratives: Numeric confidence + GPT reasoning builds trust.

Join the Mission

RabitAI is now public. Choose your path:

  1. Free 30-day trial: Test daily signals in our private Discord
  2. Monthly subscription: Real-time alerts, email reports, Discord access
  3. Build your own: Use this blueprint, adapt the code, or hire us for custom solutions
JOIN THE COMMUNITY

Appendix

Source Code Modules
  • extract_features()
  • calculate_trade_probability()
  • calculate_tp_sl()
  • generate_prompt()
  • render_chart()
  • send_email_report()
API & Environment
  • OPENAI_API_KEY
  • NEWS_API_KEY
  • EMAIL_USER, EMAIL_PASS
  • CAPITAL_API_KEY / ALPACA_API_KEY

from dotenv import load_dotenv
load_dotenv('signals_cred.env')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
Datasets & Libraries
  • Yahoo Finance, Capital.com, NewsAPI
  • ta, scikit-learn, statsmodels, arch, matplotlib
  • feedparser, vaderSentiment, openai, dotenv, requests, pandas, numpy, tweepy