Learn Algo Trading with Python | Codes | Youtube Series

thankyou sir, it solved my problem. :blush:

1 Like

HII @Tradehull_Imran Sir Please Help me to solve this problem Why ‘traded’ is showing hear is the problem image and code also

import time
import datetime
from Dhan_Tradehull import Tradehull
import talib
import winsound
import openpyxl
from openpyxl.styles import Font, Alignment

# ------------------------------ DHAN API LOGIN SETUP ------------------------------

client_code  = ""
token_id     = ""
tsl          = Tradehull(client_code, token_id)

watchlist    = ['ICICIBANK']
single_order = {'name': None,'date': None,'entry_time': None,'entry_price': None,'buy_sell': None,'qty': None,'sl': None,'exit_time': None,'exit_price': None,'pnl': None,'remark': None,'traded': None}
orderbook    = {}
reentry      = "yes"  # "yes/no"
completed_orders = []

# Calculate current loss
my_loss      = 0
max_loss     = -150

# Maximum allowed open positions
max_open_positions = 2

# ---------------------------- TELEGRAM ALERT FUNCTION ------------------------------

bot_token    = ""
receiver_chat_id = ""

# ---------------------------- FUNCTION TO GET LIVE DATA ------------------------------


for name in watchlist:
    orderbook[name] = single_order.copy()

# ------------------------------ SOUND FUNCTION ------------------------------

def play_sound():
    winsound.Beep(9500, 500)

#----------------------------------- EXCEL DATA --------------------------------------


def create_and_write_to_excel(file_name, sheet_name, data):
    """
    Creates an Excel file and writes data to it.

    Args:
        file_name (str): The name of the Excel file (e.g., 'output.xlsx').
        sheet_name (str): The name of the sheet in the Excel file.
        data (list of dict): List of dictionaries where keys are column headers and values are row data.
    """
    # Check if the data is empty
    if not data:
        print(f"No data to write for sheet '{sheet_name}'. Skipping Excel file creation.")
        return

    # Create a new workbook
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.title = sheet_name

    # Add headers
    headers = list(data[0].keys())
    for col_num, header in enumerate(headers, 1):
        cell = sheet.cell(row=1, column=col_num, value=header)
        cell.font = Font(bold=True)
        cell.alignment = Alignment(horizontal='center', vertical='center')

    # Add rows
    for row_num, row_data in enumerate(data, start=2):
        for col_num, header in enumerate(headers, start=1):
            sheet.cell(row=row_num, column=col_num, value=row_data[header])

    # Adjust column widths
    for col_num, header in enumerate(headers, start=1):
        column_width = max(len(header), 15)  # Minimum column width
        sheet.column_dimensions[openpyxl.utils.get_column_letter(col_num)].width = column_width

    # Save the file
    wb.save(file_name)
    print(f"Excel file '{file_name}' created and data written successfully.")


# Initialize orderbook for each stock in the watchlist
for name in watchlist:
    orderbook[name] = {
        'single_order': single_order.copy(),
        'completed_orders': []  # Initialize as an empty list
    }

# Process completed orders for each stock
for name in orderbook:
    completed_orders = orderbook[name]['completed_orders']
    
    if completed_orders:  # Only process non-empty lists
        create_and_write_to_excel(file_name='trade_log.xlsx', sheet_name='TradeLog', data=completed_orders)
    else:
        print(f"No completed orders for {name}. Skipping Excel creation.")


# ------------------------------- QTY FUNCTION ------------------------------

def calculate_trade_quantity(balance, risk_per_trade, stock_price):
    risk_amount = balance * risk_per_trade
    quantity = risk_amount // stock_price
    return max(5, int(quantity))

# ------------------------------ MAIN ALGO ------------------------------


