6.3 — Order Execution — Complete Flow With Error Handling
Order Execution — Complete Flow With Error Handling
Of course. Here is the full lesson content, written in the requested tone and format.
Pakistan Ka Pehla Professional Trading Bot Course
MODULE 6: Execution Engine — Automatically Orders Place Karna
LESSON 6.3: Order Execution — Complete Flow With Error Handling
Duration: 35 Minutes
Chalo bhai, welcome to the real deal. Ab tak humne signals generate karna seekha, strategies banayi, lekin yeh sab theory hai jab tak paisa market mein na lagay. This lesson is where the rubber meets the road — jahan aapka code asli paisa banata ya gawata hai. Isliye ankhain, kaan, aur dimaag khula rakhna.
The Core Logic: Signal ko Action Mein Kaise Badlein?
Aapke scanner.py ne ya ai/gemini.py ne ek zabardast signal generate kiya. For example, "Kya Pakistan T20 World Cup semi-final jeetay ga?" ka market 60 cents pe mil raha hai. Aapki strategy, strategies/theta_sniper.py, kehti hai, "Buy!".
Ab kya? Ab execution.py ka kaam shuru hota hai. Yeh aapke bot ka muscle hai. Iska kaam hai signal ko aakhri anjaam tak pohanchana: order place karna. Lekin yeh sirf ek button dabane jaisa nahi hai. There are checks and balances. We need to be smart, warna broker ko muft ki fees dete raho ge.
The Golden Rule of Pakistani Engineering: Execute First, Log Later
Ek baat गांठ बांध lo. This is non-negotiable.
Pehle trade execute karo. Jab exchange se confirmation aa jaye ke trade ho gayi hai, tab usko apne database (db.py) mein log karo.
Kyun? Imagine the opposite. Aapne pehle db.py mein likha, "Buying 100 shares of YES on Pakistan's win". Phir aapne order place karne ki koshish ki, aur internet connection chala gaya. Ya exchange ne order reject kar diya. Ab kya hoga? Aapke database mein ek "ghost position" ban gayi hai. Aapka bot soche ga ke usne trade le li hai, jabke असल mein koi trade hui hi nahi. This will mess up your entire portfolio tracking, risk management, sab kuch.
Execute -> Get Confirmation -> Log. This is the way.
The Anatomy of execute_trade — Step-by-Step Code Breakdown
Chalo ab execution.py ke sabse critical function ko cheer phaar ke dekhte hain. Yeh function aapke bot ka dil hai. Har cheez iske gird ghoomti hai.
# --- Helper/Dummy functions for demonstration ---
# In a real system, these would make actual API calls.
def fetch_market_by_id(market_id: str) -> dict | None:
"""Simulates fetching market data from an API like Polymarket."""
print(f"[API] Fetching market data for {market_id}...")
# Dummy data for a cricket match market
if market_id == "PK-vs-IND-2024":
return {
"id": "PK-vs-IND-2024",
"question": "Will Pakistan beat India in the T20 match?",
"outcomes": [
{"price": 65, "side": "YES"}, # Price is in percentage (cents)
{"price": 35, "side": "NO"}
]
}
return None
def get_market_price(market: dict) -> float:
"""Extracts the price from the market data."""
# This is a simplification. A real function would need to know which side's price to get.
# For this lesson, we assume we're interested in the first outcome's price.
return market["outcomes"][0]["price"]
def get_token_id(market_id: str, side: str) -> str | None:
"""Simulates getting the unique token ID for a market outcome."""
print(f"[API] Resolving token ID for {market_id} - {side}...")
# In a real blockchain-based system, YES and NO are separate tokens (ERC-20, etc.)
if market_id == "PK-vs-IND-2024" and side == "YES":
return "0xTokenIDForYesOutcome"
elif market_id == "PK-vs-IND-2024" and side == "NO":
return "0xTokenIDForNoOutcome"
return None
def place_order(market_id: str, side: str, amount: float, strategy: str) -> dict:
"""Simulates placing an order on the exchange."""
import random
import time
print(f"[EXCHANGE] Placing order: {side} ${amount:.2f} on {market_id} using {strategy} strategy...")
time.sleep(1) # Simulate network latency
# Simulate random network failure or success
if random.random() > 0.2: # 80% success rate
return {
"success": True,
"order_id": f"ord_{int(time.time())}",
"filled_amount": amount,
"price_filled_at": 65.5 # Simulate a slightly different fill price
}
else:
return {
"success": False,
"error": "Insufficient liquidity"
}
# --- The Main Function We Are Studying ---
def execute_trade(market_id, side, amount, strategy='', question=''):
"""Complete trade execution with all safety checks."""
# 1. Minimum order check
if amount < 1.0:
print(f'[EXEC] Amount ${amount:.2f} below minimum $1. Bumping to $1.')
amount = 1.0
# 2. Get fresh market price (prevent stale orders)
market = fetch_market_by_id(market_id)
if not market:
print(f'[EXEC] Market not found: {market_id}')
return None
current_price = get_market_price(market)
# 3. Price ceiling check
if current_price > 96:
print(f'[EXEC] Price {current_price}% > 96% ceiling. ABORT.')
return None
# 4. Get token ID
token_id = get_token_id(market_id, side)
if not token_id:
print(f'[EXEC] Could not resolve token ID for {side}')
return None
# 5. Execute
print(f'\n[EXEC] ATTEMPTING TRADE: {side} ${amount:.2f} on "{market["question"]}"')
result = place_order(market_id, side, amount, strategy=strategy)
if result and result.get('success'):
print(f'[EXEC] SUCCESS: {side} ${amount:.2f} @ {current_price}%')
# Log to database (This would call a function in db.py)
# db.add_position(market_id, question, side, current_price/100, amount, strategy)
print(f'[DB] Logging successful trade to database. Order ID: {result.get("order_id")}')
return result
print(f'[EXEC] FAILED to execute trade. Reason: {result.get("error", "Unknown")}')
return None
# --- Example Usage ---
# execute_trade("PK-vs-IND-2024", "YES", 25.5, strategy="gemini_v1.5_flash")
Let's break it down, step-by-step.
Step 1: Minimum Order Value Check
# 1. Minimum order check
if amount < 1.0:
print(f'[EXEC] Amount ${amount:.2f} below minimum $1. Bumping to $1.')
amount = 1.0
Scene kya hai? Polymarket jaisi platforms pe minimum order size hota hai, usually $1. Agar aapka signal generator kehta hai ke sirf $0.50 invest karo, toh exchange order reject kar dega. Hum yahan pehle hi isko check kar rahe hain. Agar amount chota hai, toh hum usko automatically minimum $1 pe bump kar dete hain. Simple, effective, aur فضول ke API calls se bachata hai.
Step 2: Price Freshness Check
# 2. Get fresh market price (prevent stale orders)
market = fetch_market_by_id(market_id)
if not market:
print(f'[EXEC] Market not found: {market_id}')
return None
current_price = get_market_price(market)
Yeh bohat zaroori hai. Market prices change every second. Aapka scanner.py shayad 30 second purani price pe signal generate kare. Jab tak execution.py chalta hai, price badal chuki hoti hai.
Robust error handling ensures your bot recovers gracefully from network failures and API issues.
📺 Recommended Videos & Resources
- Exception Handling Best Practices — Python error handling
- Type: Python Official Docs
- Link description: Learn try-except-finally for robust code
- Retry Strategies & Exponential Backoff — Handling transient failures
- Type: AWS Blog
- Link description: Learn retry logic and backoff strategies
- Order Validation & Pre-Checks — Preventing bad trades
- Type: YouTube
- Link description: Search "order validation and pre-checks"
- Network Resilience — Handling connectivity issues
- Type: Wikipedia
- Link description: Learn about resilient systems
- Idempotency in APIs — Avoiding duplicate orders
- Type: YouTube
- Link description: Search "idempotent API design"
🎯 Mini-Challenge
5-Minute Practical Task: Create an order execution function that: (1) Validates price before execution, (2) Retries up to 3 times on failure, (3) Logs all errors, (4) Has a 30-second timeout. Test with both successful and failed scenarios to verify error handling works.
🖼️ Visual Reference
📊 Resilient Order Execution Flow
┌──────────────────┐
│ Order Signal │
│ (Fresh price OK?)│
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Validate │
│ - Slippage OK? │
│ - Size OK? │
│ - Budget OK? │
└────┬──────────┬──┘
┌─NO─┘ │
│ ┌─YES─┘
▼ ▼
[REJECT] ┌──────────────┐
│ Send to API │
└────┬────┬────┘
┌─OK─┘ │
│ ┌─FAIL┴─────┐
│ │ │
▼ ▼ ▼
[OK] [RETRY] [MAX RETRY]
(1/3) │
│ [CANCEL]
│ Log error
▼
[FILL]
[Log OK]
Lesson Summary
Quiz: [Module 6 Lesson 6.3]
4 questions to test your understanding. Score 60% or higher to pass.