o
    ̿Si\	                     @   s   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	m
Z
mZmZmZmZ eeZe  Zddeddfd	d
ZdS )    N)datetime)get_mongo_db))close_paper_trades_for_intraday_time_exit)backend_market_windowformat_windowis_backend_market_hours	local_nowlocal_time_strnext_backend_market_open_localseconds_until<   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 [ t }t }t|}zt||d}W z|  W n tyv   Y nw z|  W w  ty   Y w w |drt|dpd	d	krt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)zForce-close OPEN paper trades at PAPER_TRADE_END.

    This runs only during the backend market window (BACKEND_MARKET_START/END).
       Nz/[PaperIntradayExit] Loop started (interval=%ss)TzD[PaperIntradayExit] Backend skipped due to time | now=%s | window=%s)now_utcranclosedr   zL[PaperIntradayExit] Paper trade force-closed at 15:00 | closed=%s scanned=%sscannedz$[PaperIntradayExit] Unexpected error)asynciosleeploggerinfointr   r
   r	   r   r   r   r   _INTRADAY_EXIT_LOCKlockedr   utcnowr   nextr   close	Exceptionget	exception)r   nxtnowdb_gendbres r&   C/var/www/html/Trade-python/app/v1/background/paper_intraday_exit.pypaper_intraday_exit_loop   sb    (r(   )r   )r   loggingr   app.db.databaser   app.v1.services.paper_tradingr   app.v1.utils.market_timer   r   r   r   r	   r
   r   	getLogger__name__r   Lockr   r   r(   r&   r&   r&   r'   <module>   s    $
