
    HYj                    H   d 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mZm	Z	 ddl
mZ  ed          Zedz  Zedz  Ze                    d	d	
           edz  Zedz  Zd                                ZddZddZddZd dZd!dZedk    r e e                      dS )"a9  Continuous Hermes one-shot worker for XAUUSD hybrid M5 OHLCV collection only.

The parent process never reads or prints raw OHLCV. Each child run must save raw bars
straight into hybrid/data/ohlcv_M5.json and return only a compact statistical/progress
summary, so the parent/current chat only receives summaries.
    )annotationsN)datetimetimezone)Pathz9/home/aryy/.hermes/profiles/finance/backtests/xauusd_2026zhybrid/collector_state.jsonzhybrid/reportsT)parentsexist_okzm5_collector.logzhybrid/m5_collector.locka
  
You are Aryy Finance M5 data collector. Process exactly ONE pending XAUUSD M5 OHLCV chunk for the hybrid backtest, save raw data to file, summarize via Python/statistics only, then stop.

Project directory: /home/aryy/.hermes/profiles/finance/backtests/xauusd_2026
Collector state: hybrid/collector_state.json
Scope: M5 ONLY. Do not collect M15/D/H4/M30/H1/W. Do not run scanner/backtest. Do not write trades/candidates/reviews.

Critical privacy/context rule from Aryy:
- Do NOT include raw OHLCV bars in the final answer.
- Save raw bars to hybrid/data/ohlcv_M5.json.
- Send back only summary statistics/progress: chunk id, range, kept bar count, output total bars, first/last output time, remaining M5 chunks, and any concise error.

Process:
1. Read hybrid/collector_state.json.
2. Find the first chunk where suffix='M5' and (status='pending' OR status='failed' with attempts < 3).
3. If no such M5 chunk exists, update collector_state.status_m5='complete' and final response 'M5 COMPLETE' with output total bars only.
4. Use TradingView MCP only:
   - chart_set_symbol OANDA:XAUUSD
   - chart_set_timeframe chunk.timeframe
   - chart_set_visible_range from=chunk.from to=chunk.to
   - data_get_ohlcv count=500 summary=false
5. Keep only bars with numeric time inside chunk.from..chunk.to plus one M5 tolerance (300 sec). Discard unrelated bars.
6. Merge kept bars into hybrid/data/ohlcv_M5.json. Preserve existing bars, dedupe by numeric time, sort ascending.
   Schema: {"metadata":{"symbol":"XAUUSD","timeframe":"M5","source":"tradingview_mcp_visible_range_chunks","start":"2026-01-01","end":"2026-07-17","bar_count":N,"first_time":...,"last_time":...,"last_updated":"UTC ISO"},"bars":[{"time":int,"timestamp":"UTC ISO","open":float,"high":float,"low":float,"close":float,"volume":number|null}]}
7. Update the chunk: attempts += 1, bars_collected = kept bar count, status='done' if kept bars > 0 else 'failed', last_error=null or concise reason.
8. Write/overwrite hybrid/reports/m5_processing_summary.json with statistical summary only: chunk counts, output bar count, first/last time, average/median range/body for saved M5 bars. Do this by Python script/terminal or equivalent, not by pasting raw bars.
9. Validate JSON for collector_state, ohlcv_M5.json (if exists), and m5_processing_summary.json with python3 -m json.tool.
10. Final response exactly one compact line, no raw bars.

