Hello, I recently encountered problems with multiprocessing websockets.
When I do conn.run
with threading, then no errors.
p = threading.Thread(target=conn.run, daemon=False, args=(streams,))
p.start()
print(p)
But when I do it thru multiprocess module,
#t = multiprocess.Process(target=conn.run, args=(streams,))
#t.start()
#print(t)
I get:
ERROR:root:error while consuming ws messages: [Errno 9] Bad file descriptor
The reason I prefer to use multiprocess module is because it can be terminated and its easier to handle for some reason then threading. Please see full code below:
import threading
import multiprocess
import multiprocessing
from time import sleep
import alpaca_trade_api as tradeapi
import pandas as pd
base_url = 'https://paper-api.alpaca.markets'
data_url = 'wss://data.alpaca.markets'
trade_taken = False
# instantiate REST API
global api
api = tradeapi.REST('insert your key',
'insert-secret-key', base_url=base_url, api_version='v2')
# init WebSocket
global conn
conn = tradeapi.stream2.StreamConn(
'insert your key', 'insert-secret-key', data_url=data_url, data_stream='alpacadatav1')
@conn.on(r'^Q.AAPL$')
async def on_second_bars_EWN(conn, channel, bar):
print(bar)
@conn.on(r'^Q.BAC$')
async def on_second_bars_ENZL(conn, channel, bar):
print(bar)
#Multiprocess gives an error: ERROR:root:error while consuming ws messages: [Errno 9] Bad file #descriptor
streams = ['Q.AAPL', 'Q.BAC']
#t = multiprocess.Process(target=conn.run, args=(streams,))
#t.start()
#print(t)
# Threading works fine. You can comment here and uncomment above.
p = threading.Thread(target=conn.run, daemon=False, args=(streams,))
p.start()
print(p)
Please let me know how to make it work with multiprocess? Or if you have similar module that would work. Thank you!!!