o
    xöújJ  ã                   @   s  d Z ddlZddlmZmZ ddlmZ ddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZe d¡ZedƒZeeee	e
eedœZdZi i i d	d
dœdddddœddddœdœg d¢ddddddddddddœdddd œddd!dd"d#œd$œZd%d&„ ZG d'd(„ d(ƒZdS ))a"  
ev3.py -- [2026-10-23] ENTRY VERSION 3 (EV3) for the trade bot, the user's decision: "retire the trade bot for now and replace it
with EV3". Live from Monday 10/26 (paper). config.json -> smart_engine.entry_mode "ev3" + section "ev3". Revert: entry_mode "v2".
ENTRIES = the user's chart setups (built from the practice charts, tested on 2 years with the give-back exit):
  R3   opening push -> first pullback holds -> turn      ONLY stocks with daily ATR 6-10% (2y: +0.153%/trade, y1 +0.167 y2 +0.142)
  R1A  fast double bottom after a flush                  (2y: +0.076%/trade, +0.067 / +0.085)
  R4   runner's second leg after the base                (2y: +0.129%/trade, +0.002 / +0.201)
  R1B  undercut & reclaim after a flush (PEPG deep V)    (rare: 24 trades in 2 years, mixed -- included for data)
  R1D  spring: the flush bar itself, buyers absorbing it (CERT 2/27/25) -- added 10/23 night, setting undercut 0.3%, volume 3x,
       buyers 45%; EXEMPT from the N2+N3 gate (2y C3: +0.328%/trade, y1 +0.355 / y2 +0.312, 61 trades; gated it lost)
  R1E  selling exhaustion at the low (RKT 2/28/25) -- added 10/23 night, setting 8 bars, 15-min buyers +10 points, 1.5x
       volume (2y C3: +0.786%/trade, y1 +0.717 / y2 +0.827, only 16 trades)
  R7 is left out (to be improved); R5 / R8 / R9 / R1 / R2 / R6 lost with every exit.
  Each setup is checked once per FINISHED minute on the stream's bars and per-minute buy/sell flow (the same code the 2-year
  test ran: r1a_setup / r1b_setup / r3_setup / r4_setup), with its own cool-down per stock.
STOP = under the setup's own support (support x (1 - stop_buf)), clamped to stop_min_pct..stop_max_pct under the price.
EXIT = the 1/4 GIVE-BACK: nothing but the stop until the peak since the buy is >= arm_pct above the buy; then sell when the
  price falls to peak - giveback x (peak - buy) while it is falling (price under the last finished close). 15:55 by the bot.
NO-TRADE gate (2026-10-23, the user after QBTS 2/24/25; tested on the 833 2-year EV3 buys, live give-back exit: -0.052%/trade
  -> +0.018%, y1 +0.016 / y2 +0.020, 535 kept; the 298 blocked averaged -0.178%): a setup's buy is NOT taken when
    N2  the trigger bar closes under the previous day's low, or
    N3  the 15-min buy share (trigger minute + 14 before) is under 45%.
  A blocked trigger still starts that setup's cool-down (as in the test).
E1 (2026-10-23, the user's sell block from JOBY 10/23/24 + DERM 11/5/24; tested as "E2et" on the 833 2-year EV3 buys:
  give-back alone -0.052%/trade -> +0.096%, y1 +0.227 / y2 -0.009): when the give-back fires, E1 OVERRIDES it (holds) while
    buyers are in control: 5-min buy share >= 50% AND NOT the last 2 finished minutes both "seller minutes" (1-min buy share
    < 40% on volume >= 0.5x the 15-bar average -- a lone small print is not a seller minute), OR
    the dip is noise: peak - last finished close < 2 x the mean 1-min range of the last 15 bars.
  Re-checked every finished minute; when E1 stops holding and the give-back is still true -> sell. Never overrides the stop;
  never holds once the price is at/under the buy price. Reads finished bars + per-minute flow only.
