Production Architecture v2.0

Babingepet
2.0

Multi-market quantitative trading framework — BTC Futures · Altcoin · IHSG · IHSG Scanner

4
Market Engines
27
BTC Signals
17
AI Agents
60s
BTC Cycle
~60%
Win Rate
01 — Architecture

System Architecture

Complete component map showing all four engines, shared infrastructure, AI layers, and data flows.

DATA SOURCES Binance Futures API · WS · REST Google News RSS · 5 keywords yfinance IDX OHLCV · Daily Broker Data RTI · Stockbit · Invezgo OpenRouter Gemini · DeepSeek · Qwen Telegram @domex_aibot TRADING ENGINES BTC/USDT ENGINE 60s cycle · 12-source voting collector.py signals.py ai_estimator.py decision_engine.py ALTCOIN ENGINE 4h cycle · 15 coins · 5 agents altcoin_engine.py altcoin_learner.py IHSG ENGINE 2× daily · 40 stocks · 4 agents ihsg_engine.py ihsg_learning.py IHSG SCANNER On-demand · 5 signals ihsg_scanner.py broker_intel.py SHARED INTELLIGENCE LAYER Supabase / PostgreSQL 16 tables · Real-time API candles · signals · decisions · picks portfolio · learning · news Hermes Agent Framework 4 analytics agents · SQLite memory 6 Babingepet tools · MCP bridge Sentinel · SOUL.md persona FastAPI + APScheduler Port 8420 · Uvicorn 13 scheduled jobs REST + HTML dashboards ML Layer XGBoost · Wilson CI Regime detector · Kelly sizing Learning insights · Bayesian OUTPUT LAYER Nginx + SSL mauuang.com · Let's Encrypt Reverse proxy HTML Dashboards / · /ihsg · /altcoins · /scanner Telegram Alerts STRONG signals · Session picks Systemd + Ubuntu VPS hermes-gateway.service nohup uvicorn · Restart=always PAPER TRADING SIMULATORS BTC Simulator $1K · Kelly · Trailing stop Altcoin Simulator $10K · 3 max positions · Sector gate IHSG Simulator Next-day return tracking Learning loop LEGEND Data flow Learning feedback
02 — Engine Deep Dive

BTC/USDT Engine

60-second cycle, 27 signals, 8-agent AI swarm, 12-source weighted voting decision engine.

Signal Pipeline
Binance API
60s pull
collector.py
OHLCV · OB · Trades
signals.py
VPIN · OFI · Edge
ai_estimator.py
8 agents · 10min
decision_engine.py
12-source vote
Simulator
Kelly · Trailing SL
12-Source Voting Weights
ml_xgboost
0.15
whale_flow
0.12
vpin
0.11
ai_consensus
0.10
mtf_alignment
0.10
regime
0.09
ofi_contrarian
0.08
vwap
0.07
funding_rate
0.06
as_fair_value
0.05
sentiment
0.04
hour_seasonality
0.03
AI Swarm Configuration
Consensus: 40% generalist (accuracy-weighted) + 60% swarm (equal weight)
AgentPersonaModel
geminiGeneralistgemini-2.5-pro
claudeGeneralistdeepseek-r1:free
gptGeneralistqwen3.6-plus:free
momentumTrend followergemini-flash
contrarian_sharkMean reversiongemini-flash
flow_readerMicrostructuregemini-flash
macro_sageMacro contextgemini-flash
conservative_filterRisk managergemini-flash
Verdict Thresholds & Hour Logic
STRONG_BUY
≥ 0.28
BUY
≥ 0.20
SELL
≤ -0.20
STRONG_SELL
≤ -0.28
BLOCKED hours (UTC)
171819230
BOOSTED hours (UTC) — 1.3× edge
23789
03 — Engine Deep Dive

Altcoin Engine

4-hour cycle, 15-coin universe, 8-factor composite scoring, 5-agent AI swarm with sector gating.

