โœ–

Home Forums General Questions How to build 1-minute candles from live ticks using Zerodha WebSocket?

How to build 1-minute candles from live ticks using Zerodha WebSocket?

  • Author
    Posts
    • ๐Ÿ“ Question Details
      I am receiving live tick data from Zerodha WebSocket, but indicators like Supertrend and others require candle data.
      How can I correctly convert live ticks into 1-minute candles in real-time?
      Since i use the boiler plate of the websocket from the Zerodha’s python examples Repo from github.
    • Yes, Zerodha’s WebSocket provides the tick-tick data, we will have to aggregate the ticks and convert that into candle of different timeframes whatever you want.

      To do that can refer below code:

      from datetime import datetime
      
      CANDLE_STATE = {}
      
      def build_candle(symbol, tick, timeframe=1):
          ts = tick["timestamp"]
          price = tick["price"]
      
          # Adject timeframe
          minute = (ts.minute // timeframe) * timeframe
          bucket = ts.replace(minute=minute, second=0, microsecond=0)
      
          if symbol not in CANDLE_STATE:
              CANDLE_STATE[symbol] = {}
      
          candles = CANDLE_STATE[symbol]
      
          # Create new candle
          if bucket not in candles:
              candles[bucket] = {
                  "open": price,
                  "high": price,
                  "low": price,
                  "close": price
              }
          else:
              c = candles[bucket]
              c["high"] = max(c["high"], price)
              c["low"] = min(c["low"], price)
              c["close"] = price
      
          return candles
      # Replace the tick's static data with the live feed
      ticks = [
          {"timestamp": datetime(2026, 4, 24, 9, 15, 5), "price": 100},
          {"timestamp": datetime(2026, 4, 24, 9, 15, 20), "price": 102},
          {"timestamp": datetime(2026, 4, 24, 9, 15, 40), "price": 99},
          {"timestamp": datetime(2026, 4, 24, 9, 16, 10), "price": 105},
      ]
      
      symbol = "TEST"
      
      for t in ticks:
          candles = build_candle(symbol, t, timeframe=1)
      
      # Print result
      for time, candle in candles.items():
          print(time, candle)
Viewing 1 reply thread
×

Start a Discussion

Get help from the AlgoDelta community.

×

Welcome Back!

Enter your email to sign in or create an account. No passwords needed.

โณ

Pending Approval

โš ๏ธ

Delete This?

Are you sure you want to delete this? This action is permanent and cannot be undone.

Scroll to Top