Back
Learning Hub/ Python for Algo Trading/ Lesson 2 Phase 1 of 6
Python for Algo Trading · Phase 1

If / Else Conditions

Every trading bot makes decisions: go long, go short, or stay flat. Learn how Python evaluates conditions to fire buy/sell signals, trigger stop-losses, and activate kill-switches — all with real NIFTY & BankNifty logic.

Lesson 2 of 9 ~35 min Beginner NSE / NIFTY examples
Lesson 2 of 9 — If / Else Conditions 22% complete
LESSON 02 · SECTION 1
What is a Condition?
beginner

A condition is a question Python can answer with True or False. Is the LTP above VWAP? Is our drawdown beyond the limit? Is it after 3:15 PM? The if / elif / else structure lets your program act differently based on the answer.

🔀
Decision branching
Code takes different paths depending on whether a condition is True or False.
⚖️
Comparison operators
Use ==, !=, >, <, >=, <= to compare values.
🔗
Logical operators
Combine conditions with and, or, not for complex signal logic.
📐
Indentation matters
Python uses 4-space indentation to define which code belongs inside an if block. No curly braces!
basic_if.pypython
# Basic if / elif / else structure
ltp = 22450
vwap = 22380

if ltp > vwap:
    print("Price is ABOVE VWAP — bullish bias")
elif ltp == vwap:
    print("Price is AT VWAP — neutral")
else:
    print("Price is BELOW VWAP — bearish bias")
Output
Price is ABOVE VWAP — bullish bias

Section 2
Comparison Operators in Trading

Comparison operators return True or False. In a trading bot, you use them constantly to check prices, quantities, time, and risk limits.

OperatorMeaningTrading ExampleResult
==Equal tosignal == "BUY"True if signal is BUY
!=Not equal toposition != "FLAT"True if holding a trade
>Greater thanltp > entry_priceTrue if in profit
<Less thanltp < stop_lossTrue → exit now!
>=Greater than or equalrsi >= 70True if overbought
<=Less than or equaldrawdown <= -5000True → kill switch
comparisons.pypython
entry_price = 22100
ltp         = 22450
stop_loss   = 21900
target      = 22500

print(ltp > entry_price)   # True  — trade in profit
print(ltp < stop_loss)    # False — SL not hit yet
print(ltp >= target)      # False — target not reached
print(ltp != entry_price) # True  — price has moved
Output
True
False
False
True

Section 3
Logical Operators: and / or / not

Real trading signals rarely depend on a single condition. A buy signal might require LTP above VWAP AND RSI below 60 AND no open position. Logical operators let you combine multiple conditions into one decision.

logical_operators.pypython
ltp         = 22450
vwap        = 22380
rsi         = 55
position    = "FLAT"
daily_loss  = -2000   # rupees

# BUY signal: price above VWAP AND RSI not overbought AND no open trade
if ltp > vwap and rsi < 60 and position == "FLAT":
    print("✅ BUY Signal fired")

# SELL signal: price below VWAP OR RSI overbought
if ltp < vwap or rsi >= 70:
    print("🔴 Consider EXIT")

# Kill switch: NOT allowed to trade if loss > 5000
kill_switch = daily_loss <= -5000
if not kill_switch:
    print("🟢 Trading allowed")
else:
    print("🚫 Kill switch active — stop trading")
Output
✅ BUY Signal fired
🟢 Trading allowed
💡 PRO TIP
Python evaluates and conditions left to right and short-circuits: if the first condition is False, it won't even check the rest. Put your cheapest/most-likely-to-fail check first to improve performance.

Section 4
VWAP Signal Engine

VWAP (Volume Weighted Average Price) is the most widely used intraday reference level for institutional traders. Let's build a complete signal engine that generates BUY / SELL / HOLD signals based on price vs VWAP with confirmation filters.

vwap_signal.pypython
# VWAP Signal Engine — NIFTY Futures
symbol      = "NIFTY25JUNFUT"
ltp         = 22485
vwap        = 22380
rsi         = 53
volume_ratio = 1.4     # current vol / average vol
position    = "FLAT"

# Determine signal
if ltp > vwap and rsi < 65 and volume_ratio >= 1.2:
    signal = "BUY"
    confidence = "HIGH"
elif ltp > vwap and rsi < 65:
    signal = "BUY"
    confidence = "MEDIUM"
elif ltp < vwap and rsi > 35:
    signal = "SELL"
    confidence = "MEDIUM"
else:
    signal = "HOLD"
    confidence = "LOW"

print(f"Symbol   : {symbol}")
print(f"LTP      : ₹{ltp}")
print(f"VWAP     : ₹{vwap}")
print(f"Signal   : {signal}")
print(f"Confidence: {confidence}")
Output
Symbol   : NIFTY25JUNFUT
LTP      : ₹22485
VWAP     : ₹22380
Signal   : BUY
Confidence: HIGH

Section 5
Stop-Loss & Target Checker

Once a trade is open, every tick must be checked against your stop-loss and target. This section builds the real-time trade monitoring logic used in live algo systems.

sl_target_checker.pypython
# Trade Monitor — BANKNIFTY Long
symbol      = "BANKNIFTY25JUNFUT"
entry_price = 48200
ltp         = 48540
stop_loss   = 47900    # -300 points SL
target      = 48700    # +500 points target
lot_size    = 15
position    = "LONG"

pnl = (ltp - entry_price) * lot_size

