Skip to main content

Hannibal B-Book System

Business and Functional Specification

Version 1.0 | January 2026

This document explains the B-Book system in non-technical terms. For implementation details and code specifications, see BBOOK_SYSTEM_DESIGN.md


Executive Summary

The B-Book is an optional business feature that allows Hannibal to act as the counterparty to user bets instead of passing all bets to external exchanges like Betfair or Pinnacle. When a recreational user places a bet, the platform can choose to "take the other side" of that bet using its own capital pool.

This creates an additional revenue stream because recreational bettors, on average, lose money over time. By taking the opposite side of their bets, the platform captures the margin that would otherwise go to external exchanges.

Key Principles:

  1. Completely Optional: The entire B-Book can be turned on or off with a single switch
  2. Risk Controlled: A maximum liability limit ensures the platform never risks more than intended
  3. Sharp Protection: Professional bettors (who win consistently) are never B-Booked
  4. Transparent Accounting: B-Book profits and losses are tracked separately from exchange operations
  5. Flexible Currency: Works with points today, designed to support real money in the future

Table of Contents

  1. Understanding the B-Book
  2. How Orders Flow Through the System
  3. The Capital Pool and Limits
  4. The Filter Engine: Routing Decisions
  5. Understanding Liability and Exposure
  6. Sharp User Management
  7. Settlement: When Events Conclude
  8. Accounting and Financial Tracking
  9. Administrative Controls
  10. Risk Monitoring and Safety
  11. Data Storage and State Management
  12. System Integration Points
  13. Error Scenarios and Handling
  14. Currency and Points System
  15. Performance and Scalability
  16. Quality Assurance
  17. Deployment and Operations
  18. Enabling B-Book on Existing Systems
  19. Security and Access Control
  20. Terminology Reference
  21. Decisions Requiring Input
  22. Worked Examples

1. Understanding the B-Book

1.1 The Two Ways to Handle Bets

When a user places a bet on Hannibal, the platform has two fundamental choices for how to handle it:

A-Book (Pass-Through): The bet is forwarded to an external exchange like Betfair or Pinnacle. The platform acts as an intermediary, earning a small commission. The platform has no financial stake in whether the user wins or loses—the exchange pays out winners and collects from losers.

B-Book (Counterparty): The platform itself takes the opposite side of the bet. If the user bets that Mumbai will win, the platform is effectively betting that Mumbai will lose. The platform uses its own capital pool to back this position.

1.2 Why Would the Platform B-Book?

The answer lies in statistics. Recreational bettors—casual users who bet for entertainment—lose money on average over time. Industry data suggests recreational bettors lose approximately 5-15% of their wagered amount over the long run.

When the platform takes the opposite side of recreational bets, it captures this statistical edge. Instead of letting Betfair profit from these users' losses, the platform keeps that margin itself.

However, professional bettors (called "sharps") consistently beat the market. They have positive expected value and would drain the B-Book pool over time. This is why sharp users must be identified and excluded from the B-Book—their bets always go to external exchanges.

1.3 The Hybrid Approach

Hannibal doesn't B-Book everything or nothing. Instead, it uses a sophisticated routing system that:

  • Sends sharp user bets entirely to exchanges
  • Sends a portion of recreational bets to the B-Book (up to configured limits)
  • Sends the remainder to exchanges
  • Can split a single bet across both venues

This hybrid approach maximizes revenue while managing risk.


2. How Orders Flow Through the System

2.1 The Journey of an Order

When a user places a bet, it goes through several decision points:

Step 1: Validation The system first validates the order—checking that the user has sufficient balance, the market is open, and the bet parameters are valid. This happens regardless of whether B-Book is enabled.

Step 2: B-Book Check If B-Book is disabled, the order goes directly to the exchange. If B-Book is enabled, the system proceeds to evaluate the order for potential B-Book routing.

Step 3: Sharp Check The system checks if the user is on the "sharp list"—a manually maintained list of professional bettors. If the user is sharp, their order goes entirely to the exchange, bypassing the B-Book completely.

Step 4: Capacity Calculation For non-sharp users, the system calculates how much of this order the B-Book can accept. This depends on multiple limits (explained in Section 3).

Step 5: Routing Decision Based on the capacity calculation, the system decides how to split the order:

  • If B-Book has full capacity: Up to the maximum percentage goes to B-Book
  • If B-Book is at limit: Order goes to exchange
  • If partial capacity: Order is split between B-Book and exchange

Step 6: Execution The B-Book portion is executed immediately (the platform records its position). The exchange portion is sent to Betfair or Pinnacle for execution.

Step 7: Confirmation The user receives a single confirmation showing their order was filled, with details about how it was routed (though this routing detail may be hidden from users based on business decisions).

