import redis import os, time from time import sleep import datetime import json import random import pickle import pandas as pd os.environ['TZ'] = 'Asia/Calcutta' time.tzset() client = redis.Redis(host='127.0.0.1',port='6379') #redis_ind = 1 #thread_count = 3 tms_now=datetime.datetime.now() str_time_now = tms_now.strftime("%Y_%m_%d") str_date = str(str_time_now) candles_1 ={} while True: tms_now=datetime.datetime.now() tms_min_1 = datetime.datetime(tms_now.year, tms_now.month, tms_now.day, tms_now.hour,tms_now.minute) tms_min_prev=tms_now-datetime.timedelta(minutes=1) tms_min_0=datetime.datetime(tms_min_prev.year, tms_min_prev.month, tms_min_prev.day, tms_min_prev.hour,tms_min_prev.minute) str1 = client.rpop(str_date) if (str1!=None): y = pickle.loads(str1) i=1 for tick in y: i=i+1 if ("instrument_token" in tick) : instrument=tick["instrument_token"] if(instrument==256265 or instrument==260105) : ltt=tick["timestamp"] else : ltt=tick["last_trade_time"] ltt_min_1=datetime.datetime(ltt.year, ltt.month, ltt.day, ltt.hour,ltt.minute) try: if ltt_min_1 in candles_1[instrument]: 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 if(instrument==256265 or instrument==260105) : pass else : candles_1[instrument][ltt_min_1]["volume"]=max(candles_1[instrument][ltt_min_1]["volume"],tick["volume"]) #1.5 Use the max in volume instead of last. else: #print(candles_1) candles_1[instrument][ltt_min_1]={} candles_1[instrument][ltt_min_1]["high"]=tick["last_price"] #4 candles_1[instrument][ltt_min_1]["low"]=tick["last_price"] #5 candles_1[instrument][ltt_min_1]["open"]=tick["last_price"] #6 candles_1[instrument][ltt_min_1]["close"]=tick["last_price"] #7 if(instrument==256265 or instrument==260105) : pass else : candles_1[instrument][ltt_min_1]["volume"]=tick["volume"] #3.5 except KeyError: if instrument not in candles_1: candles_1[instrument]={} if ltt_min_1 not in candles_1[instrument]: candles_1[instrument][ltt_min_1]={} #print(candles_1) candles_1[instrument][ltt_min_1]["high"]=tick["last_price"] #8 candles_1[instrument][ltt_min_1]["low"]=tick["last_price"] #9 candles_1[instrument][ltt_min_1]["open"]=tick["last_price"] #10 candles_1[instrument][ltt_min_1]["close"]=tick["last_price"] #11 if(instrument==256265 or instrument==260105) : pass else : candles_1[instrument][ltt_min_1]["volume"]=tick["volume"] #3.5 if len(candles_1)>0 : for instrument in candles_1: r_key = str(instrument)+"_"+str(tms_min_0) if tms_min_0 in candles_1[instrument]: client.set(r_key,pickle.dumps(candles_1[instrument][tms_min_0])) r_key = str(instrument)+"_"+str(tms_min_1) if tms_min_1 in candles_1[instrument]: client.set(r_key,pickle.dumps(candles_1[instrument][tms_min_1])) else : sleep(1/100000)