Python`websockets`库服务器不传输任何数据,但连接并首先发送/接收正常
我试图得到一个简单的Polygon.io tick数据的随机价格模拟器,用于在市场关闭时测试随机信号上的简单技术指标。由于市场在周末关闭,polygon.io不会返回价格,这显然是正确的。所以我只想要一个100行Python`websockets`库服务器不传输任何数据,但连接并首先发送/接收正常,python,python-3.x,websocket,server,client,Python,Python 3.x,Websocket,Server,Client,我试图得到一个简单的Polygon.io tick数据的随机价格模拟器,用于在市场关闭时测试随机信号上的简单技术指标。由于市场在周末关闭,polygon.io不会返回价格,这显然是正确的。所以我只想要一个100行websocketslibrary服务器模拟器。但它不起作用 服务器代码: import asyncio, websockets, time, json CONNECTING, AUTHENTICATING, SUBSCRIBING, STREAMING = range(4) stat
websockets
library服务器模拟器。但它不起作用
服务器代码:
import asyncio, websockets, time, json
CONNECTING, AUTHENTICATING, SUBSCRIBING, STREAMING = range(4)
state = CONNECTING
timestamp = 0
async def polygon_io_simulator(websocket, path):
global state, timestamp
while True:
if state == STREAMING:
ask_price = 0.0
bid_price = 1.0
response = [{
"t": timestamp,
"a": ask_price,
"b": bid_price,
}]
#await websocket.recv()
await websocket.send(json.dumps(response))
timestamp += 1
elif state == CONNECTING:
await websocket.send("Connected Successfully")
state = AUTHENTICATING
elif state == AUTHENTICATING:
await websocket.recv()
await websocket.send('authenticated')
state = SUBSCRIBING
elif state == SUBSCRIBING:
data = await websocket.recv()
print(data)
await websocket.send('subscribed')
state = STREAMING
#time.sleep(0.05)
start_server = websockets.serve(polygon_io_simulator, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
import websocket
#websocket.enableTrace(True)
import os, json, sys
from datetime import datetime
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication
API_KEY = os.environ['POLYGON_IO_APIKEY']
FOREX_ASSET = 'EUR/USD'
WEBSOCKET_URL = 'ws://localhost:8000' # wss://socket.polygon.io/forex
START, CONNECTING, AUTHENTICATING, SUBSCRIBING, STREAMING = range(5)
state = START
def on_message(ws, msg):
global state, curve, data_x, data_y, widget
if state == STREAMING:
# Realtime data plot. Each time this function is called, the data display is updated
json_data = json.loads(msg)[0]
mid_price = (json_data['a'] + json_data['b'])/2.0
print(mid_price)
elif state == CONNECTING:
if 'Connected Successfully' in msg:
state = AUTHENTICATING
ws.send(f'{{"action":"auth","params":"{API_KEY}"}}')
print('Authenticating....')
else:
print("FAILED TO CONNECT")
elif state == AUTHENTICATING:
if "authenticated" in msg:
state = SUBSCRIBING
ws.send(f'{{"action":"subscribe","params":"C.{FOREX_ASSET}"}}')
print(f'Subscribing to {FOREX_ASSET} ....')
else:
print("FAILED TO AUTHENTICATE")
elif state == SUBSCRIBING:
if "subscribed" in msg:
state = STREAMING
print('Streaming data ....')
else:
print("FAILED TO SUBSCRIBE")
def on_error(ws, err):
print(err)
def on_open(ws):
print('WebSocket connection opened.')
def on_close(ws):
print('WebSocket connection closed.')
state = CONNECTING
class WebSocketThread(QThread):
def __init__(self):
super().__init__()
self._ws = websocket.WebSocketApp(
WEBSOCKET_URL,
on_close=on_close,
on_message=on_message,
on_error=on_error,
on_open=on_open)
def run(self):
self._ws.run_forever()
if __name__ == '__main__':
app = QApplication([])
thread = WebSocketThread()
thread.start()
sys.exit(app.exec_())
WebSocket connection opened.
Authenticating....
Subscribing to EUR/USD ....
Streaming data ....
客户端代码:
import asyncio, websockets, time, json
CONNECTING, AUTHENTICATING, SUBSCRIBING, STREAMING = range(4)
state = CONNECTING
timestamp = 0
async def polygon_io_simulator(websocket, path):
global state, timestamp
while True:
if state == STREAMING:
ask_price = 0.0
bid_price = 1.0
response = [{
"t": timestamp,
"a": ask_price,
"b": bid_price,
}]
#await websocket.recv()
await websocket.send(json.dumps(response))
timestamp += 1
elif state == CONNECTING:
await websocket.send("Connected Successfully")
state = AUTHENTICATING
elif state == AUTHENTICATING:
await websocket.recv()
await websocket.send('authenticated')
state = SUBSCRIBING
elif state == SUBSCRIBING:
data = await websocket.recv()
print(data)
await websocket.send('subscribed')
state = STREAMING
#time.sleep(0.05)
start_server = websockets.serve(polygon_io_simulator, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
import websocket
#websocket.enableTrace(True)
import os, json, sys
from datetime import datetime
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication
API_KEY = os.environ['POLYGON_IO_APIKEY']
FOREX_ASSET = 'EUR/USD'
WEBSOCKET_URL = 'ws://localhost:8000' # wss://socket.polygon.io/forex
START, CONNECTING, AUTHENTICATING, SUBSCRIBING, STREAMING = range(5)
state = START
def on_message(ws, msg):
global state, curve, data_x, data_y, widget
if state == STREAMING:
# Realtime data plot. Each time this function is called, the data display is updated
json_data = json.loads(msg)[0]
mid_price = (json_data['a'] + json_data['b'])/2.0
print(mid_price)
elif state == CONNECTING:
if 'Connected Successfully' in msg:
state = AUTHENTICATING
ws.send(f'{{"action":"auth","params":"{API_KEY}"}}')
print('Authenticating....')
else:
print("FAILED TO CONNECT")
elif state == AUTHENTICATING:
if "authenticated" in msg:
state = SUBSCRIBING
ws.send(f'{{"action":"subscribe","params":"C.{FOREX_ASSET}"}}')
print(f'Subscribing to {FOREX_ASSET} ....')
else:
print("FAILED TO AUTHENTICATE")
elif state == SUBSCRIBING:
if "subscribed" in msg:
state = STREAMING
print('Streaming data ....')
else:
print("FAILED TO SUBSCRIBE")
def on_error(ws, err):
print(err)
def on_open(ws):
print('WebSocket connection opened.')
def on_close(ws):
print('WebSocket connection closed.')
state = CONNECTING
class WebSocketThread(QThread):
def __init__(self):
super().__init__()
self._ws = websocket.WebSocketApp(
WEBSOCKET_URL,
on_close=on_close,
on_message=on_message,
on_error=on_error,
on_open=on_open)
def run(self):
self._ws.run_forever()
if __name__ == '__main__':
app = QApplication([])
thread = WebSocketThread()
thread.start()
sys.exit(app.exec_())
WebSocket connection opened.
Authenticating....
Subscribing to EUR/USD ....
Streaming data ....
客户端打印:
import asyncio, websockets, time, json
CONNECTING, AUTHENTICATING, SUBSCRIBING, STREAMING = range(4)
state = CONNECTING
timestamp = 0
async def polygon_io_simulator(websocket, path):
global state, timestamp
while True:
if state == STREAMING:
ask_price = 0.0
bid_price = 1.0
response = [{
"t": timestamp,
"a": ask_price,
"b": bid_price,
}]
#await websocket.recv()
await websocket.send(json.dumps(response))
timestamp += 1
elif state == CONNECTING:
await websocket.send("Connected Successfully")
state = AUTHENTICATING
elif state == AUTHENTICATING:
await websocket.recv()
await websocket.send('authenticated')
state = SUBSCRIBING
elif state == SUBSCRIBING:
data = await websocket.recv()
print(data)
await websocket.send('subscribed')
state = STREAMING
#time.sleep(0.05)
start_server = websockets.serve(polygon_io_simulator, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
import websocket
#websocket.enableTrace(True)
import os, json, sys
from datetime import datetime
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication
API_KEY = os.environ['POLYGON_IO_APIKEY']
FOREX_ASSET = 'EUR/USD'
WEBSOCKET_URL = 'ws://localhost:8000' # wss://socket.polygon.io/forex
START, CONNECTING, AUTHENTICATING, SUBSCRIBING, STREAMING = range(5)
state = START
def on_message(ws, msg):
global state, curve, data_x, data_y, widget
if state == STREAMING:
# Realtime data plot. Each time this function is called, the data display is updated
json_data = json.loads(msg)[0]
mid_price = (json_data['a'] + json_data['b'])/2.0
print(mid_price)
elif state == CONNECTING:
if 'Connected Successfully' in msg:
state = AUTHENTICATING
ws.send(f'{{"action":"auth","params":"{API_KEY}"}}')
print('Authenticating....')
else:
print("FAILED TO CONNECT")
elif state == AUTHENTICATING:
if "authenticated" in msg:
state = SUBSCRIBING
ws.send(f'{{"action":"subscribe","params":"C.{FOREX_ASSET}"}}')
print(f'Subscribing to {FOREX_ASSET} ....')
else:
print("FAILED TO AUTHENTICATE")
elif state == SUBSCRIBING:
if "subscribed" in msg:
state = STREAMING
print('Streaming data ....')
else:
print("FAILED TO SUBSCRIBE")
def on_error(ws, err):
print(err)
def on_open(ws):
print('WebSocket connection opened.')
def on_close(ws):
print('WebSocket connection closed.')
state = CONNECTING
class WebSocketThread(QThread):
def __init__(self):
super().__init__()
self._ws = websocket.WebSocketApp(
WEBSOCKET_URL,
on_close=on_close,
on_message=on_message,
on_error=on_error,
on_open=on_open)
def run(self):
self._ws.run_forever()
if __name__ == '__main__':
app = QApplication([])
thread = WebSocketThread()
thread.start()
sys.exit(app.exec_())
WebSocket connection opened.
Authenticating....
Subscribing to EUR/USD ....
Streaming data ....
因此,很明显,WebSocket在两侧都起作用。我的调试器说服务器正在重复访问STREAMING send()行,但是,我的客户端在on_消息
例程中没有接收到任何内容
这很奇怪