Learn Algo Trading with Python | Codes | Youtube Series

Hi @rahulcse56 ,

The open source backtesting video will be released by this weekend.

6 Likes

Thanks @Tradehull_Imran ,
but, if possible can we get the strikes dynamic like, ITM, OTM as like this one,

because dynamix strikes will be much helpful and less tiresome.

atm, OC = tsl.get_option_chain(Underlying=“NIFTY”, exchange=“INDEX”, expiry=0, num_strikes=5)

@Tradehull_Imran , I got this error while installing TA-lib, kindly help.

watchlist = [“COALINDIA”]

for stock_name in watchlist:
chart_5 = tsl.get_historical_data(stock_name, “NSE”, “5”)
if chart_5 is not None:
chart_5[“rsi”] = talib.RSI(chart_5[‘close’], timeperiod=14) #rsi
chart_5[‘average_volume’] = chart_5[‘volume’].rolling(window=20).mean() #average volume
chart_5.set_index(pd.DatetimeIndex(chart_5[‘timestamp’]), inplace=True) #vwap
chart_5[‘vwap’] = pta.vwap(chart_5[‘high’],chart_5[‘low’],chart_5[‘close’],chart_5[‘volume’])
indi = ta.supertrend(chart_5[‘high’],chart_5[‘low’],chart_5[‘close’],10,2) #supertrend
chart_5 = pd.concat([chart_5, indi],axis=1, join=‘inner’)

    scanned_candle              = chart_5.iloc[-2]      #           
    breakout_candle             = chart_5.iloc[-1]      #.between_time("09:20","09:25")
    first_candle                = chart_5.between_time("9:15","09:15").iloc[-1]   
            
    sc1 = scanned_candle['rsi'] < 35 and scanned_candle['close'] < scanned_candle['SUPERT_10_2.0'] and scanned_candle['close'] < scanned_candle['vwap'] and scanned_candle['close'] < scanned_candle['open'] 
    sc2 = breakout_candle['rsi'] < scanned_candle['rsi'] and breakout_candle['close'] < scanned_candle['low']  and breakout_candle['open'] > breakout_candle['close']
    sc3 = breakout_candle['open'] > breakout_candle['close']


if sc1 and sc2 and sc3:
    ltp = tsl.get_ltp_data(names=[stock_name])[stock_name]
    print(f"sell this script {stock_name} at {scanned_candle['close']}")

    ce_name, pe_name, strike = tsl.ATM_Strike_Selection(stock_name, Expiry=0)
    ce_ltp                   = tsl.get_ltp_data(names=[ce_name])[ce_name]

    # pdb.set_trace()

This error is solved now, it was mismatch of the wheel file version.

1 Like

@Tradehull_Imran Sir, the tradingsymbol I executed does not match the tradingsymbol present in the get_positions() DataFrame. What is the solution? Please guide me.

Excel file

excel_file = “Nifty1.xlsx”

try:
df = pd.read_excel(excel_file, sheet_name=‘trade_info’, engine=‘openpyxl’)

if df.empty:
    time.sleep(1)
else:
    for index, row in df.iterrows():
        Strike = row['Strike Symbol']
        entry = row['Entry Price']
        target = row['target']
        sl = row['SL Price']
        

        # Get live market data for the current strike
        data = tsl.get_ltp_data(Strike)
        ltp = data.get(Strike, None)
        lot_size = tsl.get_lot_size(Strike)
        
        if ltp and ltp < sl:
            active_positions = tsl.get_positions()
            print(active_positions)
            # If no active positions, directly check holdings
            if active_positions is None or (isinstance(active_positions, pd.DataFrame) and active_positions.empty):
                print(f"[{Strike}] No active positions found.")
            else:
                # Proceed with active position logic
                active_Strike = active_positions[active_positions['tradingSymbol'] == Strike]

                # Check if a SELL order already exists
                if 'positionType' in active_positions.columns:
                    sell_order_exists = not active_Strike[active_Strike['positionType'] == "CLOSE"].empty
                    if sell_order_exists:
                        print(f"[{Strike}] Sell order already exists. Skipping.")
                buy_Strike = active_Strike[active_Strike['positionType'] == "LONG"]
                if not buy_Strike.empty:
                    quantity = buy_Strike.iloc[0].get('buyQty', 1)  # Use 'buyQty'
                    print(f"[{Strike}] Buy position found with quantity: {quantity}. Placing sell order.")

                    orderid = tsl.order_placement(Strike, 'NFO', quantity, 0, 0, 'MARKET', 'SELL', 'MIS')
                else:
                    print(f"[{Strike}] No buy position found. Checking holdings.")

