6.2 — Paper vs Live Gate — Safety Ka Switch
Paper vs Live Gate — Safety Ka Switch
Alright, chalo bachon, class shuru karte hain. Welcome to Module 6. Ab tak humne markets ko scan karna, strategies banana, aur AI se signals generate karna seekha hai. Lekin ab aati hai asli cheez: Execution. Yani, bot ko ijazat dena ke woh tumhare behalf pe, tumhare paison se, orders place kare.
COURSE: Pakistan Ka Pehla Professional Trading Bot Course
MODULE 6: Execution Engine — Automatically Orders Place Karna
LESSON 6.2: Paper vs Live Gate — Safety Ka Switch
Suno ghौर se. Yeh lesson shayad is poore course ka sab se important lesson hai. Ek choti si galti, ek if statement idhar se udhar, aur tumhara poora account balance saaf ho sakta hai. Yeh koi mazak nahi hai, this is where the bot touches real money. Isliye hum ek "safety switch" banayenge jo humein tabahi se bachayega.
The Big Idea: Aik Fuse Box Ki Tarah
Socho tumhare ghar mein ek fuse box (circuit breaker) hai. Agar koi cheez short circuit hoti hai, toh poore ghar ki bijli jalane ke bajaye, sirf woh ek switch trip ho jata hai. Safety first.
Hamare trading bot mein, yeh safety switch hai Paper Mode vs Live Mode.
- Paper Mode (Kaghazi Karwai): Bot sab kuch karega—strategy run karega, signals generate karega, order place karne ka sochega. Lekin jab order place karne ka time ayega, toh woh asli paise nahi lagayega. Sirf ek log file mein likh dega, "Bhai, main yahan pe 5000 PKR ki YES shares khareed leta agar live hota." Is se tum apni strategy test kar sakte ho bina ek rupiya risk kiye.
- Live Mode (Asli Maidan): Yeh hai real deal. Is mode mein bot tumhare wallet se connect hoga aur asli, on-chain transactions karega. Paisa lagega bhi, aur banega (ya doobega) bhi.
Rule Number 1, aur aakhri rule bhi yahi hai: BOT KABHI BHI DEFAULT MEIN LIVE NAHI HONA CHAHIYE. Live trading hamesha ek manual, deliberate action honi chahiye. Tumhein explicitly batana padega, "Haan bhai, ab real paisa lagao."
The Code: Hamara Safety Switch
Yeh logic hamare execution.py file mein rehta hai. Iska kaam strategy se order lena aur usko aage process karna hai. Lekin process karne se pehle, yeh check karta hai ke "safety on hai ya off?"
Chalo code dekhte hain. Yeh bilkul wohi code hai jo hum apne Polymarket Oracle bot mein use karte hain.
# execution.py
import os
import logging
# Setup basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# === THE SAFETY SWITCH ===
# Environment variable se setting uthao. Agar set nahi hai, toh default 'false' hai.
# Iska matlab, agar tum kuch na karo, toh bot hamesha SAFE (paper) mode mein chalega.
LIVE_TRADING = os.environ.get('ORACLE_LIVE_TRADING', 'false').lower() == 'true'
def place_order(market_id: str, side: str, amount: float, price_limit: float = None, strategy: str = ''):
"""
Order place karo — paper ya live mode ke hisaab se.
:param market_id: Market ka unique identifier
:param side: 'YES' ya 'NO'
:param amount: Kitne USD ki trade karni hai
:param price_limit: Maximum price for YES, minimum for NO
:param strategy: Kaunsi strategy ne yeh order trigger kiya (e.g., 'theta_sniper')
"""
# --- YEH HAI ASLI GATE ---
if not LIVE_TRADING:
# PAPER MODE — sirf log karo, asli paisa nahi
tx_hash = 'PAPER_MODE_TX'
logging.info(f"[PAPER] Strategy '{strategy}' would place a {side} order of ${amount:.2f} on market {market_id}.")
# Hum ek dictionary return karte hain taake baaki system ko pata chale kya hua
return {
'success': True,
'tx_hash': tx_hash,
'mode': 'paper',
'market_id': market_id,
'side': side,
'amount': amount,
'strategy': strategy
}
# --- AGAR UPAR WALA GATE KHULA HAI, TABHI YAHAN AAYEGA ---
# LIVE MODE — real trade
logging.warning(f"[LIVE] Executing a REAL {side} order of ${amount:.2f} from strategy '{strategy}' on market {market_id}.")
# Yahan pe asli on-chain transaction ka code aayega.
# Hum Polymarket ke liye py_clob_client library use karte hain.
# For now, hum isko simulate kar rahe hain.
# from py_clob_client import ClobClient, get_order_builder, OrderType
# client = ClobClient(...)
# signed_order = client.create_and_post_order(...)
logging.info(f"[LIVE] Successfully placed order for market {market_id}.")
return {
'success': True,
'tx_hash': '0x' + os.urandom(32).hex(), # Fake transaction hash
'mode': 'live',
'market_id': market_id,
'side': side,
'amount': amount,
'strategy': strategy
}
def sell_position(market_id: str, shares: int, price_limit: float = None):
"""Position sell karo."""
if not LIVE_TRADING:
logging.info(f'[PAPER] Would SELL {shares} shares of market {market_id}')
return {'success': True, 'tx_hash': 'PAPER_MODE_TX', 'mode': 'paper'}
# Live sell logic yahan pe aayega
logging.warning(f"[LIVE] Executing a REAL SELL of {shares} shares for market {market_id}.")
return {
'success': True,
'tx_hash': '0x' + os.urandom(32).hex(), # Fake transaction hash
'mode': 'live'
}
# --- Example Usage ---
if __name__ == "__main__":
print(f"--- Running in {'LIVE' if LIVE_TRADING else 'PAPER'} mode ---")
# Farz karo, hamari Theta Sniper strategy ne ek signal diya hai
# "Pakistan to win the next T20 match?" market pe
market_example = "0x123abc..."
# Strategy kehti hai ke YES khareedo
result = place_order(
market_id=market_example,
side='YES',
amount=50.0, # $50 ki trade
price_limit=0.65,
strategy='theta_sniper'
)
print("\nOrder Placement Result:")
print(result)
# Thori der baad, strategy kehti hai ke position bech do
sell_result = sell_position(
market_id=market_example,
shares=75 # 75 shares
)
print("\nSell Position Result:")
print(sell_result)
Code Breakdown: Line by Line Samjho
Chalo is code ka post-mortem karte hain.
-
import os: Yeh Python ki built-in library hai.oska matlab hai "Operating System". Is se hum environment variables jaisi system-level cheezein access kar sakte hain. -
LIVE_TRADING = os.environ.get('ORACLE_LIVE_TRADING', 'false').lower() == 'true': Yeh hai hamara master switch.os.environ: Yeh ek dictionary ki tarah hai jis mein tumhare system ke saare environment variables store hotay hain..get('ORACLE_LIVE_TRADING', 'false'): Yeh kehta hai, "os.environmeinORACLE_LIVE_TRADINGnaam ka variable dhoondo. Agar mil jaye, toh uski value de do. Agar NAHI milta, toh default value'false'use karo." Yahi hai hamara safety net. Galti se variable set karna bhool gaye? Koi masla nahi, bot safe mode mein hi rahega..lower(): Yeh value ko lowercase mein convert karta hai. Taake'TRUE','True', ya'true'sab ek hi tarah treat hon.== 'true': Finally, yeh check karta hai ke value'true'ke barabar hai ya nahi. Agar hai, tohLIVE_TRADINGvariableTrue(boolean) set ho jayega. WarnaFalse.
-
if not LIVE_TRADING::place_orderfunction ke andar yeh pehli cheez hai jo check hoti hai. "AgarLIVE_TRADINGFalsehai toh..." Is block ke andar jo bhi hai, woh paper trading ke liye hai.
The safety switch ensures your bot never accidentally executes real trades during testing.
📺 Recommended Videos & Resources
- Feature Flags & Safe Deployments — Safe coding practices
- Type: Wikipedia
- Link description: Learn about feature toggles for safe releases
- Testing in Production — Deployment strategies
- Type: YouTube
- Link description: Search "blue-green deployment and feature flags"
- Logging Critical Operations — Audit trails
- Type: Python Official Docs
- Link description: Learn Python logging module for audit trails
- Monitoring & Alerts — Real-time oversight
- Type: YouTube
- Link description: Search "bot monitoring and alerting systems"
- Circuit Breakers Pattern — Failsafe mechanisms
- Type: Wikipedia
- Link description: Learn circuit breaker pattern for safety
🎯 Mini-Challenge
5-Minute Practical Task: Create a trading function with: (1) LIVE_TRADING flag from .env, (2) If False, log "PAPER: Would buy..." instead of executing, (3) If True, actually execute. Test both modes with sample trades and verify the flag controls execution correctly.
🖼️ Visual Reference
📊 Safety Gate Flowchart
┌─────────────────┐
│ Execute Trade? │
└────────┬────────┘
│
▼
┌─────────────────┐
│ Check: │
│ LIVE_TRADING? │
└────┬────────┬───┘
│ │
┌─NO─┘ │
│ ┌─YES──┘
▼ ▼
┌─────────┐ ┌──────────┐
│PAPER │ │ REAL$$$$ │
│TRADING: │ │EXECUTION:│
│ │ │ │
│ Log │ │ Blockchain
│ Only │ │ API call
│ │ │ Money at
│ Simulate│ │ risk!
│ order │ │
└─────────┘ └──────────┘
Lesson Summary
Quiz: [Module 6 Lesson 6.2]
4 questions to test your understanding. Score 60% or higher to pass.