How I Engineered an 79% Win-Rate Trading Algorithm
By Charl Van Zyl | RABITAI Trading Signals
JOIN THE COMMUNITYI 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.
This blueprint reveals the exact process, from architecture to execution, so you can understand and replicate high-conviction AI trading signals.
calculate_trade_probability()
signals.py
– main runtimefeature_engineering.py
– feature constructionsentiment.py
– sentiment analysischarting.py
– chart generationemail_report.py
– HTML/email outputexecution.py
– trading API (optional)80% of the system's edge comes from robust feature engineering. RabitAI fuses technical, volatility, and structure features across multiple timeframes.
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.
RabitAI adapts to trending and mean-reverting markets by classifying regimes using entropy, ADX, and volatility relationships.
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'
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
RabitAI integrates news headlines, client sentiment, VADER, and GPT-based summaries to avoid trading against major news flow.
sentiment_score = analyzer.polarity_scores(news_text)['compound']
if sentiment_score < -0.3 and signal == 'BUY':
confidence *= 0.8
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)
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?
"""
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% |
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()
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)
{
"date": "2025-05-26",
"total_signals": 4,
"executed": 2,
"capital_allocated": "$4,000",
"estimated_risk": "$120",
"expected_return": "$360"
}
RabitAI is now public. Choose your path:
extract_features()
calculate_trade_probability()
calculate_tp_sl()
generate_prompt()
render_chart()
send_email_report()
from dotenv import load_dotenv
load_dotenv('signals_cred.env')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')