Polymarket Bot Tutorial · अध्याय 30 of 32
Polymarket bots के लिए production-grade risk management code: position caps, daily loss limits, halt sentinels, fill-rate watchdogs, reconcile-on-restart, idempotent retries। real production trader से code patterns.
यह अध्याय क्या कवर करता है
Risk code एक production trading bot का सबसे बड़ा हिस्सा है। Strategy logic आसान हिस्सा है; उसके आसपास के caps, halts, watchdogs, और reconcilers तय करते हैं कि bot अपनी पहली खराब हफ्ते में बचेगा या नहीं। यह अध्याय production-grade risk pattern है।
- क्यों risk code एक real trading bot का सबसे बड़ा हिस्सा है
- Position caps (per-market, per-strategy, total)
- Daily loss kill switch
- Halt sentinels (file-based emergency stop)
- Fill-rate watchdog
- Restart पर diary vs on-chain reconcile करना
- Code: production-grade halt-aware loop
क्यों risk code एक real trading bot का सबसे बड़ा हिस्सा है
हमने अपने own bot codebase पर एक measurement की: LOC का 60% risk code है (caps, halts, watchdogs, reconciliation)। 30% strategy है। 10% glue है।
यह ratio सही है। Strategy आसान हिस्सा है - कब enter करना है और कब exit करना है, यह कुछ दर्जन lines में fit हो जाता है। Risk code बाकी सब कुछ है: जब price आपके खिलाफ उम्मीद से तेज़ चले तो क्या करना है, जब fills रुक जाएँ तो क्या करना है, जब WebSocket drop हो जाए तो क्या करना है, जब strategy unprofitable साबित हो तो क्या करना है।
ज्यादातर builder failure stories एक जैसी होती हैं: strategy काम कर रही थी, लेकिन bot regime change के दौरान trading करता रहा क्योंकि कोई halt fire नहीं हुआ। Strategy लिखने से पहले halts लिखें।
Position caps (per-market, per-strategy, total)
तीन caps, code में enforced।
- Per-market cap: edge confidence चाहे जो भी हो, प्रति market max $X। Typical: छोटे bots के लिए $25-100, production के लिए $200-500। एक single market में गलत call का blast radius सीमित करता है।
- Per-strategy cap: अगर आप multiple strategies चलाते हैं, तो हर strategy को total capital का एक slice मिलता है। Typical: प्रति strategy 30-50%। एक strategy के खराब दिन को बाकी strategies के capital को consume करने से रोकता है।
- Total cap: wallet balance का max % जो एक साथ deployed हो सकता है। Typical: 50-70%। unexpected opportunities के लिए या bot की अपनी bookkeeping bugs पकड़ने के लिए capital छोड़े रखता है।
तीनों caps को order-placement function के अंदर enforce किया जाना चाहिए, सिर्फ strategy logic में नहीं। Strategy में bug हो सकता है; order-placement gate आख़िरी defense line है।
Daily loss kill switch
सबसे महत्वपूर्ण single risk control: daily-loss kill switch।
Rule: अगर midnight UTC के बाद से realized + unrealized PnL शुरुआती daily balance के -X% से नीचे चला जाए, तो bot नए positions खोलना बंद कर देता है और (optional) मौजूदा positions को flatten करता है। Typical X: 5-10%।
Math: 60% expected win rate वाले bot के लिए शायद 10-trade losing streak की 5% chance हो। Kill switch के बिना, यह streak compound होती है: $200 loss → bot trading जारी रखता है → फिर $200 loss → wallet 40% down। -10% पर switch fire होने से bad day $200 पर cap हो जाता है, और कल bot fresh start करता है।
Switch server-side enforced होना चाहिए: halt file लिखें या database flag set करें जिसे trading loop हर iteration में check करे। Restart सिर्फ manual review के बाद।
Halt sentinels (file-based emergency stop)
सबसे simple halt mechanism: bot हर loop iteration में एक file (जैसे /opt/pmt/HALT) check करता है और file मौजूद होने पर trading रोक देता है।
def trading_loop():
while True:
if os.path.exists("/opt/pmt/HALT"):
log("HALT file detected, sleeping")
time.sleep(30)
continue
run_one_iteration()
time.sleep(5)
कहीं से भी तुरंत halt करने के लिए (SSH, Telegram bot, monitoring system): touch /opt/pmt/HALT। Resume करने के लिए: rm /opt/pmt/HALT।
File-based approach जानबूझकर low-tech है क्योंकि यह उन परिस्थितियों में काम करता है जहाँ more sophisticated halt mechanisms fail हो जाते हैं: जब bot partially crashed हो, जब database unreachable हो, जब API key rate-limited हो। File-system access हमेशा उपलब्ध रहता है।
Fill-rate watchdog
Strategy मानती है कि FOK orders कुछ rate पर fill होंगे (अक्सर 60-80%)। जब rate काफी गिर जाता है, तो कुछ बदल गया है: market makers हट गए, आपकी strategy पहचान ली गई, कोई API outage चल रही है। वजह चाहे जो भी हो, वह assumption टूट गई है जिसने strategy के PnL math को drive किया था।
Watchdog logic: rolling 24-hour fill-rate count। अगर < 30% (या expected का 50%) हो, तो alert + auto-halt। Resume सिर्फ manual review के बाद।
Watchdog diagnostic के रूप में भी उपयोगी है। अचानक fill-rate drop आमतौर पर किसी external event (Polymarket deploy, Polygon congestion, आपका IP rate-limited होना) से correlate करता है, जिसके बारे में trading impact से अलग भी जानना आप चाहेंगे।
Restart पर diary vs on-chain reconcile करना
Bot positions की एक diary रखता है जिन्हें वह मानता है कि उसके पास हैं। Chain truth रखती है। दोनों हमेशा agree होने चाहिए; जब नहीं होते, तो bot गलत belief के आधार पर operate कर रहा होता है और गलत trade करेगा।
Reconciliation logic: हर restart पर और normal operation के दौरान हर एक घंटे में, bot द्वारा touch किए गए हर token के on-chain balances fetch करें। Diary से compare करें; अगर किसी token का balance rounding tolerance से ज्यादा अलग हो, तो alert + halt करें।
Divergence का सबसे common कारण वह successful order होता है जिसे bot की API call miss कर देती है (timeout, retry record नहीं हुआ)। Chain के पास position होती है; bot को लगता है कि नहीं है। Reconciliation के बिना, bot take-profit exit post नहीं करेगा और position resolution तक चली जाएगी।
Code: production-grade halt-aware loop
Reference: production trading loop जिसमें सभी risk controls wire किए गए हैं।
def production_loop():
while True:
# Halt checks
if os.path.exists("/opt/pmt/HALT"):
sleep_with_log(30); continue
if daily_pnl_below_threshold():
create_halt("daily PnL kill"); continue
# Reconcile every hour
if now() - last_reconcile > 3600:
ok = reconcile_diary_vs_chain()
last_reconcile = now()
if not ok: create_halt("reconciliation failed"); continue
# Fill-rate watchdog
if recent_fill_rate() < 0.30:
create_halt("fill rate collapse"); continue
# Strategy
try:
run_strategy_once()
except Exception as e:
log_exception(e)
if consecutive_exceptions >= 5:
create_halt(f"exceptions: {e}"); continue
time.sleep(5)
Pattern: हर iteration gate से होकर गुजरती है। Construction के हिसाब से strategy bugs controls को bypass नहीं कर सकते।












