Skip to content

Instantly share code, notes, and snippets.

@ashuthinks
Created October 19, 2020 18:14
Show Gist options
  • Save ashuthinks/8dbb49de9fc05a0e86b99e658503b46d to your computer and use it in GitHub Desktop.
Save ashuthinks/8dbb49de9fc05a0e86b99e658503b46d to your computer and use it in GitHub Desktop.
bank nifty index python script form candle
################## Ticks to candles in kiteconnect python ####################
# Author : Ashish (code updated)
# Reference :
# http://ezeetrading.in/Articles/Candles_formation_from_tick_data_zerodha.html
# Purpose : Convert ticks to candles by putting ticks in a queue. This redues
# time wasted in on_ticks function
################################################################################
from kiteconnect import KiteTicker
from kiteconnect import KiteConnect
import datetime
from copy import copy
import queue
import os
import pandas as pd
import json
import logging
logging.basicConfig(level=logging.DEBUG)
class Event(object):
"""
Event is base class providing an interface for all subsequent
(inherited) events, that will trigger further events in the
trading infrastructure.
"""
pass
class TickEvent(Event):
"""
Handles the event of receiving a new market ticks
"""
def __init__(self,ticks):
"""
Initialises the MarketEvent.
"""
self.type = 'TICK'
self.data = ticks
class CandleEvent(Event):
"""
Handles the event of receiving a 1min candle
"""
def __init__(self, symbol,candle):
self.type = 'CANDLE'
self.symbol = symbol
self.data = candle
def print_self(self):
print("CANDLE:",self.data)
class CandleEvent15Min(Event):
"""
Handles the event of 15 min candle.
"""
def __init__(self, symbol, candle):
"""
Initialises the 15mincandle event.
"""
self.type = '15MinCANDLE'
self.symbol = symbol
self.data = candle
def print_self(self):
"""
Outputs the values within the Order.
"""
print("CANDLE: = ",self.data)
class CandleEvent5Min(Event):
"""
Handles the event of 5 min candle.
"""
def __init__(self, symbol, candle):
"""
Initialises the 5mincandle event.
"""
self.type = '5MinCANDLE'
self.symbol = symbol
self.data = candle
def print_self(self):
"""
Outputs the values within the Order.
"""
print("CANDLE: = ",self.data)
# Enter the user api_key and the access_token generated for that day
credentials = {'api_key': "my", 'api_secret': "my", 'request_token':"my"}
kite = KiteConnect(credentials["api_key"])
data = kite.generate_session(credentials["request_token"], api_secret=credentials["api_secret"])
print(data.get('access_token'))
# test
print(kite.quote('NSE:INFY'))
# test
# Initialise
kws = KiteTicker(credentials["api_key"], data.get('access_token'))
token_dict = {260105:'bank nifty'} #you can put any F&O tokens here
# Creation of 1min , 5min and 15 min candles
candles_1 = {}
candles_15 = {}
candles_5 = {}
EventQ = queue.Queue()
def on_ticks(ws, ticks):
# Callback to receive ticks.
#logging.debug("Ticks: {}".format(ticks))
tick = TickEvent(ticks)
EventQ.put(tick)
def on_connect(ws, response):
# Callback on successful connect.
# Subscribe to a list of instrument_tokens (RELIANCE and ACC here).
instruments = list(token_dict.keys())
print(instruments)
#exit()
ws.subscribe(instruments)
# Set tick in `full` mode.
ws.set_mode(ws.MODE_FULL, instruments)
#def on_close(ws, code, reason):
# On connection close stop the main loop
# Reconnection will not happen after executing `ws.stop()`
# ws.stop()
kws.on_ticks = on_ticks
kws.on_connect = on_connect
#kws.on_close = on_close
# Infinite loop on the main thread. Nothing after this will run.
# You have to use the pre-defined callbacks to manage subscriptions.
kws.connect(threaded=True)
def main():
while True:
try:
event = EventQ.get(False)
#print (ticks)
except queue.Empty:
continue
else:
if event.type == 'TICK':
ticks = event.data
for tick in ticks:
instrument = tick["instrument_token"]
#instrument = token_dict[instrument_token]
#print(instrument_token,instrument)
ltt = tick["timestamp"]
#print(tick)
ltt_min_1 = datetime.datetime(ltt.year, ltt.month, ltt.day, ltt.hour,ltt.minute)
ltt_min_2 = ltt_min_1 - datetime.timedelta(minutes=1)
ltt_min_5 = datetime.datetime(ltt.year, ltt.month, ltt.day, ltt.hour,ltt.minute // 5 * 5)
ltt_min_6 = ltt_min_5 - datetime.timedelta(minutes=5)
ltt_min_15 = datetime.datetime(ltt.year, ltt.month, ltt.day, ltt.hour, ltt.minute // 15 * 15)
ltt_min_215 = ltt_min_15 - datetime.timedelta(minutes=15)
#print(ltt_min_1,end='\r')
#print(ltt_min_15,ltt_min_215)
#exit()
# For any other timeframe. Simply change ltt_min_1
# variable defination.
# e.g.
# ltt_min_15=datetime.datetime(ltt.year, ltt.month,
# ltt.day, ltt.hour,ltt.minute//15*15)
### Forming 1 Min Candles...
if instrument in candles_1:
if ltt_min_1 in candles_1[instrument]:
#print(tick)
candles_1[instrument][ltt_min_1]["high"] = max(candles_1[instrument][ltt_min_1]["high"],tick["last_price"]) # 1
candles_1[instrument][ltt_min_1]["low"] = min(candles_1[instrument][ltt_min_1]["low"],tick["last_price"]) # 2
candles_1[instrument][ltt_min_1]["close"] = tick["last_price"] # 3
else:
# print(instrument,str(ltt_min_1),candles_1[instrument][ltt_min_1])
candles_1[instrument][ltt_min_1] = {}
candles_1[instrument][ltt_min_1]["high"] = copy(tick["last_price"]) # 8
candles_1[instrument][ltt_min_1]["low"] = copy(tick["last_price"])
candles_1[instrument][ltt_min_1]["open"] = copy(tick["last_price"])
candles_1[instrument][ltt_min_1]["close"] = copy(tick["last_price"])
if ltt_min_2 in candles_1[instrument]:
print(candles_1)
candle = {"token": instrument, "Time": ltt_min_2,
"open": candles_1[instrument][ltt_min_2]["open"],
"high": candles_1[instrument][ltt_min_2]["high"],
"low": candles_1[instrument][ltt_min_2]["low"],
"close": candles_1[instrument][ltt_min_2]["close"]
}
candleevent = CandleEvent(instrument, candle)
EventQ.put(candleevent)
else:
candles_1[instrument] = {}
print("created dict for " + str(instrument))
### Forming 5 Min Candles...
if instrument in candles_5:
if ltt_min_5 in candles_5[instrument]:
#print(tick)
candles_5[instrument][ltt_min_5]["high"] = max(candles_5[instrument][ltt_min_5]["high"],tick["last_price"]) # 1
candles_5[instrument][ltt_min_5]["low"] = min(candles_5[instrument][ltt_min_5]["low"],tick["last_price"]) # 2
candles_5[instrument][ltt_min_5]["close"] = tick["last_price"] # 3
else:
#print(instrument,str(ltt_min_5),candles_5[instrument][ltt_min_5])
candles_5[instrument][ltt_min_5] = {}
candles_5[instrument][ltt_min_5]["high"] = copy(tick["last_price"]) # 8
candles_5[instrument][ltt_min_5]["low"] = copy(tick["last_price"])
candles_5[instrument][ltt_min_5]["open"] = copy(tick["last_price"])
candles_5[instrument][ltt_min_5]["close"] = copy(tick["last_price"])
if ltt_min_6 in candles_5[instrument]:
print(candles_5)
candle = {"token": instrument, "Time": ltt_min_6,
"open": candles_5[instrument][ltt_min_6]["open"],
"high": candles_5[instrument][ltt_min_6]["high"],
"low": candles_5[instrument][ltt_min_6]["low"],
"close": candles_5[instrument][ltt_min_6]["close"]
}
candleevent = CandleEvent5Min(instrument, candle)
EventQ.put(candleevent)
else:
candles_5[instrument] = {}
print("created dict for " + str(instrument))
### Forming 15 Min Candles...
if instrument in candles_15:
if ltt_min_15 in candles_15[instrument]:
#print(tick)
candles_15[instrument][ltt_min_15]["high"] = max(candles_15[instrument][ltt_min_15]["high"],tick["last_price"]) # 1
candles_15[instrument][ltt_min_15]["low"] = min(candles_15[instrument][ltt_min_15]["low"],tick["last_price"]) # 2
candles_15[instrument][ltt_min_15]["close"] = tick["last_price"] # 3
else:
#print(instrument,str(ltt_min_15),candles_15[instrument][ltt_min_15])
candles_15[instrument][ltt_min_15] = {}
candles_15[instrument][ltt_min_15]["high"] = copy(tick["last_price"]) # 8
candles_15[instrument][ltt_min_15]["low"] = copy(tick["last_price"])
candles_15[instrument][ltt_min_15]["open"] = copy(tick["last_price"])
candles_15[instrument][ltt_min_15]["close"] = copy(tick["last_price"])
if ltt_min_215 in candles_15[instrument]:
#print(candles_15)
candle = {"token": instrument, "Time": ltt_min_215,
"open": candles_15[instrument][ltt_min_215]["open"],
"high": candles_15[instrument][ltt_min_215]["high"],
"low": candles_15[instrument][ltt_min_215]["low"],
"close": candles_15[instrument][ltt_min_215]["close"]
}
candleevent = CandleEvent15Min(instrument, candle)
EventQ.put(candleevent)
else:
candles_15[instrument] = {}
print("created dict for " + str(instrument))
elif event.type == "CANDLE":
#print(event.type)
#print(event.symbol,event.data)
event.data.update(token_dict[event.symbol])
df = pd.DataFrame(event.data,index=[0])
#logging.debug("1 min Ticks: {}".format(df))
#print(df)
elif event.type == "15MinCANDLE":
#print(event.symbol, event.data)
event.data.update(token_dict[event.symbol])
df = pd.DataFrame(event.data, index=[0])
#logging.debug("15 min Ticks: {}".format(df))
#print(df)
elif event.type == "5MinCANDLE":
#print(event.symbol, event.data)
event.data.update(token_dict[event.symbol])
df = pd.DataFrame(event.data, index=[0])
# logging.debug("5 min Ticks: {}".format(df))
#print(df)
#print('\n')
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment