起初,我能够使用异步流式处理示例输出到控制台。
接下来,我根据网上的各种资料和ChatGPT,使用Python Web Framework的tornado和chart.js创建了server.py(*2)和client.html(*3)
但是,当我运行 server.py 并打开 client.html 时,它没有响应。 况且我看polygon dashboard的时候,原来是连不上
问题。 (*2) 中的代码有什么问题?
(*1) https://github.com/pssolanki111/polygon -> 异步流示例
import asyncio
import polygon
from polygon.enums import StreamCluster
async def stock_trades_handler(msg): # it is possible to create one common message handler for different services.
print(f'msg received: {msg}')
async def main():
api_key = 'YOUR_KEY'
stream_client = polygon.AsyncStreamClient(api_key, StreamCluster.STOCKS)
await stream_client.subscribe_stock_trades(['AMD', 'NVDA'], stock_trades_handler)
while 1:
await stream_client.handle_messages() # the lib provides auto reconnect functionality. See docs for info
if __name__ == '__main__':
asyncio.run(main())
(*2) 服务器.py
import tornado.ioloop
import tornado.web
import tornado.websocket
import os
import polygon
from polygon.enums import StreamCluster
class StockTradesHandler(tornado.websocket.WebSocketHandler):
async def open(self):
print('WebSocket opened')
self.ioloop = tornado.ioloop.IOLoop.instance()
api_key = os.environ.get('POLYGON_API')
stream_client = polygon.AsyncStreamClient(api_key, StreamCluster.STOCKS)
await stream_client.subscribe_stock_trades(['AMD', 'NVDA'], self.stock_trades_handler)
while not self.ws_connection.closed:
await stream_client.handle_messages()
def on_message(self, message):
pass
async def stock_trades_handler(self, msg):
print(f'msg received: {msg}')
await self.write_message(msg)
def on_close(self):
print('WebSocket closed')
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/stocktrades", StockTradesHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
(*3) 客户端.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Real-time Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'AMD',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
data: []
}]
},
options: {
responsive: true,
scales: {
xAxes: [{
type: 'time',
distribution: 'linear',
time: {
unit: 'second',
displayFormats: {
second: 'h:mm:ss a'
}
}
}]
}
}
});
var ws = new WebSocket("ws://localhost:8888/ws");
ws.onmessage = function (event) {
var msg = JSON.parse(event.data);
if (msg.sym == "AMD") {
chart.data.labels.push(new Date(msg.t));
chart.data.datasets[0].data.push(msg.p);
chart.update();
}
};
</script>
</body>
</html>