robcarver17 / pysystemtrade

Systematic Trading in python
GNU General Public License v3.0
2.66k stars 837 forks source link

/reconcile Endpoint Fails on Second and Subsequent Requests #1388

Open craigmediaservices opened 4 months ago

craigmediaservices commented 4 months ago

I have encountered an issue with the /reconcile endpoint in the Dashboard. The endpoint works correctly on the first request but fails to load on the second and subsequent requests.

Steps to Reproduce:

from flask import Flask
import asyncio

app = Flask(__name__)

# Global variable to store the cached result
cached_result = None

@app.route("/reconcile")
def reconcile():
    global cached_result  # Use the global variable

    # Check if we have a cached result
    if cached_result is not None:
        return cached_result

    retval = {"gateway_ok": True}
    try:
        asyncio.set_event_loop(asyncio.new_event_loop())
        retval["optimal"] = reporting_api.table_of_optimal_positions().Body
        retval["ib"] = reporting_api.table_of_ib_positions().Body
        retval["my"] = reporting_api.table_of_my_positions().Body

        # Reindex the position dataframes
        retval["ib"].set_index(
            ["instrument_code", "contract_date"], inplace=True, drop=False
        )
        retval["my"].set_index(
            ["instrument_code", "contract_date"], inplace=True, drop=False
        )
    except:
        # IB gateway connection failed
        retval["gateway_ok"] = False
    if "optimal" in retval["optimal"].columns:
        retval["optimal"]["optimal"] = retval["optimal"]["optimal"].astype(str)

    retval = dict_of_df_to_dict(retval, orient="index")

    # Cache the result
    cached_result = retval

    return retval

Specifically it's hanging on retval["ib"] = reporting_api.table_of_ib_positions().Body

I can't replicate the issue manually in Python, but seems to be specifically with the Flask application.