2.2 Split Orders

A single user order may be split across venues. For example, a 100,000 point bet might be filled as:

  • 70,000 points via B-Book
  • 30,000 points via Betfair

The user experiences this as a single filled order. The split is tracked internally for accounting purposes.


3. The Capital Pool and Limits

3.1 What is the Pool?

The B-Book pool is the capital the platform allocates for taking the opposite side of bets. Think of it as a dedicated fund with a maximum size. The platform can never risk more than this pool limit, regardless of how many bets come in.

3.2 The Limit Hierarchy

The B-Book enforces limits at multiple levels to prevent concentration risk:

Global Pool Limit (e.g., 10,000,000 points) This is the absolute maximum total exposure across all markets, all selections, and all users combined. It represents the platform's total risk appetite for B-Book operations.

Per-Market Limit (e.g., 2,000,000 points) No single market (such as "Mumbai vs Chennai, Match Winner") can consume more than this limit. This prevents a single high-profile match from dominating the B-Book.

Per-Selection Limit (e.g., 500,000 points) No single selection within a market (such as "Mumbai to Win") can exceed this limit. This prevents excessive exposure to any single outcome.

Per-User Limit (e.g., 50,000 points) No single user can have more than this amount of B-Book exposure at any time. This prevents any individual from having outsized impact on the pool.

Percentage Cap (e.g., 70%) No more than this percentage of any single order can go to the B-Book. This ensures some portion always goes to the exchange, maintaining market connectivity.

3.3 How Limits Interact

When an order comes in, the system calculates available capacity by finding the most restrictive limit:

Consider a user placing a 100,000 point bet:

  • Global pool has 5,000,000 remaining capacity
  • This market has 1,000,000 remaining capacity
  • This selection has 200,000 remaining capacity
  • This user has 30,000 remaining capacity ← Most restrictive!
  • 70% rule allows 70,000 maximum

The B-Book can only accept 30,000 points (the user limit), even though other limits would allow more. The remaining 70,000 goes to the exchange.

3.4 Capacity Replenishment

The pool is self-replenishing:

  • When users lose B-Book bets, the pool grows (platform keeps the stake)
  • When users win B-Book bets, the pool shrinks (platform pays out)
  • When positions settle, capacity is released regardless of outcome
  • Opposite bets can offset each other, reducing net exposure

4. The Filter Engine: Routing Decisions

4.1 What is the Filter Engine?

The Filter Engine is the decision-making component that determines how each order should be routed. It evaluates every order against a series of rules and limits to produce a routing plan.

4.2 The Decision Process

The Filter Engine follows this logic for each order:

First Question: Is B-Book enabled? If the admin has disabled the B-Book, all orders go to exchanges. The Filter Engine effectively becomes a pass-through.

Second Question: Is this user on the sharp list? If yes, the entire order goes to the exchange. Sharp users never interact with the B-Book.

Third Question: What is the available B-Book capacity? The engine calculates capacity across all limit levels (global, market, selection, user, percentage) and takes the minimum.

Fourth Question: Does this order help balance existing exposure? If the platform already has significant exposure on one side (say, lots of BACK bets on Mumbai), a LAY bet on Mumbai would reduce that exposure. Balancing orders may receive preferential treatment—they help the platform rather than increasing risk.

Fifth Question: Is there a side imbalance? If the ratio of BACK to LAY positions exceeds a threshold (say, 3:1), the engine may restrict new bets on the heavy side while still accepting bets on the light side.

4.3 The Routing Output

After evaluation, the Filter Engine produces a routing plan specifying:

  • How many points should go to B-Book
  • How many points should go to exchange
  • The reason if any limits were hit (for logging and debugging)

4.4 Balancing and Its Benefits

When opposite bets exist on the same selection, they offset each other:

Example: If the platform has B-Booked 100,000 points of BACK bets on Mumbai, its liability is the potential payout if Mumbai wins. If LAY bets then come in, they reduce this liability because LAY bettors lose if Mumbai wins.

A perfectly balanced selection (equal BACK and LAY liability) has zero net exposure—the platform profits regardless of the outcome through the built-in margin.


5. Understanding Liability and Exposure

5.1 What is Liability?

Liability is the maximum amount the platform could lose on a position if the outcome goes against it.

For BACK Bets (User bets something will happen): The platform is effectively laying the bet. If the selection wins, the platform must pay out. Liability = Stake × (Odds - 1)

Example: User backs Mumbai at odds 2.50 with 10,000 points Platform liability = 10,000 × (2.50 - 1) = 15,000 points

