Learn Algo Trading with Python | Codes | Youtube Series

Sir, if possible, please create an ascending chart that follows the spot chart according to the Greeks. In my opinion, the spot chart is primary, and options are only followers. OTM options are speculative, while ATM options are the best followers of the spot, followed by ITM options.

For example, Nifty’s daily movement generally ranges from 100 to 150 points upward and -50 to 50 points downward (on 8 out of 10 days).

If we can create an ascending option selection table aligned with the spot chart, it would help achieve maximum profit potential. This would provide a direct suggestion to the user, indicating which option to buy with the highest probability of success.

Hi @Tradehull_Imran,

How to fetch the last day intraday 2 min data? what is the syntex?
please help

Rahul

kindly add function for… “trailing stop loss”

import pdb
from Dhan_Tradehull import Tradehull
import pandas as pd
import talib

# Trading API client setup
client_code = "********"
token_id = "token_id_used"
tsl = Tradehull(client_code, token_id)

# Intraday strategy parameters
available_balance = tsl.get_balance()
leveraged_margin = available_balance * 5
max_trades = 3
per_trade_margin = leveraged_margin / max_trades

# Watchlist
watchlist = [
    'MOTHERSON', 'OFSS', 'MANAPPURAM', 'BSOFT', 'CHAMBLFERT', 'DIXON', 'NATIONALUM',
    'DLF', 'IDEA', 'ADANIPORTS', 'SAIL', 'HINDCOPPER', 'INDIGO', 'RECLTD', 'PNB',
    'HINDUNILVR', 'TATAPOWER', 'BPCL', 'HCLTECH', 'WIPRO'
]

traded_watchlist = []

# Main loop
while True:
    for stock_name in watchlist:
        print(stock_name)
        
        # Fetch intraday data
        chart = tsl.get_intraday_data(stock_name, 'NSE', 1)
        if chart is None or chart.empty:
            print(f"No data retrieved for {stock_name}. Skipping...")
            continue
        
        # Calculate RSI
        try:
            chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
        except TypeError:
            print(f"Data is missing for {stock_name}. Skipping...")
            continue

        # Define candles for analysis
        bc = chart.iloc[-2]  # Breakout candle
        ic = chart.iloc[-3]  # Inside candle
        ba_c = chart.iloc[-4]  # Base candle

        # Determine trend and conditions
        uptrend = bc['rsi'] > 50
        downtrend = bc['rsi'] < 49
        inside_candle_formed = (ba_c['high'] > ic['high']) and (ba_c['low'] < ic['low'])
        upper_side_breakout = bc['high'] > ba_c['high']
        down_side_breakout = bc['low'] < ba_c['low']
        
        no_repeat_order = stock_name not in traded_watchlist
        max_order_limit = len(traded_watchlist) <= max_trades
        
        # Execute buy order
        if uptrend and inside_candle_formed and upper_side_breakout and no_repeat_order and max_order_limit:
            print(stock_name, "is in uptrend. Buy this script.")
            qty = int(per_trade_margin / bc['close'])
            buy_entry_orderid = tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 0, 'MARKET', 'BUY', 'MIS')
            traded_watchlist.append(stock_name)
        
        # Execute sell order
        elif downtrend and inside_candle_formed and down_side_breakout and no_repeat_order and max_order_limit:
            print(stock_name, "is in downtrend. Sell this script.")
            qty = int(per_trade_margin / bc['close'])
            sell_entry_orderid = tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 0, 'MARKET', 'SELL', 'MIS')
            traded_watchlist.append(stock_name)

for my code above i was not able to get any buy/sell signal for one whole hour. Is there something wrong with my code/process. Can you please share the complete code you have explained in the session 6

C:\Users\amnid\Downloads\5. Session5- Python Part 2\5. Session5- Python Part 2\Ltp Based Strike Selection>py “Dhan_codebase usage.py”
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-01.csv
Got the instrument file
MOTHERSON
OFSS
MANAPPURAM
BSOFT
CHAMBLFERT
DIXON
NATIONALUM
DLF
IDEA
ADANIPORTS
SAIL
HINDCOPPER
INDIGO
RECLTD
PNB
HINDUNILVR
TATAPOWER
BPCL
HCLTECH
WIPRO
MOTHERSON
OFSS
MANAPPURAM
BSOFT

Please try to run it in market hours and check is it same showing same result or not ?

import pdb
from Dhan_Tradehull import Tradehull
import pandas as pd
import talib

