B-Book V3 — Complete Feature Guide
What is a B-Book?
In sports betting, a B-Book (also called "book-making" or "principal risk") is when a betting operator keeps some or all of a player's bet instead of forwarding it to an exchange like Betfair. When the player loses, the operator profits. When the player wins, the operator pays out from their own funds.
Think of it like insurance: the operator "insures" the bet outcome. If they're smart about which bets to keep and which to forward, they can consistently profit because most recreational bettors lose over time.
The Two Models
| Model | How it works | Risk | Profit potential |
|---|---|---|---|
| A-Book (100% forwarding) | Every bet goes to Betfair. Operator earns a small commission. | Zero risk | Low margin (~2-5%) |
| B-Book (retain some bets) | Operator keeps selected bets. Acts as the counterparty. | Exposure risk | High margin (~15-40%) |
Most operators use a hybrid model — forwarding risky bets (sharp players, large stakes) and retaining profitable ones (recreational players, small stakes).
Our Implementation: The Cascade Engine
Our B-Book system is built around a multi-level agent hierarchy. Bets don't just go to one operator — they flow through a chain of agents, each deciding how much to keep and how much to pass upward:
Player places bet
↓
Agent Level 0 (player's direct agent) — keeps 40%, forwards 60%
↓
Agent Level 1 (regional agent) — keeps 30% of forwarded, forwards 70%
↓
Agent Level 2 (platform/terminal) — keeps remainder, hedges excess on Betfair
Each agent independently controls their risk appetite through configurable rules.
The Agent Hierarchy
How Agents Are Organized
The system uses a tree structure where each agent has one parent and can have multiple children:
- Platform Agent (root/terminal): The top-level operator. Has no parent. Anything not retained by downstream agents ends up here.
- Regional/Master Agents: Mid-level agents managing groups of sub-agents.
- Direct Agents: The agent directly serving players. This is where bets enter the system.
- Players/Users: The actual bettors, each assigned to exactly one direct agent.
Hierarchy Access
Agents can see and manage everything below them in the tree:
- A platform agent sees ALL users across ALL sub-agents
- A regional agent sees users of their direct sub-agents and those agents' sub-agents
- A direct agent sees only their own players
The system uses a BFS (Breadth-First Search) traversal to find all descendant agents, ensuring no sub-agent or player is missed.
Core Feature: The Cascade Engine
The cascade engine is the heart of B-Book V3. When a player places a bet, it flows through multiple processing steps at each agent level.
Step-by-Step Bet Flow
1. Health Check
Before anything else, the system checks if all services are healthy. If the system is degraded (Betfair down, Redis issues), ALL bets are forwarded 100% to protect agents from blind risk.
2. Load Agent Hierarchy
The system loads the complete chain from the player's direct agent up to the platform agent. This is cached in Redis for speed.
3. Top-Slice Reservations
Before the cascade begins, parent agents can "skim" a percentage off the top. This is called top-slicing.
Example: If the platform takes a 10% top-slice on a 10,000 stake:
- 1,000 is reserved for the platform
- 9,000 enters the cascade for distribution
This ensures platform agents earn revenue on every bet regardless of downstream forwarding decisions.
4. Stake Reduction (Player Limits)
Before the bet enters the cascade, the system checks player-level limits:
- Per-Click Win Limit: Maximum payout from a single bet (default: 50,000). If a bet's potential win exceeds this, the stake is reduced proportionally.
- Daily Aggregate Win Limit: Maximum total winnings per day (default: 200,000). Once a player has won this much today, further bets have stakes reduced.
- Minimum Stake: Bets below this threshold are rejected (default: 100).
5. Per-Level Cascade Processing
At each agent level (bottom to top), the following happens:
a. Skip Check: If the agent is suspended or has B-Book disabled, the bet passes through entirely (100% forwarded).
b. Source Type Resolution: The system determines what "type" of bettor is placing this bet, using a priority chain:
- User Override: Agent has manually classified this user (e.g., marked as SHARP)
- Trusted Downstream: The sending agent is trusted, so their classification carries forward
- Default: NORMAL (standard recreational bettor)
c. Matrix Resolution (see detailed section below): Determines what percentage to forward based on 5 dimensions of the bet.
d. Liability Calculation:
- BACK bet: Liability = Stake × (Odds − 1). If a player bets 1,000 at odds 3.0, the agent's liability is 2,000.
- LAY bet: Liability = Stake. The agent risks the stake amount itself.
e. Limit Enforcement: The system checks ALL applicable exposure limits:
- GLOBAL limit (total exposure across everything)
- SPORT limit (exposure per sport, e.g., max 100k on Cricket)
- MARKET limit (exposure per specific event)
- NIGHT_PERIOD limit (exposure during night hours when monitoring is reduced)
- WEEKLY_PERIOD limit (exposure within a rolling week)
The most restrictive limit wins. If the agent wants to retain 5,000 but only has 3,000 of capacity left, they retain 3,000 and forward the overflow.
f. Book Balancing (optional): If enabled, the system analyzes whether this bet improves or worsens the agent's risk balance:
- Hedging bet (reduces exposure): Gets up to 10% bonus retention capacity at high utilization
- Worsening bet (increases one-sided exposure): May have retention reduced or even rejected at 95%+ utilization
g. Overflow Handling: Any amount that exceeds limits is forwarded to the next level.
6. Terminal Level (Platform Agent)
The platform agent at the top of the chain has special behavior:
- Retains what it can based on its own matrix rules and limits
- Everything remaining becomes the hedge amount — placed on Betfair as a real bet
7. Result
The cascade returns a complete breakdown:
- Per-level: who retained how much, what rule was used, was balancing applied
- Hedge amount to place on Betfair
- Total processing time (target: under 110ms)
- Matrix version snapshot (for audit trail)
Safety Mechanisms
- Stake Conservation: The sum of all retained amounts plus the hedge amount always equals the original stake. No money is created or lost.
- Integer Arithmetic: All calculations use paisa (1/100 of currency unit) to avoid floating-point errors.
- Max Cascade Levels: Hard cap of 10 levels prevents infinite loops in malformed hierarchies.
The Forwarding Matrix: 5-Dimensional Rule Engine
The matrix is how agents define their forwarding rules. Instead of a simple "forward X% of everything," agents create granular rules based on 5 dimensions.
The 5 Dimensions
| Dimension | What it means | Example values |
|---|---|---|
| Market Type | The type of bet market | MATCH_ODDS, OVER_UNDER, PLAYER_RUN, CORRECT_SCORE |
| Sport Type | Which sport | CRICKET, SOCCER, TENNIS, BASKETBALL |
| Event Phase | When the bet is placed | PRE_MATCH (before game), LIVE (during game) |
| Source Type | What kind of bettor | NORMAL, SHARP, SYNDICATE, VIP |
| Liquidity Band | How liquid the market is | HIGH (lots of activity), MEDIUM, LOW |
Wildcard Matching
Each dimension can be set to * (wildcard) meaning "any value." This allows creating broad rules that apply to many situations.
Example Rules:
Rule 1: Cricket + SHARP + any market + any phase + any liquidity → Forward 90%
Rule 2: Soccer + MATCH_ODDS + LIVE + any source + any liquidity → Forward 60%
Rule 3: Any sport + any market + any phase + NORMAL + HIGH → Forward 20%
Specificity & Priority
When multiple rules match a bet, the most specific rule wins. Specificity is calculated as the number of non-wildcard dimensions (0 to 5).
Tie-breaking (when specificity is equal):
- Higher forward percentage wins (conservative/safe choice)
- If still tied: oldest rule wins (first-created)
4-Level Precedence Chain
Before even checking matrix rules, the system checks for overrides:
- User Override (highest priority): Agent has set a specific forward % for this particular user
- Market/Event Override: Agent has set a specific forward % for this particular sporting event
- Matrix Rule: The 5D rule engine described above
- Agent Default: The fallback percentage (set in agent settings)
The first match wins — if a user override exists, matrix rules are never consulted.
Sharp Detection: Identifying Professional Bettors
Sharp bettors (professionals who consistently beat the market) are the biggest risk to B-Book profitability. The system uses 5 independent detection methods, each contributing to a composite score.
The 5 Pillars
Pillar 1: CLV (Closing Line Value) — Weight: 30%
What it measures: Whether a bettor consistently gets odds better than the final (closing) odds.
How it works: For each settled bet, compare the odds the player got vs. the closing odds:
- CLV = (Closing Odds − Opening Odds) / Opening Odds
- Calculated over the last 500 bets, weighted by stake size
- Sharp threshold: Average CLV > 2% indicates a sharp bettor
Why it matters: If a player consistently beats the closing line, they have superior information or models — exactly the players you don't want to B-Book.
Pillar 2: Device Fingerprinting — Weight: 15%
What it measures: Whether multiple accounts are controlled by the same person/device.
Detection methods:
- Same device ID → 100% confidence
- Same canvas hash (browser fingerprint) → 90% confidence
- Same IP + browser combination → 70% confidence
- Same screen resolution + timezone → 30% confidence
Why it matters: Sharp bettors often use multiple accounts to bypass limits.
Pillar 3: IP/Network Correlation — Weight: 10%
What it measures: Whether different users share the same IP addresses.
How it works: Find users sharing 2+ IP addresses (one shared IP could be public WiFi, two is suspicious). Confidence increases with more shared IPs, maxing out at 5+.
Pillar 4: Betting Pattern Similarity — Weight: 20%
What it measures: Whether two users bet suspiciously similarly.
Metrics analyzed:
- Outcome correlation (same selections)
- Timing correlation (bets within 5 minutes of each other)
- Market overlap (percentage of same markets)
- Stake distribution similarity (similar bet sizes)
Pillar 5: Payment Method Overlap — Weight: 25%
What it measures: Whether users share bank accounts, UPI IDs, or wallet addresses.
Why it matters: Shared payment methods are a strong indicator of the same person or syndicate operating multiple accounts.
Composite Score
All 5 pillar scores are combined into a single 0-100 composite score:
- 0-30: NORMAL — standard recreational bettor
- 30-50: Elevated — monitor closely
- 50-80: Likely SHARP — recommend forwarding their bets 100%
- 80+: Definitely SHARP — automatic classification recommended
Collusion Detection: Preventing Agent Gaming
Collusion detection prevents agents from gaming the system by rapidly changing player classifications to exploit favorable forwarding rates.
The Problem
An unscrupulous agent could:
- Classify a player as SHARP (forward 90% of their bets)
- Wait for the player to go on a losing streak
- Quickly reclassify them as NORMAL (retain 80% of their bets)
- Profit from the retained losing bets
- Reclassify back to SHARP when the player starts winning
Cooling-Off Periods
To prevent this, classification changes don't take effect immediately:
- NORMAL → SHARP: 24-hour cooling-off (upgrading to sharp is relatively safe)
- SHARP → NORMAL: 72-hour cooling-off (downgrading from sharp is risky — could be gaming)
During the cooling-off period, the old classification remains active.
Flip Frequency Limits
Maximum 3 classification changes per week per user. This prevents rapid back-and-forth switching.
Collusion Score (0-180)
The system calculates a collusion score based on 4 signals:
| Signal | Max Score | What it detects |
|---|---|---|
| Flip Frequency | 50 | How often classifications are changed (6+ flips = max score) |
| Flip Timing | 50 | Whether flips correlate with winning streaks (flip before wins = gaming) |
| Retained vs Forwarded P&L | 50 | Asymmetry between retained win rate vs forwarded win rate |
| Volume Concentration | 30 | Single user dominating forwarded volume (>30% = flag) |
Severity Levels
- < 25 (NONE): No action needed
- 25-74 (INFORMATIONAL): Alert generated for ops team
- 75-149 (REVIEW): Manual approval required for future classification changes
- 150+ (AUTO_FREEZE): Agent is automatically frozen — all classification changes blocked, pending changes cancelled, P1 alert created. Admin must manually unfreeze.
Exposure Management
Exposure Ledger: Dual-Tier Architecture
The exposure ledger tracks how much risk each agent currently holds, using a high-performance dual-tier system:
Redis (Fast Tier)
- All read/write operations go through Redis first
- Sub-millisecond response times
- Atomic INCRBY/DECRBY operations for concurrent bet processing
- Keys expire after inactivity
PostgreSQL (Durable Tier)
- Redis data is flushed to PostgreSQL every 5 seconds (write-behind pattern)
- Serves as source of truth for reconciliation
- Used directly (with row locking) when utilization exceeds 85% to prevent over-commitment
Scope Types
Exposure is tracked across 5 scope types simultaneously:
| Scope | What it limits | Example |
|---|---|---|
| GLOBAL | Total exposure across everything | "No more than 500,000 total risk" |
| SPORT | Exposure per sport | "No more than 100,000 on Cricket" |
| MARKET | Exposure per event | "No more than 50,000 on India vs Australia" |
| NIGHT_PERIOD | Exposure during night hours | "No more than 200,000 between 11 PM - 7 AM" |
| WEEKLY_PERIOD | Exposure per rolling week | "No more than 1,000,000 per week" |
NO_NEW_RISK Flag
When any limit is fully exhausted (0 remaining capacity), the system sets a NO_NEW_RISK flag for that scope. This immediately blocks all new retained bets on that scope — everything is forwarded 100% until exposure decreases (through settlement or voiding).
Platform Event Cap
An aggregate cap of 5,000,000 paisa (50,000 INR) across ALL agents on a single event. This prevents coordinated large bets (syndicate attacks) from creating excessive platform-wide exposure on one event.
Panic Mode: Emergency Risk Control
What It Does
When an agent activates panic mode, the system immediately:
- Forwards 100% of all new bets (B-Book completely bypassed)
- Sets NO_NEW_RISK on all scopes (no retained positions)
- Places hedge orders on Betfair for ALL currently open retained positions
- Creates a P1 alert notifying the ops team
When to Use It
- Unexpected large losses on a single event
- Suspicion of coordinated sharp betting
- External events creating unpredictable outcomes (weather, player injuries)
- System issues requiring investigation
Cost Escalation
Panic mode has increasing costs to prevent abuse:
- 1st activation: Free (platform absorbs hedging spread)
- 2nd activation: Free
- 3rd+ activation: 100% charged to the agent (full hedging spread)
Cooling-Off Period
After activation, there's a mandatory 30-minute cooling-off before the agent can deactivate panic and return to normal matrix-based routing. The minimum hedge duration is 15 minutes.
Queued Changes
While panic is active, any configuration changes (matrix rules, overrides) are queued and applied automatically when panic is deactivated.
Gaming Detection
The system monitors panic usage patterns to detect gaming:
- Frequency: 10+ panics in 21 days = high frequency score
- Asymmetry: If 80%+ of panics occur when the agent is losing, this indicates gaming (activating panic only when losing to hedge losses, then deactivating when winning)
- Consequences: Warnings → full spread charges → panic feature suspended
Book Balancing
Book balancing is an optional feature that helps agents maintain balanced risk exposure.
How It Works
For each event, the system tracks the worst-case exposure — the maximum amount the agent could lose across all possible outcomes.
Example:
- Agent has retained 3 BACK bets on Team A (total liability: 15,000)
- Agent has retained 1 BACK bet on Team B (total liability: 5,000)
- Worst case: Team A wins → agent pays 15,000
- Imbalance ratio: (15,000 - 5,000) / 20,000 = 50%
Bet Impact Evaluation
When a new bet arrives, the system checks if it would improve or worsen the balance:
-
Hedging bet (e.g., a bet on Team B when most exposure is on Team A):
- At 85%+ utilization: gets 10% bonus retention capacity
- Encouraged to naturally balance the book
-
Worsening bet (e.g., another bet on Team A when already heavily exposed):
- At 85-95% utilization: retention reduced proportionally to imbalance
- At 95%+ utilization: retention set to zero (bet fully forwarded)
Balancing Score
Each bet gets a balancing score from -1.0 to +1.0:
- -1.0: Perfect hedge (maximum balance improvement)
- 0.0: Neutral impact
- +1.0: Maximum worsening of balance
Settlement: How Results Flow Back
When a sporting event concludes and results are known, the settlement cascade processes all open positions.
Settlement Flow
-
Load Positions: Find all OPEN positions for the settled event/market
-
Determine Outcome per position:
- BACK bet + selection won → Agent LOSES (pays out liability)
- BACK bet + selection lost → Agent WINS (keeps the stake)
- LAY bet + selection won → Agent WINS (keeps the stake)
- LAY bet + selection lost → Agent LOSES (pays out liability)
- VOID → All money returned (no P&L)
-
P&L Calculation (from agent's perspective):
- WIN: profitLoss = -liability (agent pays the winner)
- LOSS: profitLoss = +stake (agent keeps the loser's stake)
- VOID/PUSH: profitLoss = 0
-
Transactional Write: Each position is settled atomically with row locking to prevent double-settlement
-
Exposure Decrement: After settlement, exposure counters are reduced for all applicable scopes
-
NO_NEW_RISK Re-evaluation: If exposure has dropped below limits, the NO_NEW_RISK flag is cleared, allowing new bets again
Safety Mechanisms
- Idempotency Keys: SHA-256 hash of position ID + result prevents double-payment if settlement runs twice
- Row Locking:
SELECT ... FOR UPDATE SKIP LOCKEDprevents race conditions - Failure Isolation: One position failing doesn't block others from settling
Dead Letter Queue (DLQ): Failed Bet Handling
When bet processing, settlement, or hedging fails despite retries, the failed operation is sent to the Dead Letter Queue.
Retry Pipeline
In-Process (Synchronous) Retries:
- Immediate attempt
- After 50ms delay
- After 200ms delay
- After 500ms delay
If all 4 attempts fail → enqueued to DLQ.
DLQ (Asynchronous) Retries:
- After 5 minutes
- After 15 minutes
- After 30 minutes
If all 3 escalation retries fail → status becomes ESCALATED and a P1 alert is created.
Poison Detection
Some bets can never succeed (user doesn't exist, market is closed, etc.). These "poison bets" skip the retry pipeline entirely and go straight to ESCALATED status.
Manual Resolution
Admins can resolve escalated entries with one of 4 options:
- VOID_REFUND: Cancel the bet and refund the player
- FORCE_PROCESS: Force-settle despite the error
- MANUAL_OVERRIDE: Admin manually fixes the underlying issue
- ACKNOWLEDGED: Logged for records, no further action
DLQ Sources
| Source | What failed |
|---|---|
| BET_PROCESSING | Initial bet placement cascade |
| SETTLEMENT | Result settlement cascade |
| HEDGE_EXECUTION | Betfair hedge order placement |
Reconciliation
Reconciliation ensures the exposure ledger (fast Redis counters) stays in sync with actual open positions (source of truth in PostgreSQL).
Nightly Reconciliation
Runs automatically at 4:00 AM IST every day:
- For each agent + scope combination:
- Read the exposure ledger value
- Calculate the actual sum of open position liabilities from the database
- Compare the two values
- If there's any drift (mismatch):
- Log a warning
- Create a P2 alert (RECONCILIATION_MISMATCH)
- Does NOT auto-correct — requires human investigation
Manual Recompute
Admins can manually recompute and sync the exposure ledger for a specific agent/scope after investigating a mismatch. This updates both Redis and PostgreSQL to match the actual open positions.
Alert System
Alert Types
| Alert Type | Severity | Trigger |
|---|---|---|
| NO_NEW_RISK_ACTIVATED | P2 | An exposure limit was fully exhausted |
| SETTLEMENT_FAILURE | P1 | A position failed to settle after retries |
| HEDGE_FAILED | P1 | Betfair hedge order couldn't be placed |
| DLQ_ENTRY | P2 | A bet/settlement entered the dead letter queue |
| RECONCILIATION_MISMATCH | P2 | Nightly reconciliation found a discrepancy |
| BETFAIR_DOWN | P1 | 3 consecutive health checks to Betfair failed |
| PANIC_ACTIVATED | P1 | An agent activated panic mode |
| COLLUSION_FREEZE | P1 | An agent was frozen due to collusion score exceeding 150 |
Severity Levels
- P1 (Critical): Immediate attention required. Sent via Slack and Telegram.
- P2 (Warning): Should be reviewed soon. Sent via Slack.
- P3 (Info): Informational, review when convenient.
Alert Lifecycle
- ACTIVE: Alert created, notifications sent
- ACKNOWLEDGED: Someone has seen it and is investigating
- RESOLVED: Issue has been fixed
User Interface Pages
Agent-Facing Pages (11 pages)
1. Dashboard (Command Center)
The main overview page showing:
- Sleep-Well Number: A large utilization percentage with traffic light (GREEN/AMBER/RED) indicating overall risk health
- Risk Thermometer: Visual gradient bar from green (safe) through amber (caution) to red (danger)
- Exposure Bar Chart: Top 8 markets by retained liability
- Utilization Trend: 24-hour area chart showing how exposure has changed
- Retained vs Forwarded Chart: Stacked bar showing liability breakdown over time
- Player Heatmap: Grid of player initials color-coded by activity level (active/moderate/idle)
- Top High-Stakes Players: Ranked leaderboard of the 5 biggest bettors
- B-Book Status Panel: Shows if B-Book is enabled, balancing status, matrix version
- Panic Button: Red emergency button with cost tier warning and cooling-off timer
2. Bet History
Complete ledger of all bets with filtering and detail views:
- Filter by status (OPEN, SETTLED, CANCELLED, etc.), side (BACK/LAY), date range
- Each bet shows: ID, user, event, selection, side, stake, odds, routing status
- Routing badges: RETAINED (blue), FORWARDED (purple), SPLIT (amber), PANIC_FORWARDED (red)
- Expandable detail view showing cascade positions at each agent level
- Cash Out: Calculate and offer cash-out value with margin
- Cancel: Cancel open bets with confirmation
3. Exposure Drill-Down
Detailed view of exposure across all scopes:
- 4 summary cards: Total Retained, Total Forwarded, Peak Utilization, NO_NEW_RISK Scopes
- Filter by scope type and search by scope key
- Each scope shows: utilization bar with 50% and 85% threshold markers, back/lay breakdown, imbalance ratio
4. Matrix Editor
Create and manage forwarding rules:
- Rules sorted by specificity (most specific first)
- Each rule shows: 5 dimension badges, forward %, status toggle
- Rule creation form with dropdown selectors for all 5 dimensions
- Matrix Test: Enter test parameters and see which rule would match and what percentage would be forwarded
5. Bet Simulator
Dry-run a bet through the cascade without actually placing it:
- Enter bet parameters (selection, side, stake, odds, market type, sport, phase, liquidity)
- See cascade breakdown: each agent level's retention, forwarding, and the rule that was applied
- Shows hedge amount and any stake reductions
6. User Management
Classify and manage player risk profiles:
- View all users with their classification badges: NORMAL (gray), SHARP (red), VIP (amber), NEW_ACCOUNT (cyan)
- Set user-level forwarding overrides (e.g., "Forward 100% of Sharp Player X's bets")
- View sharp scores and recommended classifications
- Set per-click win limits, daily aggregate win limits, and minimum stakes per user
7. Sharp Analytics
Deep dive into sharp detection scores:
- View all 5 pillar scores per user (CLV, Device, IP, Pattern, Payment)
- Color-coded bars (0-100 scale) for each metric
- Recommended classification based on composite score
- Expandable signal explanations
8. Collusion Detection
Monitor for classification gaming:
- Collusion scores with severity badges (NONE/INFORMATIONAL/REVIEW/AUTO_FREEZE)
- Individual signal breakdowns (flip frequency, timing, P&L asymmetry, volume concentration)
- Classification flip history showing all changes over time
9. Hierarchy Visualization
Interactive tree view of the agent hierarchy:
- Parent agent at top with visual connectors to children
- Each node shows: agent code, name, status badge, role
- Color coding: Indigo (current agent), Green (active), Red (suspended), Amber (platform), Cyan (player)
- Shows bet flow direction through the hierarchy
10. Settings
All configurable parameters:
- Default Forward %: Slider for the fallback forwarding percentage
- Balancing: Toggle on/off, threshold percentage, top-slice percentage
- Time Periods: Night period start/end times, weekly period start day
- Timezone: Dropdown of common timezones
- Exposure Limits: Add/edit/delete limits by scope type with amounts
- User Overrides: List of active per-user forwarding overrides
- Market Event Overrides: Per-event forwarding overrides with expiration
11. Setup Wizard
4-step onboarding for new agents:
- Welcome: Explanation of what B-Book is and its benefits
- Risk Appetite: Choose from 3 presets:
- Conservative (80% forwarded, 20% retained) — low risk, low reward
- Moderate (50/50) — balanced approach
- Aggressive (20% forwarded, 80% retained) — high risk, high reward
- Limits Setup: Set global and sport-specific exposure limits
- Confirmation: Review and save
Admin-Facing Pages (8 pages)
1. Admin Dashboard
System-wide health overview:
- Service health indicators (green/red)
- Circuit breaker state (CLOSED = healthy, OPEN = protecting system)
- Total exposure across all agents
- Alert counts by severity (P1/P2/P3)
- Pending classification changes awaiting application
2. Agent Dashboard (Admin View)
Same as agent dashboard but viewable for any agent in the system. Admins can activate/deactivate panic mode on behalf of agents.
3. Agent Matrix Management
View and edit matrix rules for any agent. Useful for ops team to help agents configure rules or fix misconfigured matrices.
4. Agent Settings (Admin)
Adjust configuration for any agent. Can modify limits, defaults, and overrides.
5. Agent Bets (Admin)
View all bets for any agent. Additional capabilities: void bets, partial void.
6. Alerts Center
Central alert management:
- Filter by severity (P1/P2/P3), type, status (ACTIVE/ACKNOWLEDGED/RESOLVED)
- Acknowledge and resolve alerts
- Detail modal with full metadata
7. Failed Bets (DLQ)
Dead letter queue management:
- Filter by status (PENDING/RETRYING/ESCALATED/RESOLVED) and source
- View error details, retry counts, payloads
- Retry failed entries or resolve manually
8. Reconciliation
Run and review exposure reconciliation:
- Manual "Run Reconciliation" button
- Results showing per-agent drift between ledger and computed exposure
- Green/red status indicators for matched/mismatched
Visualization Components
The dashboard uses several custom visualization components:
| Component | What it shows |
|---|---|
| Risk Thermometer | Gradient bar (green→amber→red) with diamond indicator showing current utilization |
| Traffic Light | 3-light indicator with pulse animation showing GREEN/AMBER/RED status |
| Sleep-Well Number | Large utilization percentage with color-coded bar |
| Exposure Bar Chart | Horizontal bars showing top 8 markets by retained liability |
| Utilization Area Chart | 24-hour trend of exposure utilization with gradient fill |
| Retained/Forwarded Chart | Stacked bars showing retained (blue) + forwarded (purple) over time |
| Player Heatmap | Grid of player initials, color-coded by activity level |
| Top Players Table | Ranked leaderboard (1-5) with medal for rank 1 |
| B-Book Status Panel | Status toggles showing if B-Book, balancing, and algorithm are active |
| Anomaly Alert Badge | Red badge showing count of active anomalies |
Data Models (Database Schema)
Core Tables
| Table | Purpose | Key Fields |
|---|---|---|
| v3_bets | All bets placed through B-Book | userId, agentId, eventId, selection, side, stake, odds, status |
| v3_positions | Retained/forwarded position per agent per bet | betId, agentId, positionType, stake, liability, potentialWin |
| v3_settlements | Settlement records per position | positionId, settlementType (WIN/LOSS/VOID), payout, profitLoss |
| v3_exposure_ledger | Current exposure per agent per scope | agentId, scopeType, scopeKey, retainedLiability, forwardedLiability |
| v3_forwarding_matrix_rules | 5D forwarding rules | agentId, marketType, sportType, eventPhase, sourceType, liquidityBand, forwardPercentage |
| v3_agent_limits | Exposure limits per scope type | agentId, limitType, sportType, limitAmount, isActive |
| v3_user_overrides | Per-user forwarding override | userId, agentId, forwardPercentage, expiresAt |
| v3_market_overrides | Per-event forwarding override | agentId, eventId, forwardPercentage, expiresAt |
| v3_user_classifications | Player classification (NORMAL/SHARP/VIP) | userId, agentId, classification |
| v3_classification_changes | Pending classification changes with cooling-off | agentId, userId, from, to, effectiveAt, status |
| v3_agent_trust_configs | Trust between upline/downline agents | uplineAgentId, downlineAgentId, trustLevel, minRetentionPercent |
| v3_dead_letter_queue | Failed operations awaiting retry/resolution | source, referenceId, errorMessage, retryCount, status |
| v3_alerts | System alerts | agentId, alertType, severity, status, message, metadata |
| v3_device_fingerprints | Device fingerprints for sharp detection | userId, deviceId, canvasHash, userAgent, ip |
| v3_ip_access_log | IP access history for correlation | userId, ip, firstSeen, lastSeen, requestCount |
| v3_clv_entries | Closing Line Value records | betId, userId, odds, closingOdds, stake, side |
| v3_agent_override_freezes | Agent freeze records from collusion detection | agentId, frozenBy, reason |
Key Numbers & Thresholds
| Parameter | Value | Purpose |
|---|---|---|
| Max Cascade Levels | 10 | Prevents infinite loops |
| Bet Processing Timeout | 110ms | Total cascade + write budget |
| Near-Limit Threshold | 85% | Switch to PostgreSQL locking |
| Hard Reject Threshold | 95% | Reject worsening bets |
| Hedge Bonus Factor | 10% | Extra capacity for hedging bets |
| Platform Event Cap | 50,000 INR | Max aggregate exposure per event |
| Exposure Flush Interval | 5 seconds | Redis → PostgreSQL sync |
| Default Per-Click Win Limit | 50,000 INR | Single bet payout cap |
| Default Daily Win Limit | 200,000 INR | Daily user payout cap |
| Default Minimum Stake | 100 INR | Below this, bet rejected |
| DLQ Fast Retries | 4 attempts | 0ms, 50ms, 200ms, 500ms delays |
| DLQ Escalation Retries | 3 attempts | 5min, 15min, 30min delays |
| Panic Cooling-Off | 30 minutes | Mandatory wait before deactivation |
| Minimum Hedge Duration | 15 minutes | Minimum time hedges must remain |
| CLV Window | 500 bets | Bets analyzed for CLV calculation |
| CLV Sharp Threshold | 2% | Average CLV above this = sharp |
| NORMAL→SHARP Cooling | 24 hours | Classification change wait |
| SHARP→NORMAL Cooling | 72 hours | Classification change wait |
| Max Flips Per Week | 3 | Classification change frequency limit |
| Collusion Auto-Freeze | 150+ | Score threshold for automatic freeze |
| Panic Gaming High Frequency | 10 in 21 days | Suspiciously frequent panic usage |
| Panic Gaming Asymmetry | 80% | Suspiciously correlated with losses |
API Endpoints Summary
The B-Book V3 backend exposes 50+ REST endpoints organized into these groups:
Bet Operations (6 endpoints)
- Place bet, simulate bet, list bets, get bet detail, cancel bet, cash-out offer
Exposure & Limits (8 endpoints)
- Get exposure by scope, get exposure detail, set limits, get limits, update limit, delete limit
Matrix Rules (5 endpoints)
- Create rule, list rules, update rule, delete rule, test matrix
User Management (6 endpoints)
- Classify user, get classification, set user override, set market override, get users, get user detail
Configuration (4 endpoints)
- Get agent config, update agent config, set trust config, get trust configs
Panic Mode (5 endpoints)
- Activate, deactivate, get status, queue config change, get queued changes
Settlement (2 endpoints)
- Settle event/market, list settlements
Sharp & Collusion Detection (5 endpoints)
- Run sharp check, get CLV, get collusion score, request classification change, get pending changes
Alerts & Monitoring (6 endpoints)
- List alerts, alert history, acknowledge, resolve, get counts, system health
DLQ Management (4 endpoints)
- List entries, retry entry, resolve entry, get statistics
Reconciliation (2 endpoints)
- Run reconciliation, manual recompute
Hierarchy (1 endpoint)
- Get agent hierarchy tree
Notification Channels
Slack Integration
All P1 and P2 alerts are sent to a configured Slack webhook with formatted messages including severity, alert type, agent ID, and relevant metadata.
Telegram Integration
Agents with linked Telegram accounts receive push notifications for alerts affecting their agents. Messages use HTML formatting for readability.
Help System
Every page in the B-Book UI includes a help button that opens a detailed guide with:
- Summary: One-paragraph explanation of the page
- Detail Points: 4+ bullet points explaining each feature
- Real-World Examples: 2+ practical scenarios showing how to use the feature
- Pro Tips: Expert advice for getting the most out of each feature
This ensures that even users unfamiliar with sports betting risk management can effectively use the system.
Technical Architecture
Performance Design
- Redis-first reads: Sub-millisecond exposure checks
- Write-behind pattern: Redis → PostgreSQL every 5 seconds
- Parallel processing: Independent operations run concurrently
- Integer arithmetic: Paisa-based calculations avoid floating-point errors
- Circuit breakers: Betfair and Redis have circuit breakers to gracefully handle outages
Safety Design
- Stake conservation: Mathematical guarantee that retained + forwarded = original
- Idempotency: SHA-256 keys prevent double-processing
- Row locking: Prevents race conditions in settlement and near-limit scenarios
- Immutable ledger: Positions and settlements are append-only, never modified
- Failure isolation: Individual failures don't cascade to other operations
Monitoring Design
- Real-time dashboards: 10-second refresh intervals
- Multi-channel alerts: Slack + Telegram notifications
- Nightly reconciliation: Automatic exposure verification
- Gaming detection: Behavioral analysis of agent actions
- Audit trail: Every classification change, override, and panic activation is recorded