0% found this document useful (0 votes)
68 views13 pages

Level-Based Breakout Trading Strategy

The document outlines a Level-Based Breakout Trading Strategy that utilizes real-time support and resistance levels for trading indices and options. It details the trading logic, key features, risk management parameters, and the integration of options trading, emphasizing the importance of paper trading for risk mitigation. Additionally, it provides insights into the strategy's configuration, entry and exit logic, and best practices for successful trading.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views13 pages

Level-Based Breakout Trading Strategy

The document outlines a Level-Based Breakout Trading Strategy that utilizes real-time support and resistance levels for trading indices and options. It details the trading logic, key features, risk management parameters, and the integration of options trading, emphasizing the importance of paper trading for risk mitigation. Additionally, it provides insights into the strategy's configuration, entry and exit logic, and best practices for successful trading.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

8/7/25, 9:18 AM Level-Based Trading Strategy Explained

📊 Level-Based Breakout Trading Strategy


Real-Time Support & Resistance Level Trading with Websocket
Automated Breakout System for Indices and Options

🎯 Strategy Overview

📈 Level-Based Trading Concept


Upper Level (Resistance) ₹21,800

🔄 Trading Zone
Current Price ₹20,850 📈
🔄 Trading Zone
Lower Level (Support) ₹19,900

🎯 Trading Logic
Upper Breakout: Buy when price breaks above resistance

Lower Breakdown: Sell when price breaks below support

Real-time Monitoring: Continuous websocket price updates

Flexible Trading: Trade index directly or options

Risk Management: Automatic stop-loss and targets

Multiple Trades: Up to 4 trades per session

⚡ Key Features
Dual Mode: Index trading or options trading

Trailing Stop Loss: Lock in profits automatically

Time-based Exit: EOD position closure

Multi-Broker Support: 11 different brokers

Paper Trading: Test strategies safely

Real-time Logging: Complete trade history

⚠️ Important Educational Disclaimer


This code is for learning purposes only. Level-based trading involves significant risk. Support and resistance levels can fail, leading to losses.
Always understand the risks, start with paper trading, and never trade with money you cannot afford to lose.

[Link] 1/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained

⚙️ Strategy Configuration

📋 Core Trading Parameters

📅 Entry Time 📈 Symbol 🔺 Upper Level 🔻 Lower Level

00:00:00 NIFTY 50 ₹21,800 ₹19,900


Strategy start time NSE:NIFTY 50 (base instrument) Resistance level for buy signal Support level for sell signal
(customizable)

🎯 OTM Distance 📦 Quantity

500 pts 75
Out-of-the-money for options Number of lots to trade

🔧 Risk Management Parameters

Stop Loss & Target Configuration


SL_percentage = 0.02 (2%): Stop loss at 2% from entry
target_percentage = 0.4 (40%): Target at 40% profit from entry
maxtrade = 4: Maximum 4 trades per session

Trailing Stop Loss Settings


for_every_x_point = 1: For every 1 point profit
trail_by_y_point = 1: Trail stop loss by 1 point
Helps lock in profits as price moves favorably

🔄 Trading Mode Selection

Index Trading Mode (tradeOption = 0)


Trades the underlying index directly (NSE:NIFTY 50)
Direct exposure to index movement

Lower leverage, lower risk

Suitable for conservative traders

Options Trading Mode (tradeOption = 1)

[Link] 2/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained
Trades NIFTY options based on breakout direction
Higher leverage, higher risk/reward

CE for upper breakout, PE for lower breakdown

Time decay consideration important

[Link] 3/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained

🔄 Trading State Machine

📊 State Definitions
State (st) Description Condition Action

0 Waiting for Entry No position, monitoring levels Check for breakout signals

1 In Buy Trade Upper level broken Monitor SL/Target for long position

2 In Sell Trade Lower level broken Monitor SL/Target for short position

-1 No Trade Zone Target hit, no more entries Wait for next session

🔄 State Transition Flow

STATE 0: WAITING
Monitor Upper & Lower Levels

LEVEL BREAKOUT?
Price > Upper OR Price < Lower

ENTER TRADE
State 1 (Buy) or State 2 (Sell)

MONITOR POSITION
Check SL, Target, Trailing, Time Exit

EXIT TRADE
Return to State 0 or State -1

[Link] 4/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained

🎯 Entry & Exit Logic

📈 Buy Entry Logic (Upper Breakout)


if ltp > upperLevel and number_of_trade < maxtrade: print('Upper Level Broken') sl = float(ltp) * (1 -
SL_percentage/100) target = float(ltp) * (1 + target_percentage/100) st = 1 # Set state to buy trade if tradeOption ==
1: # Buy CE option oidentry = findStrikePriceATM(checkInstrument, "CE") else: # Buy index directly oidentry =
placeOrder1(checkInstrument, "BUY", qty, "MARKET", ltp)

🎯 Example: Upper Breakout


