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.
True or False.==, !=, >, <, >=, <= to compare values.and, or, not for complex signal logic.if block. No curly braces!# 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")
Price is ABOVE VWAP — bullish bias
Comparison operators return True or False. In a trading bot, you use them constantly to check prices, quantities, time, and risk limits.
| Operator | Meaning | Trading Example | Result |
|---|---|---|---|
== | Equal to | signal == "BUY" | True if signal is BUY |
!= | Not equal to | position != "FLAT" | True if holding a trade |
> | Greater than | ltp > entry_price | True if in profit |
< | Less than | ltp < stop_loss | True → exit now! |
>= | Greater than or equal | rsi >= 70 | True if overbought |
<= | Less than or equal | drawdown <= -5000 | True → kill switch |
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
True False False True
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.
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")
✅ BUY Signal fired 🟢 Trading allowed
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.
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 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}")
Symbol : NIFTY25JUNFUT LTP : ₹22485 VWAP : ₹22380 Signal : BUY Confidence: HIGH
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.
# 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}")
Symbol : BANKNIFTY25JUNFUT Entry : ₹48200 | LTP: ₹48540 P&L : ₹+5,100 Action : HOLD — Trail stop loss up
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.
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 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")
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
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.
# 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}")
Result : PROFIT Bias : BULLISH P&L : +350 pts ✅
label = "WIN" if pnl > 0 else "LOSS" do?rsi = 45.
ltp=22500, vwap=22380, rsi=52.
and with chained comparisons like 40 <= rsi <= 65.SAFE TO TRADE
or ALL SYSTEMS HALT message.
or.for and while —
the engine behind scanning all stocks, iterating over candles, and running real-time monitoring loops.