Hard rules:
- Exactly ONE M5 chunk per child run.
- Do not use execute_code.
- Do not use screenshots/vision.
- Do not analyze strategy.
- Do not write data/journal.json, backtest-data, shadow-trades, candidates, or reviews.
- If MCP returns no in-range bars, mark only that chunk failed and stop; do not loop.
msgstrreturnNonec                ,   t          j        t          j                                                   d|  }t          |d           t                              dd          5 }|                    |dz              d d d            d S # 1 swxY w Y   d S )N T)flushazutf-8)encoding
)	r   nowr   utc	isoformatprintLOG_FILEopenwrite)r	   linefs      &hybrid/scripts/run_m5_mcp_collector.pylogr   @   s    l8<((2244<<s<<D	$d	sW	-	- 	t                 s   #B		BBdictc                 X    t          j        t                                                    S )N)jsonloadsSTATE	read_text     r   
load_stater&   G   s    :eoo''(((r%   statedict[str, int]c                    i }|                      dg           D ]N}|                     d          dk    r|                     dd          }|                     |d          dz   ||<   O|S )NchunkssuffixM5statusunknownr      get)r'   outcr-   s       r   	m5_countsr4   K   sr    CYYx$$ - -55??d""x++ggfa((1,FJr%   boolc                    d |                      dg           D             }t          |          ot          d |D                       S )Nc                D    g | ]}|                     d           dk    |S )r+   r,   r0   .0r3   s     r   
<listcomp>zm5_complete.<locals>.<listcomp>V   s,    	H	H	Hh40G0G!0G0G0Gr%   r*   c              3  H   K   | ]}|                     d           dk    V  dS )r-   doneNr0   r8   s     r   	<genexpr>zm5_complete.<locals>.<genexpr>W   s1      BB!AEE(OOv5BBBBBBr%   )r1   r5   all)r'   m5s     r   m5_completer@   U   sK    	H	HUYYx,,	H	H	HB88BBBrBBBBBBr%   intc                 x   t          j        t                     t                                          r^	 t          j        t                                          pd          } n# t          $ r i } Y nw xY wt          dt           d|  d           dS t          
                    t          j        t          j        t          j                                                  t          j                    dd          dz              	 d	}	 t%                      }t'          |          }t          d|            t)          |          rt          d           d|d<   t          j        t          j                                      d	                                                              dd          |d<   t,          
                    t          j        |d          dz              	 	 t                              d
           d	S # t          $ r}t          d|            Y d }~d	S d }~ww xY w|dz  }t          d|            t           j                                        }d|d<   ddddddt4          g}t7          j        |t;          t                    |d
d
d           }t          d!|j                    |j                                         rEt          d"|j                                                             dd#          d$d          z              |j!                                         rEt          d%|j!                                                             dd#          d$d          z              |j        d	k    r[t          d&           |j        	 t                              d
           S # t          $ r}t          d|            Y d }~S d }~ww xY wtE          j#        d           # 	 t                              d
           w # t          $ r}t          d|            Y d }~w d }~ww xY wxY w)'Nz{}zLOCK_EXISTS r   z&; exiting to avoid duplicate M5 worker   )
started_atpid)indentr   r   Tz	M5_STATE zM5_COMPLETE all M5 chunks donecomplete	status_m5)microsecondz+00:00Zm5_completed_at)
missing_okzLOCK_REMOVE_ERROR r/   zRUN_M5_CHUNK iteration=financeHERMES_PROFILEhermesz
--providerzcustom:9routerz--modelzag/gemini-pro-agentz-zi  )cwdenvtextcapture_outputtimeoutzHERMES_EXIT code=zSTDOUT z | i0zSTDERR z6STOP nonzero hermes exit; leaving state for inspection)$oschdirROOTLOCKexistsr    r!   r#   	Exceptionr   
write_textdumpsr   r   r   r   r   getpidr&   r4   r@   replacer"   unlinkenvironcopyPROMPT
subprocessrunr
   
returncodestdoutstripstderrtimesleep)payload	iterationr'   ctsexcrQ   cmdprocs           r   mainrq   Z   sU   HTNNN{{}} 	j!1!1!9T::GG 	 	 	GGG	Q4QQ'QQQRRRqOODJhl8<.H.H.R.R.T.T]_]f]h]hiirstttw{{|||%,		LLEE""C!C!!"""5!! 4555%/k"+3<+E+E+M+MZ[+M+\+\+f+f+h+h+p+pqy{~++'(  E!!<!<!<t!CDDD.	,KK4K((((( 	, 	, 	,*S**+++++++++	,1 NI5)55666*//##C$-C !.0f	C >#3t99#DY]gjkkkD5DO55666{  "" RI 1 1 3 3 ; ;D% H H PPQQQ{  "" RI 1 1 3 3 ; ;D% H H PPQQQ!##LMMM	,KK4K(((( 	, 	, 	,*S**++++++++	,	 JqMMM=	@	,KK4K(((( 	, 	, 	,*S**++++++++	,s   -A" "A10A1C!O2 (H 
H,H''H,/E'O2 N33
O=OOO2 2P94PP9
P6P1,P91P66P9__main__)r	   r
   r   r   )r   r   )r'   r   r   r(   )r'   r   r   r5   )r   rA   )__doc__
__future__r   r    rU   rc   sysri   r   r   pathlibr   rW   r"   
REPORT_DIRmkdirr   rX   rg   rb   r   r&   r4   r@   rq   __name__
SystemExitr$   r%   r   <module>r{      s~    # " " " " "  				     



  ' ' ' ' ' ' ' '      tGHH,,$$
 
    - - -**(($
H 
EGGI N   ) ) ) )   C C C C
/, /, /, /,d z
*TTVV

 r%   