4.4 — Tier 3 — Sonnet: The Decision Maker
Tier 3 — Sonnet: The Decision Maker
Alright, chalo bachon, class shuru karte hain.
Pakistan Ka Pehla Professional Trading Bot Course
MODULE 4: AI Signal Engine — 4-Tier Decision System Banana
Lesson 4.4: Tier 3 — Sonnet: The Decision Maker
Duration: 35 minutes
Assalam-o-Alaikum! Last lessons mein humne Haiku aur Gemini se kaam karwaya. Wo aisi hain jese aapke junior analysts, data laa kar de rahe hain, initial screening kar rahe hain. Lekin paisa lagane ka decision junior ke haath mein nahi de sakte, aag laga dega account ko. That's where Tier 3 comes in. Sonnet hamara fund manager hai, the final boss.
Kyun Zaroori Hai Yeh? (The Hook)
Yaar dekho, Haiku fast hai lekin halka hai, Gemini thora deep sochta hai. Lekin trading mein, analysis ke baad jo final "YES" ya "NO" bolna hota hai, woh sabse critical hai. Ek ghalat decision aapka 5-10% portfolio ura sakta hai. Sonnet ko humne aisi training deni hai ke woh hamare rules ke andar rehte hue, ek professional trader ki tarah, paisa deploy karne ka faisla kare. This isn't just another analysis step; this is the step where the bot commits capital. Yahan ghalti ki gunjaish nahi.
Sonnet Ka Role: The Final Authority
Socho hamare system ka workflow:
- Tier 1 (Haiku):
scanner.pyne 100 markets uthayi.ai/haiku.pyne 90 ko reject kar diya. "Sir, yeh 10 promising lag rahi hain." - Tier 2 (Gemini):
ai/gemini.pyne un 10 markets ka detailed "financial report" banaya. "Sir, in 10 mein se yeh 3 aisi hain jahan numbers strong hain, sentiment positive hai." - Tier 3 (Sonnet): Ab
ai/sonnet.pyka kaam hai. Woh Gemini ki report parhega aur bolega, "Theek hai. Market #2 pe 1500 rupay laga do, YES side pe. Market #1 aur #3 ko choro, risk/reward ajeeb hai."
Sonnet is not doing new research. It's taking the refined analysis from Gemini and applying a trading personality to it to make the final call. It's the brain that connects analysis to action.
Bot ki Personality: The System Prompt
Yeh sab se important cheez hai. AI model ek kora kaaghaz (blank slate) hai. Usko batana parta hai ke woh hai kon aur uska kaam kya hai. Yeh hum SYSTEM_PROMPT ke zariye karte hain. Hamare Polymarket Oracle bot mein, Sonnet ka system prompt ai/sonnet.py file ke andar define hua hai.
Let's break down the exact code. Yeh copy-paste nahi hai, this is the production code we use.
# ai/sonnet.py
import os
import requests
import json
# Replace with the actual Anthropic API URL
API_URL = "https://api.anthropic.com/v1/messages"
# A helper function to safely parse JSON. LLMs can sometimes return broken JSON.
def safe_parse_json(json_string: str) -> dict:
"""Safely parses a JSON string, returning a dictionary or an error message."""
try:
# The LLM often wraps the JSON in ```json ... ```, so we strip that.
if json_string.strip().startswith('```json'):
json_string = json_string.strip()[7:-3]
return json.loads(json_string)
except json.JSONDecodeError:
return {"decision": "SKIP", "reasoning": f"Error: Failed to decode LLM JSON response: {json_string}"}
# --- YAHAN SE HAMARA MAIN LOGIC SHURU HOTA HAI ---
SONNET_MODEL = 'claude-3-sonnet-20240229' # Always use the latest stable model
SYSTEM_PROMPT = """You are an aggressive prediction market trader managing a $30 portfolio.
RULES:
1. If edge >= 3% and confidence >= 0.60, BUY. Don't wait for perfect setups.
2. NEVER exceed $5 per trade.
3. NEVER buy above 96% (96c risk for 4c reward = bad EV).
4. Take profit at 94%+. Stop loss at 12% adverse move.
RESPOND IN THIS JSON FORMAT:
{
"decision": "BUY/SKIP",
"side": "YES/NO",
"amount_eur": 0.00,
"reasoning": "2-3 sentences max",
"confidence": 0.0-1.0,
"edge_pct": 0.0
}"""
Let's dissect this SYSTEM_PROMPT word-for-word:
-
You are an aggressive prediction market trader managing a $30 portfolio.aggressive: Yeh keyword sabse ahem hai. Iska matlab hai bot ne "safe" nahi khelna. Agar usko a decent chance (edge) nazar aa raha hai, woh trade lega. He's not a passive advisor; he's an active trader looking to deploy capital. Humne usko conservative nahi banaya.$30 portfolio: Is se usko context milta hai ke capital kitna hai. Woh 30 dollar ke portfolio pe 20 dollar ki trade nahi maaray ga. It grounds its decisions in reality. (Yeh abhi EUR mein hai, but you get the point).
-
RULES:If edge >= 3% and confidence >= 0.60, BUY. Don't wait for perfect setups.- Yeh hamari core strategy hai, for example
strategies/theta_sniper.pyse aayi hai. Hum usko bata rahe hain ke agar tumhara analysis kehta hai ke 60% chance hai ke hum jeetain ge aur market price se 3% sasta mil raha hai, toBUY. "Don't wait" reinforces the aggressive nature.
- Yeh hamari core strategy hai, for example
NEVER exceed $5 per trade.- Hard rule for risk management. Portfolio ka ~15-17% se zyada ek trade pe nahi lagana. Simple. Isko aap PKR mein bhi de sakte ho, for example "NEVER exceed 1500 PKR per trade."
NEVER buy above 96%.- Yeh Expected Value (EV) ka concept hai. Agar aap 96 rupay laga rahe ho 4 rupay kamanay ke liye, to aapko 24 out of 25 times jeetna paray ga sirf break-even karne ke liye. It's a mathematically bad trade. Yeh rule bot ko stupid trades se bachata hai.
Take profit at 94%+. Stop loss at 12% adverse move.- Yeh bot ko trade management sikha raha hai. Iska abhi decision se direct talluq nahi, lekin uski overall "thinking" ka part ban jata hai.
-
RESPOND IN THIS JSON FORMAT:- This is non-negotiable. Hamara
execution.pyscript koi kahani nahi parh sakta. Usko structured data chahiye. decision: Simple "BUY" ya "SKIP".side: "YES" ya "NO".amount_eur: Kitna paisa lagana hai.reasoning: Yeh hamare liye hai,db.pyisko database mein log karta hai taake hum baad mein review kar sakein ke bot ne kya soch ke decision liya.confidence,edge_pct: Yeh Gemini ki analysis se nikal ke deta hai, taake hum log kar sakein ke kis confidence/edge pe trade li gayi.
- This is non-negotiable. Hamara
💡 Pro Tip: Chain of Thought for Complex Decisions
Kabhi kabhi, market bohot complex hoti hai. For example, "Will Pakistan qualify for the T20 World Cup semi-finals?" Iske bohot se factors hain: doosri teams ki performance, net run rate, player injuries. Aise cases mein, aap Sonnet ko force kar sakte ho ke woh pehle "soche" aur phir final JSON de.
You can modify the user prompt like this:
prompt = f"""Analyze this complex candidate:
{candidate_analysis}
First, think step-by-step inside <thinking> tags about the pros and cons.
Then, based on your thinking, provide the final JSON response.
"""
Is se Sonnet pehle ek detailed reasoning likhega (<thinking>...</thinking>) aur uske baad aakhir mein JSON dega. This significantly improves the quality of its decision-making by showing intermediate reasoning steps.
Tier 3 uses extended thinking for high-stakes decisions where accuracy justifies the cost.
📺 Recommended Videos & Resources
- Claude Sonnet Advanced Features — Extended thinking and advanced prompting
- Type: Official Documentation
- Link description: Learn Sonnet capabilities and thinking mode
- Chain-of-Thought Prompting — Improving LLM reasoning
- Type: Wikipedia
- Link description: Learn how to elicit better reasoning from models
- Risk Management in Trading Decisions — Portfolio risk concepts
- Type: YouTube
- Link description: Search "trading risk management position sizing"
- Extended Thinking in LLMs — Leveraging model reasoning
- Type: YouTube
- Link description: Search "Claude extended thinking mode usage"
- Decision-Making Frameworks — Structuring choices
- Type: Wikipedia
- Link description: Learn frameworks for systematic decision-making
🎯 Mini-Challenge
5-Minute Practical Task: Write a Tier 3 decision function using Claude Sonnet that evaluates 3 finalists from Tier 2. It should: (1) Compare all three markets side-by-side, (2) Identify pros/cons of trading each, (3) Return a JSON with final_choice (market_id), action (BUY/SELL/HOLD), size (position %), and confidence (0-1). Test with sample finalists.
🖼️ Visual Reference
📊 Tier 3 (Claude Sonnet) Final Decision Process
┌────────────────────────────────┐
│ From Tier 2 (Top Candidates) │
│ - 3 qualified markets │
│ - Confidence scores 0.75-0.90 │
└────────────┬───────────────────┘
│
▼
┌────────────────────────────────┐
│ Sonnet Receives: │
│ - All 3 market analyses │
│ - Full price histories │
│ - Risk parameters │
│ - Portfolio state │
└────────────┬───────────────────┘
│
▼
┌────────────────────────────────┐
│ Extended Thinking (~$0.01-0.02)│
│ - Reasoning: Why each market │
│ - Risk assessment │
│ - Correlation analysis │
│ - Final ranking & decision │
└────────────┬───────────────────┘
│
▼
┌────────────────────────────────┐
│ Final Output: │
│ { │
│ "chosen_market": "POL_567", │
│ "action": "BUY", │
│ "position_size": 50, │
│ "confidence": 0.92, │
│ "exit_level": 85, │
│ "stop_loss": 55 │
│ } │
└────────────┬───────────────────┘
│
▼
┌────────────────────────────────┐
│ Trade Execution │
│ (Bot places order) │
└────────────────────────────────┘
Lesson Summary
Quiz: Tier 3 — Sonnet: The Decision Maker
4 questions to test your understanding. Score 60% or higher to pass.