while True:
    
    live_pnl = tsl.get_live_pnl()
    current_time = datetime.datetime.now().time()

    if current_time < datetime.time(9, 30):
        print(f"Wait for market to start Chetan", {str(current_time.time())[:8]})
        time.sleep(1)
        continue

    if current_time > datetime.time(14, 45):
        order_details = tsl.cancel_all_orders()
        print(f"Market over Chetan. Closing all trades! Logging data to Excel. {str(current_time.time())[:8]}")
        create_and_write_to_excel("trades.xlsx", "Trade Log", completed_orders)
        break

    if my_loss <= int(max_loss) and tsl.cancel_all_orders == "yes" and tsl.kill_switch == 'ON':
        print("Max loss reached! Cancelling all orders and stopping trading.")
        tsl.cancel_all_orders()
        break

    print("\n started while Loop \n")

    all_ltp = tsl.get_ltp_data(names=watchlist)

    for name in watchlist:

        current_time         = datetime.datetime.now()
        print(f"Scanning     {name} {str(current_time.time())[:8]}")

        try:
            chart_1 = tsl.get_historical_data(tradingsymbol=name.upper(),exchange='NSE',timeframe='5')
            chart_1['upperband'], chart_1['middleband'], chart_1['lowerband'] = talib.BBANDS(chart_1['close'], timeperiod=20, nbdevup=1.5, nbdevdn=1.5, matype=0)

            # Define index for the latest candle
            index = len(chart_1) - 1  # Last index in the DataFrame

            # Reference the latest two candles (previous and current)
            alert_candle = chart_1.iloc[index - 1]  # Second last candle (previous candle)
            letest_candle = chart_1.iloc[index]  # Last candle (current candle)

            # BUY ENTRY CONDITION
            bc1 = alert_candle['close'] < alert_candle['lowerband'] 

            bc6 = orderbook[name]['traded'] is None

            # SELL ENTRY CONDITION
            sc1 = alert_candle['close'] > alert_candle['upperband'] 

            sc6 = orderbook[name]['traded'] is None

        except Exception as e:
            print(e)
            continue

        if bc1 and bc6:
            print("buy ", name, "\t")

            margin_available = tsl.get_balance()
            margin_required = alert_candle['close'] / 5.0  # LEVERAGE AMOUNT

            if margin_available < margin_required:
                print(f"Less margin, not taking order: margin_available is {margin_available} and margin_required is {margin_required} for {name}")
                continue

            # Calculating the quantity to trade
            stock_price = alert_candle['close']  # Use the close price of the alert candle as the stock price
            risk_per_trade = 0.04  # Risk 4%
            trade_quantity = calculate_trade_quantity(balance=margin_available, risk_per_trade=risk_per_trade, stock_price=stock_price)

            orderbook[name]['name'] = name
            orderbook[name]['date'] = str(current_time.date())
            orderbook[name]['entry_time'] = str(current_time.time())[:8]
            orderbook[name]['buy_sell'] = "BUY"
            orderbook[name]['qty'] = trade_quantity

            try:
                entry_orderid = tsl.order_placement(
                    tradingsymbol=name,
                    exchange='NSE',
                    quantity=orderbook[name]['qty'],
                    price=0,
                    trigger_price=0,
                    order_type='MARKET',
                    transaction_type='BUY',
                    trade_type='MIS'
                )
                orderbook[name]['entry_orderid'] = entry_orderid
                orderbook[name]['entry_price'] = tsl.get_executed_price(orderid=orderbook[name]['entry_orderid'])

                # Stop-loss and target calculations
                stop_loss_amount = alert_candle['high'] - alert_candle['low']
                stop_loss_price = orderbook[name]['entry_price'] - stop_loss_amount
                target_profit_price = orderbook[name]['entry_price'] + (4 * stop_loss_amount)

                orderbook[name]['sl'] = round(stop_loss_price, 2)
                orderbook[name]['tg'] = round(target_profit_price, 2)

                sl_orderid = tsl.order_placement(
                    tradingsymbol=name,
                    exchange='NSE',
                    quantity=orderbook[name]['qty'],
                    price=0,
                    trigger_price=orderbook[name]['sl'],
                    order_type='STOPMARKET',
                    transaction_type='SELL',
                    trade_type='MIS'
                )
                orderbook[name]['sl_orderid'] = sl_orderid
                orderbook[name]['traded'] = "yes"


                message = "\n".join(f"{key}: {repr(value)}" for key, value in orderbook[name].items())
                message = f"Entry_done {name} \n\n {message}"

                tsl.send_telegram_alert(message=message, receiver_chat_id=receiver_chat_id, bot_token=bot_token)

                max_open_positions += 1

            except Exception as e:
                print(e)

        if orderbook[name]['traded'] == "yes":
            bought = orderbook[name]['buy_sell'] == "BUY"

            if bought:
                try:
                    ltp = all_ltp[name]
                    sl_hit = tsl.get_order_status(orderid=orderbook[name]['sl_orderid']) == "TRADED"
                    tg_hit = ltp > orderbook[name]['tg']
                except Exception as e:
                    print(e)

                if sl_hit:
                    try:
                        orderbook[name]['exit_time'] = str(current_time.time())[:8]
                        orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=orderbook[name]['sl_orderid'])
                        orderbook[name]['pnl'] = round((orderbook[name]['exit_price'] - orderbook[name]['entry_price']) * orderbook[name]['qty'], 1)
                        orderbook[name]['remark'] = "Bought_SL_hit"

                        # TELEGRAM MESSAGE
                        message = "\n".join(f"{key}: {repr(value)}" for key, value in orderbook[name].items())
                        message = f"SL_HIT {name} \n\n {message}"

                        tsl.send_telegram_alert(message=message, receiver_chat_id=receiver_chat_id, bot_token=bot_token)

                        if reentry == "yes":
                            completed_orders.append(orderbook[name])
                            orderbook[name] = single_order.copy()

                    except Exception as e:
                        print(e)

                if tg_hit:
                    try:
                        tsl.cancel_order(OrderID=orderbook[name]['sl_orderid'])
                        time.sleep(2)
                        square_off_buy_order = tsl.order_placement(
                            tradingsymbol=orderbook[name]['name'],
                            exchange='NSE',
                            quantity=orderbook[name]['qty'],
                            price=0,
                            trigger_price=0,
                            order_type='MARKET',
                            transaction_type='SELL',
                            trade_type='MIS'
                        )

                        orderbook[name]['exit_time'] = str(current_time.time())[:8]
                        orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=square_off_buy_order)
                        orderbook[name]['pnl'] = (orderbook[name]['exit_price'] - orderbook[name]['entry_price']) * orderbook[name]['qty']
                        orderbook[name]['remark'] = "Bought_TG_hit"

                        # TELEGRAM MESSAGE
                        message = "\n".join(f"{key}: {repr(value)}" for key, value in orderbook[name].items())
                        message = f"TG_HIT {name} \n\n {message}"

                        tsl.send_telegram_alert(message=message, receiver_chat_id=receiver_chat_id, bot_token=bot_token)

                        if reentry == "yes":
                            completed_orders.append(orderbook[name])
                            orderbook[name] = single_order.copy()


                        play_sound()

                    except Exception as e:
                        print(e)
                                     

		# SELL ENTRY LOGIC
        elif sc1 and sc6:
            print("sell ", name, "\t")

            margin_available = tsl.get_balance()
            margin_required = alert_candle['close'] / 5.0  # LEVERAGE AMOUNT

            if margin_available < margin_required:
                print(f"Less margin, not taking order: margin_available is {margin_available} and margin_required is {margin_required} for {name}")
                continue

            # Calculating the quantity to trade
            stock_price = alert_candle['close']  # Use the close price of the alert candle as the stock price
            risk_per_trade = 0.04  # Risk 4%
            trade_quantity = calculate_trade_quantity(balance=margin_available, risk_per_trade=risk_per_trade, stock_price=stock_price)

            orderbook[name]['name'] = name
            orderbook[name]['date'] = str(current_time.date())
            orderbook[name]['entry_time'] = str(current_time.time())[:8]
            orderbook[name]['buy_sell'] = "SELL"
            orderbook[name]['qty'] = trade_quantity

            try:
                entry_orderid = tsl.order_placement(
                    tradingsymbol=name,
                    exchange='NSE',
                    quantity=orderbook[name]['qty'],
                    price=0,
                    trigger_price=0,
                    order_type='MARKET',
                    transaction_type='SELL',
                    trade_type='MIS'
                )
                orderbook[name]['entry_orderid'] = entry_orderid
                orderbook[name]['entry_price'] = tsl.get_executed_price(orderid=orderbook[name]['entry_orderid'])

                # Stop-loss and target calculations
                stop_loss_amount = alert_candle['high'] - alert_candle['low']
                stop_loss_price = orderbook[name]['entry_price'] + stop_loss_amount
                target_profit_price = orderbook[name]['entry_price'] - (4 * stop_loss_amount)

                orderbook[name]['sl'] = round(stop_loss_price, 2)
                orderbook[name]['tg'] = round(target_profit_price, 2)

                sl_orderid = tsl.order_placement(
                    tradingsymbol=name,
                    exchange='NSE',
                    quantity=orderbook[name]['qty'],
                    price=0,
                    trigger_price=orderbook[name]['sl'],
                    order_type='STOPMARKET',
                    transaction_type='BUY',
                    trade_type='MIS'
                )
                orderbook[name]['sl_orderid'] = sl_orderid
                orderbook[name]['traded'] = "yes"

                message = "\n".join(f"{key}: {repr(value)}" for key, value in orderbook[name].items())
                message = f"Entry_done {name} \n\n {message}"

                tsl.send_telegram_alert(message=message, receiver_chat_id=receiver_chat_id, bot_token=bot_token)

                max_open_positions += 1

            except Exception as e:
                print(e)

			# Exit Logic for Sell Positions
            if orderbook[name]['traded'] == "yes":
                sold = orderbook[name]['buy_sell'] == "SELL"
    
                if sold:
                    try:
                        ltp = all_ltp[name]
                        sl_hit = tsl.get_order_status(orderid=orderbook[name]['sl_orderid']) == "TRADED"
                        tg_hit = ltp < orderbook[name]['tg']
                    except Exception as e:
                        print(e)
    
                    if sl_hit:
                        try:
                            orderbook[name]['exit_time'] = str(current_time.time())[:8]
                            orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=orderbook[name]['sl_orderid'])
                            orderbook[name]['pnl'] = round((orderbook[name]['entry_price'] - orderbook[name]['exit_price']) * orderbook[name]['qty'], 1)
                            orderbook[name]['remark'] = "Sold_SL_hit"
    
                            message = "\n".join(f"{key}: {repr(value)}" for key, value in orderbook[name].items())
                            message = f"SL_HIT {name} \n\n {message}"
    
                            tsl.send_telegram_alert(message=message, receiver_chat_id=receiver_chat_id, bot_token=bot_token)
    
                            if reentry == "yes":
                                completed_orders.append(orderbook[name])
                                orderbook[name] = single_order.copy()
    
                        except Exception as e:
                            print(e)
    
                    if tg_hit:
                        try:
                            tsl.cancel_order(OrderID=orderbook[name]['sl_orderid'])
                            time.sleep(2)
                            square_off_sell_order = tsl.order_placement(
                                tradingsymbol=orderbook[name]['name'],
                                exchange='NSE',
                                quantity=orderbook[name]['qty'],
                                price=0,
                                trigger_price=0,
                                order_type='MARKET',
                                transaction_type='BUY',
                                trade_type='MIS'
                            )
    
                            orderbook[name]['exit_time'] = str(current_time.time())[:8]
                            orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=square_off_sell_order)
                            orderbook[name]['pnl'] = (orderbook[name]['entry_price'] - orderbook[name]['exit_price']) * orderbook[name]['qty']
                            orderbook[name]['remark'] = "Sold_TG_hit"

    
                            message = "\n".join(f"{key}: {repr(value)}" for key, value in orderbook[name].items())
                            message = f"TG_HIT {name} \n\n {message}"
    
                            tsl.send_telegram_alert(message=message, receiver_chat_id=receiver_chat_id, bot_token=bot_token)
    
                            if reentry == "yes":
                                completed_orders.append(orderbook[name])
                                orderbook[name] = single_order.copy()
    
                            play_sound()
    
                        except Exception as e:
                            print(e)
                            

