krishnavelu / alice_blue

Official Python library for Alice Blue API trading
GNU General Public License v3.0
133 stars 82 forks source link

KeyError: 'symbol' #274

Closed sachinppatel16 closed 3 years ago

sachinppatel16 commented 3 years ago

following is code i have written to get candle data from tick data. it is saying KeyError: 'symbol' in last. not able to solve it. pls help.

`#!pip install Alice_blue from alice_blue import *

from config import Credentials

import datetime import time from time import localtime,strftime import pandas as pd import threading

User_Name = 'XXXX' Pass_Word = 'XXXX' Secret_Key = 'XXXX' App_Id = 'XXXX'

SCRIPT_LIST = ['SBIN', 'IRCTC'] CDS_SCRIPT_LIST = ['USDINR APR FUT'] MCX_SCRIPT_LIST = ['CRUDEOIL APR FUT']

socket_opened = False df = pd.DataFrame() ORB_timeFrame = 60 # in seconds ORB_df = pd.DataFrame()

def event_handler_quote_update(message): ltp = message['ltp'] timestamp = datetime.datetime.fromtimestamp(message['exchange_time_stamp']) vol = message['volume'] instrumnet = message['instrument'].symbol exchange = message['instrument'].exchange high = message['high'] low = message['low'] open = Message['open'] close = Message['close'] global df currentTime = time.strftime("%Y-%m-%d %H:%M:%S", localtime()) df = df.append({'symbol': instrumnet, 'timestamp': timestamp, 'vol': vol,'ltp': ltp, 'high': high, 'low': low ,'exchange' :exchange}, ignore_index=True)

print(f"{instrumnet} : {timestamp} : {open} : {high}: {low} : {close} : {currentTime}")

def open_callback(): global socket_opened socket_opened = True print("Socket opened")

def login(): access_token = AliceBlue.login_and_get_access_token(username=User_Name, password=Pass_Word, twoFA='a',api_secret=Secret_Key, app_id=App_Id)

alice = AliceBlue(username=User_Name, password=Pass_Word,access_token=access_token, master_contracts_to_download=['NSE', 'CDS', 'MCX'])

alice.start_websocket(subscribe_callback=event_handler_quote_update,socket_open_callback=open_callback,run_in_background=True)

while(socket_opened == False):   
    pass
for script in SCRIPT_LIST:
    alice.subscribe(alice.get_instrument_by_symbol('NSE', script), LiveFeedType.MARKET_DATA)
for script in CDS_SCRIPT_LIST:
    alice.subscribe(alice.get_instrument_by_symbol('CDS', script), LiveFeedType.MARKET_DATA)
for script in MCX_SCRIPT_LIST:
    alice.subscribe(alice.get_instrument_by_symbol('MCX', script), LiveFeedType.MARKET_DATA)
return alice

def createOHLC(alice, isFirstCandle): start = time.time() global df copydf = df.copy(deep=True).drop_duplicates() df = pd.DataFrame() if isFirstCandle: openHighForFisrtCandle(copydf) else : getOHLC_df(copydf,alice)

interval = ORB_timeFrame - (time.time() - start)
print(f"Next check will start after {interval} sec : {datetime.datetime.now()}")
threading.Timer(interval, createOHLC,args=[alice,False]).start()

def openHighForFisrtCandle(df): grouped = df. groupby('symbol') global ORB_df for name, group in grouped: group = group.sort_values('timestamp') timestamp = group['timestamp'].iloc[0] symbol = name high= group['ltp'].max()
low= group['ltp'].min()

    data = {
        'timestamp': timestamp,
        'symbol': symbol,
        'high': high,
        'low':  low }
    ORB_df = ORB_df.append(data, ignore_index=True)
ORB_df.set_index('symbol',inplace=True)
print(ORB_df)

def getOHLC_df(df,alice): grouped = df.groupby('symbol')

global ORB_df

df_final = pd.DataFrame()
for name, group in grouped:
    group = group.sort_values('timestamp')
    timestamp =  group['timestamp'].iloc[0]
    symbol =  name
    orb_high= group['high'].iloc[0]
    orb_low=group['low'].iloc[0]
    open= group['ltp'].iloc[0]
    close= group['ltp'].iloc[-1]
    high= group['ltp'].max()
    low=  group['ltp'].min()
    exchange = group['exchange'].iloc[0]
    data = {
        'timestamp': timestamp,
        'symbol': symbol,
        'orb_high': day_high,
        'orb_low': day_low,
        'open': open,
        'high': high,
        'low': low,
        'close':  close ,
        'exchange':exchange}
    df_final = df_final.append(data, ignore_index=True)
print(df_final)

if name == 'main': alice = login() interval = ORB_timeFrame - datetime.datetime.now().second print("start in ", interval) time.sleep(interval) createOHLC(alice, True)`

AnoZee commented 3 years ago

Create an issue according to the guidelines mentioned in README.md

krishnavelu commented 3 years ago

It’s not a problem of this library. It’s your own code’s problem. Moreover code is unreadable without indentation.