8-Factor Composite Score
Momentum
0.28
Funding
0.13
BTC Alpha
0.13
Volume
0.12
Volatility
0.10
RSI
0.10
Orderbook
0.09
OI Proxy
0.05
AI Swarm Personas
ALPHA HUNTER
Seeks undervalued with momentum breakout potential, sector rotation plays
FLOW READER
OFI, funding dynamics, OI divergence, whale accumulation signals
MOMENTUM WOLF
Pure trend following, volume confirmation, breakout entries
MACRO CRYPTO
BTC correlation, sector narrative, macro catalyst alignment
RISK FILTER
Eliminates overleveraged, high-funding, overextended setups
Vote scoring: Rank 1 = 3pts, Rank 2 = 2pts, Rank 3 = 1pt × conviction multiplier (HIGH=1.5×)
Coin Universe — 15 Active
ETHSOLBNBADAAVAXDOTNEARAPTSUIARBOPAAVEUNILINKINJ
BUY thresholdscore > 0.30
SELL thresholdscore < -0.20
Max positions3 concurrent
Sector limit2 per sector
Max hold24 hours
Fee accounting0.04% taker
Trailing stop+3% → 25% give
TP targetprice + 2.5×ATR
SL targetprice − 1.5×ATR
04 — Engine Deep Dive

IHSG Engine

Indonesian Stock Exchange coverage. 40-stock universe, 2× daily sessions, intraday overlay, news validation.

Session Schedule (WIB / UTC)
SessionWIBUTCFocus
Session 1 — Opening09:00–12:0002:00–05:00Momentum + Volume surge
Session 2 — Afternoon13:30–15:4906:30–08:49Mean-reversion + VWAP
Hermes pre-session agent fires at 01:20 UTC (S1) and 05:50 UTC (S2) for news research.
Multi-Factor Model
Momentum1D · 5D · 20D ROC + accel
RSI14-period
VolumeSurge vs 20D avg
VolatilityGarman-Klass annualized
VWAP deviationAbove = bullish bonus
Range positionvs 52-week H/L
Sector strengthRelative vs benchmark
BUY threshold> 0.35
SELL threshold< -0.25
Kelly sizingHalf-Kelly · max 15%
40-Stock Universe
BBCABBRIBMRIBBNITLKMASIIUNVRICBPADROPTBAINDFKLBFSMGRBRISGOTOEMTKMNCNEXCLISATANTMMDKAMEDCPGASACESAMRTCPINJPFAMAPIERAABRPTTBIGTOWRSIDOHMSPGGRMMYORINTPWIKAPTPPSRIL
05 — Scanner

IHSG Scanner

On-demand bandarmology analysis. 5-signal composite, 51-broker intelligence database, whale-adjusted scoring.

5-Signal Weights
Acc/Dist
0.30
Bandar Cycle
0.20
Foreign Flow
0.18
RRG Rotation
0.17
Frequency (FQ)
0.15
51-Broker Intelligence
TierCountExamplesWhale?
FOREIGN_BIG10RX, GR, CL, BK
FOREIGN_MID10MQ, LG, FS
DOMESTIC_BIG10CC, IF, NF, AI
DOMESTIC_MID13YP, YU, XA
RETAIL8GG, SB, BI
3+ whale consensus → vote boost. Whale lots weighted 2× in net ratio.
Bandar Cycle Phases
ACCUMULATION
Sideways/down · broker buying · low vol
MARK UP
Rising price · vol surge · breakout
DISTRIBUTION
Sideways after markup · not accumulating
MARK DOWN
Declining price · supply flooding
EXIT
Declining price · very low volume
06 — Intelligence

AI Model Map

Complete mapping of AI models to functions, cost tiers, and fallback chains.

ModelRouterUsed ForCost TierFallback
google/gemini-2.5-proOpenRouterBTC generalist · Hermes analytics agentsPAIDgemini-flash
google/gemini-2.5-flashOpenRouterBTC swarm personas · Hermes Sentinel · IHSG/Altcoin swarmLOWdeepseek-r1
deepseek/deepseek-r1:freeOpenRouterBTC generalist "claude" slotFREEqwen3-plus
qwen/qwen3.6-plus:freeOpenRouterBTC generalist "gpt" slotFREEdeepseek-r1
Various OpenRouterOpenRouterIHSG 4-agent swarm · Altcoin 5-agent swarmLOWgemini-flash
XGBoost (local)sklearnBTC ml_xgboost signal (0.15 weight)FREEedge_estimate
Model Weight Logic

Generalist weights are dynamic — derived from last 50 predictions' accuracy. Weights are NOT normalized, preserving performance differences between models. Higher historical accuracy = higher weight on next prediction.

Track record stored in crypto_ai_predictions — accuracy injected into prompts so models know their own hit rate.
Hermes Sentinel

On STRONG_BUY or STRONG_SELL (non-vetoed), spawns daemon thread → calls Gemini Flash with last 8 BTC memory cycles.