Also Please @Tradehull_Imran Sir Do Check The Code Is It Completely Correct Or Not

Subject: Request for Customizable Backtesting Code

Dear @Tradehull_Imran Sir,

I truly appreciate your efforts in developing an open-source strategy algo for all of us. However, I feel my specific strategy might not be included in it.

Therefore, I have a humble request: could you kindly share the customizable backtesting code you’re using to analyze strategies through Excel? I’d like to use it to analyze my own strategies in a similar manner.

This is an honest and heartfelt request, and I would be immensely grateful if you could share it with me.

Thank you for your time and support!

Best regards,
Chetan More

Google drive is not opening

while watching Video no 3 of this series when I deleted information from the “Websocket.xlsx” excel its not getting populated automatically…can anyone help on this?


i have subscribed to dhan data api, yet i am unable to login. can someone explain please

Hi, @Tradehull_Imran I am following the session 3 video. I have successfully fetched my balance from Dhan. now I am having an issue with historical LTP I am getting an error… and one more question where to paste Trading api and Data api. In code base or in websocket

@Tradehull_Imran Sir,

I have made a algo, in which is am scanning between 30 stock’s watchlist and then decciding based on some logics to buy or sell in equity on 3 minute timeframe, but issue is this till the time i am done fetching all the stocks last finalized data it is already we have 2 second sleep in getting intraday data, which itself will take 60 seconds to fetch data of 30 stocks and after that 30 second it takes to process and calculate certain things on the same. by then 1:30 minutes are passed and based on that when i trigger my buy sell order’s it is already late by 90 seconds, how to solve this type of issues, please help

