Learn Algo Trading with Python | Codes | Youtube Series

Thanks,
How to use num_strikes in this new version…?
I was using that as well.

Hi @Ganesh_Surwase ,

Congrats on your Algo :rocket:

Hi @banajit ,

  1. Yes, you can design your own algo by following the YouTube tutorial series and with your consistent dedication and practice.
  2. To design duel options where one can switch between paper trading and live trading, you can make changes in the code and achieve it.

Hi @Qaisar ,

Currently Dhan is not providing INDIA VIX data, tagging @Hardik for the same.

many many thanks for reply @Tradehull_Imran
I am starting to make one …

1 Like

Hi @Kusum_Kapadia ,

Can you share screenshot by running the below in cmd.

where python

how can i achieve the add or remove instruments
without stoping the websocket connection
i am new to programming

Hi @Tradehull_Imran ,

I am facing some issue while running my code

import datetime
import pandas as pd
import streamlit as st
import numpy as np
import hashlib
from streamlit_autorefresh import st_autorefresh
import logging
from Dhan_Tradehull import Tradehull  # Ensure correct import

# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

# Auto-refresh every 5 seconds
st_autorefresh(interval=5000, key="traderefresh")

def hash_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

def authenticate(username, password):
    valid_users = {
        "admin": hash_password("admin123"),
        "user1": hash_password("password1")
    }
    return username in valid_users and valid_users[username] == hash_password(password)

def main():
    st.title("Algorithmic Trading Platform")

    # Initialize session state
    if 'authenticated' not in st.session_state:
        st.session_state.authenticated = False
    if 'broker_logged_in' not in st.session_state:
        st.session_state.broker_logged_in = False
    if 'broker_client' not in st.session_state:
        st.session_state.broker_client = None

    # User Login Section
    if not st.session_state.authenticated:
        st.sidebar.header("User Login")
        username = st.sidebar.text_input("Username")
        password = st.sidebar.text_input("Password", type="password")
        
        if st.sidebar.button("Login"):
            if authenticate(username, password):
                st.session_state.authenticated = True
                st.sidebar.success("User authenticated! Connect to broker below")
            else:
                st.sidebar.error("Invalid credentials")
        return

    # Broker Login Section
    if not st.session_state.broker_logged_in:
        st.sidebar.header("Broker Connection")
        client_code = st.sidebar.text_input("Client Code")
        token_id = st.sidebar.text_input("Token ID", type="password")
        agree_terms = st.sidebar.checkbox("I agree to terms")

        if st.sidebar.button("Connect to Broker"):
            if not all([client_code, token_id, agree_terms]):
                st.sidebar.error("All fields are required")
            else:
                try:
                    # Initialize Tradehull with correct parameters
                    broker_client = Tradehull(
                        ClientCode=client_code,
                        token_id=token_id
                    )
                    st.session_state.broker_client = broker_client
                    st.session_state.broker_logged_in = True
                    st.sidebar.success("Broker connected!")
                except Exception as e:
                    logging.error(f"Broker connection failed: {str(e)}")
                    st.sidebar.error(f"Connection failed: {str(e)}")
        return

    # Main Trading Interface
    st.header("Trading Dashboard")
    broker_client = st.session_state.broker_client

    try:
        # Example usage
        st.subheader("Market Data")
        instrument = st.selectbox("Select Instrument", ["NIFTY", "BANKNIFTY", "SENSEX"])
        
        # Get OHLC data
        logging.info("Fetching OHLC data...")
        ohlc_data = broker_client.get_ohlc_data([instrument])
        st.write(f"{instrument} OHLC Data:", ohlc_data.get(instrument, "No data"))
        
        # Get Expiry list
        logging.info("Fetching expiry list...")
        expiries = broker_client.get_expiry_list(Underlying=instrument, exchange='INDEX')
        st.write("Expiries:", expiries)

        # Get Lot Size
        logging.info("Fetching lot size...")
        lot_size = broker_client.get_lot_size(instrument)
        st.write("Lot Size:", lot_size)

    except Exception as e:
        logging.error(f"Error in trading interface: {str(e)}")
        st.error(f"Error in trading interface: {str(e)}")

if __name__ == "__main__":
    main()

My code is running till the point, I have shown in the following error only. after that my code is not running further.


D:\AdvancedAlgo\MyStrategy>streamlit run 2.py

  You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8501
  Network URL: http://192.168.29.225:8501