C3 EXIT CONTROLLER (2026-10-23, the user: TTGT 6/4/25 X1 right +11.7% vs GB2 +2.9%; SVIA 6/16/25 GB2 right +3.4% vs X1 -0.1%;
  2y no look-ahead on the 535 N2+N3-kept buys: GB2 +0.108%/trade -> C3 +0.166%, y1 +0.345 / y2 +0.022; X1 took control 37x).
  When the GB2 give-back first wants to sell, X1 (exit_x1.py: stall at the top / fade into resistance / break-even after +2%)
  TAKES CONTROL instead when the gain was made BY BUYERS (finished bars only): buy share of all minutes since the buy >= 55%,
  the 15-min buy share higher than before the buy, no single bar made > 60% of the peak gain, and the dip bar's volume <= its
  15-bar average. From then on only X1 (checked once per finished minute) or the stop sells.
OPTION 3 (2026-10-25, the user): only R3 BUYS, with the per-setup gates "gates": ["A3", "A20"] (A3 = RVOL so far < 1.5x the
  14-day volume by minute; A20 = opened 0.5-3% under the previous close) -- the only combination positive in BOTH 2016-18 (out of
  sample, +4.7%) and 2024-26 (+8.1%). R1A R1D R1E R4 are "record_only": their buys are logged ([EV3] RECORD ONLY), not taken,
  and they do not take the minute from R3.
DV1 (2026-11-16, the user): deep-V FIRST cross of the day (rules note RN-13 plain, dv1_setup.py), buys next to R3 with the same
  exit; exempt from the N2+N3 no-trade gate. 2y entry-only below cost, EV3 exit on it untested. Off: setups.DV1.enabled false.