@Tradehull_Imran
It is now functioning properly on the web server.

All credit goes to you and the Dhan community.
For the past year and a half, I’ve been trying to automate strategies on platforms like Tradetron, Quantman, Algotest,… but I haven’t achieved the results I expected. Unfortunately, there’s no one who teaches us from the basics to advanced levels for free and helps us solve our problems. I just want to say thank you from the bottom of my heart for all your support.

2 Likes

Guys, Does any one knows a source to download OHLCV data for a stock for 1 to 2 years? if yes pls help, it is needed to backtest my strategies pls.

@Kanha_Meher What do you mean by web server? are you able to run the scripts on cloud? If so, can you explain how did you do it. please?

hi @Tradehull_Imran 
i got this error rsi value None
import pdb
import time
import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as pta
import pandas_ta as ta
import warnings

warnings.filterwarnings("ignore")


# --------------- For Dhan Login --------------

client_code = ""
token_id = ""
tsl = Tradehull(client_code,token_id)

pdb.set_trace()

index_chart = tsl.get_historical_data(tradingsymbol='GOLDM FEB FUT',exchange='MCX',timeframe="60")

index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)
C:\Users\abhay\OneDrive\Desktop\Dhan Python\2 Candle Theory\2. 2 Candle Theory Algo>py commodity.py
Codebase Version 2.3 : Solved - ATM issues
-----Logged into Dhan-----
reading existing file all_instrument 2025-01-13.csv
Got the instrument file
Error processing GMRINFRA: No expiry date found for GMRINFRA