Codebase Version 3
2025-02-17 20:28:43,926 - INFO - Dhan.py  started system
2025-02-17 20:28:43,927 - INFO - STARTED THE PROGRAM
-----Logged into Dhan-----
reading existing file all_instrument 2025-02-17.csv
Got the instrument file

Can you please help in this regard? My further code has to be executed after this point. Please help me


Hi Imran
Thank you for your prompt response
So I also have pycharm on my machine which I use to run other python codes. I recently installed everything again based on the instruction given by you in video. but seems like python is doubled? can you please suggest some solution.

Blockquote
atm_strike,option_Chain = tsl.get_option_chain(Underlying=“SBIN”,exchange=“NSE”,expiry=0,num_strikes = 5)
print(atm_strike)
print(option_Chain)

Blockquote
Traceback (most recent call last):
File “c:\Users\mudav\OneDrive\Documents\Log files\tradehull2.py”, line 38, in
atm_strike,option_Chain = tsl.get_option_chain(Underlying=“SBIN”,exchange=“NSE”,expiry=0,num_strikes = 5)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Tradehull.get_option_chain() got an unexpected keyword argument ‘num_strikes’

Blockquote
Traceback (most recent call last):
File “c:\Users\mudav\OneDrive\Documents\Log files\tradehull2.py”, line 38, in
atm_strike,option_Chain = tsl.get_option_chain(Underlying=“NIFTY”,exchange=“INDEX”,expiry=1,num_strikes = 5)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Tradehull.get_option_chain() got an unexpected keyword argument ‘num_strikes’

My code and Error i got on VS Code. Please look into this ,Sir
num_strikes not working in vscode ,sir.

i have tried your code for nifty and as well as stock, but num_strikes is not working in both the cases. And it giving above errors in both cases

@Dhan it would be helpful to take decision if we get VIX data. Kindly enable this feature as well.

Mac os main kese instal kare
please help

@Tradehull_Imran I still see incorrect data for high/low. Not sure what’s wrong.

NIFTY FEB FUT: high=23061.1 low=22933.0
BANKNIFTY FEB FUT: high=49557.0 low=49169.25
FINNIFTY FEB FUT: high=23423.4 low=23222.75
MIDCPNIFTY FEB FUT: high=11257.55 low=11154.0
SENSEX FEB FUT: high=76179.0 low=76062.05
BANKEX FEB FUT: high=55783.0 low=55783.0

@Raju2
You are missing to use reference: ‘from Dhan_Tradehull_V2 import Tradehull’
OR missing initializing it as : tsl = Tradehull(client_code, token_id)
and then use: option_chain = tsl.get_option_chain(Underlying=“NIFTY”, exchange=“INDEX”, expiry=0, num_strikes=5)

Also, as of today, Dhan API is allowing only 1 symbol in a request every 3 seconds otherwise you get an API limit warning and not sure when they could make it work for multiple instruments in single request which many of us are waiting for it.

@K_R_Krishna
i have imported
from Dhan_Tradehull_V2 import Tradehull
but in vs code , num_strikes error i we are getting.
Bcz i think num_strikes option works only in Code Base not in vscode

Hi @Akshay_Bawane ,

We will be updating with num_strikes in further version, as of now do use the below code:

num_strikes = 10
strike_step = 50
CE_symbol_name, PE_symbol_name, atm_strike = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry=0)
oc_df = tsl.get_option_chain(Underlying="NIFTY", exchange="INDEX", expiry=0)
df = oc_df[(oc_df['Strike Price'] >= str(atm_strike - num_strikes * strike_step)) & (oc_df['Strike Price'] <= str(atm_strike + num_strikes * strike_step))].sort_values(by='Strike Price').reset_index(drop=True)

1 Like

Hi @Bhoot_Nath ,

Managing WebSocket can be complex, so we’ve designed our codebase to work with rest api calls, allowing you to add or remove instruments directly with ease.

Do update codebase on your system

  • Open Command Prompt: Press Win, type cmd, and press Enter.
  • Install Dhan-Tradehull: Run pip install Dhan-Tradehull
  • Confirm the installation by running pip show Dhan-Tradehull

refer the below video for updated codebase :

Hi @Kusum_Kapadia ,

Do uninstall all existing versions of Python and proceed with a fresh installation of Python 3.8.

Refer the below video to install:

Hello @Kusum_Kapadia @Tradehull_Imran

You can get India VIX data on Dhan APIs. You can find the same as an index on the Security ID list. Let me know in case you are facing issues with this.

Hi @Raghuveer_K ,

At the moment, Streamlit is not within the scope of discussion.