Learn Algo Trading with Python | Codes | Youtube Series

Thank you , sir…

1 Like

The sample code is right above in my previous reply. The function, and its call and output. Please check. It is still no working.

Hi @Tradehull_Imran,

Is it possible to increase the market depth?

sir @Tradehull_Imran How we can run python code in cloud , so it can run smoothly even if any internet or any issue

hey @Aijaz_Ahmad have u tried trailling sl with modifying order

Hi @Himansshu_Joshi,

No, haven’t tried yet.

Hello sir, @Tradehull_Imran
How can i do this in macbook.
Pls Share files that can run on mac book also

Hello sir, @Tradehull_Imran
strategy ko back test kane ke liye code kaise likhe
Please help

@Tradehull_Imran I have Mac. Do you support it?

Hi @Tradehull_Imran,

How to connect & live market data feed, can you please share template or code.

@Tradehull_Imran HI, I am getting an error, while running “Dhan_websocket.py”.
Disconnected from WebSocket feed.
WebSocket connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)
Reconnecting Again…

Hi @Tradehull_Imran, please help with the below error.

Codebase Version 2.1
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-02.csv
Got the instrument file
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-904’, ‘error_type’: ‘Rate_Limit’, ‘error_message’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}, ‘data’: {‘errorType’: ‘Rate_Limit’, ‘errorCode’: ‘DH-904’, ‘errorMessage’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}}
Traceback (most recent call last):
File “Q test.py”, line 113, in
chart[‘rsi’] = talib.RSI(chart[‘close’], timeperiod=14)
TypeError: ‘NoneType’ object is not subscriptable

Hi Imran Sir, Good evening, In my message box it’s not showing the </> symbol to send you my code and errors. Please help me sir.

Hi, how can this be understandable by non-coders sir. Is there any way?

i am not getting the question properly. please explain in detail.

About the request structure (dhanhq.co/docs)

Does it support on Mac?

Hi, need to know what all python libraries are required for the installation as I need to perform the same on mac OS.

Hi @kristrades99

The code seems to ran fine at my end, there was no issue, it has enough time.sleep(60).
Do re run the code tomorrow. we need to add sleep between consecutive calls also

import pdb
import time
import datetime
import traceback
import pandas as pd
from pprint import pprint
import talib
# import pandas_ta as pta
import pandas_ta as ta
import warnings,sys

warnings.filterwarnings("ignore")

path = r'C:/Users/krish/OneDrive/Documents/Krishna/2 Areas/Finance/Stock Market/Trading/Trading Courses/Development/AlgoTrading/Dhan/DhanAlgoTrading'
# path = r'../DhanAlgoTrading'
sys.path.insert(0, path)
import credentials as cred
from Dhan_Tradehull_V2 import Tradehull

# ---------------Basic setup for dhan login & Defining Constants------------------------
client_code = cred.CLIENT_ID
token_id = cred.ACCESS_TOKEN
tsl = Tradehull(client_code,token_id)

available_balance = tsl.get_balance()
# leveraged_margin  = available_balance*5
max_trades = 5
per_trade_margin = (available_balance/max_trades/5)
max_loss = -available_balance/100
EXPIRY ='26-12-2024'
LOT_SIZE = 3
VOLUME = 10000
# ---------------------------------------------------------------------------------------

traded = "no"
trade_info = {"options_name":None, "qty":None, "sl":None, "CE_PE":None}