Pure logic + per-symbol state; no orders (monitor.py / position_manager.py place them).
é    N)ÚdatetimeÚtimezone)ÚZoneInfoztrade_bot.ev3zAmerica/New_York)ÚR1AÚR1BÚR3ÚR4ÚR1DÚR1EÚDV1)ÚenabledÚatr_minÚatr_maxÚno_trade_exemptÚ_noteÚgatesÚrecord_onlyg      @g      $@)r   r   g333333Ó?g      @gÍÌÌÌÌÌÜ?T)Úundercut_pctÚheavy_xÚ	absorb_bsr   é   gš™™™™™¹?ç      ø?)Úbleed_nÚdiv_upÚbleed_x)r   r   r   r   r	   r
   )r   r   r	   r
   r   r   g      ð?g      Ð?gü©ñÒMb`?ç      à?g      @ih  gš™™™™™á?g333333ã?)r   Úrun_bsÚ	spike_maxÚrising15Ú	light_dip)r   Úbelow_prev_lowÚmin_bs15gš™™™™™Ù?g       @)r   Úbs5_minÚ	seller_bsÚthin_xÚnoise_k)ÚsetupsÚorderÚarm_pctÚgivebackÚstop_bufÚstop_min_pctÚstop_max_pctÚlast_entry_minuteÚ
controllerÚno_tradeÚe1c                 C   s:   t | tƒst | tj¡} |  t¡} | jd d | j d S )Né	   é<   é   )	Ú
isinstancer   Úfromtimestampr   ÚutcÚ
astimezoneÚETÚhourÚminute©Út© r=   ú/var/www/screener/trade/ev3.pyÚ	minute_ofK   s   

r?   c                   @   s`   e Zd Zddd„Zdd„ Zedd„ ƒZdd	„ Zd
d„ Zedd„ ƒZ	dd„ Z
ddd„Zdd„ ZdS )ÚEV3Nc                 C   sº   i t ¥|pi ¥}i t d ¥|pi  d¡pi ¥|d< i t d ¥|p!i  d¡p&i ¥|d< i t d ¥|p2i  d¡p7i ¥|d< i t d ¥|pCi  d¡pHi ¥|d< || _i | _i | _i | _i | _d S )Nr&   r0   r/   r.   )ÚDEFAULTSÚgetÚcÚ_last_mÚ
_last_trigÚ_peakÚ_e1_last)ÚselfÚcfgrC   r=   r=   r>   Ú__init__S   s   """"
zEV3.__init__c                 C   s¶  |r|  d¡r|  d¡sdS dd„ |dd… D ƒ}t|ƒdk r!dS t|d d ƒ}| j  |¡|ks8|| jd	 kr:dS || j|< d
gd d
gd }}|D ](\}	}
t|	ƒ}d|  kr^dk rtn qL||  |
d 7  < ||  |
d 7  < qL||dœ}|d |d  d }| jd D �]N}| jd   |¡}|du sŸ|  d¡du r q‰d|v r«||d k r«q‰d|v r¶||d kr¶q‰t| }|| j  ||fd¡ |j  dd¡k rÍq‰z| ||||dd„ | 	¡ D ƒpÞd¡\}}W n! t
�y } zt d|› d|› d|› �¡ W Y d}~q‰d}~ww |�rØ|| j||f< |d d }|  d¡�rg n|  ||||¡}||  |  d ¡�p/g |||¡7 }|  d!¡�rlt d"|› d#|› d$|�rPd%d& |¡ d' nd(› d)|d* d+ d, › d-|d* d+ d.›d/|d0›d1�¡ q‰|�r–t d2|› d#|› d3|d* d+ d, › d-|d* d+ d.›d/|d0›d4d& |¡› �¡ q‰|  d5¡�p¬|  d6¡�p¥|d7 d| jd8   }tt||d| jd9 d   ƒ|d| jd: d   ƒ}||t|d;ƒ||t|dƒd<œ  S q‰dS )=zÈbars: the stream's bars (last one forming); min_flow: {minute bucket datetime: [buy, sell]};
        ref: reference.load(). -> None or {"setup", "info", "stop", "price", "m"} once per finished minute.Úatr14Ú
prev_closeNc                 S   ó0   g | ]}d t |d ƒ  krdk rn n|‘qS ©r   r<   é†  ©r?   ©Ú.0Úbr=   r=   r>   Ú
<listcomp>e   ó   0 z#EV3.entry_check.<locals>.<listcomp>éÿÿÿÿé   r<   r-   ç        rO   r   é   ©ÚbuyÚselléd   r'   r&   r   Fr   r   iñØÿÿÚcooldowné   c                 S   s   i | ]\}}|t vr||“qS r=   )ÚCONTROL_KEYS)rR   ÚkÚvr=   r=   r>   Ú
<dictcomp>   s    z#EV3.entry_check.<locals>.<dictcomp>z[EV3] ú z check failed: rC   r   r   r   z[EV3] RECORD ONLY z: z would zbe blocked (z; ú)r[   z at the r3   r2   r1   ú:Ú02dz bar close ú.4gz -- not tradedz[EV3] NO-TRADE z triggered at the z -- blocked: ÚstopÚsupportç®Gáz®ï?r*   r,   r+   é   )ÚsetupÚinfori   ÚpriceÚmÚatr)rB   Úlenr?   rD   rC   ÚMODSrE   rA   ÚcheckÚitemsÚ	ExceptionÚlogÚwarningr/   Úsetup_gatesrn   ÚjoinÚminÚmaxÚround)rH   ÚsymbolÚbarsÚmin_flowÚrefÚdonerp   ÚfbÚfsr<   rb   ra   ÚflowÚatrpÚnameÚscÚmodÚokrn   ÚeÚPÚntÚsupri   r=   r=   r>   Úentry_check`   sz   
(€
$,€þ  0ÿÿ
ÿ4ÿÿ.4"ñzEV3.entry_checkc           
      C   sò   g }dd„ |D ƒ}d| v rG|  d¡pg }t|ƒ|kr$t|d|d … ƒnd}|r3tdd	„ |D ƒƒ| nd}|durG|d
k rG| d|d›d�¡ d| v rw|rw|  d¡rw|d d |d  d d }	d|	  krjdkrwn |S | d|	d›d�¡ |S )zh[2026-10-25] per-setup do-not-trade gates -> reasons. A3: RVOL so far < 1.5x; A20: gap-down open 0.5-3%.c                 S   rM   rN   rP   rQ   r=   r=   r>   rT   ™   rU   z#EV3.setup_gates.<locals>.<listcomp>ÚA3Úvol_per_minNrY   r   c                 s   ó   � | ]}|d  V  qdS ©rb   Nr=   rQ   r=   r=   r>   Ú	<genexpr>�   ó   € z"EV3.setup_gates.<locals>.<genexpr>r   zA3 RVOL so far ú.2fzx < 1.5xÚA20rL   Úor]   éýÿÿÿg      à¿zA20 gap-down open z+.1fz#% (0.5-3% under the previous close))rB   rr   ÚsumÚappend)
r   r‚   r�   rp   ÚoutÚregÚvpmÚnormÚrvÚgapr=   r=   r>   ry   •   s   $ÿzEV3.setup_gatesc           
      C   sê   | j d }| d¡sg S g }| d¡r)| d¡r)||d k r)| d|d d›�¡ t|d td|d	 ƒ|d
 … ƒ}t|d td|d	 ƒ|d
 … ƒ}|| rU|||  nd}	| d¡durs|	|d k rs| d|	d›d|d d›�¡ |S )z3N2 / N3 -> list of reasons (empty = trade allowed).r/   r   r    Úprev_lowz N2 under the previous day's low rh   r[   r   é   rY   r\   r   r!   NzN3 15-min buy share ú.0%ú < )rC   rB   r›   rš   r|   )
rH   rŒ   r…   r�   rp   Úgrœ   ÚBÚSÚbs15r=   r=   r>   r/   ¦   s   

 DzEV3.no_tradec              	      sÐ  | j d ‰dd„ |D ƒ‰ˆ d¡rtˆƒdk rdS dgd dgd ‰‰|D ](\}}t|ƒ}d	|  kr8dk rNn q&ˆ|  |d	 7  < ˆ|  |d
 7  < q&‡‡fdd„‰‡fdd„‰ ‡ ‡‡‡fdd„}tˆƒd
 }tˆ| d ƒ}	ˆ|	dƒ}
||ƒo�||d
 ƒ}tdd„ ˆdd… D ƒƒtˆdd… ƒ }|ˆ| d  }|
ˆd kr°|s°dd|
d›d�fS |ˆd | k rÊdd|d›d ˆd d!›d"|d›�fS d#d$|
d›�|rÔd%nd& d'|d›d(ˆd d!›d)|d›� fS )*zJE1: (hold?, why) from the FINISHED regular-session bars + per-minute flow.r0   c                 S   rM   rN   rP   rQ   r=   r=   r>   rT   ¸   rU   zEV3.e1_hold.<locals>.<listcomp>r   é   )FzE1 offrX   rO   r   rY   c                    s\   t ˆ td| | d ƒ| d … ƒ}t ˆtd| | d ƒ| d … ƒ}|| r,|||  S dS )Nr   rY   r   ©rš   r|   )rp   Únr§   r¨   )rƒ   r„   r=   r>   ÚbsÀ   s   DzEV3.e1_hold.<locals>.bsc                    s8   ˆ t d| d ƒ| … }|rtdd„ |D ƒƒt|ƒ S dS )Nr   r_   c                 s   r’   r“   r=   ©rR   Úxr=   r=   r>   r”   Å   r•   z,EV3.e1_hold.<locals>.avgv.<locals>.<genexpr>)r|   rš   rr   )ÚiÚw)r‚   r=   r>   ÚavgvÃ   s   "zEV3.e1_hold.<locals>.avgvc                    s:   ˆt ˆ|  d ƒdƒˆd k oˆ|  d ˆd ˆ | ƒ kS )Nr<   rY   r#   rb   r$   rP   )r°   )r²   r­   r‚   r‹   r=   r>   ÚsellerÆ   s   :zEV3.e1_hold.<locals>.sellerr<   rW   c                 s   s    � | ]}|d  |d  V  qdS )ÚhÚlNr=   r®   r=   r=   r>   r”   Ê   s   € zEV3.e1_hold.<locals>.<genexpr>iñÿÿÿNrC   r"   Tz#buyers in control: 5-min buy share r¤   z, no 2 seller minutes in a rowr%   znoise: dip rh   r¥   r¦   z x 1-min range Fzbuyers gone: 5-min buy share z, 2 seller minutes in a rowÚ z; dip z >= z	 x range )rC   rB   rr   r?   rš   )rH   Ú	bars_doner€   Úpeakr<   rb   Úk_r³   ra   rp   Úb5ÚtwoÚrngÚdipr=   )r²   r­   r‚   r‹   rƒ   r„   r>   Úe1_holdµ   s0   
(€*$ÿzEV3.e1_holdc                 C   sv   dgd dgd }}| D ](\}}t |ƒ}d|  krdk r5n q||  |d 7  < ||  |d 7  < q||dœS )NrX   rO   r   rY   rZ   rP   )r€   rƒ   r„   r<   rb   r¹   r=   r=   r>   Ú_flow_arraysÓ   s   (€
zEV3._flow_arraysc                    sä  | j d }tˆƒd }|dk s||krdS dd„ ˆD ƒ}‡ fdd„}	|	|| || ƒ}
|
|d k r?d	d
|
d›d|d d›�fS |	|| d || ƒ|	||d  d ||d  ƒ}}| d¡rp||kspd	d|d›d|d›d�fS ‡fdd„t|d |d ƒD ƒˆ| d | g }|| dks›t|ƒ|d ||  kr°d	d||kr©t|ƒ||  ndd›d�fS ˆtd|d ƒ|… }| d¡r×|r×ˆ| d tdd„ |D ƒƒt|ƒ kr×dS dd|
d›d |d›d|d›d!t|ƒ||  d›d"�	fS )#zhC3: does X1 take control? reg = finished regular-session bars, bi = index of the buy bar. -> (bool, why)r.   rY   )Fz	too earlyc                 S   s   g | ]}t |d  ƒ‘qS r;   rP   rQ   r=   r=   r>   rT   â   s    z#EV3.c3_controls.<locals>.<listcomp>c                    sT   t ˆ d td| ƒ|d … ƒ}t ˆ d td| ƒ|d … ƒ}|| r(|||  S dS )Nr[   r   rY   r\   r   r«   )Úm0Úm1r§   r¨   )r…   r=   r>   r­   ã   s   <zEV3.c3_controls.<locals>.bsr   Fzrun buy share r¤   r¥   r£   r   z15-min buy share not rising (z -> re   c                    s(   g | ]}ˆ | d  ˆ |d  d   ‘qS )rC   rY   r=   )rR   r°   )r�   r=   r>   rT   ì   s   ( rC   r   r   za spike: one bar made z of the gainr_   r   rb   c                 s   r’   r“   r=   r®   r=   r=   r>   r”   ð   r•   z"EV3.c3_controls.<locals>.<genexpr>)Fzthe dip bar is heavyTzbuyers made the run: z! buy share since the buy, 15-min z, biggest bar z of the gain, light dip)rC   rr   rB   Úranger|   rš   )rH   r�   r…   ÚentryÚbir¸   r¦   ra   Úminsr­   ÚrunÚb15Úb15_0Úupsr±   r=   )r…   r�   r>   Úc3_controlsÜ   s*   
62$*4
ÿzEV3.c3_controlsr=   c                    s~  |d |  d¡p|d d }}| j  |¡}|r"|  d¡|  d¡kr/|  d¡|dœ }| j|< |  d¡r;t |d ¡nd‰ |dd… }	‡ fdd	„|	D ƒ}
|
r^t|d
 tdd„ |
D ƒƒƒ|d
< ||krwdd|d›d|d›d|  dd¡› d�dfS |  d¡dkrÜdd	„ |	D ƒ}|rÑ|  d¡t|d d ƒkrÑt|d d ƒ|d< t‡ fdd„t|ƒD ƒdƒ}|durÑt 	||  
|¡||¡\}}|rÑdd|› d|  d¡› d�| d¡fS t|d
 |ƒ|d
< d S |d
 | }||| jd!  d" k�r4|	�r4|d
 | jd# |  }||k�r4||	d d$ k �r4d%|d
 d›d&|| d" d'›d(|d›d|d›d)td*| jd#  ƒ› d+�}| jd,   d-¡�r³z.d.d	„ |	D ƒ}t‡ fd/d„t|ƒD ƒdƒ}|du�r_|  ||  
|¡|||d
 ¡nd0\}}W n t�y€ } zd1d2|› d�}}W Y d}~nd}~ww |�r³d|d< |d d  t¡d3›|d< t|d d ƒ|d< t d4|› d5|› d6|d›d7|› �¡ d S ||k�r/z|  |	||d
 ¡\}}W n t�yá } zd1d8|› d�}}W Y d}~nd}~ww t|	d d ƒ}|�r| j  |¡|dfk�r|df| j|< t d9|› d5|› d:|d›d;|› �¡ d S | j  |d<¡d* �r(| d=d>¡d?|› � }| j |d¡ d|d1fS t|d
 |ƒ|d
< d S )@zm-> (should_exit, reason, is_risk_exit). pos: position_manager position (entry_price, stop_price, entry_time).Úentry_priceÚ
stop_pricerk   Ú
entry_time)rÍ   r¸   NrV   c                    s.   g | ]}ˆ d u s|d ˆ j ddd�kr|‘qS ©Nr<   r   )ÚsecondÚmicrosecond©ÚreplacerQ   ©Úetr=   r>   rT   ý   s   . z"EV3.exit_check.<locals>.<listcomp>r¸   c                 s   r’   )r´   Nr=   rQ   r=   r=   r>   r”   ÿ   r•   z!EV3.exit_check.<locals>.<genexpr>Tz
EV3 stop: rh   z <= z (under the Ú	ev3_setuprm   z	 support)ÚmodeÚX1c                 S   rM   rN   rP   rQ   r=   r=   r>   rT     rU   Úx1_mr<   c                 3   ó6   � | ]\}}ˆ d u s|d ˆ j ddd�kr|V  qd S rÎ   rÑ   ©rR   r°   rS   rÓ   r=   r>   r”     ó   €4 zEV3 z (X1 had control since Úx1_sincere   zX1 break-even)Fr¶   Fr(   r]   r)   rC   zEV3 give-back: peak z (+r–   z
%), price z (1/rY   z given back)r.   r   c                 S   rM   rN   rP   rQ   r=   r=   r>   rT     rU   c                 3   rÙ   rÎ   rÑ   rÚ   rÓ   r=   r>   r”     rÛ   )Fr¶   FzC3 failed (z%H:%Mz[EV3] C3: X1 TAKES CONTROL of z @ z instead of the give-back (z) -- zE1 failed (z[EV3] E1 HOLD z: give-back level z touched, held -- )NFzEV3 give-backzEV3 give-back after E1 releasedz | )rB   rF   r   Úfromisoformatr|   r?   ÚnextÚ	enumerateÚexit_x1rt   r¿   Ú
startswithrC   r}   rÊ   rv   r7   r8   rw   rn   r¾   rG   rÒ   Úpop)rH   r~   Úposr   ro   r€   rÃ   ri   Ústr‚   Úsincer�   rÄ   r\   ÚwhyÚgainÚlvlÚgbÚtookÚcwhyÚexr´   Úmkr=   rÓ   r>   Ú
exit_checkõ   s„     *$ÿÿÿ2€ÿ"$
€ÿ$
zEV3.exit_checkc                 C   s    | j  |d ¡ | j |d ¡ d S ©N)rF   râ   rG   )rH   r~   r=   r=   r>   Úforget2  s   z
EV3.forgetrï   )r=   )Ú__name__Ú
__module__Ú__qualname__rJ   r�   Ústaticmethodry   r/   r¾   r¿   rÊ   rî   rð   r=   r=   r=   r>   r@   R   s    
5


=r@   )Ú__doc__Úloggingr   r   Úzoneinfor   Ú	r1a_setupÚ	r1b_setupÚr3_setupÚr4_setupÚ	r1d_setupÚ	r1e_setupÚ	dv1_setuprà   Ú	getLoggerrw   r8   rs   r`   rA   r?   r@   r=   r=   r=   r>   Ú<module>   s:    ,

þ

÷