From 09fa9a8b0aa0fd4f439493028276d9a82eea4415 Mon Sep 17 00:00:00 2001 From: PrimeThai Automation Date: Mon, 26 Oct 2026 21:17:02 +0700 Subject: [PATCH] Fix Pi MT5 server-clock conversion blocking live orders --- mt5_app/.env.example | 3 +++ mt5_app/README.md | 19 +++++++++++++++ mt5_app/app.py | 4 ++++ mt5_app/broker.py | 57 ++++++++++++++++++++++++++++++++++++-------- mt5_app/config.py | 4 ++++ mt5_app/index.html | 6 ++++- mt5_app/service.py | 4 ++++ 7 files changed, 86 insertions(+), 11 deletions(-) diff --git a/mt5_app/.env.example b/mt5_app/.env.example index eb828d9..e007300 100644 --- a/mt5_app/.env.example +++ b/mt5_app/.env.example @@ -7,6 +7,9 @@ MT5_AUTO_TRADE=false MT5_AUTO_START_DATE= # Empty end date means every trading day until paused. MT5_AUTO_END_DATE= +# Pi server-clock timestamps observed as Bangkok time (+07:00): 420 minutes. +# Use 0 only if that terminal actually returns UTC epochs. Do not infer from stale ticks. +MT5_SERVER_UTC_OFFSET_MINUTES=420 MT5_MAGIC=1061501 MT5_MODEL_START=2026-01-01 MT5_HISTORY_BARS=1000 diff --git a/mt5_app/README.md b/mt5_app/README.md index 67fe50b..2ed0312 100644 --- a/mt5_app/README.md +++ b/mt5_app/README.md @@ -271,3 +271,22 @@ python -m pytest -q -p no:cacheprovider tests mt5_app/tests การทดสอบส่งคำสั่งใช้ fake terminal เท่านั้น ครอบคลุมบัญชีผิด ส่งซ้ำ เงินไม่พอ ขายเกินหุ้น lot/tick ผิด การข้ามแล้วจัดงบใหม่ local request protection และ pipeline เปรียบเทียบข้อมูลเหมือนกัน เอกสาร API: [Python integration](https://www.mql5.com/en/docs/python_metatrader5), [D1 history](https://www.mql5.com/en/docs/python_metatrader5/mt5copyratesfrompos_py), [order_check](https://www.mql5.com/en/docs/python_metatrader5/mt5ordercheck_py), [order_send](https://www.mql5.com/en/docs/python_metatrader5/mt5ordersend_py). + +## ฐานเวลา MT5 และการตรวจว่าส่งคำสั่งจริงได้ + +วันที่ 26 ต.ค. 2026 ตรวจพบว่าราคาจาก Pi terminal เครื่องนี้บันทึก epoch ตามนาฬิกา server เวลาไทย ตัวอย่างแท่ง M1 แรกมีเลขเวลาเมื่ออ่านเป็น UTC เป็น `09:57Z` ทั้งที่เป็นรอบเปิด `09:57 Asia/Bangkok` จึงต้องหัก offset 7 ชั่วโมงเพื่อให้ได้ UTC จริงก่อนเปรียบเทียบกับนาฬิกาเครื่อง ค่าเดิมที่ถือว่า epoch เป็น UTC ทำให้ราคาดูอยู่ล่วงหน้าและถูกกั้นทุกคำสั่ง + +สำหรับ Pi terminal ที่ตรวจครั้งนี้ ตั้งใน `mt5_app/.env` แล้วเริ่มแอปใหม่: + +```dotenv +MT5_SERVER_UTC_OFFSET_MINUTES=420 +``` + +- ค่านี้แปลงเวลา tick / position / order / deal และขอบเขตที่ใช้ขอประวัติ ไม่ปรับวันที่แท่ง D1 เพราะใช้เป็นป้ายวันที่ session สำหรับกลยุทธ์เดิม +- เก็บเวลา tick เดิมใน `time_raw` และเวลาเดิมของประวัติใน `_broker_times` เพื่อย้อนตรวจได้ ไม่แก้ข้อมูลดิบของโบรกเกอร์ +- ค่า `0` หมายถึง terminal ส่ง UTC epochs จริง หากเปลี่ยน terminal/server ต้องตรวจฐานเวลาใหม่จากแท่งระหว่างวัน ไม่คำนวณ offset อัตโนมัติจาก tick ล่าสุด เพราะนอกเวลาตลาด tick อาจหยุดอัปเดต +- ยังตรวจวันทำการ เวลาตลาด สิทธิ์บัญชี และราคาของ SET/หุ้นอายุไม่เกิน 120 วินาทีเหมือนเดิม หากเวลาราคาอยู่ล่วงหน้าจะแจ้งแยกจากราคาเก่า พร้อมระบุ offset ที่ใช้อยู่ +- เพิ่ม SET และหุ้นที่อ่านราคาเข้า Market Watch เมื่อยังไม่ได้เปิดรับ เพื่อรับข้อมูลปัจจุบัน +- หน้าแรกแสดงเวลา SET ที่แปลงแล้ว และเหตุผลรอบส่งล่าสุดที่ถูกกั้น ข้อความข้อมูลพร้อมหรือการเชื่อมต่อสำเร็จไม่ได้ยืนยันว่ามีการส่งคำสั่ง ต้องดูคำสั่งที่แอปบันทึก ผลตอบกลับโบรกเกอร์ คำสั่งค้าง และ fills ร่วมกัน + +การแก้ฐานเวลานี้ไม่ได้ปิดการตรวจความสดของราคา และไม่ได้ยืนยันว่าคำสั่งรอบถัดไปจะถูกโบรกเกอร์รับหรือจับคู่ ต้องผ่าน `order_check` และอ่านผลจริงจาก MT5 อีกครั้ง diff --git a/mt5_app/app.py b/mt5_app/app.py index f5000ca..98350f7 100644 --- a/mt5_app/app.py +++ b/mt5_app/app.py @@ -131,6 +131,10 @@ def run(settings, *, auto_refresh=True): print(f'PrimeThai MT5: http://127.0.0.1:{settings.port}/', flush=True) print(f'Live orders: {settings.live_orders}; automatic: {settings.auto_trade}; start: {settings.auto_start or "not scheduled"}.', flush=True) print('SET common stocks only; Bangkok windows 10:05-12:25 and 14:05-16:25; holidays blocked.', flush=True) + logging.getLogger('mt5desk').info( + 'startup port=%s live=%s automatic=%s start=%s server_utc_offset_minutes=%s', + settings.port, settings.live_orders, settings.auto_trade, settings.auto_start, + settings.server_utc_offset_minutes) try: server.serve_forever() except KeyboardInterrupt: diff --git a/mt5_app/broker.py b/mt5_app/broker.py index 0830ea4..ad44659 100644 --- a/mt5_app/broker.py +++ b/mt5_app/broker.py @@ -23,6 +23,25 @@ class Broker: self.lock = threading.RLock() self.market = market or Market() + def normalized_times(self, value): + """Convert explicitly configured broker-clock epochs to actual UTC. + + Preserve raw fields for auditing. D1 bar dates are session labels and + deliberately do not pass through this conversion. + """ + data = value._asdict() if hasattr(value, '_asdict') else dict(value) + offset = self.settings.server_utc_offset_minutes * 60 + if not offset: + return data + raw = {} + for key, stamp in list(data.items()): + if (key == 'time' or key.startswith('time_')) and isinstance(stamp, (int, float)) and stamp > 0: + raw[key] = stamp + data[key] = stamp - offset * (1000 if key.endswith('_msc') else 1) + if raw: + data['_broker_times'] = raw + return data + def require_execution_ready(self, request): self.market.require_open() # Require a current exchange feed AND a current stock quote. Calendar @@ -31,8 +50,13 @@ class Broker: for symbol in ('SET', request['symbol']): quote = self.quote(symbol) age = now - float((quote or {}).get('time', 0)) - if quote is None or not -5 <= age <= 120: - raise ValueError(f'{symbol}: ราคาจาก MT5 ไม่สดภายใน 120 วินาที หยุดส่งคำสั่ง') + if quote is None: + raise ValueError(f'{symbol}: อ่านราคา MT5 ไม่ได้ หยุดส่งคำสั่ง') + if age < -5: + raise ValueError(f'{symbol}: เวลาราคาอยู่ล่วงหน้า {abs(age):,.0f} วินาที ' + f'(server UTC offset={self.settings.server_utc_offset_minutes} นาที) หยุดส่งคำสั่ง') + if age > 120: + raise ValueError(f'{symbol}: ราคา MT5 อายุ {age:,.0f} วินาที เกิน 120 วินาที หยุดส่งคำสั่ง') if symbol != 'SET': side_price = quote['ask'] if request['type'] == self.api.ORDER_TYPE_BUY_LIMIT else quote['bid'] if not math.isfinite(side_price) or side_price <= 0: @@ -83,14 +107,17 @@ class Broker: if positions is None or orders is None: raise RuntimeError(f"อ่านพอร์ต/คำสั่งไม่ได้: {mt.last_error()}") now = datetime.now(timezone.utc) - deals = mt.history_deals_get(now - timedelta(days=120), now) + # Query boundaries use the same encoded server clock as the broker + # records; otherwise today's latest fills can be missing for hours. + broker_now = now + timedelta(minutes=self.settings.server_utc_offset_minutes) + deals = mt.history_deals_get(broker_now - timedelta(days=120), broker_now) if deals is None: raise RuntimeError(f"อ่านประวัติไม่ได้: {mt.last_error()}") - history_orders = mt.history_orders_get(now - timedelta(days=120), now) + history_orders = mt.history_orders_get(broker_now - timedelta(days=120), broker_now) if history_orders is None: raise RuntimeError(f"อ่านประวัติคำสั่งไม่ได้: {mt.last_error()}") - pos = [p._asdict() for p in positions] - pending = [o._asdict() for o in orders] + pos = [self.normalized_times(p) for p in positions] + pending = [self.normalized_times(o) for o in orders] account_data = {k: getattr(account, k, None) for k in ( "balance", "equity", "profit", "margin_free", "margin", "assets", "liabilities", "currency", "server", "trade_allowed", "trade_expert", "margin_mode", @@ -108,11 +135,12 @@ class Broker: result = { "updated_at": now_iso(), "account": account_data, "positions": pos, "orders": pending, - "deals": [d._asdict() for d in deals], - "history_orders": [o._asdict() for o in history_orders], + "deals": [self.normalized_times(d) for d in deals], + "history_orders": [self.normalized_times(o) for o in history_orders], "quotes": quotes, "terminal": {k: getattr(terminal, k, None) for k in ( "connected", "trade_allowed", "tradeapi_disabled", "build", "name")}, + "server_utc_offset_minutes": self.settings.server_utc_offset_minutes, "warnings": ([f"Equity จาก server กับมูลค่าหุ้นรวมต่างกัน {differences:,.2f} บาท; ใช้เงินว่างจากโบรกเกอร์เป็นงบ"] if differences > .02 else []), } @@ -123,12 +151,21 @@ class Broker: def quote(self, symbol): with self.lock: info = self.api.symbol_info(symbol) - tick = self.api.symbol_info_tick(symbol) if info is None: return None + if not getattr(info, 'visible', True) or not getattr(info, 'select', True): + if not self.api.symbol_select(symbol, True): + raise ValueError(f'{symbol}: เปิดรับราคาใน Market Watch ไม่สำเร็จ: {self.api.last_error()}') + info = self.api.symbol_info(symbol) + if info is None: + return None + tick = self.api.symbol_info_tick(symbol) + raw_time = int(tick.time if tick else info.time) + offset = self.settings.server_utc_offset_minutes * 60 return { "symbol": symbol, "bid": float(info.bid), "ask": float(info.ask), "last": float(info.last), - "time": int(tick.time if tick else info.time), + "time": raw_time - offset if raw_time else 0, + "time_raw": raw_time, "server_utc_offset_minutes": self.settings.server_utc_offset_minutes, "contract_size": float(info.trade_contract_size), "volume_step": float(info.volume_step), "volume_min": float(info.volume_min), "trade_mode": int(info.trade_mode), "path": info.path, diff --git a/mt5_app/config.py b/mt5_app/config.py index 3baf36e..f05087e 100644 --- a/mt5_app/config.py +++ b/mt5_app/config.py @@ -17,6 +17,7 @@ class Settings: auto_trade: bool = False auto_start: str = "" auto_end: str = "" + server_utc_offset_minutes: int = 0 magic: int = 1061501 model_start: str = "2026-01-01" history_bars: int = 1000 @@ -61,6 +62,7 @@ class Settings: auto_trade=values.get("MT5_AUTO_TRADE", "false").lower() == "true", auto_start=values.get("MT5_AUTO_START_DATE", ""), auto_end=values.get("MT5_AUTO_END_DATE", ""), + server_utc_offset_minutes=int(values.get("MT5_SERVER_UTC_OFFSET_MINUTES", 0)), magic=int(values.get("MT5_MAGIC", 1061501)), model_start=values.get("MT5_MODEL_START", "2026-01-01"), history_bars=int(values.get("MT5_HISTORY_BARS", 1000)), @@ -81,4 +83,6 @@ class Settings: datetime.strptime(day, '%Y-%m-%d') if config.auto_end and config.auto_end < config.auto_start: raise ValueError("Automatic execution end date precedes start date") + if not -720 <= config.server_utc_offset_minutes <= 840: + raise ValueError("MT5 server UTC offset must be between -720 and 840 minutes") return config diff --git a/mt5_app/index.html b/mt5_app/index.html index e682f3d..ad4d817 100644 --- a/mt5_app/index.html +++ b/mt5_app/index.html @@ -13,7 +13,7 @@
PRIMETHAI / LOCAL MT5 DESK