if position == "LONG":
    if ltp <= stop_loss:
        action = "EXIT — Stop Loss Hit"
    elif ltp >= target:
        action = "EXIT — Target Reached 🎯"
    elif ltp > entry_price + 200:
        action = "HOLD — Trail stop loss up"
    else:
        action = "HOLD — Wait for breakout"
else:
    action = "No open position"

print(f"Symbol : {symbol}")
print(f"Entry  : ₹{entry_price}  |  LTP: ₹{ltp}")
print(f"P&L    : ₹{pnl:+,.0f}")
print(f"Action : {action}")
Output
Symbol : BANKNIFTY25JUNFUT
Entry  : ₹48200  |  LTP: ₹48540
P&L    : ₹+5,100
Action : HOLD — Trail stop loss up
⚠️ NESTED IF
The inner if/elif/else only runs when position == "LONG". This pattern — a condition inside a condition — is called nested if. Keep nesting to 2 levels max for readability.

Section 6
Kill Switch Logic

A kill switch shuts down trading when daily loss exceeds a preset limit. This is mandatory risk management in any professional algo system — SEBI also requires automated systems to have pre-trade risk checks.

kill_switch.pypython
# Kill Switch System
daily_loss_limit = -10000   # ₹10,000 max loss per day
daily_pnl        = -12500   # today's running P&L
max_trades       = 10
trades_taken     = 7
time_now         = 15        # 3 PM (24-hr format hour)
cutoff_time      = 15        # no new trades at/after 3 PM

kill_by_loss  = daily_pnl <= daily_loss_limit
kill_by_trades = trades_taken >= max_trades
kill_by_time  = time_now >= cutoff_time

trading_allowed = not (kill_by_loss or kill_by_trades or kill_by_time)

print(f"Daily P&L       : ₹{daily_pnl:,}")
print(f"Loss Kill Switch : {kill_by_loss}")
print(f"Trade Limit Kill : {kill_by_trades}")
print(f"Time Kill Switch : {kill_by_time}")
print(f"Trading Allowed  : {trading_allowed}")

if kill_by_loss:
    print("🚨 KILL SWITCH: Daily loss limit exceeded — all trading halted")
elif kill_by_time:
    print("⏰ TIME KILL: Market close window — no new entries")
elif kill_by_trades:
    print("📊 TRADE LIMIT: Max trades for the day reached")
Output
Daily P&L       : ₹-12,500
Loss Kill Switch : True
Trade Limit Kill : False
Time Kill Switch : True
Trading Allowed  : False
🚨 KILL SWITCH: Daily loss limit exceeded — all trading halted

Section 7
Ternary (One-Line) Conditions

Python supports a compact one-line conditional expression called the ternary operator. It's ideal for quick value assignments in trading scripts — like labelling a trade as profitable or a loss without writing a full if/else block.

ternary.pypython
# Syntax: value_if_true if condition else value_if_false
ltp        = 22450
entry      = 22100
vwap       = 22380

trade_result = "PROFIT" if ltp > entry else "LOSS"
bias         = "BULLISH" if ltp > vwap else "BEARISH"
rsi_zone     = "OVERBOUGHT" if 70 >= 70 else "NORMAL"

pnl_pts = ltp - entry
pnl_label = f"+{pnl_pts} pts ✅" if pnl_pts > 0 else f"{pnl_pts} pts ❌"

print(f"Result : {trade_result}")
print(f"Bias   : {bias}")
print(f"P&L    : {pnl_label}")
Output
Result : PROFIT
Bias   : BULLISH
P&L    : +350 pts ✅

Section 8
Quick Quiz
QUESTION 1 OF 3
Which condition correctly checks if LTP has hit the stop-loss of 22000?
Altp == 22000
Bltp <= 22000
Cltp >= 22000
Dltp != 22000
QUESTION 2 OF 3
You want to place a BUY only if RSI < 60 AND position is "FLAT". Which is correct?
Aif rsi < 60 or position == "FLAT":
Bif rsi < 60 and position == "FLAT":
Cif not rsi < 60 and position == "FLAT":
Dif rsi < 60 and not position:
QUESTION 3 OF 3
What does label = "WIN" if pnl > 0 else "LOSS" do?
ARaises an error — invalid syntax
BPrints WIN or LOSS to console
CAssigns "WIN" if pnl > 0, else assigns "LOSS" to label
DAlways assigns "WIN"

Section 9
Practice Exercises
EXERCISE 1 · EASY
RSI Zone Classifier
Write an if/elif/else block that classifies RSI into zones: RSI ≥ 70 → "Overbought", RSI ≤ 30 → "Oversold", else → "Neutral". Test with rsi = 45.
Hint: use three elif/else branches, print the zone label.
EXERCISE 2 · MEDIUM
Multi-condition NIFTY Signal
Build a signal generator: BUY if LTP > VWAP AND RSI between 40–65. SELL if LTP < VWAP AND RSI between 35–60. HOLD otherwise. Test with ltp=22500, vwap=22380, rsi=52.
Hint: use and with chained comparisons like 40 <= rsi <= 65.
EXERCISE 3 · CHALLENGE
Full Risk Dashboard
Create a risk status checker with three kill conditions: daily P&L ≤ -15000, trades taken ≥ 12, or current hour ≥ 15. Print each condition's status and a final SAFE TO TRADE or ALL SYSTEMS HALT message.
Hint: store each condition in a boolean variable first, then combine with or.
🚀 UP NEXT — LESSON 3
You can now make decisions. But what if you need to check 50 ticks in a row? Lesson 3: Loops teaches you for and while — the engine behind scanning all stocks, iterating over candles, and running real-time monitoring loops.
Prev