Upper Level: ₹21,800
Current Price: ₹21,805 (breakout!)
Stop Loss: ₹21,805 × (1 - 0.02) = ₹21,368
Target: ₹21,805 × (1 + 0.4) = ₹30,527
Action: Buy CE option or Index

📉 Sell Entry Logic (Lower Breakdown)


if ltp < lowerLevel and number_of_trade < maxtrade: print('Lower Level Broken') sl = float(ltp) * (1 +
SL_percentage/100) target = float(ltp) * (1 - target_percentage/100) st = 2 # Set state to sell trade if tradeOption ==
1: # Buy PE option oidentry = findStrikePriceATM(checkInstrument, "PE") else: # Sell index directly oidentry =
placeOrder1(checkInstrument, "SELL", qty, "MARKET", ltp)

🎯 Example: Lower Breakdown


Lower Level: ₹19,900
Current Price: ₹19,895 (breakdown!)
Stop Loss: ₹19,895 × (1 + 0.02) = ₹20,293
Target: ₹19,895 × (1 - 0.4) = ₹11,937
Action: Buy PE option or Sell Index

🛡️ Exit Conditions

❌ Stop Loss Exit


Buy Trade (State 1): Exit when ltp ≤ sl
Sell Trade (State 2): Exit when ltp ≥ sl
Returns to State 0 (can take new trades)

✅ Target Exit
Buy Trade (State 1): Exit when ltp ≥ target

[Link] 5/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained
Sell Trade (State 2): Exit when ltp ≤ target
Goes to State -1 (no more trades)

⏰ Time-based Exit (EOD)


Automatic exit at 15:15 (3:15 PM) regardless of P&L
Prevents overnight risk and assignment issues with options

[Link] 6/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained

📈 Trailing Stop Loss Mechanism

🔄 Buy Trade Trailing Logic


# For Buy Trades (State 1) if ltp > originalEntryPrice + for_every_x_point: originalEntryPrice = originalEntryPrice +
for_every_x_point sl = sl + trail_by_y_point

📊 Trailing Example - Buy Trade

Entry: ₹21,805 SL: ₹21,368

Price: ₹21,806 (+1) New SL: ₹21,369 (+1)

Price: ₹21,810 (+5) New SL: ₹21,373 (+5)

Price: ₹21,815 (+10) New SL: ₹21,378 (+10)

🔄 Sell Trade Trailing Logic


# For Sell Trades (State 2) if ltp < originalEntryPrice - for_every_x_point: originalEntryPrice = originalEntryPrice -
for_every_x_point sl = sl - trail_by_y_point

📊 Trailing Example - Sell Trade

Entry: ₹19,895 SL: ₹20,293

Price: ₹19,894 (-1) New SL: ₹20,292 (-1)

Price: ₹19,890 (-5) New SL: ₹20,288 (-5)

Price: ₹19,885 (-10) New SL: ₹20,283 (-10)

🎯 Benefits of Trailing Stop Loss


Profit Protection: Locks in gains as price moves favorably

Automatic Adjustment: No manual intervention required

Risk Reduction: Prevents giving back large profits

Trend Following: Stays with the trend longer

[Link] 7/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained

🎲 Options Trading Integration

📈 Call Option Strategy (Upper Breakout)


def findStrikePriceATM(name, cepe): # Get current index price ltp = [Link](name) # Calculate ATM strike if
stock == "NIFTY": closest_Strike = int(round((ltp / 50),0) * 50) elif stock == "BANKNIFTY": closest_Strike =
int(round((ltp / 100),0) * 100) # Add OTM distance for CE closest_Strike_CE = closest_Strike + otm atmCE =
[Link](stock, intExpiry, closest_Strike_CE, "CE") # Buy CE option oidentry = placeOrder1(atmCE, "BUY",
qty, "MARKET", ltp)

🎯 CE Option Example
NIFTY Spot: ₹21,805 (upper breakout)
ATM Strike: 21,800
OTM Distance: 500 points
CE Strike: 22,300 (21,800 + 500)
Action: Buy 22,300 CE

📉 Put Option Strategy (Lower Breakdown)


def findStrikePriceATM(name, cepe): # Get current index price ltp = [Link](name) # Calculate ATM strike if
stock == "NIFTY": closest_Strike = int(round((ltp / 50),0) * 50) elif stock == "BANKNIFTY": closest_Strike =
int(round((ltp / 100),0) * 100) # Subtract OTM distance for PE closest_Strike_PE = closest_Strike - otm atmPE =
[Link](stock, intExpiry, closest_Strike_PE, "PE") # Buy PE option oidentry = placeOrder1(atmPE, "BUY",
qty, "MARKET", ltp)

🎯 PE Option Example
NIFTY Spot: ₹19,895 (lower breakdown)
ATM Strike: 19,900
OTM Distance: 500 points
PE Strike: 19,400 (19,900 - 500)
Action: Buy 19,400 PE