while True:
    live_pnl = tsl.get_live_pnl()
    current_time = datetime.datetime.now().time()
    month = datetime.datetime.now().strftime("%b").upper()
    
    if current_time < datetime.time(9, 30):
        print("Market yet to open", current_time)
        continue
    
    if (current_time > datetime.time(15, 15)) or (live_pnl < max_loss):
        order_details = tsl.cancel_all_orders()
        print("Market is closed!", current_time)
        break
    
    index_chart  = tsl.get_historical_data(tradingsymbol=f'NIFTY {month} FUT', exchange='NFO', timeframe="1")
    time.sleep(60)

    index_ltp    = tsl.get_ltp_data(names = [f'NIFTY {month} FUT'])[f'NIFTY {month} FUT']
    
    if index_chart is None or index_ltp is None:
        print("Data unavailable. Retrying...")
        time.sleep(60)
        continue

	# rsi    ------------------------ apply indicators
    index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)

	# vwap
    index_chart.set_index(pd.DatetimeIndex(index_chart['timestamp']), inplace=True)
    index_chart['vwap'] = ta.vwap(index_chart['high'] , index_chart['low'], index_chart['close'] , index_chart['volume'])

	# Supertrend
    supertrend = ta.supertrend(index_chart['high'], index_chart['low'], index_chart['close'], 10, 2)
    index_chart = pd.concat([index_chart, supertrend], axis=1, join='inner')

	# vwma
    index_chart['pv'] = index_chart['close'] * index_chart['volume']
    index_chart['vwma'] = index_chart['pv'].rolling(20).mean() / index_chart['volume'].rolling(20).mean()

    first_candle   = index_chart.iloc[-3]
    second_candle  = index_chart.iloc[-2]
    running_candle = index_chart.iloc[-1]

    # print(index_chart)
    

	# ---------------------------- BUY ENTRY CONDITIONS ----------------------------
    buy_condition_1 = first_candle['close'] > first_candle['vwap']                # First Candle close is above VWAP
    buy_condition_2 = first_candle['close'] > first_candle['SUPERT_10_2.0']       # First Candle close is above Supertrend 
    buy_condition_3 = first_candle['close'] > first_candle['vwma']                # First Candle close is above VWMA
    buy_condition_4 = first_candle['rsi'] < 80                                    # First candle RSI < 80	
    buy_condition_5 = second_candle['volume'] > VOLUME                             # Second candle Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
    buy_condition_6 = traded == "no"
    buy_condition_7 = index_ltp > first_candle['low']
    print(f"BUY \t {current_time} \t {buy_condition_1} \t {buy_condition_2} \t {buy_condition_3} \t {buy_condition_4} \t {buy_condition_5} \t {buy_condition_6} \t {buy_condition_7} \t first_candle {str(first_candle['timestamp'].time())}")


	# ---------------------------- SELL ENTRY CONDITIONS ----------------------------
    sell_condition_1 = first_candle['close'] < first_candle['vwap']                # First Candle close is below VWAP
    sell_condition_2 = first_candle['close'] < first_candle['SUPERT_10_2.0']       # First Candle close is below Supertrend 
    sell_condition_3 = first_candle['close'] < first_candle['vwma']                # First Candle close is below VWMA
    sell_condition_4 = first_candle['rsi'] > 20                                    # First candle RSI < 80	
    sell_condition_5 = second_candle['volume'] > VOLUME                             # Second candle Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
    sell_condition_6 = traded == "no"
    sell_condition_7 = index_ltp < first_candle['high']
    print(f"SELL \t {current_time} \t {sell_condition_1} \t {sell_condition_2} \t {sell_condition_3} \t {sell_condition_4} \t {sell_condition_5} \t {buy_condition_7} \t {sell_condition_7} \t first_candle {str(first_candle['timestamp'].time())} \n")

    # pdb.set_trace()

    if buy_condition_1 and buy_condition_2 and buy_condition_3 and buy_condition_4 and buy_condition_5 and buy_condition_6 and buy_condition_7:
        print("Buy Signal Formed")  
        ce_name, pe_name, strike   = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry =EXPIRY)
        time.sleep(1)
        total_lots                 = tsl.get_lot_size(ce_name)*LOT_SIZE
        time.sleep(1)

        # call_buy_orderid           = tsl.order_placement(ce_name,'NFO', total_lots, 0, 0, 'MARKET', 'BUY', 'MIS')
        traded                     = "yes"
        trade_info['options_name'] = ce_name
        trade_info['qty']          = total_lots
        time.sleep(1)
        trade_info['buy_price']    = tsl.get_ltp_data(names = [ce_name])[ce_name]   #call_buy_orderid['price']
        trade_info['create_time']  = datetime.datetime.now()
        trade_info['sl']           = first_candle['low']
        trade_info['CE_PE']        = "CE"

    if sell_condition_1 and sell_condition_2 and sell_condition_3 and sell_condition_4 and sell_condition_5 and sell_condition_6 and sell_condition_7:
        print("Sell Signal Formed")
        ce_name, pe_name, strike   = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry =EXPIRY)
        time.sleep(1)
        total_lots                 = tsl.get_lot_size(pe_name)*LOT_SIZE
        time.sleep(1)
        # put_buy_orderid            = tsl.order_placement(pe_name,'NFO', total_lots, 0, 0, 'MARKET', 'BUY', 'MIS')
        traded      secs               = "yes"
        trade_info['options_name'] = pe_name
        trade_info['qty']          = total_lots
        time.sleep(1)
        trade_info['buy_price']    = tsl.get_ltp_data(names = [pe_name])[pe_name]
        trade_info['create_time']  = datetime.datetime.now()
        trade_info['sl']           = first_candle['high']
        trade_info['CE_PE']        = "PE"


	# ---------------------------- check for exit SL/TG-----------------------------
    if traded == "yes":
        long_position  = trade_info['CE_PE'] == "CE"
        short_position = trade_info['CE_PE'] == "PE"
        
        if long_position:
            stop_loss_hit = index_ltp < trade_info['sl']
            target_hit = index_ltp < running_candle['SUPERT_10_2.0']

            if stop_loss_hit or target_hit:
                # call_exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
                if stop_loss_hit:
                    trade_info['exit_reason']   = 'SL Hit'
                else:
                    trade_info['exit_reason']   = 'Target Hit'
                trade_info['sell_price']   = tsl.get_ltp_data(names = [ce_name])[ce_name]
                trade_info['exit_time']  = datetime.datetime.now()
                print("Order Exited", trade_info)
                traded = "no"
                # pdb.set_trace()

        if short_position:
            stop_loss_hit = index_ltp > trade_info['sl']
            target_hit = index_ltp > running_candle['SUPERT_10_2.0']

            if stop_loss_hit or target_hit:
                # put_exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
                if stop_loss_hit:
                    trade_info['exit_reason']   = 'SL Hit'
                else:
                    trade_info['exit_reason']   = 'Target Hit'
                trade_info['sell_price']   = tsl.get_ltp_data(names = [pe_name])[pe_name]
                trade_info['exit_time']  = datetime.datetime.now()
                print("Order Exited", trade_info)
                traded = "no"
                # pdb.set_trace()








in session 2, there is a bat file with name “install libraries.bat”. It has list of all required libraries. I think by changing it as per Mac OS, you can install all required libraries.

1 Like