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

          How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

          Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?