CONFIRM
CAUTION
WARN

Result written as hermes_note to btc_decisions table

07 — Agent Framework

Hermes Integration

Self-improving AI agent framework with SQLite persistent memory, 4 analytics agents, 6 Babingepet tools, and MCP bridge.

4 Analytics Agents (APScheduler)
AgentScheduleGoal
Signal Calibrationevery 6hAudit 50 predictions + 30 decisions
IHSG Pre-Session S101:20 UTCMacro + per-stock news research
IHSG Pre-Session S205:50 UTCAfternoon session stance
Altcoin Narrativeevery 4h+10minNarrative/catalyst per coin
Weekly ReviewSun 13:00 UTCFull portfolio + predictions report
6 Babingepet Tools (Hermes)
TOOLbabingepet_btc_signalsLive BTC signal state from Supabase
TOOLbabingepet_portfolioCurrent positions + P&L
TOOLbabingepet_predictionsAI swarm p_up history
TOOLbabingepet_decisionsDecision verdicts + hermes_note
TOOLbabingepet_ihsg_picksSession picks + AI thesis
TOOLbabingepet_altcoin_picksTop 3 altcoin picks per cycle
MCP Bridge (7 read-only endpoints)
GET/hermes/statusSystem health + agent states
GET/hermes/btc_stateCurrent BTC signals + verdict
GET/hermes/portfolioAll open positions
GET/hermes/predictionsAI prediction history
GET/hermes/memoryHermes SQLite persistent memory
GET/hermes/ihsgIHSG session picks + AI analysis
GET/hermes/altcoinsAltcoin top 3 + swarm votes
SOUL.md persona: For BTC/portfolio/IHSG/altcoin queries → call babingepet_* tools FIRST. Never web search for portfolio data. Concise, data-driven, quant analyst style.
08 — Risk Management

Risk Management Layer

All veto conditions, gates, and guards across all four engines.

BTC Engine — Veto Conditions
VETOAI agreement < 0.40 AND score > BUY threshold
VETORANGING regime vetoes most entries
GATEHour blocking: UTC 17,18,19,23,0 → no signals
GATEMin 5 of 12 sources must agree direction
GUARDSignal debounce: opposing signals → NEUTRAL
GUARDVWAP failed reclaim → score penalty (not override)
GUARDHermes WARN → flag in btc_decisions (advisory only)
Altcoin + IHSG Gates
VETOAltcoin: No new LONGs when BTC regime = TRENDING_DOWN
GATEAltcoin LONG requires score ≥ 0.05 at entry
GATEMax 2 coins per sector (L1/L2/DeFi/Meme/AI/Payment/Storage)
GATEMax 3 concurrent altcoin positions
GUARDAltcoin: score_warning flag when negative score for LONG
GUARDWilson CI hi < 0.45 → skip pattern (learning system)
GUARDIHSG news contradiction → swap pick with alternate
Kelly Criterion Position Sizing
Formula
f = (bp - q) / b
b = TP/SL ratio
p = win probability
q = 1 - p
BTC Parameters
Take Profit1.8%
Stop Loss0.6%
b ratio3.0×
ATR-Based (Alt/IHSG)
TPprice + 2.5×ATR
SLprice − 1.5×ATR
IHSG KellyHalf-Kelly · max 15%
09 — Adaptive Systems

Learning Feedback Loops

How trade outcomes feed back into future decisions across all three engines.

Altcoin Learning (Wilson CI)
ConditionAction
ci_hi < 0.45skip pattern
ci_hi < 0.50reduce_size
ci_lo > 0.55boost 1.2×
ci_lo > 0.65boost 1.4×
ci_lo > 0.75boost 1.6×
Min 20 trades for ACTIVE status. Patterns: ticker · sector · RSI regime · funding regime · score range · volume level
IHSG Learning (Bayesian)
ThresholdStatus
8+ samplesGenerated
10+ samplesACTIVE
10+ samplesApplied to scoring
Empirical win rate uses Bayesian shrinkage with 50% neutral prior. Pattern key format: insight_type:condition_key (e.g. confidence:HIGH, session:Opening)
Pattern dimensions:
tickerconfidencesessionscore_bucketRSI_regimeaction_type
10 — Data Layer

Database Schema

Complete Supabase/PostgreSQL schema — all 16 tables with key columns and relationships.

