[英]Keeping an always-running ib_insync connection with Sanic
我正在开发一个 API(使用 Sanic),它是通往 IB 的网关,使用 ib_insync 这个 API 公开端点以下新订单并获得实时头寸,但也负责使用 ib_insync 事件更新数据库中的订单状态.
我的问题是 - 是否可以让 API 在 IB 启动时仅连接一次,并对所有请求重新使用相同的连接?
我目前在每个请求上都使用connectAsync
连接到 IB。 虽然这正在工作 - 如果当前未处理请求,API 将不会接收事件。
这是一个端点代码,供参考
@app.post("/order/<symbol>")
async def post_order(request, symbol):
order = jsonpickle.decode(request.body)
with await IB().connectAsync("127.0.0.1", 7496, clientId=100) as ib:
ib.orderStatusEvent += onOrderStatus
ib.errorEvent += onTWSError
ib.newOrderEvent += onNewOrderEvent
contract = await ib.qualifyContractsAsync(contract)
trade = ib.placeOrder(contract[0], order)
return text(trade.order.orderId)
所以我希望不使用with
语句,而只使用全局 ib 连接。
当我在模块 init 上连接时(使用connectAsync
),以后的每个异步调用(例如qualifyContractsAsync
)都会挂起。 调试显示它挂在asyncio.gather
上,这意味着我在事件循环上做错了。
我不熟悉这种特殊的联系,但是应该是可能的。 大概with
语句是打开和关闭连接。
相反,请使用侦听器打开和关闭它。
@app.before_server_start
async def connect(app,_):
app.ctx.foo = await Foobar()
@app.route("/")
async def handler(request):
await request.app.ctx.foo.do_something()
@app.after_server_stop
async def close(app,_):
app.ctx.foo.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.