⚖️ Index vs Options Comparison


Aspect Index Trading Options Trading

Leverage Lower leverage Higher leverage (10-50x)

Risk Moderate risk Higher risk (can lose 100%)

Time Decay No time decay Theta decay affects options

Capital Required Higher capital Lower capital

Profit Potential Linear with index movement Exponential with favorable movement

[Link] 8/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained

🏦 Multi-Broker Integration

🔗 Supported Trading Platforms


Groww Zerodha Angel One Upstox ICICI Direct Fyers Alice Blue Shoonya
✅ Currently Available Available Available Available Available Available Available
Active

IIFL Dhan Nuvama


Available Available Available

🔧 Dynamic Library Import


def importLibrary(): # Dynamic import based on broker selection if groww_broker == 1: from growwapi import GrowwAPI
import helper_groww as helper token = open("groww_token.txt",'r').read() groww = GrowwAPI(token) if zerodha_broker == 1:
from kiteconnect import KiteConnect import helper_zerodha as helper apiKey = open("zerodha_api_key.txt",'r').read()
accessToken = open("zerodha_access_token.txt",'r').read() kc = KiteConnect(api_key=apiKey)
kc.set_access_token(accessToken)

⚡ Paper Trading Safety


papertrading = 0 → Paper trading mode (No real orders)
papertrading = 1 → Live trading mode (Real money at risk)

⚠️ Always test with paper trading first!

[Link] 9/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained

💻 Code Architecture & Functions

🏗️ Core Strategy Functions


findStrikePriceATM(name, cepe)
Purpose: Calculates and places option orders based on ATM
Parameters: Index name, option type (CE/PE)
Returns: Order ID for the placed option trade

exitPosition(tradeOption)
Purpose: Exits existing option position
Logic: Places opposite order to close position
Usage: Called on SL, target, or time exit

Main Trading Loop


Purpose: Continuous monitoring and state management
Logic: Checks levels, manages positions, handles exits
States: 0 (wait), 1 (buy), 2 (sell), -1 (done)

🔧 Utility Functions
placeOrder1()
Purpose: Universal order placement across brokers
Features: Logging, paper trading, broker routing

getHistorical1()
Purpose: Fetch historical data from any broker
Usage: Technical analysis and backtesting

importLibrary()
Purpose: Dynamic broker library import
Logic: Loads only required broker modules

📊 Data Logging & Trade Management


# Real-time trade logging tradesDF = [Link](columns=["Date", "Time", "Symbol", "Direction", "Price", "Qty",
"PaperTrading"]) # Update DataFrame with each trade [Link][len(tradesDF)] = [ddate, dtime, inst, t_type, price,
qty, papertrading] # File-based logging for persistence trade_log = f"{ddate},{dtime},{inst},{t_type},{price},{qty},
{papertrading}\n" with open("level_results.txt", "a") as f: [Link](trade_log)

⚡ Real-time Monitoring
Websocket Integration: Real-time price updates for instant decision making
State Machine: Efficient state management for different trading scenarios
Error Handling: Robust error handling for network and API issues

[Link] 10/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained
Multi-threading: Handles multiple data streams simultaneously

[Link] 11/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained

📚 Learning Outcomes & Best Practices

🎓 Key Learning Points


Level-based Trading: Support and resistance breakout strategies

State Machine Design: Systematic approach to trading logic

Real-time Processing: Handling live market data streams

Risk Management: Stop-loss, targets, and position sizing

Options Integration: Directional options trading

Multi-broker Systems: Creating platform-agnostic solutions

⚡ Best Practices
Level Identification: Use historical data to identify strong levels

Volume Confirmation: Look for volume confirmation on breakouts

False Breakout Management: Quick stop-loss on failed breakouts

Time-based Rules: Avoid trading during low-liquidity periods

Position Sizing: Never risk more than 2% per trade

Paper Trading First: Always test before live deployment

⚠️ Common Pitfalls to Avoid

False Breakouts: Levels can be tested multiple times before breaking

Overtrading: Respect the maximum trade limit per session

Ignoring Time Decay: Options lose value over time

Poor Level Selection: Use significant historical levels

No Exit Plan: Always have stop-loss and target defined

🎯 Success Factors
Choose levels with strong historical significance

Wait for clean breakouts with good volume

Use appropriate position sizing (1-2% risk per trade)

Maintain discipline with stop-losses

Track and analyze all trades for improvement

Understand market context and volatility

🚨 Final Risk Warning


This educational material demonstrates level-based trading concepts but should not be used for actual trading without proper
understanding of risks. Support and resistance levels can fail, leading to significant losses. The code provided is for educational purposes and

[Link] 12/13
8/7/25, 9:18 AM Level-Based Trading Strategy Explained
requires proper risk management, market knowledge, and broker setup before any live usage.

[Link] 13/13

You might also like