pythonpython-2.7websocketpoloniex

How to write websocket push api output to text file?


I'm using a python script to get realtime updates from an orderbook on the cryptocurrency exchange Poloniex.

Currently it prints the information pushed by the websocket to stdout, what do I need to do to print it into a file instead? I'm using python-2.7, thanks in advance!

Below is the script I'm using:

#!/usr/bin/python
import sys, getopt
import websocket
import thread
import time
import json

try:
    opts, args = getopt.getopt(sys.argv[1:], 'p:', ['parity='])
except getopt.GetoptError:
    sys.exit(2)

for opt, arg in opts:
    if opt in ('-p', '--paridade'):
        parity = arg
    else:
        sys.exit(2)

data = {'command':'subscribe','channel':''+parity+''}

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    print("ONOPEN")
    def run(*args):
        ws.send(json.dumps(data))
        while True:
            time.sleep(1)
        ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())


if __name__ == "__main__":

    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://api2.poloniex.com/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

Solution

  • python has built in support for file operations: https://docs.python.org/2/library/stdtypes.html#bltin-file-objects

    instead of print(message) you can do:

    file_path = '/example/file.txt' #choose your file path
    with open(file_path, "w") as output_file:
        output_file.write(message + "\n")
    

    note that the + "\n" is so that each message will be written to a new line in the file since python won't put it there on its own