7.2 — Exit Rules — Take Profit, Stop Loss, Trailing Stop
Exit Rules — Take Profit, Stop Loss, Trailing Stop
Waah, chalo shabash. Welcome back to the course. Pichlay lesson mein humne Kelly Criterion se position sizing seekhi. Ab paisa laga toh diya, lekin sab se zaroori sawaal: Nikalna kab hai?
COURSE: Pakistan Ka Pehla Professional Trading Bot Course
MODULE 7: Risk Management — Kelly Criterion Aur Position Sizing
LESSON 7.2: Exit Rules — Take Profit, Stop Loss, Trailing Stop
Suno, bachay. Trading mein 90% log paisa isliye nahi banate kyunke unhe pata hi nahi hota ke position close kab karni hai. Entry toh har koi le leta hai, "buy the dip" ke naare laga ke. Asal game exit ka hai. A good exit strategy protects your capital and locks your profit. Emotions ko side pe rakho, rules pe chalo.
Aaj hum apne bot ka dimaagh banayenge — woh set of rules jo decide karega ke kab tak "hold" karna hai aur kab "sell" ka button dabana hai.
The Core Logic: Hamara check_exit_triggers Function
Yeh hai hamare bot ke risk management system ka dil. Yeh function scanner.py har thori der mein har open position ke liye call karega. Iska kaam simple hai: position lo, current market price lo, aur batao ke bhai, nikalne ka time Aagaya hai ya nahi?
Pehle poora code dekhlo, phir iski चीर پھاڑ (cheer-phaar) karte hain.
# These are our constants, defined at the top of our strategy file,
# for example, in strategies/theta_sniper.py
TAKE_PROFIT = 94.0 # Sell when our side hits 94%+
STOP_LOSS = 12.0 # Cut at 12% adverse move (AI can review)
HARD_STOP = 20.0 # Auto-sell at 20% adverse, no AI debate
TRAILING_PCT = 12.0 # Sell if price drops 12% from its peak
def check_exit_triggers(position, current_price):
"""Position ke exit triggers check karo."""
# Prices are stored from 0.0 to 1.0 in DB, so we convert to 0-100 for calcs
entry = position['entry_price'] * 100
peak = position.get('peak_price', position['entry_price']) * 100
side = position['side'] # 'YES' or 'NO'
# Calculate how much the price has moved against us
if side == 'YES':
# For YES, an adverse move is the price going down
move_pct = current_price - entry
else: # side == 'NO'
# For NO, an adverse move is the price going up
# Our entry profit potential was (100 - entry)
# Our current profit potential is (100 - current_price)
# The move is the difference
move_pct = (100 - current_price) - (100 - entry)
triggers = []
# 1. Take Profit Trigger — Profit jeb mein daalo
our_price = current_price if side == 'YES' else (100 - current_price)
if our_price >= TAKE_PROFIT:
triggers.append({
'type': 'take_profit',
'urgency': 'high',
'reason': f'Our side price {our_price:.1f}% hit TP of {TAKE_PROFIT}%'
})
# 2. Hard Stop Trigger — Critical situation, फौरन निकलो
if move_pct <= -HARD_STOP:
triggers.append({
'type': 'hard_stop',
'urgency': 'critical',
'reason': f'Adverse move of {move_pct:+.1f}% breached hard stop of -{HARD_STOP}%'
})
# 3. Stop Loss Trigger — AI se poocho, but be ready to sell
elif move_pct <= -STOP_LOSS:
triggers.append({
'type': 'stop_loss',
'urgency': 'high',
'reason': f'Adverse move of {move_pct:+.1f}% breached stop loss of -{STOP_LOSS}%'
})
# 4. Trailing Stop Trigger — Winner ko protect karo
if side == 'YES':
drop_from_peak = peak - current_price
else: # side == 'NO'
# For NO, a "drop" means the price went up from its lowest point (our peak)
# Our peak was when the price was lowest.
drop_from_peak = current_price - peak
if drop_from_peak >= TRAILING_PCT and our_price > entry: # Only trigger if we are in profit
triggers.append({
'type': 'trailing_stop',
'urgency': 'medium',
'reason': f'Dropped {drop_from_peak:.1f}% from peak price of {peak:.1f}%'
})
return triggers
Yeh function ek list of "triggers" return karta hai. Agar list khaali hai, matlab "sab changa si," hold karo. Agar list mein kuch hai, toh execution.py ko signal jaayega ke bhai, action lena hai.
Ab ek ek rule ko samjho.
Take Profit (TP) @ 94% — Greed is Your Enemy
Scene yeh hai ke tumne ek market pe bet lagayi, for example, "Will KSE-100 index cross 80,000 by end of month?". Tumne 'YES' khareeda 60 cents (Rs. 60) pe. Market tumhare haqq mein gayi aur price 94 cents (Rs. 94) tak pohanch gayi.
Rule: Jaise hi hamari side ki price 94% hit kare, sell.
Kyun? Why not 99% or 100%? Simple. The last 5-6% are the hardest and slowest to get. Price 94 se 95 jaaney mein utna time laga sakti hai jitna 60 se 90 jaaney mein laga. Isse behtar hai ke 94 pe profit lock karo, azaad ho, aur apna capital kisi nayi opportunity mein daalo. Time is money, and locked capital is dead capital.
Code Breakdown:
# 1. Take Profit Trigger — Profit jeb mein daalo
our_price = current_price if side == 'YES' else (100 - current_price)
if our_price >= TAKE_PROFIT:
triggers.append({
'type': 'take_profit',
'urgency': 'high',
'reason': f'Our side price {our_price:.1f}% hit TP of {TAKE_PROFIT}%'
})
our_price: Agar 'YES' liya hai, tohcurrent_pricehamari price hai. Agar 'NO' liya hai, toh(100 - current_price)hamari price hai.- Condition simple hai:
our_pricejaise hiTAKE_PROFIT(94.0) se upar jaaye, trigger fire kardo.
Example in action:
# --- Runnable Example 1: Take Profit ---
print("--- Example 1: Take Profit Trigger ---")
position_yes = {
'market_id': 'KSE-80K',
'side': 'YES',
'entry_price': 0.60, # 60 cents
'peak_price': 0.95 # Price has already peaked at 95
}
# Market price hits 95 cents
current_market_price = 95.0
triggers = check_exit_triggers(position_yes, current_market_price)
if triggers:
print(f"Position: YES @ 60, Current Price: {current_market_price}")
for trigger in triggers:
print(f" -> Trigger Found: {trigger['type']} ({trigger['urgency']})")
Disciplined exit rules are critical for protecting profits and limiting losses.
---
## 📺 Recommended Videos & Resources
- **[Stop Loss & Take Profit Strategies](https://www.youtube.com/results?search_query=stop+loss+take+profit+trading+strategies)** — Exit mechanics
- Type: YouTube
- Link description: Search "stop loss and take profit strategies"
- **[Trailing Stops Explained](https://en.wikipedia.org/wiki/Trailing_stop)** — Dynamic exits
- Type: Wikipedia
- Link description: Learn about trailing stop mechanisms
- **[Win Rate vs Risk:Reward](https://en.wikipedia.org/wiki/Win_rate)** — Balancing entry and exit
- Type: Wikipedia
- Link description: Learn risk:reward ratio calculations
- **[Breakeven Strategies](https://www.youtube.com/results?search_query=breakeven+stop+loss+trading)** — Protecting capital
- Type: YouTube
- Link description: Search "breakeven stop loss strategy"
- **[Emotional Exits vs Rules-Based](https://www.youtube.com/results?search_query=trading+discipline+emotional+exits)** — Discipline
- Type: YouTube
- Link description: Search "trading discipline and emotional control"
---
## 🎯 Mini-Challenge
**5-Minute Practical Task:** For 3 open trades (entry prices: $50, $75, $100), set: (1) Take profit at 20% above entry, (2) Stop loss at 10% below entry. Track price changes and identify when each exit triggers. Verify your exit logic executes correctly.
---
## 🖼️ Visual Reference
📊 Exit Rules in Action Entry: $75 | TP: $90 (20%) | SL: $67.50 (10%)
Price Trigger? Action ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ $75 None (Entry, watching) $80 None (In position, up 6%) $85 None (In position, up 13%) $90 TP TRIGGER ← (EXIT for PROFIT)
Entry: $75 | TP: $90 (20%) | SL: $67.50 (10%)
Price Trigger? Action ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ $75 None (Entry, watching) $78 None (In position, up 4%) $70 None (In position, down 7%) $68 SL TRIGGER ← (EXIT for LOSS) $65 N/A (Already exited)
Disciplined exits prevent:
- Holding winners too long
- Letting losers grow
- Emotional decision-making
---
Lesson Summary
Quiz: [Module 7 Lesson 7.2]
4 questions to test your understanding. Score 60% or higher to pass.