I am trying to work with NSE data. Data I have taken from Angel One broker. I am getting the above error. I am sharing my code. Please check.
pip install pycryptodome
pip install pyotp
pip install logzero
pip install websocket-client
from SmartApi import SmartConnect #or from SmartApi.smartConnect import SmartConnect
import pyotp
from logzero import logger
api_key = 'MK2nfbKA'
username = 'VINJ1173'
pwd = '1290'
smartApi = SmartConnect(api_key)
try:
token = "VPAAPUM2OL25SKMGGSEZYVS4PA"
totp = pyotp.TOTP(token).now()
except Exception as e:
logger.error("Invalid Token: The provided token is not valid.")
raise e
correlation_id = "abcde"
data = smartApi.generateSession(username, pwd, totp)
bearer=''
if data['status'] == False:
logger.error(data)
else:
# login api call
# logger.info(f"You Credentials: {data}")
authToken = data['data']['jwtToken']
bearer=data['data']['jwtToken']
refreshToken = data['data']['refreshToken']
# fetch the feedtoken
feedToken = smartApi.getfeedToken()
# fetch User Profile
res = smartApi.getProfile(refreshToken)
smartApi.generateToken(refreshToken)
res=res['data']['exchanges']
import http.client
conn = http.client.HTTPSConnection("apiconnect.angelone.in")
payload = """{"exchange":"NSE","symboltoken":"99926000","interval":"ONE_DAY","fromdate":"2022-11-09 09:31","todate":"2024-11-08 03:15"}"""
headers = {
'X-PrivateKey': 'MK2nfbKA',
'Accept': 'application/json',
'X-SourceID': 'WEB',
'X-ClientLocalIP': 'CLIENT_LOCAL_IP',
'X-ClientPublicIP': 'CLIENT_PUBLIC_IP',
'X-MACAddress': 'MAC_ADDRESS',
'X-UserType': 'USER',
'Authorization': f"{bearer}",
'Accept': 'application/json',
'X-SourceID': 'WEB',
'Content-Type': 'application/json'
}
conn.request("POST", "/rest/secure/angelbroking/historical/v1/getCandleData", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
# For data manipulation
import pandas as pd
import numpy as np
from scipy.signal import argrelextrema
import warnings
warnings.filterwarnings('ignore')
import json as j
work_data = j.loads(data.decode("utf-8"))
df = pd.DataFrame(work_data['data'],columns=['Time','Open','High','Low','Close','Volume'])
df['Time'] = pd.to_datetime(df['Time']).apply(lambda x: x.date())
print(df)
import sys
sys.path.append('..')
# Fetch dataframes of minima and maxima values
minima_prices, maxima_prices = get_min_max(df, 3)
# Store values of both minima and maxima points in a sequential order
min_max = pd.concat([minima_prices, maxima_prices]).sort_index()
# For data manipulation
import datetime
import numpy as np
import pandas as pd
from scipy.signal import argrelextrema
# For data visualisation
import matplotlib.pyplot as plt
plt.style.use('seaborn-darkgrid')
def get_min_max(data, argrel_window):
# Use the argrelextrema to compute the local minima and maxima points
local_min = argrelextrema(
data.iloc[:-argrel_window]['Low'].values, np.less, order=argrel_window)[0]
local_max = argrelextrema(
data.iloc[:-argrel_window]['High'].values, np.greater, order=argrel_window)[0]
# Store the minima and maxima values in a dataframe
minima = data.iloc[local_min].Low
maxima = data.iloc[local_max].High
# Return dataframes containing minima and maxima values
return minima, maxima
def get_support(price_data, argrel_window=15):
assert price_data.shape[0] > argrel_window, "Length of data is less then argel_window"
support_list = argrelextrema(
price_data.iloc[:-argrel_window]['Low'].values, np.less, order=argrel_window)[0]
price_data['support'] = price_data.iloc[support_list, 2]
ltp = price_data.Close.iloc[-1]
price_data['support'] = np.where(price_data['support'] < ltp, price_data['support'], np.nan)
try:
return price_data.loc[price_data.support.dropna().index.max(), 'support']
except:
return np.nan
def get_resistance(price_data, argrel_window=15):
resistance_list = argrelextrema(
price_data.iloc[:-argrel_window]['High'].values, np.greater, order=argrel_window)[0]
price_data['resistance'] = price_data.iloc[resistance_list, 1]
ltp = price_data.Close.iloc[-1]
price_data['resistance'] = np.where(price_data['resistance'] > ltp, price_data['resistance'], np.nan)
try:
return price_data.loc[price_data.resistance.dropna().index.max(), 'resistance']
except:
return np.nan
def backtester(data):
# ------------------------------- Initial Settings -------------------------------------
# Create dataframes for round trips, storing trades, and mtm
round_trips_details = pd.DataFrame()
trades = pd.DataFrame()
# Initialise current position, number of trades,cumulative pnl, stop-loss to 0 and take-profit to 100000
current_position = 0
trade_num = 0
cum_pnl = 0
sl = 0
tp = 100000
# Set exit flag to False
exit_flag = False
entry_flag = False
# ------------------------------- Backtest over historical data -------------------------------------
for i in data.index:
# ------------------- Positions Check ----------------------------
# No positions
if (current_position == 0) & (data.loc[i, 'signal'] != 0):
current_position = data.loc[i, 'signal']
entry_flag = True
# Short Position
elif current_position == -1:
if data.loc[i, 'Close'] > stop_loss:
exit_type = 'SL'
exit_flag = True
elif data.loc[i, 'Close'] < take_profit:
exit_type = 'TP'
exit_flag = True
# Long Position
elif current_position == 1:
if data.loc[i, 'Close'] < stop_loss:
exit_type = 'SL'
exit_flag = True
elif data.loc[i, 'Close'] > take_profit:
exit_type = 'TP'
exit_flag = True
# ------------------------------- Entry Position Update -------------------------------------
if entry_flag:
# Populate the trades dataframe
trades = pd.DataFrame(index=[0])
trades['entry_date'] = i
trades['entry_price'] = round(data.loc[i, 'Close'], 2)
trades['position'] = current_position
stop_loss = data.loc[i, 'stoploss']
take_profit = data.loc[i, 'target']
# Increase number of trades by 1
trade_num += 1
# Print trade details
print(
f"\033[34mTrade No: {trade_num}\033[0m | Entry Date: {i} | Entry Price: {trades.entry_price[0]} | Position: {current_position}")
# Set exit flag to false
entry_flag = False
continue
# ------------------------------- Exit Position Update -------------------------------------
if exit_flag: