Resampling Live Websocket Ticks to Candles using Pandas in python The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceAdding new column to existing DataFrame in Python pandaspandas resample documentationPython Pandas Error tokenizing dataCombine two columns of text in dataframe in pandas/pythonResampling OHLC tick data and filling gaps in PandasHow to avoid Python/Pandas creating an index in a saved csv?pandas resample .csv tick data to OHLCTrouble resampling data in PandasResample python list with pandasaggregate tick data to open high low close non time related

How do you keep chess fun when your opponent constantly beats you?

Is this wall load bearing? Blueprints and photos attached

Define a list range inside a list

Match Roman Numerals

Working through the single responsibility principle (SRP) in Python when calls are expensive

How to make Illustrator type tool selection automatically adapt with text length

How many cones with angle theta can I pack into the unit sphere?

How do spell lists change if the party levels up without taking a long rest?

"... to apply for a visa" or "... and applied for a visa"?

Why did Peik Lin say, "I'm not an animal"?

Button changing its text & action. Good or terrible?

Can the Right Ascension and Argument of Perigee of a spacecraft's orbit keep varying by themselves with time?

Circular reasoning in L'Hopital's rule

how can a perfect fourth interval be considered either consonant or dissonant?

Is an up-to-date browser secure on an out-of-date OS?

Why can't wing-mounted spoilers be used to steepen approaches?

What information about me do stores get via my credit card?

Do warforged have souls?

What was the last x86 CPU that did not have the x87 floating-point unit built in?

Did the new image of black hole confirm the general theory of relativity?

"is" operation returns false even though two objects have same id

Does Parliament hold absolute power in the UK?

Is there a way to generate uniformly distributed points on a sphere from a fixed amount of random real numbers per point?

What aspect of planet Earth must be changed to prevent the industrial revolution?



Resampling Live Websocket Ticks to Candles using Pandas in python



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceAdding new column to existing DataFrame in Python pandaspandas resample documentationPython Pandas Error tokenizing dataCombine two columns of text in dataframe in pandas/pythonResampling OHLC tick data and filling gaps in PandasHow to avoid Python/Pandas creating an index in a saved csv?pandas resample .csv tick data to OHLCTrouble resampling data in PandasResample python list with pandasaggregate tick data to open high low close non time related



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am trying to resample live ticks from KiteTicker websocket into OHLC candles using pandas and this is the code I have written, which works fine with single instrument (The commented trd_portfolio on line 9) but doesn't work with multiple instruments (Line 8) as it mixes up data of different instruments.



Is there any way to relate the final candles df to instrument tokens? or make this work with multiple intruments?



I would like to run my algo on multiple instruments at once, please suggest if there is a better way around it.



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",4632577:"JUBLFOOD"
# 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()









share|improve this question




























    0















    I am trying to resample live ticks from KiteTicker websocket into OHLC candles using pandas and this is the code I have written, which works fine with single instrument (The commented trd_portfolio on line 9) but doesn't work with multiple instruments (Line 8) as it mixes up data of different instruments.



    Is there any way to relate the final candles df to instrument tokens? or make this work with multiple intruments?



    I would like to run my algo on multiple instruments at once, please suggest if there is a better way around it.



    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",4632577:"JUBLFOOD"
    # 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()









    share|improve this question
























      0












      0








      0








      I am trying to resample live ticks from KiteTicker websocket into OHLC candles using pandas and this is the code I have written, which works fine with single instrument (The commented trd_portfolio on line 9) but doesn't work with multiple instruments (Line 8) as it mixes up data of different instruments.



      Is there any way to relate the final candles df to instrument tokens? or make this work with multiple intruments?



      I would like to run my algo on multiple instruments at once, please suggest if there is a better way around it.



      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",4632577:"JUBLFOOD"
      # 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()









      share|improve this question














      I am trying to resample live ticks from KiteTicker websocket into OHLC candles using pandas and this is the code I have written, which works fine with single instrument (The commented trd_portfolio on line 9) but doesn't work with multiple instruments (Line 8) as it mixes up data of different instruments.



      Is there any way to relate the final candles df to instrument tokens? or make this work with multiple intruments?



      I would like to run my algo on multiple instruments at once, please suggest if there is a better way around it.



      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",4632577:"JUBLFOOD"
      # 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()






      python pandas resampling






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 22 at 5:39









      Parva PatelParva Patel

      193




      193






















          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55293504%2fresampling-live-websocket-ticks-to-candles-using-pandas-in-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55293504%2fresampling-live-websocket-ticks-to-candles-using-pandas-in-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현