For LAY Bets (User bets something won't happen): The platform is effectively backing the bet. If the selection loses, the platform keeps the stake. Liability = Stake

Example: User lays Mumbai at odds 2.50 with 10,000 points Platform liability = 10,000 points

5.2 Net Exposure

The actual risk is not the sum of all liabilities—it's the difference between opposing positions.

Net Exposure = |BACK Liability - LAY Liability|

Example for Mumbai Win selection:

  • Total BACK liability: 100,000 points
  • Total LAY liability: 60,000 points
  • Net exposure: 40,000 points

The platform's maximum loss on this selection is 40,000 points, not 160,000.

5.3 Position Direction

Based on net exposure, the platform's position can be described as:

Short (More BACK than LAY): Platform loses if selection wins Long (More LAY than BACK): Platform loses if selection loses Balanced (Equal BACK and LAY): Platform wins regardless of outcome

5.4 Multi-Level Tracking

The system tracks exposure at every level:

  • Per selection (Mumbai Win, Mumbai Lose, Draw)
  • Per market (aggregate of all selections)
  • Per user (that user's total B-Book exposure)
  • Per fixture (all markets for a match)
  • Global (entire platform B-Book exposure)

This multi-level tracking enables sophisticated risk management and limit enforcement.


6. Sharp User Management

6.1 Who are Sharp Users?

Sharp users are professional or highly skilled bettors who consistently achieve positive returns. They beat the market by:

  • Finding value in odds before they move
  • Exploiting pricing inefficiencies
  • Using sophisticated models or insider knowledge
  • Timing bets strategically (e.g., close to event start)

Over time, sharp users would drain the B-Book pool. They must be excluded.

6.2 Identifying Sharp Users

For the initial version, sharp identification is manual. The operations team reviews user performance and flags users as sharp based on criteria such as:

High Win Rate: Sustained win rate above 55% over 200+ bets Positive Closing Line Value: Their bets consistently beat the closing price Precise Stakes: Using exact amounts (e.g., 8,347 points) rather than round numbers Strategic Timing: Placing bets just before events start Market Selection: Focusing on niche or low-liquidity markets

Future versions may include automated sharp detection based on these metrics.

6.3 The Sharp List

Sharp users are maintained in a list with the following information:

  • User identifier
  • Reason for classification (why they were flagged)
  • Who added them (admin accountability)
  • When they were added
  • Whether classification is active

6.4 Impact of Sharp Classification

When a user is added to the sharp list:

  • All future orders route 100% to exchanges
  • Existing B-Book positions remain until settled (not retroactively changed)
  • The change takes effect immediately for new orders
  • The user is not notified (internal classification)

Sharp users can be removed from the list if circumstances change (e.g., their edge disappears). Removal restores normal B-Book eligibility.


7. Settlement: When Events Conclude

7.1 The Settlement Process

When an event concludes (e.g., Mumbai wins the match), all B-Book positions on that selection must be settled:

Step 1: Retrieve All Open Positions The system gathers all B-Book positions for the concluded selection that are still marked as open.

Step 2: Calculate Each Position's Outcome For each position, determine whether the user won or lost based on their bet type and the actual result.

Step 3: Update User Balances Winners receive their payouts credited to their balance. Losers have already had their stakes deducted (at bet placement), so no further action needed.

Step 4: Update Pool State The platform's B-Book P&L is recorded. Winning positions (for users) debit the pool. Losing positions (for users) credit the pool.

Step 5: Release Capacity Once settled, the positions no longer count against limits. Capacity is freed for new bets.

Step 6: Mark Positions Settled Each position is marked as settled with a timestamp, preventing double-settlement.

7.2 Settlement Outcomes by Position Type

If the selection WINS:

User's Bet TypeUser OutcomePlatform Outcome
BACK (bet it would happen)User winsPlatform pays liability
LAY (bet it wouldn't happen)User losesPlatform keeps stake

If the selection LOSES:

User's Bet TypeUser OutcomePlatform Outcome
BACK (bet it would happen)User losesPlatform keeps stake
LAY (bet it wouldn't happen)User winsPlatform pays liability

7.3 Void and Cancelled Events

Sometimes events are voided (cancelled, abandoned, or result unknown):

  • All stakes are returned to users
  • No profit or loss recorded
  • Positions marked as voided (not settled)
  • Capacity released

7.4 Settlement Example

Selection: Mumbai Win at odds 2.50 Result: Mumbai WINS

Positions:

  • User A: BACK 10,000 points → Wins 15,000 (Platform pays 15,000)
  • User B: BACK 5,000 points → Wins 7,000 (Platform pays 7,000)
  • User C: LAY 8,000 points → Loses 8,000 (Platform keeps 8,000)

Platform net result: -15,000 - 7,000 + 8,000 = -14,000 points (loss)

If Mumbai had LOST:

  • User A: Loses 10,000 (Platform keeps 10,000)
  • User B: Loses 5,000 (Platform keeps 5,000)
  • User C: Wins 12,000 (Platform pays 12,000)

Platform net result: +10,000 + 5,000 - 12,000 = +3,000 points (profit)


8. Accounting and Financial Tracking

8.1 The Critical Separation

B-Book accounting and exchange accounting are completely separate.

This separation exists because the agent model only applies to exchange orders:

  • Agents distribute points to their punters
  • When punters bet on exchanges, settlement flows through the agent structure
  • Agents share in profits/losses from their punters' exchange activity

B-Book orders bypass this entirely:

  • The platform is the counterparty, not an exchange
  • There is no external settlement to reconcile
  • P&L belongs directly to the platform
  • Agents have no claim to B-Book profits or losses

8.2 What This Means in Practice

For Exchange Orders:

  • User P&L flows through agent accounting
  • Weekly settlement between agents and platform
  • Commission share paid to agents
  • NGR (Net Gaming Revenue) share if profitable

For B-Book Orders:

  • User P&L is directly with the platform
  • No agent involvement
  • No commission sharing
  • Platform keeps 100% of edge

8.3 Order-Level Tracking

Each order records how it was split:

  • B-Book portion amount
  • Exchange portion amount
  • Routing venue (B-Book only, exchange only, or split)
  • P&L calculated separately for each portion at settlement

8.4 Commission Handling

Exchange Orders: Standard commission charged on winnings, flowing through the existing agent commission structure.

B-Book Orders: No commission charged. The platform's profit is the statistical edge on recreational flow, not a commission fee.

8.5 Ledger and Audit Trail

All B-Book transactions create ledger entries:

  • When a B-Book fill occurs, an entry records the exposure increase
  • When settlement occurs, entries record the P&L
  • These entries are tagged distinctly from exchange entries
  • Full audit trail maintained for regulatory and reconciliation purposes

8.6 B-Book Reporting

The platform generates B-Book-specific reports showing:

  • Total volume routed to B-Book
  • Realized P&L (settled positions)
  • Unrealized P&L (open positions marked to market)
  • Pool utilization over time
  • Peak exposure levels
  • Win rate and other performance metrics

8.7 Impact on Agent Settlement

When calculating what agents are owed or owe:

  • Only exchange orders are considered
  • B-Book portions of split orders are excluded
  • Agent commission share based on exchange activity only
  • NGR calculations exclude B-Book P&L

9. Administrative Controls

9.1 The Master Switch

The most important control is the B-Book enable/disable toggle:

When Disabled:

  • All orders route to exchanges
  • Filter Engine is bypassed
  • Existing B-Book positions remain until settled
  • B-Book state is preserved but not updated

When Enabled:

  • Filter Engine evaluates every order
  • Orders may be routed to B-Book or exchange
  • All limits and rules enforced

9.2 Configurable Limits

Administrators can adjust all limits through the admin panel:

SettingPurposeTypical Default
Global Pool LimitMaximum total exposure10,000,000 points
Per-Market LimitMaximum exposure per market2,000,000 points
Per-Selection LimitMaximum exposure per selection500,000 points
Per-User LimitMaximum exposure from any user50,000 points
Max B-Book PercentageMaximum % of any order for B-Book70%
Side Imbalance ThresholdRatio triggering side restriction3.0
Auto-Hedge ThresholdPool % triggering auto-hedge alerts80%
Emergency Shutdown ThresholdPool % triggering automatic suspension95%
Daily Loss LimitDaily loss triggering suspension500,000 points

9.3 Sharp List Management

Admins can:

  • View all users on the sharp list
  • Add users to the sharp list (with required reason)
  • Remove users from the sharp list
  • See who added each user and when

9.4 Real-Time Monitoring

The admin dashboard shows live B-Book status:

  • Current pool utilization percentage
  • Capacity remaining at each level
  • Largest exposures by market and selection
  • Today's P&L
  • Side imbalance warnings
  • Recent routing decisions

9.5 Configuration Change Audit

All configuration changes are logged:

  • Who made the change
  • When it was made
  • What was changed (old value → new value)
  • IP address and session information

10. Risk Monitoring and Safety

10.1 Automated Monitoring

The system continuously monitors B-Book health metrics:

  • Pool utilization (updated in real-time)
  • Daily P&L (cumulative throughout the day)
  • Side imbalance ratios
  • Market concentration (any single market dominating)
  • Selection concentration (any single selection dominating)

10.2 Alert Thresholds

Alerts are triggered at specific thresholds:

Warning Level (e.g., 80% utilization):

  • Operations team notified
  • Increased monitoring recommended
  • No automatic action taken

Critical Level (e.g., 95% utilization):

  • Immediate notification to all stakeholders
  • B-Book may auto-suspend
  • Manual intervention required

Daily Loss Approaching (e.g., 80% of limit):

  • Warning notification sent
  • Increased scrutiny on new positions

Daily Loss Breached (e.g., 100% of limit):

  • B-Book automatically suspended
  • Immediate investigation required

10.3 Side Restriction

When the imbalance ratio exceeds threshold:

  • Heavy side orders restricted (still go to exchange)
  • Light side orders encouraged (accepted to B-Book)
  • This naturally rebalances exposure

Example: If BACK:LAY ratio is 4:1 (threshold 3:1):

  • New BACK bets: Route to exchange only
  • New LAY bets: Eligible for B-Book (helps balance)

10.4 Emergency Shutdown

In extreme scenarios, the system can automatically suspend B-Book:

  • Pool utilization exceeds emergency threshold
  • Daily loss limit breached
  • Unusual activity detected

When suspended:

  • No new B-Book fills accepted
  • All orders route to exchange
  • Existing positions unaffected (settle normally)
  • Requires manual intervention to re-enable

10.5 Auto-Hedge Concept (Future)

When exposure becomes uncomfortably large on a selection, the platform could automatically place opposing bets on exchanges to reduce B-Book exposure. This is planned for future versions; initial version relies on manual monitoring and intervention.


11. Data Storage and State Management

11.1 What Data is Stored

The B-Book requires storing several types of data:

Configuration Data:

  • All limit settings
  • Enable/disable state
  • Threshold values

Position Data:

  • Individual B-Book fills (who bet what, at what odds)
  • Status (open, settled, voided)
  • Settlement details (P&L, timestamp)

State Data:

  • Selection-level exposure (aggregated by selection)
  • Market-level exposure (aggregated by market)
  • User-level exposure (aggregated by user)
  • Global pool state (total exposure, utilization)

Reference Data:

  • Sharp user list
  • P&L records for audit

11.2 Speed vs Durability Trade-off

B-Book operations need to be fast (capacity checks on every order) but also durable (can't lose position data).

The system uses a two-layer approach:

  • Fast Layer (Cache): For quick reads during order processing
  • Durable Layer (Database): Source of truth for all data

Both are kept in sync: writes go to both, reads prefer cache but fall back to database.

11.3 State Consistency

The system ensures state is always consistent:

  • All updates happen atomically (all-or-nothing)
  • If cache and database ever disagree, database wins
  • On system startup, cache is rebuilt from database
  • Scheduled reconciliation catches any drift

11.4 Position State Updates

When a B-Book fill occurs, multiple state updates happen together:

  1. Position record created
  2. Selection state updated (liabilities adjusted)
  3. Market state updated (total exposure adjusted)
  4. User state updated (user's exposure adjusted)
  5. Pool state updated (global exposure adjusted)

All five updates succeed or fail together—never partially.


12. System Integration Points

12.1 Order Service Integration

The B-Book integrates at the order routing stage:

  • After order validation, before exchange submission
  • Receives validated order details
  • Returns routing decision (how to split)
  • Executes B-Book fill if applicable

12.2 Exchange Connector Integration

Works alongside existing exchange connections:

  • B-Book portion handled internally
  • Exchange portion forwarded to Betfair/Pinnacle
  • Results combined for user response

12.3 Settlement Service Integration

When events conclude:

  • Settlement service receives event results
  • Triggers B-Book position settlement
  • Triggers exchange position settlement (existing flow)
  • Results recorded in respective accounting systems

12.4 Accounting System Integration

B-Book creates its own accounting entries:

  • Ledger entries for B-Book fills
  • Ledger entries for B-Book settlements
  • Clearly tagged and separated from exchange entries
  • Available for reconciliation and reporting

12.5 User Balance Integration

B-Book affects user balances directly:

  • Stakes deducted at bet placement (same as exchange)
  • Winnings credited at settlement
  • Uses existing balance management (points system)

13. Error Scenarios and Handling

13.1 Exchange Unavailable

If Betfair or Pinnacle becomes unavailable:

With B-Book Enabled:

  • Sharp users: Orders rejected (can't route to exchange)
  • Non-sharp users: Attempt to fill via B-Book up to limits
  • If B-Book has capacity: Order filled via B-Book
  • If B-Book at limit: Order rejected

With B-Book Disabled:

  • All orders rejected until exchange recovers

13.2 Concurrent Orders Exceeding Limits

Multiple orders arriving simultaneously could theoretically exceed limits:

Prevention:

  • Capacity is reserved before filling
  • Reservation uses locking to prevent races
  • If reservation fails (another order grabbed capacity), retry or route to exchange

13.3 Partial Fill Scenarios

Various partial fill situations can occur:

ScenarioOutcome
B-Book fills 70%, exchange fills 30%Success, full order filled
B-Book fills 70%, exchange rejects 30%Partial fill (70%) returned to user
B-Book fails, exchange succeedsExchange-only fill
Both failOrder rejected, no state changes

13.4 Settlement Failures

If settlement partially fails:

  • Already-settled positions remain settled
  • Failed positions retry automatically
  • Never double-settle (idempotent checks)
  • Alert generated for manual review if retries exhaust

13.5 Missing Event Results

If event results don't arrive:

  • Positions remain open
  • Exposure continues counting against limits
  • Alert after 24 hours
  • Admin can manually settle or void

13.6 Price Differences

B-Book fills at the requested odds, not market odds:

  • User gets exactly what they asked for
  • No price slippage (unlike exchanges where price may move)
  • This is a user benefit but means platform can't get better prices

14. Currency and Points System

14.1 Current Implementation

The B-Book operates on Hannibal's points system:

  • All stakes, payouts, and limits are in points
  • Points are Hannibal's internal unit of value
  • No direct currency conversion in B-Book logic

14.2 Currency Abstraction

The system is designed to be currency-agnostic:

  • All monetary operations go through a "currency provider"
  • Current provider implements points operations
  • Future providers could implement INR, USD, crypto, etc.

14.3 Currency Provider Operations

A currency provider handles:

  • Checking user balances
  • Reserving funds for pending bets
  • Debiting (taking money out)
  • Crediting (putting money in)
  • Pool operations (platform's B-Book fund)

14.4 Multi-Currency Future

If Hannibal supports multiple currencies:

  • Each could have its own B-Book pool
  • Limits configured per currency
  • Reporting in each currency plus aggregated
  • Exchange rates for consolidated reporting

15. Performance and Scalability

15.1 Speed Requirements

B-Book operations must be fast:

  • Sharp check: Under 5 milliseconds
  • Capacity calculation: Under 10 milliseconds
  • B-Book fill: Under 50 milliseconds
  • Users should not perceive any delay

15.2 Volume Requirements

The system should handle:

  • Hundreds of orders per second during peaks
  • Thousands of concurrent open positions
  • Tens of thousands of positions settled daily

15.3 Caching Strategy

Frequently-accessed data is cached for speed:

  • Sharp list (checked on every order)
  • Pool state (current utilization)
  • Selection states (for active markets)
  • Configuration (limits and thresholds)

Cache is invalidated when underlying data changes.

15.4 Scaling Approach

As volume grows, the system can scale:

  • Multiple instances of the Filter Engine (stateless)
  • Partitioned position state (by market or selection)
  • Queue-based settlement (multiple workers)
  • Database read replicas for reporting

15.5 Database Efficiency

Large tables are optimized:

  • Older positions moved to archive storage
  • Indexes on frequently-queried fields
  • Bulk operations for settlement
  • Connection pooling for efficiency

16. Quality Assurance

16.1 Testing Philosophy

The B-Book handles real money (or points with real value), so testing is comprehensive:

  • Every feature tested before deployment
  • Edge cases specifically targeted
  • Performance tested under load
  • Failure scenarios simulated

16.2 Test Categories

Unit Tests: Individual functions work correctly

  • Capacity calculation returns correct values
  • Liability calculation is accurate
  • Sharp check returns correct result

Integration Tests: Components work together

  • Full order flow from placement to fill
  • Settlement from event result to payout
  • Configuration changes take effect

Load Tests: System handles volume

  • Many concurrent orders
  • Many concurrent settlements
  • No race conditions or data corruption

16.3 Critical Test Scenarios

ScenarioWhat's Tested
Two orders exceed limitOnly one gets B-Book fill
Settlement during orderBoth complete without conflict
Cache missSystem falls back to database
Emergency shutdownNew orders route to exchange
Sharp user addedNext order goes to exchange
Configuration changeNew limits apply immediately

17. Deployment and Operations

17.1 Deployment Options

Option A: Within Main Application B-Book logic runs inside the main Hannibal backend. Simpler to deploy and operate, but B-Book issues could affect the entire system.

Option B: Separate Service B-Book runs as its own service, communicating with main backend. More complex but provides isolation—B-Book problems don't affect order routing to exchanges.

17.2 Feature Flags

Gradual rollout is controlled via feature flags:

  • Enable for specific users first
  • Enable for a percentage of users
  • Enable specific features (like auto-hedge)
  • Emergency kill switch

17.3 Rollback Procedure

If problems are detected after deployment:

  1. Disable B-Book (single switch, immediate)
  2. Verify new orders route to exchange
  3. Existing positions continue to settle normally
  4. Investigate and fix the issue
  5. Re-enable when resolved

17.4 Monitoring Dashboards

Operations team monitors via dashboards:

  • Pool health (utilization, capacity, status)
  • P&L metrics (daily, cumulative, by market)
  • Volume metrics (orders routed, fill rates)
  • Risk metrics (largest exposures, imbalances)
  • Performance metrics (latency percentiles)

17.5 Alerting

Automated alerts via email, Slack, or SMS:

  • Pool utilization warnings
  • Daily loss warnings
  • Side imbalance warnings
  • System errors or failures

18. Enabling B-Book on Existing Systems

18.1 Prerequisites

Before enabling B-Book on a running Hannibal instance:

  1. Database updated with new tables
  2. Cache layer deployed and connected
  3. Admin interface updated with B-Book controls
  4. Monitoring dashboards configured
  5. Alerting configured and tested
  6. Operations team trained

18.2 Database Changes

New tables are added to store B-Book data. Existing order table gains new columns to track routing. This is done via database migration scripts that can be run during a maintenance window.

18.3 Gradual Enablement

Recommended rollout phases:

Phase 1: Shadow Mode (1 week) B-Book logic runs but doesn't affect real routing. Logs show what would have happened. Validates calculations are correct.

Phase 2: Limited Rollout (2 weeks) Enable for 5% of recreational users. Use conservative limits (e.g., 1M pool). Monitor closely, ready to disable quickly.

Phase 3: Expanded Rollout (2 weeks) Enable for 25% of users. Increase limits to 5M. Fine-tune sharp detection based on observed patterns.

Phase 4: Full Enablement Enable for all eligible users. Full limits in effect. Ongoing monitoring and optimization.

18.4 Rollback Plan

If issues arise during enablement:

  • Database migration fails → Rollback migration, fix, retry
  • B-Book fills incorrectly → Disable B-Book, manual review of affected positions
  • Performance degrades → Reduce B-Book percentage, investigate
  • Exposure calculation wrong → Disable B-Book, rebuild state from position records

19. Security and Access Control

19.1 Permission Levels

Different actions require different permissions:

ActionWho Can Do It
View B-Book configurationAdmin, Operations
Change B-Book configurationAdmin only
Enable/Disable B-BookAdmin only
View pool stateAdmin, Operations
Manage sharp listAdmin, Risk Team
View positionsAdmin, Operations, Support
Manual settlementAdmin only

19.2 Audit Logging

Every administrative action is logged:

  • What action was taken
  • Who took it (user identity)
  • When it happened (timestamp)
  • Full details (what changed)
  • Session information (IP address, etc.)

Logs are immutable and retained for compliance.

19.3 Fraud Prevention

The system watches for manipulation attempts:

RiskDetectionPrevention
Coordinated bettingMultiple users, same selection, short windowPer-selection limits
Multiple accountsSame person, multiple accountsKYC verification, device fingerprinting
Insider tradingUnusual patterns before eventsSharp monitoring, pattern analysis
Self-arbitrageOpposite bets by same userNet within user before routing

19.4 Data Protection

Sensitive data is protected:

  • User balances encrypted at rest
  • Betting history access restricted
  • Sharp list confidential (risk team only)
  • P&L records available to finance only
  • Audit logs tamper-proof

20. Terminology Reference

TermDefinition
A-BookPassing bets to external exchanges; platform is intermediary
B-BookPlatform takes opposite side of bets; platform is counterparty
BACK BetBetting that an outcome will occur (e.g., "Mumbai to win")
LAY BetBetting against an outcome (e.g., "Mumbai will not win")
LiabilityMaximum amount platform could lose on a position
Net ExposureDifference between BACK and LAY liability (actual risk)
Sharp UserProfessional bettor who consistently wins
Recreational UserCasual bettor who loses on average
Filter EngineComponent that decides how to route each order
NettingOffsetting opposite positions to reduce exposure
HedgePlacing opposite bet on exchange to reduce B-Book risk
CLVClosing Line Value; how bet price compares to final market price
NGRNet Gaming Revenue; stakes minus payouts
PoolCapital allocated for B-Book operations
UtilizationCurrent exposure as percentage of pool limit
SettlementProcess of paying out or collecting after event concludes
VoidCancelled bet with stakes returned

21. Decisions Requiring Input

The following questions need stakeholder decisions before implementation:

21.1 Business Decisions

QuestionOptionsRecommendation
Should agents receive any B-Book profit share?No share / Small share / Same as exchangeNo share—B-Book is platform risk
What should the initial pool limit be?5M / 10M / 20M pointsStart at 5M (conservative)
Should users know their bet is B-Booked?Yes (transparent) / No (seamless)No—seamless experience
How aggressive should sharp detection be?Conservative / AggressiveConservative (minimize false positives)
Which markets are B-Book eligible?All / Pre-match only / Exclude in-playPre-match only initially

21.2 Technical Decisions

QuestionOptionsRecommendation
Deployment model?Within main app / Separate serviceWithin main app for V1
How to handle cache failures?Reject orders / Fall back to databaseFall back to database (slower but safe)
Position data retention?90 days / 1 year / Forever90 days hot, then archive
Auto-hedge in V1?Yes / No (manual only)No—manual for V1

21.3 Operational Decisions

QuestionOptionsRecommendation
Who can modify sharp list?Admin only / Risk team / AutomatedRisk team with admin override
B-Book on/off approval process?Single admin / Two-person ruleTwo-person rule (safety)
Alert escalation path?Define on-call rotationMust define before launch
Reconciliation frequency?Daily / Weekly / MonthlyDaily automated, weekly manual review

22. Worked Examples

22.1 Example: Order Placement

Scenario: Recreational user Rahul places 100,000 points BACK on Mumbai Win at odds 2.50

Step 1: Validation

  • Rahul has 150,000 points balance ✓
  • Mumbai vs Chennai match is open ✓
  • Odds 2.50 is within acceptable range ✓

Step 2: B-Book Check

  • B-Book is enabled ✓

Step 3: Sharp Check

  • Rahul is not on sharp list ✓

Step 4: Capacity Calculation

  • Global remaining: 8,000,000 points
  • Mumbai vs Chennai market: 1,500,000 remaining
  • Mumbai Win selection: 400,000 remaining
  • Rahul's user limit: 30,000 remaining ← Most restrictive
  • 70% cap: 70,000 points

Available B-Book capacity: 30,000 points

Step 5: Routing Decision

  • B-Book: 30,000 points
  • Exchange: 70,000 points

Step 6: Execution

  • B-Book fill: 30,000 points BACK Mumbai @ 2.50
    • Liability recorded: 30,000 × (2.50 - 1) = 45,000 points
    • Rahul's B-Book exposure: +45,000
    • Selection exposure: +45,000
  • Exchange fill: 70,000 points BACK Mumbai @ 2.50 on Betfair

Step 7: Confirmation Rahul sees: "Order placed: 100,000 points BACK Mumbai Win @ 2.50"

22.2 Example: Settlement

Scenario: Mumbai wins the match

B-Book Positions on Mumbai Win:

  • Rahul: BACK 30,000 @ 2.50 (liability 45,000)
  • Priya: BACK 20,000 @ 2.40 (liability 28,000)
  • Amit: LAY 25,000 @ 2.50 (liability 25,000)

Settlement Calculations:

Since Mumbai WON:

UserBet TypeStakeOutcomeUser P&LPlatform P&L
RahulBACK30,000WIN+45,000-45,000
PriyaBACK20,000WIN+28,000-28,000
AmitLAY25,000LOSE-25,000+25,000
Total+48,000-48,000

Actions:

  • Credit Rahul's balance: 75,000 points (original stake + winnings)
  • Credit Priya's balance: 48,000 points (original stake + winnings)
  • Amit's stake already deducted—no action needed
  • Platform B-Book P&L: -48,000 points (loss on this settlement)
  • Release all capacity (positions now settled)

22.3 Example: Sharp User Detection

Scenario: Ops team reviews user Vikram's performance

Vikram's Statistics:

  • Total bets: 450
  • Win rate: 58%
  • Average Closing Line Value: +3.2%
  • Stake patterns: Precise amounts (8,347 points, 12,891 points)
  • Timing: 82% of bets within 30 minutes of event start
  • Markets: Focus on niche cricket leagues

Decision: Vikram shows clear sharp characteristics

  • High win rate over large sample
  • Consistently beating closing line
  • Non-round stakes suggest calculated sizing
  • Late betting (informed punter behavior)

Action: Add Vikram to sharp list

Impact:

  • Vikram's next order: 100% routed to Betfair
  • Vikram's existing B-Book positions: Settle normally
  • Vikram is not notified of classification

22.4 Example: Balancing Benefit

Scenario: Selection has existing imbalance, new order comes in

Current State on Mumbai Win:

  • BACK liability: 100,000 points
  • LAY liability: 40,000 points
  • Net exposure: 60,000 points (platform is SHORT)

New Order: User places LAY 50,000 points on Mumbai Win

Analysis:

  • This LAY bet offsets existing BACK exposure
  • It reduces platform risk, doesn't increase it
  • This is a balancing order

Routing Decision:

  • Balancing orders get preferential treatment
  • May accept beyond normal limits (since it reduces risk)
  • After fill: Net exposure reduces to 10,000 points

Document Version: 1.0 Last Updated: January 2026 Author: Hannibal Product Team For technical implementation details, see BBOOK_SYSTEM_DESIGN.md