Wednesday, September 16, 2020

Alpaca data stream

 # Be sure to pip install websocket-client

# Details: https://pypi.org/project/websocket-client/

import websocket
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pyxtension.Json import Json
import numpy as np  
from datetime import datetime

def on_message(wsmessage):
    #message = message.replace('[','').replace(']','')
    x = message.replace('[','').replace(']','')
    if x.find("sym") > 0:
        x = x.replace('[','').replace(']','')
        print (x)
        y = Json(x)
        #print(y.sym)
        open  = y.open
        close = y.close
        high = y.high
        low = y.low
        vw = y.vw
        volumn = y.volumn
        timestamp = str(y.s)
        timestamp = timestamp[0:10]
        timestampEnd = str(y.e)
        timestampEnd = timestampEnd[0:10]
        dateBeg =  datetime.fromtimestamp(int(timestamp))
        dateEnd =  datetime.fromtimestamp(int(timestampEnd))
        global dfObj
        dfObj = dfObj.append({'Open':open'High':high, 'Low':low, 'Close':close, 'Volumn':volumn,'VW':vw,'Date': dateBeg, 'Date_end': dateEnd }, ignore_index=True)
        trows = len(dfObj.index)
        print("cnt:", trows)


def on_error(wserror):
    print(error)

def on_close(ws):
    #print("### closed ###")
    f.close

def on_open(ws):
    ws.send('{"action":"auth","params":"XXXX"}')
    ws.send('{"action":"subscribe","params":"A.AAPL"}')

f = open("demofile.txt""a")
dfObj = pd.DataFrame(columns=['Open''High''Low','Close''Volumn''VW''Date''Date_end'])
print("Empty Dataframe ", dfObj, sep='\n')
dfObj = dfObj.set_index(pd.DatetimeIndex(dfObj['Date']))

if __name__ == "__main__":
    # websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://socket.polygon.io/stocks",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open

    ws.run_forever()

No comments:

Post a Comment