fix: fetch klines synchronously before returning response

The background task wasn't completing before the response was returned.
Now we fetch klines synchronously (await) before returning the simulation.
This commit is contained in:
shokollm
2026-04-12 03:51:03 +00:00
parent 384f84e772
commit 13e899c851

View File

@@ -117,6 +117,12 @@ async def start_simulation(
settings = get_settings() settings = get_settings()
simulation_id = str(uuid.uuid4()) simulation_id = str(uuid.uuid4())
# Create AVE client for klines fetching
ave_client = AveCloudClient(
api_key=settings.AVE_API_KEY,
plan=settings.AVE_API_PLAN,
)
simulation_config = { simulation_config = {
"bot_id": bot_id, "bot_id": bot_id,
"token": config.token, "token": config.token,
@@ -145,16 +151,9 @@ async def start_simulation(
db.commit() db.commit()
db.refresh(simulation) db.refresh(simulation)
# Fetch klines synchronously first so user can see the chart immediately # Fetch klines SYNCHRONOUSLY so user can see chart immediately
# Then run simulation in background for signal processing
async def fetch_klines_and_run():
try: try:
# Fetch klines for chart display
token_id = f"{config.token}-{config.chain}" token_id = f"{config.token}-{config.chain}"
ave_client = AveCloudClient(
api_key=settings.AVE_API_KEY,
plan=settings.AVE_API_PLAN,
)
klines_data = await ave_client.get_klines( klines_data = await ave_client.get_klines(
token_id, token_id,
interval=config.kline_interval, interval=config.kline_interval,
@@ -164,23 +163,18 @@ async def start_simulation(
{"time": k.get("time"), "close": k.get("close")} {"time": k.get("time"), "close": k.get("close")}
for k in sorted(klines_data, key=lambda x: x.get("time", 0)) for k in sorted(klines_data, key=lambda x: x.get("time", 0))
] ]
# Update simulation with klines
# Save klines to DB immediately simulation.klines = klines_for_chart
db = SessionLocal()
try:
sim = db.query(Simulation).filter(Simulation.id == simulation_id).first()
if sim:
sim.klines = klines_for_chart
db.commit() db.commit()
finally: db.refresh(simulation)
db.close() logger.info(f"Fetched {len(klines_for_chart)} klines for simulation {simulation_id}")
# Now run the full simulation in background
run_simulation_sync(simulation_id, str(settings.DATABASE_URL), bot_id, simulation_config)
except Exception as e: except Exception as e:
logger.error(f"Failed to fetch klines: {e}") logger.error(f"Failed to fetch klines: {e}")
background_tasks.add_task(fetch_klines_and_run) # Run simulation in background for signal processing
background_tasks.add_task(
run_simulation_sync, simulation_id, str(settings.DATABASE_URL), bot_id, simulation_config
)
return simulation return simulation