BTC Tables
crypto_candles
idbigserial PKauto
timestamptimestamptzcandle open time
timeframevarchar1m · 5m · 15m
open/high/low/closenumericOHLCV
volumenumericquote volume
crypto_signals
idbigserial PK
timestamptimestamptz
vpinnumeric0–1 toxicity
ofinumericnormalized
edge_estimatenumericcomposite edge
signal_strengthvarcharSTRONG_BUY…STRONG_SELL
kelly_fractionnumericposition size
regimevarcharTRENDING_UP etc
crypto_ai_predictions
idbigserial PK
timestamptimestamptz
p_up_gemininumeric0–1
p_up_claudenumericdeepseek slot
p_up_gptnumericqwen slot
p_up_[persona]numeric×5 swarm agents
consensus_p_upnumeric40/60 blend
agreementnumericbull/bear ratio
model_weightsjsonbdynamic accuracy
btc_decisions
idbigserial PK
timestamptimestamptz
verdictvarcharSTRONG_BUY…STRONG_SELL
scorenumericweighted vote total
source_votesjsonball 12 source signals
vetobooleanvetoed flag
hermes_notevarcharCONFIRM/CAUTION/WARN
reasoningtextfull reasoning blob
crypto_trades
idbigserial PK
timestamptimestamptz
pricenumeric
quantitynumeric
is_whaleboolean>$150K trade
directionvarcharBUY · SELL
Portfolio + Market Tables
btc_sim_positions
idbigserial PK
sidevarcharLONG · SHORT
entry_pricenumeric
size_usdnumericKelly-sized
tp/slnumeric1.8% / 0.6%
trailing_highnumericpeak for trailing SL
statusvarcharOPEN · CLOSED
pnlnumericrealized
exit_reasonvarcharTP · SL · TRAIL · TIME
sim_portfolio
idbigserial PK
timestamptimestamptz
btc_equitynumericstarts $1,000
alt_equitynumericstarts $10,000
win_countinteger
loss_countinteger
altcoin_picks_history
idbigserial PK
timestamptimestamptzcycle time
picksjsonbtop 3 with scores
swarm_votesjsonbper-agent ranking
consensus_thesistextmerged narrative
btc_regimevarcharat time of picks
altcoin_sim_positions
idbigserial PK
symbolvarchar
sectorvarcharL1/L2/DeFi/etc
scorenumericentry score
size_pctnumericvol-scaled 12–25%
tp/slnumericATR-based
max_hold_attimestamptzforced close time
ihsg_picks_history
idbigserial PK
sessionvarcharOpening · Afternoon
picksjsonbtop 3 with scores
ai_thesistextper-ticker thesis
ai_overridebooleanAI changed quant order
news_validatedbooleannews check passed
learning_insights
idbigserial PK
enginevarcharbtc · altcoin · ihsg
pattern_keyvarcharinsight_type:condition
win_ratenumericWilson CI estimate
ci_lo / ci_hinumericconfidence bounds
sample_countinteger
actionvarcharskip/reduce/boost
statusvarcharACTIVE · PENDING
news
idbigserial PK
keywordvarchar5 BTC keywords
titletext
published_attimestamptz
sourcevarcharGoogle News RSS
11 — API Surface

API Endpoint Map

All FastAPI routes — method, path, purpose, and response shape.

