Skip to main content

Process Tick data to form One minute OHCLV Using SQL


|| श्री ||

Ticks to usable Time Frame

Tick data is raw data that we need to process into the usable time frame. As I am using Zerodha ticker service it gives me data every tick. If we need to find an opportunity for trading, required to process the data to make it usable.

Here I am saving data into mssql data base to store tick data. Below is my table structure. 


      You can use below script to use table. I am storing only current day data for Nifty50 stock and Nifty50Index. In my table End of the day will move this data into my historical table which store 1 min data. and truncate table.

CREATE TABLE [dbo].[TickerData](
[TimeStamp] [datetime] NULL,
[Open] [decimal](9, 2) NULL,
[High] [decimal](9, 2) NULL,
[Low] [decimal](9, 2) NULL,
[Close] [decimal](9, 2) NULL,
[Volume] [bigint] NULL,
[InstrumentID] [bigint] NULL,
[recordid] [bigint] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_TickerData] PRIMARY KEY CLUSTERED
(
[recordid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


Tick data received from ticker service is having only Latest Price, TimeStamp, And volume.
I have set my Open, close, high, low to LTP.  Now we need to understand how to get 1 min data usnig raw data.

Open
First Tick for min is Open price .i.e when LTP for any stock for 1st second (9:15:00) of the min is Open price

Close 
Last Tick for min is Close price .i.e when LTP for any stock for Last second of the min is Close price

High
Highest price for current session i.e one min. is High price

Low
Lowest Price for current session i.e one min is Low Price

Volume
Volume is cumulative so we need to subtract First tick Volume from Last tick volume.

Below is SQL script which will process raw data and convert it to 1 min data.

**********************************************************************

Declare @instrumentid BIGINT, 
 @starttime    DATETIME, 
 @endtime      DATETIME 
  BEGIN 
      DECLARE @DateTime DATETIME; 


  SET  @instrumentid=  897537 
  SET @starttime='2020-05-29 09:15:09.000'
  SET @endtime='2020-05-29 14:19:55.000' 


      SET @DateTime=Getdate(); --Dateadd(Day,0, Getdate()) 
      SELECT *, 
             Row_number() 
               OVER( 
                 partition BY s1, m1, h1 
                 ORDER BY [timestamp])      rowNum, 
             Row_number() 
               OVER( 
                 partition BY s1, m1, h1 
                 ORDER BY [timestamp] DESC) rowNum2 
      INTO   #temp2 
      FROM   (SELECT *, 
                     Datepart(hour, [timestamp])  H1, 
                     Datepart(minute, [timestamp])M1, 
                     Datepart(minute, [timestamp])S1 
              FROM   [RENDB].[dbo].[tickerdata] 
              WHERE  instrumentid = @instrumentid 
                     AND ( [timestamp] >= @starttime 
                           AND [timestamp] <= @endtime )) res 
    

      SELECT [open], 
             [close], 
             [high], 
             [low], 
             [timestamp] 'datetime', 
             [volume] 
      FROM   (SELECT Sum([open])      [Open], 
                     Sum([close])     [Close], 
                     Max([high])      [High], 
                     Max([low])       [Low], 
                     Max([timestamp]) [TimeStamp], 
                     Max([volume])    [Volume]             
              FROM   (SELECT [open], 
                             00.00  [close], 
                             0.0    [high], 
                             [open] [low], 
                             [timestamp], 
                             0      [volume] 
                      FROM   #temp2 
                      WHERE  rownum = 1 
                      UNION 
                      SELECT 00.00  [Open], 
                             [open] [close], 
                             0.0    [high], 
                             [open] [low], 
                             [timestamp], 
                             0      [volume] 
                      FROM   #temp2 
                      WHERE  rownum2 = 1 
                      /****/ 
                      UNION 
                      SELECT 00.00                         [Open], 
                             00.00                         [close], 
                             0.0                           [high], 
                             v1.[Open]                     [low], 
                             v1. [timestamp], 
                             ( v2.[volume] - v1.[volume] ) [Volume] 
                      FROM   #temp2 v1 
                             JOIN #temp2 v2 
                               ON v1.rownum = v2.rownum2 
                                  AND v1.h1 = v2.h1 
                                  AND v1.m1 = v2.m1 
                      WHERE  v1.rownum = 1 
                      /****/ 
                      UNION 
                      SELECT 00.00            [Open], 
                             00.00            [close], 
                             Max([open])      [High], 
                             Min([open])      [low], 
                             Max([timestamp]) [TimeStamp], 
                             0                [volume] 
                      FROM   [RENDB].[dbo].[tickerdata] 
                      WHERE  instrumentid = @instrumentid 
                             AND ( [timestamp] >= @starttime 
                                   AND [timestamp] <= @endtime ) 
                      GROUP  BY Datepart(year, [timestamp]), 
                                Datepart(month, [timestamp]), 
                                Datepart(day, [timestamp]), 
                                Datepart(hour, [timestamp]), 
                                Datepart(minute, [timestamp]), 
                                ( Datepart(second, [timestamp]) / 1 ) 
                      UNION 
                      SELECT 00.00            [Open], 
                             00.00            [close], 
                             0.0              [High], 
                             Min([open])      [low], 
                             Max([timestamp]) [TimeStamp], 
                             0                [volume] 
                      FROM   [RENDB].[dbo].[tickerdata] 
                      WHERE  instrumentid = @instrumentid 
                             AND ( [timestamp] >= @starttime 
                                   AND [timestamp] <= @endtime ) 
                      GROUP  BY Datepart(year, [timestamp]), 
                                Datepart(month, [timestamp]), 
                                Datepart(day, [timestamp]), 
                                Datepart(hour, [timestamp]), 
                                Datepart(minute, [timestamp]), 
                                ( Datepart(second, [timestamp]) / 1 )) res4 
              GROUP  BY Datepart(year, [timestamp]), 
                        Datepart(month, [timestamp]), 
                        Datepart(day, [timestamp]), 
                        Datepart(hour, [timestamp]), 
                        ( Datepart(minute, [timestamp]) / 1 ))res5 
      ORDER  BY [datetime] 

      DROP TABLE #temp2 
  END 


**********************************************************************


Using about script you Generate the 1 min candle(OHLC(V)) data.  As I said earlier We will keep only Data for the same day. as it will have only limited record so above scrip will not take more than 1 sec to execute.

I have observed that some time OHLCV is not exect matching to the graph. this may be because of capturing tick data i have loosed some data and hence it show some different, but we can use this data to provide it program which will scan stock trading opportunity. I have highlighted Data on TradingView and My Table in mssql. 






Thanks for visiting my blog, Please suggest your thought on above approach. if you have any doubts  please post in comment.











Comments

  1. thanks great articles I have simple question-
    I want to do a simple difference between last 5 minutes candle close value and current LTP value for bank nifty future.

    I think I can use api to get previous 5 minutes candles close value and same for current LTP price but how?

    Can you help?

    ReplyDelete

Post a Comment

Popular posts from this blog

Getting Started with Zerodha API using C#

Getting Started with Zerodha API    In today's era, every thing is automated. now day's technology changing things rapidly. Many of us might have started imagination of automating the trades. This will be very interesting if you automate your trading action using your computer. If you planing to automate your trading, then here is some important information you may get.   Zerodha offering API for trading purpose, with the help of  API you can place order, cancel, modify. Zerodha Kite API V3 is very useful for automating trades. API is available in two forms one is Ticker which will give you tick data in market hours, another is historical API which will allow you to get old data.      To subscribe Kite API you must have Zerodha Dmat Account. Once you got your account with Zerodha login/Signup to  Kite Connect . You need to create app for API . Refer below image to create app. Fill the details. It will ask you to login your Kite Dmat account to link. So you can see this

How to generate the request_token for zerodha api using C#

Zerodha Kite Api How login Zerodha api using C# application? Hi Friends, recently i have started create application for zerodha api to make my own client for trading. Many of us have question how to login and trade using our custom C# application. I also face same problem i was looking solution for the same but  i was not able to fine exact way of doing it. I have gone through zerodha api document  According to them we need web view to make us to work this. Please follow be steps to get login token for API. Steps : 1) Creaet your login URL which is kite login + API key  eg.   var kiteURL="https://kite.trade/connect/login?v=3&api_key="    var apiKey="xpma3rmciorheitb"     2) Add web Browser to you web form set below properties             webBrowser1.AllowNavigation = true;             webBrowser1.ScriptErrorsSuppressed = true;             webBrowser1.Navigate(new Uri(kiteURL+apiKey)); 3) Now you need to register event "webBrowser1_

How to Fetch Data Tick from Kite Connect API (Nifty50)

Get Nifty50 data from Zerodha API In Last blog we discuss about how to generate request token and now we are going to look how to get data from Kite Connect. Here we will subscribe Nifty50. We will go step by step If you have code from zerodha official  git hub we can start further if not you get it from my previous blog "Getting Started with Zerodha " 1) We need list of Nifty50 stock which below Can verify this list on NSE India site. Below is json which you can use you code. if need we can key value pair using it. var stocks= [{"instrumenttoken" :3861249, "tradingsymbol" : "ADANIPORTS"}, {"instrumenttoken" :60417, "tradingsymbol" : "ASIANPAINT"}, {"instrumenttoken" :1510401, "tradingsymbol" : "AXISBANK"}, {"instrumenttoken" :4267265, "tradingsymbol" : "BAJAJ-AUTO"}, {"instrumenttoken" :4268801, "tradingsymbol" : "BAJA