Python3 | Binance Websocket to CSV











up vote
0
down vote

favorite












There was another thread that had tried answering this question but Im coming up with a "str" issue when trying to save to CSV using DictWriter.



Goal: Save to CSV.



Python3: Grabbing data from Websocket and putting it into a DataFrame



from binance.client import Client
from binance.websockets import BinanceSocketManager
from binance.enums import *
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
from pandas.io.json import json_normalize
import csv

client = Client('api-key', 'api-secret')
tickers = client.get_all_tickers()

columns = ['e', 'E', 's'] # add whatever JSON keys you want

with open('names.csv', 'w', newline='') as csvfile:
fieldnames =['e', 'E', 's']
out = csv.DictWriter(open('klines.csv', 'wb'), columns,extrasaction='ignore')
out.writeheader()


### Multiplex socket
def process_message(msg):
out = csv.DictWriter(open('klines.csv', 'wb'), columns, extrasaction='ignore')
out.writeheader()
out.writerow(msg)
def printout(msg):
print(msg)
def initiate():
global bm
# Connect to client
client = Client('api-key', 'api-secret')

# Setup Socket
bm = BinanceSocketManager(client)

# then start the socket manager
conn_key = bm.start_multiplex_socket(['bnbbtc@kline_1m'], process_message)

# start the socket
bm.start()


initiate()


Websocket Example



{'stream': 'bnbbtc@kline_1m', 
'data': {'e': 'kline', 'E': 1542845036887, 's': 'BNBBTC',
'k': {'t': 1542844980000, 'T': 1542845039999, 's': 'BNBBTC', 'i': '1m', 'f': 31389820, 'L': 31389856, 'o': '0.00134810', 'c': '0.00134610', 'h': '0.00134900', 'l': '0.00134570', 'v': '1634.83000000', 'n': 37, 'x': False, 'q': '2.20069651', 'V': '613.22000000', 'Q': '0.82521938', 'B': '0'
}}}


Error I receive



File "C:/.../wss_multiplex.py", line 19, in <module>
out.writeheader()
File "C:Python37_1-64libcsv.py", line 144, in writeheader
self.writerow(header)
File "C:Python37_1-64libcsv.py", line 155, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
TypeError: a bytes-like object is required, not 'str'









