5.4 — Strategy Testing — Paper Trade Pehle, Real Baad Mein
Strategy Testing — Paper Trade Pehle, Real Baad Mein
Bismillah. Chalo bachon, course ke sab se zaroori lesson pe aagaye ho.
Lesson 5.4: Strategy Testing — Paper Trade Pehle, Real Baad Mein
Sab se tezz tareeka trading mein paisa ganwanay ka pata hai kya hai? Aik naya "killer" idea sochna aur foran uss pe real paise laga dena. Bhai, market ko zarrra farak nahi parta aapke "killer" idea se, woh aapko 2 minute mein liquidate kar degi. Is liye, real paison se pehle, hum nakli paison se larainge — isko kehte hain paper trading.
Paper Trading Kyun Zaroori Hai? (The 'Why')
Socho, aap ne aik zabardast Theta Sniper strategy banayi hai. Logic yeh hai ke jab market 80% se ooper ya 20% se neeche ho aur expire honay mein 24 ghantay se kam ho, to bot trade le le. Kaghaz pe to buhat acha lag raha hai.
Lekin kya aap ka code ajeeb markets pe trigger ho raha hai? Kya woh trade le raha hai jab usay nahi leni chahiye? Kya aap ka PnL calculation ajeeb numbers de raha hai?
Paper trading aapki strategy ka test nahi hai, yeh aapke code ka test hai.
Hum is mein real paise nahi lagatay. Hum sirf record karte hain ke agar hum trade letay, to kya hota. Yeh bilkul net practice ki tarah hai. Shaheen Afridi bhi match se pehle nets mein practice karta hai, seedha final mein nahi utarta.
Taqi (haan, main, aapka ustaad) ne jab apna pehla bot live kiya tha, to $30 se kiya tha. Lekin uss $30 se pehle, 2 haftay tak 100 se zayada paper trades ki theen. Har trade ko Excel sheet mein daal ke dekha tha ke kya chal raha hai. Ghaltian karni hain, to paper pe karo. Real account pe sirf execution honi chahiye.
Paper Trading Mode Implement Karna
Sab se pehle, humein apne bot ko batana hoga ke bhai, abhi "practice mode" on hai. Real order nahi bhejna.
Yeh kaam hum execution.py file mein karengay. Kyun? Kyunke saari trades execute wahan se hoti hain. Hum aik simple global switch banayengay.
Apni config.py ya main bot file ke top pe yeh daal do:
# config.py
PAPER_TRADING = True # Set to False when you are ready to go live
Ab, execution.py mein jahan aapka real trade ka function hai (e.g., place_order), hum usko aik wrapper mein daal dengay.
# execution.py
# Farz karo yeh aapka real trade function hai jo Polymarket se baat karta hai
def place_real_polymarket_order(market_id, side, price, amount):
print(f"[LIVE] Placing REAL order: {side} on {market_id} @ {price} for ${amount}")
# Yahan pe aapka real API call ka logic hoga
# from polymarket.api import ...
# ...
return {"status": "success", "order_id": "123xyz"}
# Yeh hamara naya paper trading ka logger hai (iss pe abhi detail mein baat hogi)
def paper_trade(strategy, market_id, question, side, price, amount):
# Yeh function hum abhi banayengay
print(f"[PAPER] Logging FAKE trade: {side} on {market_id} @ {price} for ${amount}")
# ... CSV logic here ...
return {"status": "paper_logged"}
# Yeh hai hamara MASTER execution function
def execute_trade(strategy, market_id, question, side, price, amount):
"""
Master function jo decide karega real trade karni hai ya paper.
Yeh function aapki strategy files (e.g., theta_sniper.py) se call hoga.
"""
# config.py se setting import karo
from config import PAPER_TRADING
if PAPER_TRADING:
print("Paper trading mode is ON. Logging trade, no real money spent.")
return paper_trade(strategy, market_id, question, side, price, amount)
else:
print("WARNING: Live trading mode is ON. Real money will be spent.")
return place_real_polymarket_order(market_id, side, price, amount)
Ab scene on hua?
Aapki strategy, for example strategies/theta_sniper.py, hamesha execute_trade ko call karegi. Usko fikar karne ki zaroorat nahi ke mode paper hai ya live. Woh decision execution.py mein centralize ho gaya hai.
# strategies/theta_sniper.py (Example call)
import sys
# Add project root to path to allow imports
sys.path.append('../')
from execution import execute_trade
def run_theta_sniper_strategy(market):
# ... aapka logic to decide trade ...
if some_condition_is_met:
# Seedha master function call karo
execute_trade(
strategy='ThetaSniperV1',
market_id=market['id'],
question=market['question'],
side='YES',
price=0.85, # 85 cents
amount=10 # $10
)
Clean code, bhai. Separation of concerns. Strategy ka kaam hai signal dena, execution ka kaam hai order bhejna (real ya paper).
Paper Trades ko CSV Mein Log Karna
Console pe print karna acha hai, lekin 2 din baad woh history gayab. Humein data ko save karna hai taaki hum usko analyze kar sakein. Sab se asaan tareeka hai CSV (Comma-Separated Values) file. Excel mein aaram se khul jaati hai.
Yeh raha woh code jo aapko prompt mein diya gaya tha. Chalo iska post-mortem karte hain.
# execution.py (or a new file like utils/logger.py)
import csv
from datetime import datetime
def paper_trade(strategy, market_id, question, side, price, amount):
"""Paper trade log karo — real paisa nahi lagega."""
# Step 1: Trade ka data aik dictionary mein jama karo
trade = {
'timestamp': datetime.utcnow().isoformat(), # Kab trade li? ISO format standard hai.
'strategy': strategy, # Kaunsi strategy ne li? ThetaSniper? GeoScout?
'market_id': market_id, # Market ka unique ID
'question': question[:80], # Poora question, 80 chars tak.
'side': side, # 'YES' ya 'NO'
'entry_price': price, # Kis price pe li? e.g., 0.85
'amount': amount, # Kitne $ ki position? e.g., 10
'status': 'open', # Shuru mein har trade 'open' hoti hai.
'exit_price': None, # Jab close hogi tab isko fill karengay.
'pnl': None # Profit/Loss, close honay pe calculate hoga.
}
# Step 2: CSV file mein data write karo
# 'a' ka matlab hai 'append' - file ke end mein add karo, overwrite nahi.
# newline='' zaroori hai, warna CSV mein extra blank rows aati hain.
with open('paper_trades.csv', 'a', newline='', encoding='utf-8') as f:
# fieldnames batata hai ke columns kya hongay aur unka order kya hoga.
writer = csv.DictWriter(f, fieldnames=trade.keys())
# Yeh trick hai: agar file ka size 0 hai (yani file nayi hai),
# to header (column names) likho. Sirf pehli baar.
if f.tell() == 0:
writer.writeheader()
# Asal data ki row likho
writer.writerow(trade)
print(f"[PAPER] {side} '{question[:40]}...' @ {price*100:.0f}¢ | Amount: ${amount}")
return trade
Code Breakdown (Seedhi Baat):
tradeDictionary: Hum har trade ka data aik structured dictionary mein daal rahe hain. Yeh saaf suthra tareeka hai. Kal ko agar CSV ke bajaye database mein save karni ho toh yeh easily compatible hai.
Paper trading is essential before risking real capital. Detailed logging enables post-trade analysis and strategy refinement.
📺 Recommended Videos & Resources
- Backtesting Frameworks (Backtrader, Zipline) — Comprehensive backtesting platforms
- Type: Official Website
- Link description: Learn Backtrader for historical backtesting
- Forward Testing vs Backtesting — Understanding test types
- Type: Wikipedia
- Link description: Learn differences between backtesting and forward testing
- Paper Trading Platforms — Risk-free testing
- Type: YouTube
- Link description: Search "paper trading simulator for crypto/stocks"
- Trade Logging & Analysis — Tracking performance
- Type: YouTube
- Link description: Search "trade logging and performance analysis"
- Statistical Significance in Trading — Validating strategy results
- Type: Wikipedia
- Link description: Learn about stat testing for strategy performance
🎯 Mini-Challenge
5-Minute Practical Task: Run a 10-trade paper trading simulation on one strategy (theta sniper or geo scout). Record entry, exit, profit/loss for each trade. Calculate: (1) Win rate (%), (2) Average profit per win, (3) Average loss per loss, (4) Profit factor. Determine if results are statistically significant.
🖼️ Visual Reference
📊 Paper Trading → Live Trading Progression
┌──────────────────────────────┐
│ PHASE 1: STRATEGY DESIGN │
│ (Theoretical) │
│ - Rules documented │
│ - Entry/exit criteria clear │
└────────────┬─────────────────┘
│
▼
┌──────────────────────────────┐
│ PHASE 2: BACKTESTING │
│ (Historical simulation) │
│ - 100+ past trades tested │
│ - Strategy profitable? │
│ - Drawdown acceptable? │
└────────────┬─────────────────┘
┌────┴────┐
│ (FAIL) │ (PASS)
▼ ▼
[REFINE] ┌──────────────┐
│ PHASE 3: │
│ PAPER TRADE │
│ (Live data, │
│ no money) │
│ - 20+ trades │
│ - Real data │
│ - Algorithm │
│ executed OK│
└────┬─────────┘
│
▼
┌──────────────┐
│ PHASE 4: │
│ LIVE TRADING │
│ (Real money) │
│ - Small size │
│ - Monitor H24│
│ - Prepare to │
│ disable │
└──────────────┘
Lesson Summary
Quiz: [Module 5 Lesson 5.4]
4 questions to test your understanding. Score 60% or higher to pass.