C:\Users\abhay\OneDrive\Desktop\Dhan Python\2 Candle Theory\2. 2 Candle Theory Algo>py commodity.py
Codebase Version 2.3 : Solved - ATM issues
-----Logged into Dhan-----
reading existing file all_instrument 2025-01-13.csv
Got the instrument file
Error processing GMRINFRA: No expiry date found for GMRINFRA
[0] > c:\users\abhay\onedrive\desktop\dhan python\2 candle theory\2. 2 candle theory algo\commodity.py(24)<module>()
-> index_chart = tsl.get_historical_data(tradingsymbol='GOLDM FEB FUT',exchange='MCX',timeframe="60")
(Pdb++) index_chart = tsl.get_historical_data(tradingsymbol='GOLDM FEB FUT',exchange='MCX',timeframe="60")
(Pdb++)  index_chart
       open     high  ...  volume                 timestamp
0   77849.0  77950.0  ...  1103.0 2025-01-09 09:00:00+05:30
6   77939.0  77976.0  ...   451.0 2025-01-09 15:00:00+05:30
7   77943.0  78069.0  ...   859.0 2025-01-09 16:00:00+05:30
8   78052.0  78125.0  ...  1437.0 2025-01-09 17:00:00+05:30
9   78110.0  78185.0  ...  1472.0 2025-01-09 18:00:00+05:30
10  78150.0  78218.0  ...  2121.0 2025-01-09 19:00:00+05:30
11  78070.0  78199.0  ...  1222.0 2025-01-09 20:00:00+05:30
12  78103.0  78170.0  ...   929.0 2025-01-09 21:00:00+05:30
13  78067.0  78096.0  ...   998.0 2025-01-09 22:00:00+05:30
14  77980.0  78140.0  ...   959.0 2025-01-09 23:00:00+05:30
15  78389.0  78389.0  ...  1073.0 2025-01-10 09:00:00+05:30
16  78198.0  78270.0  ...   589.0 2025-01-10 10:00:00+05:30
17  78266.0  78314.0  ...   694.0 2025-01-10 11:00:00+05:30
18  78303.0  78348.0  ...   863.0 2025-01-10 12:00:00+05:30
19  78299.0  78420.0  ...  1169.0 2025-01-10 13:00:00+05:30
20  78397.0  78447.0  ...  1006.0 2025-01-10 14:00:00+05:30
21  78430.0  78467.0  ...  1064.0 2025-01-10 15:00:00+05:30
22  78415.0  78468.0  ...  1200.0 2025-01-10 16:00:00+05:30
23  78424.0  78445.0  ...  1466.0 2025-01-10 17:00:00+05:30
24  78301.0  78370.0  ...  1534.0 2025-01-10 18:00:00+05:30
25  78176.0  78673.0  ...  6890.0 2025-01-10 19:00:00+05:30
26  78638.0  78728.0  ...  3528.0 2025-01-10 20:00:00+05:30
27  78609.0  78697.0  ...  1984.0 2025-01-10 21:00:00+05:30
28  78421.0  78587.0  ...   835.0 2025-01-10 22:00:00+05:30
29  78494.0  78547.0  ...  1177.0 2025-01-10 23:00:00+05:30
30  78203.0  78624.0  ...  1607.0 2025-01-13 09:00:00+05:30
31  78580.0  78580.0  ...    81.0 2025-01-13 10:00:00+05:30