Trading API client setup

client_code = “********”
token_id = “token_id_used”
tsl = Tradehull(client_code, token_id)

Intraday strategy parameters

available_balance = tsl.get_balance()
leveraged_margin = available_balance * 5
max_trades = 3
per_trade_margin = leveraged_margin / max_trades

Watchlist

watchlist = [
‘MOTHERSON’, ‘OFSS’, ‘MANAPPURAM’, ‘BSOFT’, ‘CHAMBLFERT’, ‘DIXON’, ‘NATIONALUM’,
‘DLF’, ‘IDEA’, ‘ADANIPORTS’, ‘SAIL’, ‘HINDCOPPER’, ‘INDIGO’, ‘RECLTD’, ‘PNB’,
‘HINDUNILVR’, ‘TATAPOWER’, ‘BPCL’, ‘HCLTECH’, ‘WIPRO’
]

traded_watchlist =

Main loop

while True:
for stock_name in watchlist:
print(f"Processing {stock_name}…")

    # Fetch intraday data
    chart = tsl.get_intraday_data(stock_name, 'NSE', 1)
    if chart is None or chart.empty:
        print(f"No data retrieved for {stock_name}. Skipping...")
        continue
    
    # Calculate RSI
    try:
        chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
    except TypeError:
        print(f"Data is missing or incorrect for {stock_name}. Skipping...")
        continue
    
    # Ensure sufficient data for analysis
    if len(chart) < 4:
        print(f"Not enough data for {stock_name}. Skipping...")
        continue
    
    # Define candles for analysis
    bc = chart.iloc[-2]  # Breakout candle
    ic = chart.iloc[-3]  # Inside candle
    ba_c = chart.iloc[-4]  # Base candle

    # Determine trend and conditions
    uptrend = bc['rsi'] > 50
    downtrend = bc['rsi'] < 49
    inside_candle_formed = (ba_c['high'] > ic['high']) and (ba_c['low'] < ic['low'])
    upper_side_breakout = bc['high'] > ba_c['high']
    down_side_breakout = bc['low'] < ba_c['low']
    
    # Print values for debugging
    print(f"{stock_name} - RSI: {bc['rsi']}, uptrend: {uptrend}, downtrend: {downtrend}")
    print(f"Inside candle formed: {inside_candle_formed}, Upper breakout: {upper_side_breakout}")
    
    no_repeat_order = stock_name not in traded_watchlist
    max_order_limit = len(traded_watchlist) < max_trades  # Changed <= to < for limit enforcement

    # Execute buy order
    if uptrend and inside_candle_formed and upper_side_breakout and no_repeat_order and max_order_limit:
        print(f"{stock_name} is in uptrend. Attempting to place a buy order.")
        qty = int(per_trade_margin / bc['close'])
        try:
            buy_entry_orderid = tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 0, 'MARKET', 'BUY', 'MIS')
            traded_watchlist.append(stock_name)
            print(f"Buy order placed for {stock_name}, order ID: {buy_entry_orderid}")
        except Exception as e:
            print(f"Error placing buy order for {stock_name}: {e}")
    
    # Execute sell order
    elif downtrend and inside_candle_formed and down_side_breakout and no_repeat_order and max_order_limit:
        print(f"{stock_name} is in downtrend. Attempting to place a sell order.")
        qty = int(per_trade_margin / bc['close'])
        try:
            sell_entry_orderid = tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 0, 'MARKET', 'SELL', 'MIS')
            traded_watchlist.append(stock_name)
            print(f"Sell order placed for {stock_name}, order ID: {sell_entry_orderid}")

use this code ,make sure above stock price updated in your webshockt list.

Hello,
Request you to provide these files for MAC OS as well… and guide what different needs to be done…

Thanks

GETTING ERROR

Still problem .
market is live but still error come

here is my all code
import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd

client_code = “-----------------”
token_id = “-----------------”
tsl = Tradehull(client_code,token_id)

available_balance = tsl.get_balance()
max_risk_for_the_day = (available_balance*1)/100-1
print(“available_balance”, available_balance)

ltp1 = tsl.get_ltp(‘ONGC’)

previous_hist_data = tsl.get_historical_data(‘ONGC’,‘NSE’,12)
intraday_hist_data = tsl.get_intraday_data(‘ONGC’,‘NSE’,5)

pdb.set_trace()

Please do consider current or next expiry
not previous expiry :slightly_smiling_face:

