o
    ̿Si                     @   s   U d dl Z d dlZd dlmZ d dlmZ d dlmZ d dlmZm	Z	 d dl
mZmZmZmZmZmZmZ eeZe  Zdaee ed< dd	ed
dfddZdS )    N)datetime)Optional)get_mongo_db)close_paper_trades_for_eod_paper_day_key)backend_market_windowformat_windowis_backend_market_hours	local_nowlocal_time_strnext_backend_market_open_localseconds_until_LAST_RUN_DAY<   interval_secondsreturnc                    s  t dI dH  tdt|  	 zt s?t }tdt tt	  |dur5t t
t |I dH  nt | I dH  W qt rMt | I dH  W qt4 I dH o t }t|}t|krtt | I dH  	 W d  I dH  W qt }t|}zt||d}W z|  W n ty   Y nw z|  W w  ty   Y w w |dr|atd||d	|d
 W d  I dH  n1 I dH sw   Y  W n ty   td Y nw t | I dH  q)a?  Close all intraday paper trades at EOD (IST).

    Why this exists:
    - The per-symbol update loop closes trades only when a candle update arrives.
    - If candle updates stop before cutoff or symbols go quiet, trades can remain OPEN.

    This loop is DB-only. It runs once per day after the configured cutoff.
       Nz&[PaperEOD] Loop started (interval=%ss)Tz;[PaperEOD] Backend skipped due to time | now=%s | window=%s)now_utcranz=[PaperEOD] Closed trades at EOD | day=%s closed=%s scanned=%sclosedscannedz[PaperEOD] Unexpected error)asynciosleeploggerinfointr	   r   r   r   r   r   r
   	_EOD_LOCKlockedr   utcnowr   r   r   nextr   close	Exceptionget	exception)r   nxtnowday_keydb_gendbres r*   9/var/www/html/Trade-python/app/v1/background/paper_eod.pypaper_eod_loop   sp   

(r,   )r   )r   loggingr   typingr   app.db.databaser   app.v1.services.paper_tradingr   r   app.v1.utils.market_timer   r   r	   r
   r   r   r   	getLogger__name__r   Lockr   r   str__annotations__r   r,   r*   r*   r*   r+   <module>   s   
 $