except Exception as e:
print(f"Error: {e}")

@Tradehull_Imran Is there a way to find out GAP UP/DOWN? Thanks

Sir, currently i have made it fast using threads, will seek help if needed any in future

1 Like

@Tradehull_Imran one more, Is there an option to pick the expiry date of the index? I want my algo to trade only on the expiry day :smile:

2 Likes

@Tradehull_Imran Sir,

this solved my issues of fetching NIFTY data… thanks…

1 Like

@Tradehull_Imran sir,

I am using -

data = tsl.get_historical_data(tradingsymbol=ce_strike, exchange=‘NSE’, timeframe=“5”)

to fetch the current expiry atm ce’s 5 min data. but getting error. Pls correct it.

Thanks.

Hi @anandc ,
The code seems to be working fine, can you mention for which ce_strike are you getting error?

@Tradehull_Imran sir,

CE STRIKE= NIFTY 06 FEB 23550 CALL
PE STRIKE= NIFTY 06 FEB 23550 PUT
data = tsl.get_historical_data(tradingsymbol=ce_strike, exchange=‘NSE’, timeframe=“5”)

Error-
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-907’, ‘error_type’: ‘Data_Error’, ‘error_message’: ‘System is unable to fetch data due to incorrect parameters or no data present’}, ‘data’: {‘errorType’: ‘Data_Error’, ‘errorCode’: ‘DH-907’, ‘errorMessage’: ‘System is unable to fetch data due to incorrect parameters or no data present’}}

I tried by removing the “CALL” or “PUT” from the CE_STRIKE variable…? Still unable to fetch the data

Hi @Akshay_Bawane ,

Couldn’t understand your query, do elaborate your questions.

For my understanding, you can dynamically pass the strike names to get the oi as below:

atm, OC = tsl.get_option_chain(Underlying=“NIFTY”, exchange=“INDEX”, expiry=0, num_strikes=5)
ce_quote = tsl.get_quote([atm])
ce_oi = ce_quote[ce_otm]['oi']
1 Like

Hi @Kanha_Meher ,

It appears that the code is attempting to retrieve the tradingsymbol from the positions DataFrame using the strike value. However, due to differences in naming conventions, the match is not successful.

1 Like

Hi @anandc ,

Do change the exchange from “NSE” to “NFO”

data = tsl.get_historical_data(tradingsymbol=ce_strike, exchange='NFO', timeframe='5') 
1 Like

Hi @Rajashekhar_Rangappa ,

Refer the below code:

data = tsl.get_quote(names=['NIFTY']) 
open_price = data['NIFTY']['ohlc']['open']
close_price = data['NIFTY']['ohlc']['close']
gap_up = open_price - close_price

Hi @Rajashekhar_Rangappa ,

refer the below code to get the list of expiries:

expiry_list =  tsl.get_expiry_list("NIFTY", "NSE")

Hi @Abhishek_Pawde ,

We have fixed this issue, do use the upgraded codebase:

https://drive.google.com/file/d/1h8J6VOLrHMAaF1NGP4_vJj2wtkNxfPDw/view
1 Like

@Tradehull_Imran Sir,

Now working perfectly as expected… Thanks a lot sir…

1 Like