[32 rows x 6 columns]
(Pdb++) index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)
(Pdb++) index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)
(Pdb++) index_chart
       open     high      low  ...  volume                 timestamp   rsi
0   77849.0  77950.0  77807.0  ...  1103.0 2025-01-09 09:00:00+05:30  None
1   77816.0  77933.0  77765.0  ...   722.0 2025-01-09 10:00:00+05:30  None
2   77900.0  77906.0  77821.0  ...   384.0 2025-01-09 11:00:00+05:30  None
3   77865.0  77972.0  77850.0  ...   662.0 2025-01-09 12:00:00+05:30  None
4   77927.0  77976.0  77855.0  ...   494.0 2025-01-09 13:00:00+05:30  None
5   77969.0  77998.0  77890.0  ...   581.0 2025-01-09 14:00:00+05:30  None
6   77939.0  77976.0  77920.0  ...   451.0 2025-01-09 15:00:00+05:30  None
7   77943.0  78069.0  77918.0  ...   859.0 2025-01-09 16:00:00+05:30  None
8   78052.0  78125.0  77961.0  ...  1437.0 2025-01-09 17:00:00+05:30  None
9   78110.0  78185.0  78035.0  ...  1472.0 2025-01-09 18:00:00+05:30  None
10  78150.0  78218.0  78005.0  ...  2121.0 2025-01-09 19:00:00+05:30  None
11  78070.0  78199.0  78070.0  ...  1222.0 2025-01-09 20:00:00+05:30  None
12  78103.0  78170.0  78032.0  ...   929.0 2025-01-09 21:00:00+05:30  None
13  78067.0  78096.0  77946.0  ...   998.0 2025-01-09 22:00:00+05:30  None
14  77980.0  78140.0  77960.0  ...   959.0 2025-01-09 23:00:00+05:30  None
15  78389.0  78389.0  78170.0  ...  1073.0 2025-01-10 09:00:00+05:30  None
16  78198.0  78270.0  78175.0  ...   589.0 2025-01-10 10:00:00+05:30  No17  78266.0  78314.0  78257.0  ...   694.0 2025-01-10 11:00:00+05:30  None
18  78303.0  78348.0  78232.0  ...   863.0 2025-01-10 12:00:00+05:30  None
19  78299.0  78420.0  78224.0  ...  1169.0 2025-01-10 13:00:00+05:30  None
20  78397.0  78447.0  78357.0  ...  1006.0 2025-01-10 14:00:00+05:30  None
21  78430.0  78467.0  78351.0  ...  1064.0 2025-01-10 15:00:00+05:30  None
22  78415.0  78468.0  78391.0  ...  1200.0 2025-01-10 16:00:00+05:30  None
23  78424.0  78445.0  78275.0  ...  1466.0 2025-01-10 17:00:00+05:30  None
24  78301.0  78370.0  78230.0  ...  1534.0 2025-01-10 18:00:00+05:30  None
25  78176.0  78673.0  78018.0  ...  6890.0 2025-01-10 19:00:00+05:30  None
26  78638.0  78728.0  78380.0  ...  3528.0 2025-01-10 20:00:00+05:30  None
27  78609.0  78697.0  78374.0  ...  1984.0 2025-01-10 21:00:00+05:30  None
28  78421.0  78587.0  78415.0  ...   835.0 2025-01-10 22:00:00+05:30  None
29  78494.0  78547.0  78320.0  ...  1177.0 2025-01-10 23:00:00+05:30  None
30  78203.0  78624.0  78203.0  ...  1607.0 2025-01-13 09:00:00+05:30  None
31  78580.0  78580.0  78540.0  ...    81.0 2025-01-13 10:00:00+05:30  None

