Resampling Kite Connect Live Websocket Ticks to Candles using Pandas in python

Category > PYTHON || Published on : Monday, December 7, 2020 || Views: 188 || Resampling Kite Connect Live Websocket Ticks to Candles using Pandas in python


Here Pawan Kumar will explain how to Resampling Kite Connect Live Websocket Ticks to Candles using Pandas in python

from kiteconnect import KiteTicker;
from kiteconnect import KiteConnect;
import logging
import time,os,datetime,math;
import winsound
import pandas as pd

trd_portfolio = {954883:"USDINR19MARFUT"}

trd_tkn1 = [];

for x in trd_portfolio:
    trd_tkn1.append(x)


c_id = '****************'
ak = '************'
asecret = '*************************'

kite = KiteConnect(api_key=ak)
print('[*] Generate access Token : ',kite.login_url())
request_tkn = input('[*] Enter Your Request Token Here : ')[-32:];
data = kite.generate_session(request_tkn, api_secret=asecret)
kite.set_access_token(data['access_token'])
kws = KiteTicker(ak, data['access_token'])

#columns in data frame
df_cols = ["Timestamp", "Token", "LTP"]

data_frame = pd.DataFrame(data=[],columns=df_cols, index=[])

def on_ticks(ws, ticks):

    global data_frame, df_cols

    data = dict() 

    for company_data in ticks:
        token = company_data["instrument_token"]
        ltp = company_data["last_price"]
        timestamp = company_data['timestamp']

        data[timestamp] = [timestamp, token, ltp]

    tick_df = pd.DataFrame(data.values(), columns=df_cols, index=data.keys()) #
    data_frame = data_frame.append(tick_df)

    ggframe=data_frame.set_index(['Timestamp'],['Token'])
    print ggframe
    gticks=ggframe.ix[:,['LTP']]
    candles=gticks['LTP'].resample('1min').ohlc().dropna()
    print candles

def on_connect(kws , response):
    print('Connected')
    kws.subscribe(trd_tkn1)
    kws.set_mode(kws.MODE_FULL, trd_tkn1)

def on_close(ws, code, reason):
    print('Connection Error')


kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close

kws.connect()