share|improve this question


























    up vote
    0
    down vote

    favorite












    There was another thread that had tried answering this question but Im coming up with a "str" issue when trying to save to CSV using DictWriter.



    Goal: Save to CSV.



    Python3: Grabbing data from Websocket and putting it into a DataFrame



    from binance.client import Client
    from binance.websockets import BinanceSocketManager
    from binance.enums import *
    import datetime as dt
    import matplotlib.pyplot as plt
    from matplotlib import style
    import pandas as pd
    import pandas_datareader.data as web
    from pandas.io.json import json_normalize
    import csv

    client = Client('api-key', 'api-secret')
    tickers = client.get_all_tickers()

    columns = ['e', 'E', 's'] # add whatever JSON keys you want

    with open('names.csv', 'w', newline='') as csvfile:
    fieldnames =['e', 'E', 's']
    out = csv.DictWriter(open('klines.csv', 'wb'), columns,extrasaction='ignore')
    out.writeheader()


    ### Multiplex socket
    def process_message(msg):
    out = csv.DictWriter(open('klines.csv', 'wb'), columns, extrasaction='ignore')
    out.writeheader()
    out.writerow(msg)
    def printout(msg):
    print(msg)
    def initiate():
    global bm
    # Connect to client
    client = Client('api-key', 'api-secret')

    # Setup Socket
    bm = BinanceSocketManager(client)

    # then start the socket manager
    conn_key = bm.start_multiplex_socket(['bnbbtc@kline_1m'], process_message)

    # start the socket
    bm.start()


    initiate()


    Websocket Example



    {'stream': 'bnbbtc@kline_1m', 
    'data': {'e': 'kline', 'E': 1542845036887, 's': 'BNBBTC',
    'k': {'t': 1542844980000, 'T': 1542845039999, 's': 'BNBBTC', 'i': '1m', 'f': 31389820, 'L': 31389856, 'o': '0.00134810', 'c': '0.00134610', 'h': '0.00134900', 'l': '0.00134570', 'v': '1634.83000000', 'n': 37, 'x': False, 'q': '2.20069651', 'V': '613.22000000', 'Q': '0.82521938', 'B': '0'
    }}}


    Error I receive



    File "C:/.../wss_multiplex.py", line 19, in <module>
    out.writeheader()
    File "C:Python37_1-64libcsv.py", line 144, in writeheader
    self.writerow(header)
    File "C:Python37_1-64libcsv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
    TypeError: a bytes-like object is required, not 'str'









    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      There was another thread that had tried answering this question but Im coming up with a "str" issue when trying to save to CSV using DictWriter.



      Goal: Save to CSV.



      Python3: Grabbing data from Websocket and putting it into a DataFrame



      from binance.client import Client
      from binance.websockets import BinanceSocketManager
      from binance.enums import *
      import datetime as dt
      import matplotlib.pyplot as plt
      from matplotlib import style
      import pandas as pd
      import pandas_datareader.data as web
      from pandas.io.json import json_normalize
      import csv

      client = Client('api-key', 'api-secret')
      tickers = client.get_all_tickers()

      columns = ['e', 'E', 's'] # add whatever JSON keys you want

      with open('names.csv', 'w', newline='') as csvfile:
      fieldnames =['e', 'E', 's']
      out = csv.DictWriter(open('klines.csv', 'wb'), columns,extrasaction='ignore')
      out.writeheader()


      ### Multiplex socket
      def process_message(msg):
      out = csv.DictWriter(open('klines.csv', 'wb'), columns, extrasaction='ignore')
      out.writeheader()
      out.writerow(msg)
      def printout(msg):
      print(msg)
      def initiate():
      global bm
      # Connect to client
      client = Client('api-key', 'api-secret')

      # Setup Socket
      bm = BinanceSocketManager(client)

      # then start the socket manager
      conn_key = bm.start_multiplex_socket(['bnbbtc@kline_1m'], process_message)

      # start the socket
      bm.start()


      initiate()


      Websocket Example



      {'stream': 'bnbbtc@kline_1m', 
      'data': {'e': 'kline', 'E': 1542845036887, 's': 'BNBBTC',
      'k': {'t': 1542844980000, 'T': 1542845039999, 's': 'BNBBTC', 'i': '1m', 'f': 31389820, 'L': 31389856, 'o': '0.00134810', 'c': '0.00134610', 'h': '0.00134900', 'l': '0.00134570', 'v': '1634.83000000', 'n': 37, 'x': False, 'q': '2.20069651', 'V': '613.22000000', 'Q': '0.82521938', 'B': '0'
      }}}


      Error I receive



      File "C:/.../wss_multiplex.py", line 19, in <module>
      out.writeheader()
      File "C:Python37_1-64libcsv.py", line 144, in writeheader
      self.writerow(header)
      File "C:Python37_1-64libcsv.py", line 155, in writerow
      return self.writer.writerow(self._dict_to_list(rowdict))
      TypeError: a bytes-like object is required, not 'str'









      share|improve this question













      There was another thread that had tried answering this question but Im coming up with a "str" issue when trying to save to CSV using DictWriter.



      Goal: Save to CSV.



      Python3: Grabbing data from Websocket and putting it into a DataFrame



      from binance.client import Client
      from binance.websockets import BinanceSocketManager
      from binance.enums import *
      import datetime as dt
      import matplotlib.pyplot as plt
      from matplotlib import style
      import pandas as pd
      import pandas_datareader.data as web
      from pandas.io.json import json_normalize
      import csv

      client = Client('api-key', 'api-secret')
      tickers = client.get_all_tickers()

      columns = ['e', 'E', 's'] # add whatever JSON keys you want

      with open('names.csv', 'w', newline='') as csvfile:
      fieldnames =['e', 'E', 's']
      out = csv.DictWriter(open('klines.csv', 'wb'), columns,extrasaction='ignore')
      out.writeheader()


      ### Multiplex socket
      def process_message(msg):
      out = csv.DictWriter(open('klines.csv', 'wb'), columns, extrasaction='ignore')
      out.writeheader()
      out.writerow(msg)
      def printout(msg):
      print(msg)
      def initiate():
      global bm
      # Connect to client
      client = Client('api-key', 'api-secret')

      # Setup Socket
      bm = BinanceSocketManager(client)

      # then start the socket manager
      conn_key = bm.start_multiplex_socket(['bnbbtc@kline_1m'], process_message)

      # start the socket
      bm.start()


      initiate()


      Websocket Example



      {'stream': 'bnbbtc@kline_1m', 
      'data': {'e': 'kline', 'E': 1542845036887, 's': 'BNBBTC',
      'k': {'t': 1542844980000, 'T': 1542845039999, 's': 'BNBBTC', 'i': '1m', 'f': 31389820, 'L': 31389856, 'o': '0.00134810', 'c': '0.00134610', 'h': '0.00134900', 'l': '0.00134570', 'v': '1634.83000000', 'n': 37, 'x': False, 'q': '2.20069651', 'V': '613.22000000', 'Q': '0.82521938', 'B': '0'
      }}}


      Error I receive



      File "C:/.../wss_multiplex.py", line 19, in <module>
      out.writeheader()
      File "C:Python37_1-64libcsv.py", line 144, in writeheader
      self.writerow(header)
      File "C:Python37_1-64libcsv.py", line 155, in writerow
      return self.writer.writerow(self._dict_to_list(rowdict))
      TypeError: a bytes-like object is required, not 'str'






      python websocket export-to-csv python-3.7 binance






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 at 0:07









      jdimstrnate

      134




      134





























          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',
          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%2f53422168%2fpython3-binance-websocket-to-csv%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422168%2fpython3-binance-websocket-to-csv%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

          What visual should I use to simply compare current year value vs last year in Power BI desktop

          Alexandru Averescu

          Trompette piccolo