Please release 8th video of this series. We are eagerly waiting for it :slightly_smiling_face:

1 Like

@Tradehull_Imran Sir thanks for v2 will be eagerly waiting …right now i cant figure out how to get a particular option chain data at different time frame as i am able yo get ltp …do i have to average the ltp data over 5 min to get 5 min time frame data or somthing else , also cant figure out how to code trailing stoploss.

“Dhan waiting for everyone’s Data API subscriptions to expire, so that people will have to buy subscriptions again, which will bring profit to the Dhan. That’s why they aren’t releasing the video.”

@Tradehull_Imran
I observed this in today’s live market and I am keep on getting this error for every minute. Posting the same error message captured today. If you want to check my code, I will upload to google drive and share it with you along with recorded video.

I am also facing issue while getting available balance and getting intraday data for OTM strikes, please check this also and help me to solve these issues.

@Tradehull_Imran
Hi, Sharing the code where I am getting available balance and getting intraday data for OTM strikes error. Please check and help me to resolve it.

Hi @Kuldeep_Khaladkar
Ascending chat as in, revere strike prices on option chain?

Hi @rahulcse56
This issue is fixed and will be released this week.

Added+

1 Like

Hi @Sunitha_Manjunath
Try below code,
I think one of the conditions is continuously False for the complete 1 hour.
Find that condition and Fix it

import pdb
from Dhan_Tradehull import Tradehull
import pandas as pd
import talib

# Trading API client setup
client_code = "********"
token_id = "token_id_used"
tsl = Tradehull(client_code, token_id)

# Intraday strategy parameters
available_balance = tsl.get_balance()
leveraged_margin = available_balance * 5
max_trades = 3
per_trade_margin = leveraged_margin / max_trades

# Watchlist
watchlist = [
    'MOTHERSON', 'OFSS', 'MANAPPURAM', 'BSOFT', 'CHAMBLFERT', 'DIXON', 'NATIONALUM',
    'DLF', 'IDEA', 'ADANIPORTS', 'SAIL', 'HINDCOPPER', 'INDIGO', 'RECLTD', 'PNB',
    'HINDUNILVR', 'TATAPOWER', 'BPCL', 'HCLTECH', 'WIPRO'
]

traded_watchlist = []

# Main loop
while True:
    for stock_name in watchlist:
        print(stock_name)
        
        # Fetch intraday data
        chart = tsl.get_intraday_data(stock_name, 'NSE', 1)
        if chart is None or chart.empty:
            print(f"No data retrieved for {stock_name}. Skipping...")
            continue
        
        # Calculate RSI
        try:
            chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
        except TypeError:
            print(f"Data is missing for {stock_name}. Skipping...")
            continue

        # Define candles for analysis
        bc = chart.iloc[-2]  # Breakout candle
        ic = chart.iloc[-3]  # Inside candle
        ba_c = chart.iloc[-4]  # Base candle


        # Determine trend and conditions
        uptrend = bc['rsi'] > 50
        downtrend = bc['rsi'] < 49
        inside_candle_formed = (ba_c['high'] > ic['high']) and (ba_c['low'] < ic['low'])
        upper_side_breakout = bc['high'] > ba_c['high']
        down_side_breakout = bc['low'] < ba_c['low']
        
        no_repeat_order = stock_name not in traded_watchlist
        max_order_limit = len(traded_watchlist) <= max_trades


        # check which condition is getting continiuos False, the one that is False should be updated 
        # also increase scripts in watchlist
        print(uptrend , inside_c,le_formed , upper_side_breakout , no_repeat_order , max_order_limit)

        
        # Execute buy order
        if uptrend and inside_candle_formed and upper_side_breakout and no_repeat_order and max_order_limit:
            print(stock_name, "is in uptrend. Buy this script.")
            qty = int(per_trade_margin / bc['close'])
            buy_entry_orderid = tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 0, 'MARKET', 'BUY', 'MIS')
            traded_watchlist.append(stock_name)
        
        # Execute sell order
        elif downtrend and inside_candle_formed and down_side_breakout and no_repeat_order and max_order_limit:
            print(stock_name, "is in downtrend. Sell this script.")
            qty = int(per_trade_margin / bc['close'])
            sell_entry_orderid = tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 0, 'MARKET', 'SELL', 'MIS')
            traded_watchlist.append(stock_name)

Hi @Vishnu.sriv08
Solution for this issue is in progress…

1 Like