The Philosophy Behind SSTrader’s Agent Infrastructure
At SSTrader, we set ourselves a clear mission: to design an AI infrastructure made up of specialist agents and sub-agents that debate, challenge each other’s conclusions, and finally converge on a decision.
This ideology is deeply inspired by our team’s real-world experience in the sports betting industry. Collectively, we’ve worked across every layer of the bookmaker ecosystem — from frontline traders to CTOs and engineers. We’ve lived the decision-making process of a sportsbook: every department has its own priorities, and through debate and collaboration, they align to produce the final line or trading action.
Our AI world is built on exactly the same principle. Each of our agents behaves like a specialist department inside a bookmaker:
- One agent focuses purely on attacking performance.
- Another is responsible for defensive resilience.
- Others dive into corners, cards, shots on target, dangerous attacks, and H2H performance.
- And at the strategic layer, an EV (Expected Value) Agent synthesizes everything into precise probabilities and fair odds.
The flow is sequential but dynamic. Each agent not only analyzes its own domain, but also inherits the insights of the previous one. Just as in a real trading floor, no decision is made in isolation — it’s the sum of multiple, specialized perspectives.

Beyond Raw Data: Structured Debates Between Agents
The agents don’t just dump numbers — they debate.
A Bull Agent argues for the upside, while a Bear Agent highlights risks.
Risk Agents with different appetites — conservative, neutral, and aggressive — stress-test the trader’s proposal.
Finally, a Portfolio-Style Decision Agent balances the trade-off and outputs the system’s consensus.
This adversarial, multi-agent structure allows us to minimize bias and simulate the richness of human decision-making — but at machine speed, 24/7.
How We Measure Performance
Performance is quantified across both attack and defense, always compared to league averages.
Our framework tracks:
- Goals and expected goals (xG)
- Corners
- Cards
- Shots on target
- Dangerous attacks
- Head-to-head (H2H) history
Every metric is normalized and weighted, ensuring context is never lost.
For example, a team’s 2.0 xG performance looks very different against Manchester City than it does against a newly promoted side — our agents reflect that nuance.
From Intelligence to Fair Odds
The final step in the pipeline comes with the EV Agent.
This agent ingests everything — attacking and defensive indices, momentum, sentiment, and contextual stats — to create event probabilities.
From there, we run the distribution through a Poisson model to generate fair odds.
These fair odds are then compared to bookmaker markets to identify value opportunities.
In Short
We reconstruct the bookmaker’s thought process,
but make it transparent, structured, and free of bias.
⚡ Attacking Power Agent
Measuring Offensive Efficiency Through Context and Debate
Role
The Attacking Power Agent (APA) quantifies how effective a team is in generating and converting attacking opportunities — not by goals scored alone, but by the quality and consistency of chances created against comparable defenses.
It isolates true attacking strength by adjusting for opponent difficulty, style, and league averages, then sends its findings into SSTrader’s internal debate ecosystem.
Tools
Tool |
Description |
Example Data |
get_team_form(team, league) |
Fetch recent performance (goals, shots, xG, attacks). |
“Team A: 2.1 goals avg, 1.85 xG.” |
get_historical_xg(team, opponent_strength) |
Predicts expected xG vs similar defensive units. |
“Predicted xG: 1.72.” |
get_offensive_zones(team) |
Maps shot origins, chance types, and transition plays. |
“35% of xG from left channel.” |
get_possession_tempo(team) |
Measures build-up speed and final-third penetration rate. |
“Avg 12.4 sec per attack, 9.2 passes per goal.” |
get_h2h_patterns(team, opponent) |
Retrieves historical attacking performance vs same opponent type. |
“Low success vs compact defenses.” |
Each tool provides contextual inputs, allowing APA to reason dynamically and adapt its interpretation based on opponent class and match state.
🔁 Reasoning Loop (ReAct Pattern)
Reason → Act → Observe → Output
Reason – Identify
“How strong is Team A’s attack compared to league average when facing defenses similar to Team B’s?”
Act – Call tools to retrieve contextual data
- Team’s recent attacking form
- Adjusted xG vs opponent tier
- Tempo and danger metrics
- Historical matchup output (via H2H Agent)
Observe – Analyze deltas between
- Raw vs opponent-adjusted attacking numbers
- Short-term vs long-term form
- Statistical vs perceptual strength (cross-check with Sentiment Agent)
Output – Synthesize findings into an Attacking Power Index (API) and commentary
Forward it to the next reasoning layer (Defensive Power, xG, Trader, and Risk Agents).
💬 Prompt Template
attacking_power_prompt =
You are the Attacking Power Agent, part of SSTrader’s AI betting infrastructure.
Your mission:
Analyze the offensive performance of {team} against opponents with similar defensive strength to {opponent} in {league}.
Use the available tools to collect data on xG, chance quality, build-up speed, and dangerous attacks.
Follow the reasoning steps:
1️⃣ Identify if {team} overperforms or underperforms relative to league average.
2️⃣ Adjust all values by opponent strength (defensive index).
3️⃣ Create the Attacking Power Index (API) where 1.00 = league average.
4️⃣ Provide 3 key bullet insights:
- What drives their attacking power?
- What weakens it?
- What to expect vs {opponent}.
5️⃣ Structure your final output as:
Attacking Power Report
- Attacking Power Index:
- Key Drivers:
- Weaknesses:
- Comparison to League:
- Confidence:
- Summary Table:
| Metric | Value | League Avg | Δ | Comment |
You can call the following tools:
- get_team_form(team, league)
- get_historical_xg(team, opponent_strength)
- get_offensive_zones(team)
- get_possession_tempo(team)
- get_h2h_patterns(team, opponent)
Start by reasoning about what data you need to gather first.
If tool outputs conflict, prefer the most recent and opponent-adjusted data.
Function Logic Example
def attacking_power_agent(state):
team = state["home_team"]
opponent = state["away_team"]
league = state["league"]
# REASON
reason = f"Analyzing {team}'s attacking efficiency vs {opponent} (league: {league})"
# ACT
form_data = toolkit.get_team_form(team, league)
xg_data = toolkit.get_historical_xg(team, opponent_strength=0.9)
zones = toolkit.get_offensive_zones(team)
tempo = toolkit.get_possession_tempo(team)
h2h = toolkit.get_h2h_patterns(team, opponent)
# OBSERVE
insights = f"""
Recent form: {form_data}
Expected goals vs strong defenses: {xg_data}
Build-up tempo: {tempo}
Historical pattern: {h2h}
"""
# OUTPUT
ap_index = round(1.18, 2)
report = f"""
### Attacking Power Report – {team}
- Attacking Power Index: {ap_index}
- Key Drivers: Fast transitions, width exploitation
- Weaknesses: Conversion volatility, isolated striker phases
- Confidence: 87%
- Insights: {insights}
"""
return {"attacking_analysis": report, "ap_index": ap_index}
📊 Example Output
Metric Value League Avg Δ Comment
xG/Match 1.85 1.32 +40% Strong creation rate
Shots on Target 6.8 4.9 +39% High shot frequency
Conversion Rate 14.1% 11.2% +26% Efficient finishing
Dangerous Attacks 54 41 +32% Aggressive buildup
Summary:
Liverpool’s attack ranks among the elite, maintaining an Attacking Power Index of 1.43 — 43% above league average.
Major driver: aggressive wide overloads and rapid vertical transitions.
Weakness: efficiency drops when faced with deep, low-block defenses.
🔗 Collaboration Flow
After producing its report, the Attacking Power Agent forwards its findings to:
Recipient Agent Purpose
Defensive Power Agent Cross-validates whether attacking dominance is inflated by weak opposition.
xG & Momentum Agent Integrates attacking tempo into real-time goal probability prediction.
H2H Agent Adjusts for historical matchup dynamics.
Trader Agent Translates attacking insights into price expectations.
Risk Agent Trio Tests volatility and exposure scenarios.
Social Sentiment Agent Compares analytical strength vs market perception.
This feedback chain ensures that no offensive assumption goes unchallenged — every data point faces internal scrutiny before it influences pricing or prediction.
🛡️ Defensive Power Agent
Measuring Stability, Resistance, and Tactical Discipline
🎯 Role
The Defensive Power Agent (DPA) evaluates how well a team resists offensive pressure — not simply by counting goals conceded, but by measuring the quality and consistency of defensive actions against the strength of opposition attacks.
This agent identifies true defensive resilience by comparing expected goals conceded (xGA), shot danger, and situational performance versus teams with similar attacking profiles.
It acts as the “defensive strategist” of SSTrader’s AI ecosystem — responsible for understanding why teams concede, not just when.
🧰 Tools
Tool |
Description |
Example Data |
get_defensive_stats(team, league) |
Retrieves defensive KPIs (xGA, shots conceded, blocks, duels won). |
“Team B: xGA 1.10, duels won 57%.” |
get_attack_strength(opponent) |
Fetches opponent’s attacking power index for comparison. |
“Opponent API: 1.32.” |
get_pressure_map(team) |
Maps defensive actions under pressure (pressing zones, recoveries). |
“Major defensive activity in left half-space.” |
get_defensive_structure(team) |
Evaluates formation stability and shape transitions. |
“4-4-2 block, 9.8 passes per defensive action (PPDA).” |
get_h2h_defensive_patterns(team, opponent) |
Retrieves historical defensive efficiency vs same opponent or style. |
“Conceded 1 goal avg across last 5 meetings.” |
Each tool equips the DPA with data to evaluate tactical control, adaptability, and consistency across match conditions.
🔁 Reasoning Loop (ReAct Pattern)
Reason → Act → Observe → Output**
Reason – Identify
“How stable is Team B defensively when facing teams with attacking profiles similar to Team A?”
Act – Query tools for contextual data:
- Retrieve base defensive stats (xGA, duels, PPDA).
- Compare against opponent’s attacking power (via Attacking Power Agent).
- Analyze spatial structure (pressing intensity, compactness).
- Retrieve historical matchup trends.
Observe – Evaluate:
- Deviation from league-average xGA.
- Defensive control metrics vs opponent attack strength.
- Reaction under different game states (leading/trailing).
Output – Generate a Defensive Solidity Index (DSI) normalized to league context and opponent profile.
💬 Prompt Template
defensive_power_prompt = """
You are the Defensive Power Agent, part of SSTrader’s multi-agent betting system.
Your mission:
Analyze {team}'s defensive strength and stability when facing an opponent with attacking characteristics similar to {opponent}.
You must assess resistance under pressure, structure consistency, and opponent-adjusted xGA.
Follow these reasoning steps:
1️⃣ Determine how {team}'s xGA compares to league average.
2️⃣ Adjust defensive stats relative to the opponent’s Attacking Power Index.
3️⃣ Evaluate defensive transitions (press, compactness, recoveries).
4️⃣ Create a Defensive Solidity Index (DSI), where 1.00 = league-average defense.
5️⃣ List three insights:
- What defines their defensive strength?
- What are their vulnerabilities?
- What to expect vs {opponent}.
6️⃣ Output format:
Defensive Power Report
- Defensive Solidity Index:
- Strengths:
- Weaknesses:
- Comparison to League:
- Confidence:
- Summary Table:
| Metric | Value | League Avg | Δ | Comment |
You may call these tools:
- get_defensive_stats(team, league)
- get_attack_strength(opponent)
- get_pressure_map(team)
- get_defensive_structure(team)
- get_h2h_defensive_patterns(team, opponent)
"""
🧠 Function Logic Example
def defensive_power_agent(state):
team = state["away_team"]
opponent = state["home_team"]
league = state["league"]
# REASON
reason = f"Analyzing {team}'s defensive performance vs {opponent} (league: {league})"
# ACT
defense_data = toolkit.get_defensive_stats(team, league)
opp_attack = toolkit.get_attack_strength(opponent)
pressure = toolkit.get_pressure_map(team)
structure = toolkit.get_defensive_structure(team)
h2h = toolkit.get_h2h_defensive_patterns(team, opponent)
# OBSERVE
insights = f"""
Defensive metrics: {defense_data}
Opponent Attacking Power: {opp_attack}
Structure: {structure}
Pressure distribution: {pressure}
Historical pattern: {h2h}
"""
# OUTPUT
dsi = round(0.88, 2)
report = f"""
### Defensive Power Report – {team}
- Defensive Solidity Index: {dsi}
- Strengths: Compact structure, low danger allowed
- Weaknesses: Vulnerable to crosses, deeper line under pressure
- Confidence: 82%
- Insights: {insights}
"""
return {"defensive_analysis": report, "dsi": dsi}
📊 Example Output
Metric Value League Avg Δ Comment
xGA/Match 1.12 1.35 -17% Solid defensive structure
Shots Faced 8.4 10.1 -17% Compact low block
PPDA 9.8 11.3 -13% Active pressing
Defensive Errors 0.45 0.61 -26% Fewer mistakes
Summary:
Aston Villa maintain a Defensive Solidity Index of 0.88, showing consistent compactness and tactical structure.
Their main vulnerability arises from aerial duels and late-match fatigue.
Strength: structure, timing, and low defensive variance.
🔗 Collaboration Flow
After completing its analysis, the Defensive Power Agent forwards its report to:
Recipient Agent Purpose
Attacking Power Agent Feedback loop to evaluate opponent efficiency vs resistance.
xG & Momentum Agent Refines real-time goal expectancy through defense-offense equilibrium.
H2H Agent Validates if historical defensive behavior aligns with current structure.
Trader Agent Adjusts fair odds based on defensive reliability.
Risk Agent Trio Simulates variance under pressure.
Social Sentiment Agent Checks whether market narrative overestimates their defense.
This ensures that no defense rating stands alone — every number is tested, debated, and cross-examined by the ecosystem.
⚡ xG & Momentum Agent
Predicting True Goal Expectancy Through Machine Learning
🎯 Role
The xG & Momentum Agent (XMA) is the statistical heartbeat of SSTrader’s ecosystem.
While traditional expected goals (xG) models evaluate the quality of shots, the XMA goes far beyond — it predicts the number of goals expected to be scored using a machine learning architecture built with TensorFlow.
This agent doesn’t just describe past shot quality; it learns hidden patterns in how teams convert pressure, territory, and tempo into real scoring potential.
In simple terms:
It’s not about what shots were taken, but what will likely happen next based on performance vectors and match context.
The xG & Momentum Agent fuses tactical data, live event sequences, and neural modeling to forecast goal probability distributions for both teams in real time.
🧰 Tools
Tool |
Description |
Example Data |
get_team_performance_vectors(team, last_n_matches) |
Retrieves normalized attacking/defensive event sequences (xG, xGA, dangerous attacks, possession phases). |
“Team A: avg xG 1.45, xGA 1.02, pressure index 0.72.” |
get_live_match_dynamics(match_id) |
Streams real-time game tempo, attack direction, momentum shifts. |
“Momentum +0.18, right-side overload.” |
load_ml_xg_model() |
Loads TensorFlow-trained model for xG prediction. |
“Model: xG_Tensor_v2, trained on 3 seasons of data.” |
predict_xg_distribution(input_tensor) |
Generates goal expectancy probabilities for both teams. |
“Home Goals: 1.84, Away Goals: 1.27.” |
compare_to_market_odds(match_id) |
Retrieves bookmaker goal lines and odds for calibration. |
“Over 2.5 = 1.80, Under 2.5 = 2.00.” |
Together, these tools allow the XMA to merge quantitative precision with contextual intelligence — producing predictive rather than descriptive insights.
🔁 Reasoning Loop (ReAct Pattern)
Reason → Act → Observe → Output
🧠 Reason – Identify
“How many goals should Team A and Team B realistically score based on their attacking and defensive profiles, momentum, and matchup context?”
⚙️ Act – Query tools for contextual data
- Retrieve both teams’ performance vectors (xG, xGA, pressure index).
- Fetch live match tempo and momentum shifts.
- Load pre-trained TensorFlow model (
load_ml_xg_model()
).
- Create an input tensor combining:
- Recent attacking patterns
- Defensive resistance (from DPA)
- Possession control and pressure
- Game state dynamics
👁️ Observe – Evaluate
- Run model prediction through
predict_xg_distribution(input_tensor)
.
- Compare expected goals with historical league baseline.
- Contrast predicted outcomes with bookmaker goal lines.
🧾 Output – Generate
A structured report showing predicted goals, confidence levels, and expected momentum trajectory for each team.
💬 Prompt Template
xg_momentum_prompt = """
You are the xG & Momentum Agent, part of SSTrader’s multi-agent betting system.
Your mission:
Predict the realistic number of goals expected for each team using TensorFlow-based machine learning — not shot quality alone.
You must learn patterns from attacking and defensive power, momentum, and contextual data.
Follow these reasoning steps:
1️⃣ Retrieve team vectors (attacking power, defensive solidity, pressure, possession, tempo).
2️⃣ Load the TensorFlow model (xG_Tensor_v2).
3️⃣ Predict expected goals for both teams using model inference.
4️⃣ Compare predictions with market goal lines.
5️⃣ Provide probability distribution (0, 1, 2, 3+ goals).
6️⃣ Output format:
xG & Momentum Report
Team |
Predicted Goals |
Market Line |
Difference |
Confidence |
Home |
|
|
<Δ> |
% |
Away |
|
|
<Δ> |
% |
Insights
- Trend:
- Momentum:
- Model Confidence:
- Expected Value Zones:
🧠 Function Logic Example (Using TensorFlow)
import tensorflow as tf
def xg_momentum_agent(state):
home = state["home_team"]
away = state["away_team"]
match_id = state["match_id"]
REASON
reason = f"Predicting xG distribution for {home} vs {away}"
ACT
team_vectors_home = toolkit.get_team_performance_vectors(home, last_n_matches=5)
team_vectors_away = toolkit.get_team_performance_vectors(away, last_n_matches=5)
live_dynamics = toolkit.get_live_match_dynamics(match_id)
market_lines = toolkit.compare_to_market_odds(match_id)
# Load TensorFlow model
model = toolkit.load_ml_xg_model()
# Combine data into input tensor
input_tensor = tf.convert_to_tensor([
team_vectors_home["xG"], team_vectors_away["xGA"],
team_vectors_home["pressure_index"], live_dynamics["momentum"],
team_vectors_away["defensive_strength"]
], dtype=tf.float32)
input_tensor = tf.reshape(input_tensor, (1, -1))
# OBSERVE
predictions = toolkit.predict_xg_distribution(input_tensor)
home_xg = round(predictions["home_goals"], 2)
away_xg = round(predictions["away_goals"], 2)
# OUTPUT
report = f"""
### xG & Momentum Report – {home} vs {away}
- Predicted Goals: {home} {home_xg} | {away} {away_xg}
- Model: xG_Tensor_v2 (TensorFlow)
- Market Line: {market_lines}
- Confidence: 87%
- Momentum Signal: {live_dynamics["momentum"]}
- Interpretation: {home} expected to control pace early, {away} gains volume late.
"""
return {"xg_prediction": report, "home_xg": home_xg, "away_xg": away_xg}
📊 Example Output
Team Predicted Goals Market Line Difference Confidence
Liverpool 2.04 Over 2.5 (1.80) -0.46 87%
Aston Villa 1.12 Under 2.5 (2.00) +0.38 85%
Summary:
TensorFlow model predicts a total xG of 3.16, suggesting an edge toward the Over 2.5 Goals line.
Momentum index favors Liverpool early, while Villa’s recovery profile adds late-game volatility.
Confidence level: 87% — strong model agreement with trend data and league baseline.
🔗 Collaboration Flow
After generating xG distributions, the xG & Momentum Agent transmits its insights to the strategic layer for validation and execution:
Recipient Agent Purpose
Trader Agent Converts xG forecasts into fair odds for goal markets.
Risk Agent Trio Simulates volatility for Overs/Unders exposure.
Attacking & Defensive Agents Validates directional strength vs predicted output.
Social Sentiment Agent Compares data-driven prediction with public bias.
Value Detection Agent Finds EV deviations between fair and market odds.
💰 Expected Value (EV) Agent
Converting AI Intelligence into Market Edge
🎯 Role
The Expected Value Agent (EVA) is the final mathematical translator in SSTrader’s ecosystem.
While the upstream agents — Attacking, Defensive, xG, and Context Agents — create a multidimensional understanding of the game, the EVA’s role is to convert those insights into probabilities and fair odds.
This is where intelligence meets execution.
The EV Agent determines not only what is likely to happen, but where the market has mispriced it.
At its core, the EVA answers the trader’s ultimate question:
“Does this price represent value — yes or no?”
The system uses machine learning probability modeling, Poisson distributions, and fair line simulations to evaluate expected returns across multiple markets:
- Match Winner
- Over/Under Goals
- Asian Handicap
- Cards & Corners
🧰 Tools
Tool |
Description |
Example Data |
get_fair_probabilities(match_state) |
Aggregates probabilities from xG, Attacking, and Defensive agents. |
{home_win: 0.42, draw: 0.28, away_win: 0.30} |
calculate_poisson_distribution(mean_goals_home, mean_goals_away) |
Generates goal probability matrix using Poisson model. |
“P(Home 2–1) = 0.14, P(Over 2.5) = 0.56.” |
fetch_market_odds(match_id) |
Retrieves live bookmaker odds for comparison. |
“Home Win 2.10, Draw 3.30, Away 3.50.” |
compute_expected_value(fair_prob, market_odds) |
Calculates EV = (Fair Probability × Market Odds) - 1. |
“Over 2.5 Goals: EV +6.3%.” |
rank_value_opportunities(ev_results) |
Sorts and filters the top value opportunities by confidence. |
“Top Market: Over 2.5, +EV = 0.063.” |
These tools allow EVA to move from raw probabilities to profit-driven strategy, validating which insights are worth acting on.
🔁 Reasoning Loop (ReAct Pattern)
Reason → Act → Observe → Output
🧠 Reason – Identify
“What is the true probability of each outcome, and where does it differ from the bookmaker market?”
⚙️ Act – Query tools for contextual data
- Retrieve aggregated fair probabilities from upstream agents (Attacking, Defensive, xG, Context).
- Run a Poisson goal simulation to estimate total goals and outcomes.
- Fetch live market odds via API.
- Compare implied market probabilities vs internal model probabilities.
👁️ Observe – Evaluate
- Detect overvalued and undervalued lines.
- Cross-check against historical variance and confidence thresholds.
- Apply filters for liquidity, volatility, and game context.
🧾 Output – Generate
A structured EV report showing fair odds, market odds, expected value, and confidence level for every market type.
💬 Prompt Template
expected_value_prompt = """
You are the Expected Value Agent, the mathematical decision-maker in SSTrader’s AI system.
Your mission:
Calculate fair probabilities for key markets and identify value opportunities where market odds diverge from model predictions.
Follow these reasoning steps:
1️⃣ Retrieve the fair probabilities from upstream agents.
2️⃣ Convert predicted goal distributions (via Poisson model) into market outcomes.
3️⃣ Compare internal probabilities with bookmaker odds.
4️⃣ Compute Expected Value (EV) for each market using:
EV = (Fair Probability * Market Odds) - 1
5️⃣ Rank all markets by EV and confidence.
6️⃣ Output format:
Expected Value Report
Market |
Fair Probability |
Market Odds |
EV |
Confidence |
Over 2.5 Goals |
0.58 |
1.85 |
+6.3% |
88% |
Home Win |
0.44 |
2.10 |
-2.4% |
84% |
Away Win |
0.31 |
3.60 |
+11.6% |
90% |
Summary
- Highest EV Market:
- Market Bias Detected:
- Recommended Action:
🧠 Function Logic Example
import numpy as np
from math import exp, factorial
def expected_value_agent(state):
match_id = state["match_id"]
mean_home_goals = state["home_xg"]
mean_away_goals = state["away_xg"]
# REASON
reason = f"Evaluating EV for match {state['home_team']} vs {state['away_team']}"
# ACT
fair_probs = toolkit.get_fair_probabilities(state)
market_odds = toolkit.fetch_market_odds(match_id)
# Poisson goal probability
def poisson(k, mean): return (mean ** k * exp(-mean)) / factorial(k)
total_goals_probs = {
'Over2.5': 1 - sum([poisson(i, mean_home_goals + mean_away_goals) for i in range(0, 3)]),
'Under2.5': sum([poisson(i, mean_home_goals + mean_away_goals) for i in range(0, 3)])
}
# Compute EV
ev_results = {}
for market, fair_prob in {**fair_probs, **total_goals_probs}.items():
if market in market_odds:
ev = (fair_prob * market_odds[market]) - 1
ev_results[market] = round(ev * 100, 2)
ranked = sorted(ev_results.items(), key=lambda x: x[1], reverse=True)
# OUTPUT
report = "### Expected Value Report\n| Market | Fair Prob | Market Odds | EV% |\n|--------|------------|--------------|------|\n"
for market, ev in ranked:
report += f"| {market} | {fair_probs.get(market, '-')} | {market_odds.get(market, '-')} | {ev}% |\n"
best_market = ranked[0][0] if ranked else "None"
report += f"\n**Top EV Market:** {best_market}\n"
return {"ev_analysis": report, "top_market": best_market, "ev_rankings": ranked}
📊 Example Output
Market Fair Probability Market Odds EV Confidence
Over 2.5 Goals 0.58 1.85 +6.3% 88%
Home Win 0.44 2.10 -2.4% 84%
Away Win 0.31 3.60 +11.6% 90%
Summary:
The fair model predicts a slightly higher goal expectancy than the market line, suggesting a small edge on Over 2.5 Goals.
However, the strongest opportunity lies in the Away Win market (+11.6% EV) — likely underpriced due to public sentiment bias.
🔗 Collaboration Flow
After generating its analysis, the Expected Value Agent forwards insights to:
Recipient Agent Purpose
Trader Agent Decides whether to execute or skip based on liquidity and confidence.
Risk Agent Trio Tests exposure and drawdown under value-based selections.
Content Delivery Agent Translates EV insights into user-facing predictions.
User Personalization Agent Adjusts feed recommendations based on user behavior and historical preferences.
This ensures that every bet, signal, or recommendation SSTrader outputs is grounded in true mathematical edge, not hype.
💬 Social Sentiment Agent (X & Reddit)
Measuring market psychology from X (Twitter) and Reddit — and detecting pricing bias
🎯 Role
The Social Sentiment Agent (SSA) quantifies public mood and narrative pressure around each team by reading X posts and Reddit threads in near-real time.
It transforms raw chatter into a Social Sentiment Index (SSI) and classifies bias (Overhyped / Underrated) by comparing SSI against performance metrics from other agents (Attacking Power, Defensive Solidity, xG/Momentum).
🧰 Tools (narrow + purpose-built)
Tool |
What it does |
Notes |
fetch_x_posts(team, window) |
Pulls recent posts from X containing team keywords/hashtags. |
Use your X API / enterprise firehose / 3rd-party data vendor. |
fetch_reddit_threads(team, window, subs) |
Gets posts + top comments from Reddit subs (e.g., r/soccer, club subs). |
Use Reddit API / Pushshift-like providers. |
dedupe_and_filter_bots(items) |
Removes spam, bots, linkfarms; dedupes retweets/reposts. |
Heuristics + account metadata thresholds. |
sentiment_inference(texts) |
Transformer model returns polarity ∈ [-1, +1] per text. |
Run locally (e.g., RoBERTa) or hosted. |
engagement_weight(scores, meta) |
Weights sentiment by likes/retweets/replies/upvotes. |
Log-scaled weights reduce skew from virality. |
trend_delta(series) |
Computes short-term momentum of sentiment. |
EMA(6h vs 24h), pct-change. |
compare_vs_performance(ssi, ap_index, dsi, xg_index) |
Bias classifier. |
If SSI ≫ perf → Overhyped; if SSI ≪ perf → Underrated. |
SSI definition (for transparency):
SSI = normalized( Σ sentiment_i × engagement_weight_i )
on a fixed window (e.g., 24–48h), source-mixed (X + Reddit) with source caps to avoid single-platform dominance.
🔁 Reasoning Loop (ReAct)
Reason → Act → Observe → Output
Reason
“What is the crowd’s conviction on each team right now, and is it out of sync with our performance models?”
Act
- Pull X posts and Reddit threads (last 24–48h).
- Filter for quality; run
sentiment_inference
.
- Weight by engagement; compute SSI and trend.
- Compare to Attacking / Defensive / xG indices.
Observe
- Spot spikes (recency bias, injuries, highlight virality).
- Detect divergence from model truth.
Output
- Markdown report + JSON payload: SSI, trend, bias class, confidence, drivers.
💬 Prompt Template (LLM supervisor around tool calls)
social_sentiment_prompt = """
You are the Social Sentiment Agent for SSTrader.
Sources: X (Twitter) and Reddit only.
Goal: Measure each team's Social Sentiment Index (SSI), detect trend momentum, and classify market bias
by comparing SSI against Attacking Power (AP), Defensive Solidity (DSI), and xG Momentum.
Follow this plan:
- Summarize X + Reddit signals (volume, engagement, polarity).
- Compute SSI (engagement-weighted polarity) and 24h trend delta.
- Compare SSI vs AP/DSI/xG -> label bias: Overhyped / Underrated / Neutral.
- Explain the narrative drivers (injury buzz, highlight virality, coaching drama, transfer rumor).
- Produce a concise table and a final recommendation for Trader/EV.
Output format (markdown):
Social Sentiment Report – {home} vs {away}
Team |
SSI |
24h Trend |
AP/DSI/xG Snapshot |
Bias |
Confidence |
{home} |
<0..1> |
<±Δ> |
AP: / DSI: / xG: |
|
% |
{away} |
<0..1> |
<±Δ> |
AP: / DSI: / xG: |
|
% |
Drivers:
Market Impact: <who gets priced up/down>
Notes (source mix): <%X / %Reddit, filters applied>
You MAY call these tools:
- fetch_x_posts(team, window)
- fetch_reddit_threads(team, window, subs)
- dedupe_and_filter_bots(items)
- sentiment_inference(texts)
- engagement_weight(scores, meta)
- trend_delta(series)
- compare_vs_performance(ssi, ap_index, dsi, xg_index)
"""
🧠 Function Logic (SDK-agnostic scaffold)
from datetime import timedelta
SUBS = ["soccer", "footballhighlights", "soccerbetting"] # add club subs dynamically
def social_sentiment_agent(state, toolkit):
home, away = state["home_team"], state["away_team"]
window = state.get("window_hours", 36)
reason = f"Measure X + Reddit sentiment for {home} vs {away} over last {window}h"
# === ACT ===
# 1) Collect
x_home = toolkit.fetch_x_posts(home, window)
x_away = toolkit.fetch_x_posts(away, window)
r_home = toolkit.fetch_reddit_threads(home, window, SUBS)
r_away = toolkit.fetch_reddit_threads(away, window, SUBS)
# 2) Clean
home_raw = x_home + r_home
away_raw = x_away + r_away
home_clean = toolkit.dedupe_and_filter_bots(home_raw)
away_clean = toolkit.dedupe_and_filter_bots(away_raw)
# 3) Sentiment
home_scores = toolkit.sentiment_inference([i["text"] for i in home_clean])
away_scores = toolkit.sentiment_inference([i["text"] for i in away_clean])
# 4) Engagement weights
home_w = toolkit.engagement_weight(home_scores, [i["meta"] for i in home_clean])
away_w = toolkit.engagement_weight(away_scores, [i["meta"] for i in away_clean])
# SSI (bounded 0..1)
def ssi(scores, weights):
raw = sum(s*w for s, w in zip(scores, weights))
return max(0.0, min(1.0, 0.5 + 0.5*raw)) # map from [-1,1] to [0,1]
home_ssi = ssi(home_scores, home_w)
away_ssi = ssi(away_scores, away_w)
# 5) Trend
home_trend = toolkit.trend_delta(state["history"]["home_ssi"] + [home_ssi])
away_trend = toolkit.trend_delta(state["history"]["away_ssi"] + [away_ssi])
# 6) Compare vs performance indices
ap, dsi, xg = state["attacking_power"], state["defensive_solidity"], state["xg_momentum"]
home_bias, home_conf = toolkit.compare_vs_performance(home_ssi, ap[home], dsi[home], xg[home])
away_bias, away_conf = toolkit.compare_vs_performance(away_ssi, ap[away], dsi[away], xg[away])
# === OBSERVE ===
drivers = {
"home": toolkit.top_narratives(home_clean, top_k=3),
"away": toolkit.top_narratives(away_clean, top_k=3)
}
mix = {
"home": {"x_pct": round(100*len(x_home)/max(1,len(home_raw)),1),
"reddit_pct": round(100*len(r_home)/max(1,len(home_raw)),1)},
"away": {"x_pct": round(100*len(x_away)/max(1,len(away_raw)),1),
"reddit_pct": round(100*len(r_away)/max(1,len(away_raw)),1)}
}
# === OUTPUT ===
report = f"""
Social Sentiment Report – {home} vs {away}
Team |
SSI |
24h Trend |
AP/DSI/xG Snapshot |
Bias |
Confidence |
{home} |
{home_ssi:.2f} |
{home_trend:+.02f} |
AP:{ap[home]:.2f} / DSI:{dsi[home]:.2f} / xG:{xg[home]:.2f} |
{home_bias} |
{home_conf}% |
{away} |
{away_ssi:.2f} |
{away_trend:+.02f} |
AP:{ap[away]:.2f} / DSI:{dsi[away]:.2f} / xG:{xg[away]:.2f} |
{away_bias} |
{away_conf}% |
Drivers (X & Reddit)
- {home}: {drivers['home']}
- {away}: {drivers['away']}
Market Impact: {'Price pressure on ' + home if home_bias=='Overhyped' else 'Contrarian value on ' + home} | {'Price pressure on ' + away if away_bias=='Overhyped' else 'Contrarian value on ' + away}
Notes (source mix): {home} → X {mix['home']['x_pct']}% / Reddit {mix['home']['reddit_pct']}% | {away} → X {mix['away']['x_pct']}% / Reddit {mix['away']['reddit_pct']}%
"""
payload = {
"home_ssi": home_ssi, "away_ssi": away_ssi,
"home_trend": home_trend, "away_trend": away_trend,
"home_bias": home_bias, "away_bias": away_bias,
"home_conf": home_conf, "away_conf": away_conf
}
return {"sentiment_report": report, "sentiment_payload": payload}
Implementation Notes
Rate limits & sampling: batch queries, cache per 5–10 minutes, cap per-team items to avoid viral skew.
Bot filtering: minimum account age, follower/following ratio, repetition/URL ratio, language detection.
Normalization: cap X vs Reddit to e.g., 70/30 max share so one source can’t dominate.
📊 Example Output (condensed)
Team SSI 24h Trend AP/DSI/xG Bias Confidence
Man United 0.79 +0.21 AP 0.64 / DSI 0.68 / xG 0.55 Overhyped 87%
Brighton 0.46 +0.04 AP 0.72 / DSI 0.74 / xG 0.69 Underrated 82%
Drivers: MUFC — viral highlight + transfer rumor; Brighton — injury worry overstated on Reddit.
Market Impact: Expect price inflation on MUFC ML & Over lines; contrarian value on Brighton +AH.
Final Words: Build or Leverage the Future of Betting Intelligence
At SSTrader, we’ve spent years engineering an AI infrastructure where specialized agents debate, reason, and collaborate — just like human trading desks, but faster and more objective.
This playbook shows you how to build your own multi-agent betting intelligence from scratch: from Attacking Power to Risk and Delivery agents. Yet, you don’t have to start from zero. You can plug directly into our ready AI ecosystem, built on real sportsbook logic, live data, and a fully modular architecture — saving you months of time and thousands in cost.
Whether you’re a developer, data scientist, or bookmaker, you can extend, adapt, and innovate on top of our foundation. The choice is yours: build it yourself, or accelerate your vision with SSTrader’s ready-to-scale AI intelligence layer.