Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    1. Home
    2. Yuehua-Liu
    3. Posts
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
    • Profile
    • Following 0
    • Followers 0
    • Topics 1
    • Posts 1
    • Best 0
    • Controversial 0
    • Groups 0

    Posts made by Yuehua-Liu

    • How to create my own DataBase for my websocket data stream?

      Hi team,

      I'm trying to build my own feed.DataBase Class for my websocket service. But I'm stuck right now.
      I can run the Class and print my data correctly, but I'm not able to set the lines for my data.
      It always raise the error when I tried to assign the data.

      Here's the code I've done, can anyone help to give a example how to set the web socket data? thanks

      rom datetime import datetime
      import backtrader as bt
      import websocket
      import logging
      import json
      
      class MySocketData(bt.feeds.DataBase):
          def __init__(self):
              self.ws = None
              self.data = []
      
          def islive(self):
              return True
      
          def start(self):
              self.ws = websocket.WebSocketApp('MY_IP:PORT',
                                               on_open=self.on_open,
                                               on_message=self.next)
              print("start run forever!!!!")
              self.ws.run_forever()
      
          def stop(self):
              self.ws.close()
      
          def on_open(self, ws):
              logging.info('connected the data stream')
              ws.send('This is a test message from NB yo man!')
      
          def next(self, ws, message):
              logging.info(f'received: {message}')
              data = json.loads(message)
              self.data.append(data)
      
              if len(self.data) > 0:
                  print(datetime.strptime(self.data[0]['日期'], r'%Y/%m/%d %H:%M:%S'))
                  
                  dt = bt.date2num(datetime.strptime(self.data[0]['日期'], r'%Y/%m/%d %H:%M:%S'))
                  print(self.lines.datetime)
                  self.l.datetime[0] = dt
                  self.l.open[0] = self.data[0]['KBAR']
                  self.l.high[0] = self.data[0]['KBAR']
                  self.l.low[0] = self.data[0]['KBAR']
                  self.l.close[0] = self.data[0]['KBAR']
      
      
      if __name__ == '__main__':
          datafeed = MySocketData()
          datafeed.start()
      
      posted in General Code/Help
      Yuehua-Liu
      Yuehua-Liu
    • 1 / 1