I'm writing an API using ib_insync, Sanic and ngrok to forward webhook signals from Tradingview onto Interactive Brokers. It works on only the first attempt and the following error is thrown preventing any further orders:
[ERROR] Exception occurred while handling uri: 'http://url.ngrok.io/webhook' Traceback (most recent call last): File "handle_request", line 103, in handle_request "_future_listeners", sanic.exceptions.ServerError: Invalid response type None (need HTTPResponse)
The code is as follows:
from datetime import datetime
from sanic import Sanic
from sanic import response
from ib_insync import *
#Create Sanic object
app = Sanic(__name__)
app.ib = None
#Create root
@app.route('/')
async def root(request):
return response.text('online')
#Listen for signals and execute orders
@app.route('/webhook', methods=['POST'])
async def webhook(request):
if request.method == 'POST':
await checkIfReconnect()
#Parse alert data
alert = request.json
order = MarketOrder(alert['action'],alert['quantity'],account=app.ib.wrapper.accounts[0])
#Submit market order
stock_contract = Stock('NVDA','SMART','USD')
app.ib.placeOrder(stock_contract,order)
#Reconnect if needed
async def checkIfReconnect():
if not app.ib.isConnected() or not app.ib.client.isConnected():
app.ib.disconnect()
app.ib = IB()
app.ib.connect('127.0.0.1',7496,clientId=1)
#Run app
if __name__ == '__main__':
#Connect to IB
app.ib = IB()
app.ib.connect('127.0.0.1',7496,clientId=1)
app.run(port=5000)