Search code examples
pythonif-statementtradingngrok

Flask TypeError - ngrok 500 internal ser error - repeat Python script - Missing IF return?


When a Webhook triggers (to open forex trade) ngrok to send a POST to execute an IF statement in my Python script, my script must be returning a invalid value to ngrok. The error given by ngrok is a 500 internal service error and my flask error is giving a "TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement." I only get the error when [] is delivered to the if x['positions']==[]: If another value is sent everything works as it should. The error is bad for me because it causing the POST to be repeatedly sent for a short time (~10 s?). This is bad for me because it is a trading bot. In a volatile market where the trade is executed in a few seconds I don't want the error to reopen a new trade after my target was hit. I'm open to either eliminating resending of the POST after an error or fundamental fixing the issue. I've tried to put returns everywhere but it doesn't seem to fix the issue. Open to any ideas! Thanks for any help!

Here is my script. The error likely lies within the If ['position'] function and again only occurs with [] is provided.

from actions import *
from flask import Flask, request, abort
import oandapyV20
import oandapyV20.endpoints.positions as positions
from exampleauth import exampleAuth


# Create Flask object called app.
app = Flask(__name__)


# Create root to easily let us know its on/working.
@app.route('/')
def root():
    return 'online'


@app.route('/webhook', methods=['POST'])
def webhook():
    if request.method == 'POST':
        accountID, access_token = exampleAuth()
        api = oandapyV20.API(access_token=access_token)
        client=oandapyV20.API(access_token)
        r=positions.OpenPositions(accountID)
        x=client.request(r)
        if x['positions']==[]:
            data = parse_webhook(request.get_data(as_text=True))
            sell=data['side']
            if data['side']=='sellEURAUD':
                exec(open("marketTPSLEURAUDv2sell.py").read())
            elif data['side']=='buyEURAUD':
                exec(open("marketTPSLEURAUDv2buy.py").read())
            elif data['side']=='buyUSDCAD':
                exec(open("marketTPSLUSDCADv2buy.py").read())
            elif data['side']=='sellUSDCAD':
                exec(open("marketTPSLUSDCADv2sell.py").read())
            elif data['side']=='buyEURUSD':
                exec(open("marketTPSLEURUSDv2buy.py").read())
            elif data['side']=='sellEURUSD':
                exec(open("marketTPSLEURUSDv2sell.py").read())
            else:
                return'okay'
        else:
            return 'okay'
    else:
        return 'okay'

if __name__ == '__main__':
    app.run()
else: return 'okay'

Solution

  • If any of your execs is called, no return is executed. Not clear how you would want to remedy that.