BTC Endpoints
GET/BTC dashboard HTML
GET/api/signals{vpin, ofi, edge, signal_strength, kelly}
GET/api/predictions{p_up per model, consensus, agreement}
GET/api/decisions{verdict, score, source_votes, hermes_note}
GET/api/portfolio{equity, positions, win_rate, P&L}
GET/api/candles[{timestamp, ohlcv}] — 1m/5m/15m
GET/api/whale_trades[{price, qty, direction, is_whale}]
GET/api/news[{title, keyword, published_at}]
GET/api/regime{regime, confidence, regime_scores}
Market + Infrastructure Endpoints
GET/ihsgIHSG dashboard HTML
GET/api/ihsg/picks{session, picks[3], ai_thesis, scores}
GET/api/ihsg/learning{insights, pattern_key, action, ci}
GET/altcoinsAltcoin dashboard HTML
GET/api/altcoins/picks{picks[3], swarm_votes, consensus_thesis}
GET/api/altcoins/positions{open_positions, sector_breakdown}
GET/scannerIHSG Scanner HTML
POST/api/scanner/analyzebody: {ticker} → {5 signals, verdict, broker_pos}
GET/api/health{scheduler_jobs, last_run, db_status}
GET/hermes/*7× MCP bridge (read-only)
12 — Scheduling

Scheduler Timeline

24-hour visual timeline of all APScheduler jobs — cron and interval triggers.

UTC 00:00 — 23:59
000306091215182124
BTC Collector
every 60s — all day
BTC Signals
every 60s
BTC AI Swarm
every 10min
Altcoin Engine
00:00
06:00
12:00
18:00
Alt Price Check
every 15min
IHSG Session 1
02:00 UTC
IHSG Session 2
06:30 UTC
IHSG Price Upd
every 30min (market hours)
Hermes Pre-S1
01:20
Hermes Pre-S2
05:50
Signal Calibration
00:00
06:00
12:00
18:00
BTC Engine
Altcoin / Hermes
IHSG Engine
Calibration
Complete Job Registry
Job IDTriggerIntervalPurpose
run_collectinterval60sBTC data collection from Binance
run_signalsinterval60sVPIN, OFI, Edge computation
run_siminterval60sBTC paper trading simulator
run_aiinterval10min8-agent AI swarm prediction
run_ihsgcron02:00 + 06:30 UTCIHSG session analysis
run_ihsg_price_updateinterval30minIntraday IHSG price overlay
run_altcoinsinterval4hAltcoin engine full cycle
run_altcoin_price_checkinterval15minOpen position P&L check
hermes_signal_calibrationinterval6hAudit 50 predictions + 30 decisions
hermes_ihsg_s1cron01:20 UTCPre-session 1 research
hermes_ihsg_s2cron05:50 UTCPre-session 2 research
hermes_altcoin_narrativeinterval4h +10min offsetAltcoin narrative/catalyst research
hermes_weekly_reviewcronSun 13:00 UTCFull portfolio + predictions report
13 — Infrastructure

Deployment Architecture

VPS, Nginx, Systemd, process supervision — complete deployment topology.

Server Stack
OSUbuntu 22.04+ LTS
Domainmauuang.com
Web serverNginx (reverse proxy)
SSLLet's Encrypt
App serverUvicorn (port 8420)
FrameworkFastAPI + APScheduler
LanguagePython 3.12
DatabaseSupabase / PostgreSQL
Hermes memorySQLite (~/.hermes/babingepet.db)
Process Management
# Babingepet API nohup uvicorn crypto.api:app \ --host 0.0.0.0 \ --port 8420 & # Hermes Gateway (systemd) systemctl enable hermes-gateway.service systemctl start hermes-gateway.service # hermes-gateway.service [Service] Restart=always RestartSec=5s ExecStart=/path/hermes-gateway
Deployment Diagram
Internet Nginx SSL Term mauuang.com FastAPI :8420 Uvicorn APScheduler 4 Engine modules HTML Dashboards MCP Bridge Hermes Gateway systemd · Restart=always Telegram bot + tools Supabase PostgreSQL 16 tables OpenRouter API Gemini · DeepSeek · Qwen Binance Futures API Telegram @domex_aibot
14 — Data Flow

End-to-End Data Flow

From exchange API to learning loop — complete data lifecycle across BTC engine.

1
Exchange API Collection
Binance Futures → 1m candles, orderbook (depth 50), recent trades (1000), 24h ticker, funding rate, OI, L/S ratio, liquidations, whale detection (>$150K)
60s
2
Signal Computation
VPIN calculation (3 regimes), OFI normalization, Edge estimate (8 components), Kelly fraction, MTF alignment (5m+15m), regime classification
60s
3
AI Swarm Prediction
3 generalists × accuracy-weighted + 5 personas × equal weight → consensus p_up. Agreement score. Hermes Sentinel on STRONG signals.
10min
4
Decision Engine
12-source weighted vote → verdict. Apply veto conditions (regime, agreement, hour block). Min 5/12 source agreement. Threshold comparison.
60s
5
Paper Trading Execution
Kelly-sized entry. Trailing stop (+3% activation, 25% give). TP=1.8%, SL=0.6%. Max hold configurable. Write to btc_sim_positions.
60s
Learning Feedback Loop
Trade outcome → Hermes calibration (6h) → learning_insights → pattern-based size adjustments → future decisions. Model accuracy weights updated from last 50 predictions.
6h cycle
Babingepet 2.0
Multi-Market Quantitative Trading Framework · Architecture Document v2.0
Stack: Python 3.12 · FastAPI · APScheduler · Supabase · OpenRouter · Hermes · Telegram · Nginx