[32 rows x 7 columns]
(Pdb++)

@Kanha_Meher

did you deploy your script on cloud AWS or Google ?
If its up and running can you help us in this regard.

Thanks

Hi @CHETAN_99

The issue in in below line

bc6 = orderbook[name]['traded'] is None

Also in below link the code reference shared was a tested one,

you may run the code directly… just create a excel called Live Trade Data… and make two sheets in it named Live_Trading and completed_orders.

Also try to implement only buy side and then sell side…

we dont have to make any chnages … and the below addition to the orderbook has created issues



Explain
#----------------------------------- EXCEL DATA --------------------------------------


def create_and_write_to_excel(file_name, sheet_name, data):
    """
    Creates an Excel file and writes data to it.

    Args:
        file_name (str): The name of the Excel file (e.g., 'output.xlsx').
        sheet_name (str): The name of the sheet in the Excel file.
        data (list of dict): List of dictionaries where keys are column headers and values are row data.
    """
    # Check if the data is empty
    if not data:
        print(f"No data to write for sheet '{sheet_name}'. Skipping Excel file creation.")
        return

    # Create a new workbook
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.title = sheet_name

    # Add headers
    headers = list(data[0].keys())
    for col_num, header in enumerate(headers, 1):
        cell = sheet.cell(row=1, column=col_num, value=header)
        cell.font = Font(bold=True)
        cell.alignment = Alignment(horizontal='center', vertical='center')

    # Add rows
    for row_num, row_data in enumerate(data, start=2):
        for col_num, header in enumerate(headers, start=1):
            sheet.cell(row=row_num, column=col_num, value=row_data[header])

    # Adjust column widths
    for col_num, header in enumerate(headers, start=1):
        column_width = max(len(header), 15)  # Minimum column width
        sheet.column_dimensions[openpyxl.utils.get_column_letter(col_num)].width = column_width

    # Save the file
    wb.save(file_name)
    print(f"Excel file '{file_name}' created and data written successfully.")


# Initialize orderbook for each stock in the watchlist
for name in watchlist:
    orderbook[name] = {
        'single_order': single_order.copy(),
        'completed_orders': []  # Initialize as an empty list
    }

# Process completed orders for each stock
for name in orderbook:
    completed_orders = orderbook[name]['completed_orders']
    
    if completed_orders:  # Only process non-empty lists
        create_and_write_to_excel(file_name='trade_log.xlsx', sheet_name='TradeLog', data=completed_orders)
    else:
        print(f"No completed orders for {name}. Skipping Excel creation.")

Hi @Tradehull_Imran ,
Can you please help me with the code.
Trying to implement 2 candle theory Along with trend analysis dynamically ( Multiple symbols). But getting an error. I am attaching the file, can you please check and help me out with where I need to rectify it? https://drive.google.com/file/d/19IkAYWY2ioVGa0LmCXHwZv0DXsN9768b/view?usp=drive_link

Yes I am also facing the same issue of Rate Limits in getting intraday data for 1 script at a time. if there could be a solution it will be very helpful. if we can fetch OHLCV data of multiple stocks in single API Call.

Hi @CHETAN_99

The codes and results which are created during Backtesting will be open source, so yes you would be able to customize the code based on your strategy.
Also if you have any question regarding implementation of the code on your strategy you can definitely put the question here.

so in essence you will be able to backtest your own strategy using the same framework we will use in Open Source Backtesting.

1 Like

Hi @Kanha_Meher
we don’t need to apply point no 2.

do check below steps

Update Certificates
Press Win + S to open the search bar.
Type PowerShell.
Right-click on Windows PowerShell from the search results.
Select Run as administrator.
If prompted by User Account Control (UAC), click Yes.

Now run following two commands one by one:

certutil -generateSSTFromWU roots.sst
certutil -addstore -f root roots.sst

Also let me know if it works after that

1 Like

Hi @krish9

Do check solution link : Learn Algo Trading with Python | Codes | Youtube Series - #952 by Tradehull_Imran

Hi @Abhishek_Pawde
Mostly there is no print statement in the code I think.

can you share code as well