ดูแลพอร์ตจากบัญชีจริง

กำลังอ่านข้อมูล MT5…
อ่านพอร์ต
-

สถานะตลาดและรอบส่งคำสั่ง

กำลังอ่านเวลาตลาด…

+

สถานะตลาดและรอบส่งคำสั่ง

กำลังอ่านเวลาตลาด…

Equity ที่โบรกเกอร์รายงาน
—
จากบัญชี MT5
@@ -71,6 +71,10 @@ function render(d){state=d;const s=d.snapshot||{},a=s.account||{},r=d.research|| $('auto-status').textContent=auto.message||'ยังไม่ตั้งรอบอัตโนมัติ'; $('auto-details').textContent=`เริ่ม ${auto.start_date||'ยังไม่กำหนด'}${auto.end_date?' ถึง '+auto.end_date:' · ทุกวันทำการ'} · ส่งเฉพาะ ${market.order_windows||'—'} น. · ตรวจรอบทุก ${auto.interval_seconds||15} วินาที · อ่านพอร์ตทุก ${auto.portfolio_seconds||60} วินาที · คำนวณราคาปิดหลัง ${auto.eod_time||'20:30'} น. · ปฏิทินยืนยันปี ${(market.calendar_years||[]).join(', ')} (ปีที่ไม่มีปฏิทินจะหยุดส่ง)`; $('auto-cycle').textContent=(auto.last_cycle?'ตรวจแผนล่าสุด '+timestamp(auto.last_cycle.at)+' · '+auto.last_cycle.message:'ยังไม่ถึงรอบส่งอัตโนมัติ')+' · วิเคราะห์สัญญาณล่าสุด '+timestamp(r.updated_at); + const benchmark=s.quotes?.SET; + $('feed-status').textContent='ราคา SET ล่าสุด '+timestamp(benchmark?.time)+' · ฐานเวลา server เทียบ UTC '+(d.server_utc_offset_minutes||0)+' นาที · การเปิดส่งจริงยังต้องผ่านการตรวจราคา บัญชี เงินว่าง และโบรกเกอร์'; + const blocked=auto.last_cycle?.status==='blocked';$('execution-warning').hidden=!blocked; + if(blocked)$('execution-warning').textContent='รอบส่งล่าสุดถูกกั้น ('+timestamp(auto.last_cycle.at)+'): '+auto.last_cycle.message+' · การอัปเดตข้อมูลสำเร็จไม่ได้หมายความว่าส่งคำสั่งแล้ว'; $('pause-auto').textContent=auto.paused?'เปิดรอบอัตโนมัติต่อ':'หยุดส่งอัตโนมัติ';$('pause-auto').disabled=!auto.enabled&&!auto.paused; $('trading-mode').textContent=d.live_enabled?'ปิดการส่งจริง':'เปิดการส่งจริง'; $('job-message').textContent=job.message||'รออ่านพอร์ต';$('job').className='banner'+(job.stage==='failed'?' error':'');$('job-progress').hidden=!job.running;if(job.running){$('job-progress').max=job.total||1;$('job-progress').value=job.done||0;} diff --git a/mt5_app/service.py b/mt5_app/service.py index 52bfdb8..a339333 100644 --- a/mt5_app/service.py +++ b/mt5_app/service.py @@ -224,6 +224,9 @@ class Desk: 'done': done, 'total': total, 'updated_at': now_iso()}) def update_quotes(self, snapshot, research): + benchmark = self.broker.quote('SET') + if benchmark: + snapshot.setdefault('quotes', {})['SET'] = benchmark for signal in research.get('signals', []): quote = self.broker.quote(signal['symbol']) if quote: @@ -278,6 +281,7 @@ class Desk: 'connection_error': self.store.get('connection_error'), 'history': {k: v for k, v in history.items() if k != 'successful_symbols'}, 'live_enabled': self.settings.live_orders, 'app_magic': self.settings.magic, + 'server_utc_offset_minutes': self.settings.server_utc_offset_minutes, 'automation': self.auto_status(), 'executions': self.store.executions(), 'max_premium_pct': self.settings.max_premium_pct, 'intents': self.store.intents()}