Add separate local MT5 desk with broker portfolio sync and source comparison

This commit is contained in:
PrimeThai Automation committed 2026-10-15 22:06:41 +07:00
1 parent 7a8ee40fbb
commit a03fda22fb
19 files changed
+1794

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
# Use the data folder of the already logged-in Pi terminal. No password is needed.
MT5_DATA_PATH=C:\Users\YOUR_WINDOWS_USER\AppData\Roaming\MetaQuotes\Terminal\YOUR_PI_TERMINAL_ID
MT5_PORT=18901
MT5_ENABLE_LIVE_ORDERS=false
MT5_MAGIC=1061501
MT5_MODEL_START=2026-01-01
MT5_HISTORY_BARS=1000
MT5_EOD_HOUR=20
MT5_EOD_MINUTE=30
MT5_MAX_ENTRY_PREMIUM_PCT=2
MT5_FEE_RESERVE_PCT=0.2
MT5_REFRESH_SECONDS=60
+6
View File
@@ -0,0 +1,6 @@
.env
.venv/
data/
logs/
__pycache__/
*.pyc
+55
View File
@@ -0,0 +1,55 @@
# ผลเปรียบเทียบแอป MT5 กับระบบเดิม — 15 ต.ค. 2026
แอปแยกอยู่ใน `mt5_app/` ใช้ราคาจาก Pi MT5 และเรียกกฎ Donchian 55/20 + EMA 50/200 เดิมแบบอ่านอย่างเดียว ไม่มีการแก้โปรแกรมเดิมหรือส่งคำสั่งเงินจริงในการตรวจนี้
## สัญญาณในวันเดียวกัน: 2026-09-28
- MT5 เลือก 19 หุ้น; SiamChart เลือก 19 หุ้น
- รายชื่อและโมเดลตรงกัน: True
- ลำดับ คะแนนจัดสรรงบ และน้ำหนักตรงกัน: True, True, True
- เป้าหมายถือหุ้นย้อนหลังยังต่างกัน 61 จาก 179 วัน จึงไม่ใช่ผลที่เหมือนกันตลอดประวัติ
## Backtest บนวันร่วมกัน
2026-01-05 ถึง 2026-09-28 · ทุน 10,000 บาท · lot 100 · commission 0.15% และ slippage 5 bps ตามสมมติฐานเดิม ทั้งสองฝั่งใช้กฎและต้นทุนเดียวกัน ผลนี้ไม่ได้ใช้ทุน 1 ล้านบาทเหมือนรายงานเก่าบางชุด
| ผล | MT5 | SiamChart |
|---|---:|---:|
| ผลตอบแทน | 4.1678% | 4.2153% |
| มูลค่าปลายงวด | 10,416.78 | 10,421.53 |
| Max drawdown | -1.9754% | -2.2006% |
| Fills | 41 | 55 |
ผลตอบแทนที่ใกล้กันไม่ได้หมายความว่าเส้นทางถือหุ้นและรายการซื้อขายเหมือนกันทุกวัน และ backtest นี้ยังไม่ได้จำลองการข้ามหุ้นหรือการเลือกตามเงินว่างในหน้าจอรายบุคคล
## ข้อมูลที่เทียบ
643 วันร่วมกัน · 260 สัญลักษณ์ร่วมกัน
| ข้อมูล | แท่งที่เทียบ | ตรงกัน | ต่างกัน | ตรงกัน (%) |
|---|---:|---:|---:|---:|
| open | 158,543 | 155,883 | 2,660 | 98.3222 |
| high | 158,543 | 155,862 | 2,681 | 98.3090 |
| low | 158,543 | 155,851 | 2,692 | 98.3020 |
| close | 158,543 | 155,787 | 2,756 | 98.2617 |
| volume | 158,543 | 144,301 | 14,242 | 91.0169 |
ดัชนี SET มีราคาต่างกัน 6 วัน ขอบเขตสัญลักษณ์ที่ผ่านเกณฑ์ของสองแหล่งต่างกันด้วย จึงไม่ถือว่าข้อมูลดิบตรงกันทั้งหมด
## ปัญหาปฏิทินที่พบและแก้ในตัวอ่าน MT5
MT5 คืนแท่ง BUI และ TRUBB วันที่ 2026-03-03 ทั้งที่ไม่มีแท่ง SET วันนั้น การนับวันดังกล่าวในปฏิทินกลางทำให้ค่าเฉลี่ย SET 200 วันขาดข้อมูลและปิดสัญญาณผิดไป ตัวอ่านใหม่ใช้วัน SET D1 เป็นปฏิทินร่วมและแยกสองแท่งออกจากการคำนวณ โดยยังเก็บข้อมูลดิบใน SQLite ครบ
วันที่ 3 มี.ค. เป็นวันหยุดมาฆบูชาตาม [ปฏิทิน SET](https://www.set.or.th/en/about/event-calendar/holiday) และ [ประกาศ ก.ล.ต.](https://www.sec.or.th/EN/Pages/News_Detail.aspx?Lang=12143&NewsNo=12143&NewsYear=12143&SECID=12143) ไม่มีการเติมหรือปรับราคาเพื่อบังคับให้สัญญาณตรงกัน
## MT5 ถึงวันล่าสุด
- วันสัญญาณ: 2026-10-15 · 18 หุ้น
- Backtest ถึง 2026-10-15: 4.5807% บนทุน 10,000 บาท แสดงแยกจากตารางวันร่วมกัน
- ประวัติราคาเก็บไว้ 802 สัญลักษณ์ 492,414 แท่งก่อนแยกแท่งนอกปฏิทิน
- ACAP ไม่มีแท่งในช่วงที่ใช้; BLISS และ WELL ไม่คืน D1 history ข้อผิดพลาดเก็บในแอป
- ใช้ OHLC และ real volume จาก MT5 แต่การปรับปันผล/แตกหุ้นยังอาศัยไฟล์อ้างอิงเดิมที่มีอยู่ และอาจครอบคลุมไม่ครบ
## วิธีตรวจซ้ำ
เปิดแท็บ “เทียบ MT5 กับระบบเดิม” และ “ผล Backtest” ในแอป สามารถดาวน์โหลดรายงาน JSON ได้ รายงานเต็มและราคาที่โหลดอยู่ใน `mt5_app/data/` ซึ่งเก็บไว้เฉพาะเครื่องและไม่ถูกนำขึ้น Git ข้อมูลบัญชีจริงและประวัติส่วนตัวไม่ได้รวมในรายงานนี้
+92
View File
@@ -0,0 +1,92 @@
# PrimeThai MT5 Desk — แอป local แยกจากระบบเดิม
แอป Python สำหรับ MT5 ของ Pi อ่านพอร์ตจริง ประวัติซื้อขาย คำสั่งค้าง และราคา OHLCV รายวันจาก terminal ที่เปิดอยู่ ใช้ Donchian 55/20 หรือ EMA 50/200 ตามกฎเดิม พร้อมแสดงแผนจัดสรรงบและหน้าตรวจคำสั่ง Limit ก่อนส่งจริง
โค้ด การตั้งค่า ฐานข้อมูล และหน้าจอของแอปอยู่ใน `mt5_app/` ทั้งหมด ไม่มีการแก้ไฟล์โปรแกรม ฐานข้อมูลพอร์ต หรือ archive ของระบบเดิม การคำนวณเรียก `primethai/model_lab.py` และกฎช่วงราคาจาก `primethai/config.py` แบบอ่านอย่างเดียว เพื่อไม่ให้กฎเปลี่ยนระหว่างการเทียบสองแหล่งข้อมูล จึงต้องเก็บโฟลเดอร์นี้ไว้ใน repository เดิม
## เริ่มใช้งานบน Windows
จากโฟลเดอร์โครงการ:
```powershell
.\mt5_app\setup.ps1
.\mt5_app\run.ps1
```
เปิด `http://127.0.0.1:18901/` แอป bind เฉพาะเครื่องนี้ แยกพอร์ตจากระบบเดิมที่ 18900 ต้องเปิด MT5 ของ Pi และล็อกอินบัญชีที่ต้องการก่อน แอปจะไม่เปิด terminal ตัวอื่นให้เอง
ตัวติดตั้งสร้าง Python environment แยกใน `mt5_app/.venv/` หากยังไม่ติดตั้ง environment แยก ตัวเปิดแอปใช้ `.venv/` เดิมเป็นทางเลือกได้ คำสั่ง CLI จาก root:
```powershell
.\mt5_app\.venv\Scripts\python.exe -m mt5_app serve
.\mt5_app\.venv\Scripts\python.exe -m mt5_app status
.\mt5_app\.venv\Scripts\python.exe -m mt5_app sync
```
อย่ารัน `sync` พร้อมแอปอีกตัวที่กำลังโหลดประวัติ ใช้ปุ่มอัปเดตในแอปแทน ทุกการเรียก MT5 ภายในแอปเดียวกันถูกเรียงลำดับ
## ข้อมูลและความจำ
- `.env` คัดลอกจาก `.env.example` ระบุ `MT5_DATA_PATH` ให้ตรงกับโฟลเดอร์ terminal ไม่ต้องใส่รหัสผ่านบัญชี
- `data/mt5.sqlite3` เก็บแท่งรายวัน snapshot พอร์ต การข้ามสัญญาณ การตรวจคำสั่ง และรหัสป้องกันส่งซ้ำ
- `data/mt5_eod.zip` เป็น OHLCV จาก MT5 สำหรับคำนวณและตรวจซ้ำ
- `data/research.json`, `comparison.json`, `signal_comparison.csv` เป็นผลคำนวณล่าสุด
- `logs/app.log` เก็บรายละเอียดข้อผิดพลาดพร้อม traceback และหมุนเวียนไฟล์
- ฐานข้อมูล ข้อมูลบัญชี `.env` และ log ไม่ถูกนำขึ้น Git สำรองโฟลเดอร์ `mt5_app/data/` เมื่อย้ายเครื่อง
พอร์ตและประวัติซื้อขายเป็นข้อมูลจากโบรกเกอร์ ไม่สร้าง fill ประมาณการแบบแอปเดิม บัญชีแรกถูกผูกกับ server และเลขบัญชีในฐานข้อมูล หากสลับบัญชี แอปจะหยุดการจัดการคำสั่ง
## สัญญาณและการจัดสรร
ใช้ OHLC และ `real_volume` ของหุ้นสามัญ SET/MAI กับดัชนี SET จาก MT5 ปริมาณ tick ไม่ได้ใช้แทนจำนวนหุ้น Donchian ต้องใช้ high/low; โมเดลยังใช้ปันผลและแตกหุ้นจากไฟล์อ้างอิงเดิมที่มีอยู่ ข้อมูล corporate actions ดังกล่าวไม่ได้ดึงจาก MT5 และอาจครอบคลุมไม่ครบ
ประวัติครั้งแรกขอ 1,000 แท่งต่อหุ้น จากนั้นดึงเพิ่มช่วงล่าสุด ใช้แท่งวันนี้เป็น EOD หลัง 20:30 เวลาไทยเท่านั้น ก่อนเวลานั้นใช้วันก่อนหน้า เก็บข้อมูลไว้ในเครื่องและลองใหม่เมื่อดาวน์โหลดไม่สำเร็จ หุ้นที่ข้อมูลล่าสุดไม่ครบจะแสดงรอข้อมูล
ใช้วันที่มีแท่ง SET เป็นปฏิทินซื้อขายร่วมกัน แท่งหุ้นในวันที่ไม่มี SET จะถูกแยกออกจากการคำนวณและรายงานใน `data_quality` แต่เก็บหลักฐานดิบไว้ใน SQLite หาก SET ยังไม่ถึงวันล่าสุดของหุ้น จะพักการคำนวณแทนการเติมดัชนีเอง วิธีนี้ป้องกันแท่งวันหยุดของหุ้นบางตัวทำให้ค่าเฉลี่ย SET 200 วันขาดข้อมูล
คำนวณ universe ตามเดิม: 100 อันดับมูลค่าซื้อขายเฉลี่ย 20 วัน สูงกว่า 20 ล้านบาทต่อวัน และราคาอย่างน้อย 2 บาท หุ้นที่โมเดลใดเลือกจะอยู่ในเป้าหมายเดียวกัน เมื่อเงินไม่พอ จัดลำดับจำนวนโมเดลที่เห็นตรงกันและคะแนน momentum/ความผันผวน ใช้ขั้นต่ำ 100 หุ้น งบเป็นค่าที่น้อยกว่าระหว่าง balance กับ margin_free หักเงินเผื่อคำสั่งซื้อค้างอย่างระมัดระวัง ไม่ใช้ equity ทั้งหมดเป็นกำลังซื้อ
“ซื้อไม่ทัน” ข้ามคำแนะนำซื้อเฉพาะวันสัญญาณนั้นแล้วจัดสรรใหม่ โดยไม่เปลี่ยนหุ้นหรือเงินสดจริง สามารถคืนรายการได้ และเมื่อมีสัญญาณวันใหม่จะกลับมาประเมินอัตโนมัติ
Equity ที่โบรกเกอร์รายงานกับผลรวมหุ้นอาจต่างกัน แอปแสดงทั้งยอดและคำเตือน โดยใช้กำลังซื้อที่โบรกเกอร์รายงานในการวางแผน ไม่แก้ยอดเพื่อให้ดูตรงกัน
## คำสั่งจริง
ค่าเริ่มต้นอ่านพอร์ตและตรวจคำสั่งเท่านั้น เปิดส่งจริงได้จากปุ่มในหน้าจอสำหรับรอบเปิดแอปนี้ ทุกคำสั่งยังต้องกดตรวจและยืนยันรายครั้ง ปิดแอปแล้วเปิดใหม่จะกลับตาม `.env` ค่า `MT5_ENABLE_LIVE_ORDERS=false` จึงปิดการส่งจริงเมื่อเริ่มแอป
- รองรับ Buy Limit, Sell Limit และยกเลิกคำสั่งที่แอปนี้ส่ง ใช้ `ORDER_TIME_DAY` และ `ORDER_FILLING_RETURN` การรองรับจริงขึ้นกับ server และ `order_check`
- ไม่มีการเปิด Short ขายได้ไม่เกินหุ้นหลังหักคำสั่งขายค้าง
- ตรวจราคาให้ตรงช่วงราคา SET จำนวนครั้งละ 100 หุ้น กำลังซื้อ และส่วนต่างสูงสุดจากราคาสัญญาณ
- `MT5_MAX_ENTRY_PREMIUM_PCT=2` เป็นขอบเขตการส่งคำสั่ง ไม่ใช่เกณฑ์ที่พิสูจน์ว่าทำกำไรเพิ่มหรือส่วนหนึ่งของ backtest
- ตัวอย่างคำสั่งหมดอายุใน 60 วินาที ตรวจสิทธิ์และกำลังซื้อซ้ำก่อนส่ง
- รหัสคำสั่งถูกจองใน SQLite ก่อนส่ง หากการเชื่อมต่อหลุดจะไม่ลองส่งซ้ำอัตโนมัติ unknown/sending ต้องตรวจผลกับโบรกเกอร์ก่อน คำสั่งใหม่ในหุ้นเดียวกันถูกกั้นไว้จนตรวจสถานะแล้ว
- แอปใช้ magic แยก (`1061501`) ไม่ยกเลิกคำสั่งจากโปรแกรมอื่นหรือรายการที่ทำเอง
- โบรกเกอร์รับคำสั่งไม่เท่ากับซื้อขายสำเร็จ ดูคำสั่งค้างและประวัติ fills จาก MT5
- เปลี่ยนราคาโดยยกเลิกคำสั่งเดิม แล้วตรวจและยืนยันคำสั่งใหม่เพื่อประเมินงบซ้ำ
ไม่เปิดอัตโนมัติซื้อขายตามเวลา ทุกคำสั่งต้องยืนยันใน UI ไม่มีการส่งคำสั่งเงินจริงในการทดสอบของโครงการ
## การเปรียบเทียบ
อ่าน archive SiamChart เดิมโดยไม่ดาวน์โหลดหรือแก้ไข แล้วเทียบกับ MT5 บนวันสิ้นสุดร่วมกันและ warm-up 700 วันก่อน `MT5_MODEL_START` เดียวกัน รายงาน:
1. จำนวนและสัดส่วน OHLCV ที่ตรงกันบนแท่ง/หุ้นร่วมกัน
2. ดัชนี SET หุ้นที่ขาด และความต่างของ universe
3. รายชื่อหุ้นและโมเดลที่ให้สัญญาณในวันร่วมกัน
4. จำนวนวันที่เป้าหมายถือหุ้นในอดีตต่างกัน
5. backtest สองแหล่งข้อมูลบนช่วงวันร่วมกัน ทุน 10,000 บาท lot 100 และต้นทุนสมมติฐานเดิม
6. backtest MT5 ถึงวันล่าสุด แสดงแยก ไม่เปรียบผลตอบแทนข้ามช่วงวัน
MT5 อาจไม่มีหุ้นที่เพิกถอนหรือประวัติครบเท่า archive เดิม ราคาปรับ corporate actions/เวลาแท่ง/volume อาจต่างกัน รายงานความต่างจริง ไม่ถือว่าการรันสำเร็จแปลว่าผลเท่ากัน Backtest เป็นวิธีจำลองพอร์ตเดิม ไม่ได้จำลองการตัดสินใจข้ามหุ้นและการจัดลำดับงบรายบุคคลใน UI
## ทดสอบ
จาก environment พัฒนาที่มี pytest:
```powershell
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).
+9
View File
@@ -0,0 +1,9 @@
@echo off
cd /d "%~dp0.."
set PYTHONIOENCODING=utf-8
if exist "%~dp0.venv\Scripts\python.exe" (
"%~dp0.venv\Scripts\python.exe" -m mt5_app serve
) else (
echo Please run mt5_app\setup.ps1 first.
pause
)
+1
View File
@@ -0,0 +1 @@
"""Local MT5 desk. Runtime state and broker execution are separate from PrimeThai."""
+42
View File
@@ -0,0 +1,42 @@
import argparse
import json
from .config import Settings
def main():
parser = argparse.ArgumentParser(description='Separate local MT5 desk')
parser.add_argument('command', choices=['serve', 'sync', 'status'], nargs='?', default='serve')
parser.add_argument('--no-auto-refresh', action='store_true', help='serve cached state without a background MT5 worker')
args = parser.parse_args()
config = Settings.load()
if args.command == 'serve':
from .app import run
run(config, auto_refresh=not args.no_auto_refresh)
else:
from .service import Desk
desk = Desk(config)
if args.command == 'status':
state = desk.state()
print(json.dumps({'job': state['job'], 'history': state['history'],
'signal_as_of': state['research'].get('signal_as_of')}, ensure_ascii=False, indent=2))
else:
from .research import download_history, run_research
from .store import now_iso
def progress(stage, message, done=0, total=1):
desk.progress(stage, message, done, total)
if stage != 'history' or done % 25 == 0 or done == total:
print(message, flush=True)
try:
desk.broker.snapshot()
download_history(desk.broker, desk.store, config, progress)
result = run_research(desk.store, config, progress)
desk.update_quotes(desk.broker.snapshot(), result)
desk.store.put('job', {'running': False, 'stage': 'complete', 'message': 'พร้อมใช้งาน', 'updated_at': now_iso()})
print('Signals:', len(result['signals']), 'as of', result['signal_as_of'])
except Exception as exc:
desk.store.put('job', {'running': False, 'stage': 'failed', 'message': str(exc), 'updated_at': now_iso()})
raise
if __name__ == '__main__':
main()
+134
View File
@@ -0,0 +1,134 @@
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
import secrets
import threading
from urllib.parse import urlsplit
from .config import ROOT
from .research import plain
from .service import Desk
def handler_for(desk, token, port):
hosts = {f'127.0.0.1:{port}', f'localhost:{port}'}
origins = {'http://' + host for host in hosts}
class Handler(BaseHTTPRequestHandler):
server_version = 'PrimeThaiMT5/1.0'
def respond(self, status, value, html=False, filename=None):
body = value.encode('utf-8') if html else json.dumps(plain(value), ensure_ascii=False, allow_nan=False).encode('utf-8')
self.send_response(status)
self.send_header('Content-Type', 'text/html; charset=utf-8' if html else 'application/json; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.send_header('Cache-Control', 'no-store')
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('X-Frame-Options', 'DENY')
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'")
if filename:
self.send_header('Content-Disposition', f'attachment; filename="{filename}"')
try:
self.end_headers()
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
self.close_connection = True
def valid_host(self):
if self.headers.get('Host') not in hosts:
self.respond(403, {'error': 'Local access only'})
return False
return True
def do_GET(self):
if not self.valid_host():
return
path = urlsplit(self.path).path
if path == '/':
page = (ROOT / 'index.html').read_text(encoding='utf-8').replace('__APP_TOKEN__', token)
self.respond(200, page, html=True)
elif path == '/health':
self.respond(200, {'status': 'ok', 'app': 'mt5_app'})
elif self.headers.get('X-App-Token') != token:
self.respond(403, {'error': 'เปิดหน้าแอปใหม่เพื่อเริ่มใช้งาน'})
elif path == '/api/state':
self.respond(200, desk.state())
else:
self.respond(404, {'error': 'Not found'})
def do_POST(self):
if not self.valid_host():
return
if self.headers.get('Origin') not in origins or self.headers.get('X-App-Token') != token:
self.respond(403, {'error': 'คำขอต้องมาจากหน้าแอปในเครื่องนี้'})
return
path = urlsplit(self.path).path
try:
length = int(self.headers.get('Content-Length', '0'))
if not 0 < length <= 8192:
raise ValueError('ขนาดคำขอไม่ถูกต้อง')
body = json.loads(self.rfile.read(length))
if not isinstance(body, dict):
raise ValueError('รูปแบบคำขอไม่ถูกต้อง')
if path == '/api/refresh':
started = desk.refresh(research=bool(body.get('research')))
self.respond(202 if started else 409, {'started': started})
elif path == '/api/skip':
desk.skip(str(body.get('symbol', '')).upper(), body.get('skip', True) is not False)
self.respond(200, {'ok': True})
elif path == '/api/trading':
enabled = body.get('enabled') is True
if enabled and body.get('confirm') != 'ENABLE_LIVE':
raise ValueError('ต้องยืนยันเปิดส่งคำสั่งเข้าบัญชีจริง')
self.respond(200, desk.set_live(enabled))
elif path == '/api/preview':
self.respond(200, desk.preview(body))
elif path == '/api/submit':
if body.get('confirm') != 'SEND_LIVE':
raise ValueError('ต้องยืนยันการส่งคำสั่งจริง')
self.respond(200, desk.submit(str(body.get('id', ''))))
elif path == '/api/cancel':
if body.get('confirm') != 'CANCEL_LIVE':
raise ValueError('ต้องยืนยันการยกเลิกคำสั่งจริง')
result = desk.broker.manage_pending(int(body.get('ticket', 0)))
desk.refresh()
self.respond(200, result)
else:
self.respond(404, {'error': 'Not found'})
except (ValueError, TypeError, KeyError) as exc:
self.respond(400, {'error': str(exc)})
except Exception as exc:
logging.getLogger('mt5desk').exception('request_failed %s', path)
self.respond(500, {'error': f'{type(exc).__name__}: {exc}'})
def log_message(self, message, *args):
if '/api/state' not in self.path:
logging.getLogger('mt5desk').info('%s %s', self.client_address[0], message % args)
return Handler
def run(settings, *, auto_refresh=True):
settings.state_dir.mkdir(parents=True, exist_ok=True)
log_dir = ROOT / 'logs'
log_dir.mkdir(exist_ok=True)
logging.basicConfig(level=logging.INFO, handlers=[
logging.StreamHandler(),
RotatingFileHandler(log_dir / 'app.log', maxBytes=2_000_000, backupCount=3, encoding='utf-8'),
], format='%(asctime)s %(levelname)s %(message)s')
desk = Desk(settings)
token = secrets.token_urlsafe(32)
server = ThreadingHTTPServer(('127.0.0.1', settings.port), handler_for(desk, token, settings.port))
if auto_refresh:
threading.Thread(target=desk.scheduler, daemon=True, name='mt5-scheduler').start()
print(f'PrimeThai MT5: http://127.0.0.1:{settings.port}/', flush=True)
print(f'Live order sending enabled: {settings.live_orders}; each order requires a preview and explicit confirmation.', flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
desk.stop.set()
server.server_close()
+275
View File
@@ -0,0 +1,275 @@
"""All MT5 calls are serialized and bound to one data folder and account."""
from datetime import datetime, timedelta, timezone
import json
import math
from pathlib import Path
import subprocess
import threading
import time
import uuid
from primethai.config import ThaiMarketRules
from .store import now_iso
class Broker:
def __init__(self, settings, store, api=None):
if api is None:
import MetaTrader5 as api
self.api = api
self.settings = settings
self.store = store
self.lock = threading.RLock()
def connect(self):
mt = self.api
terminal = mt.terminal_info()
if terminal is None:
origin = self.settings.data_path / "origin.txt"
raw = origin.read_bytes()
encoding = "utf-16" if raw.startswith((b'\xff\xfe', b'\xfe\xff')) else "utf-8-sig"
exe = Path(raw.decode(encoding).strip()) / "terminal64.exe"
# initialize() may launch a terminal. Require this exact instance to
# be open already, so startup never starts other configured EAs.
result = subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-Command",
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); "
"Get-Process -Name terminal64 -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path"],
capture_output=True, text=True, encoding="utf-8", creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
timeout=15,
)
if str(exe).casefold() not in [p.strip().casefold() for p in result.stdout.splitlines()]:
raise RuntimeError("เปิด MT5 ของ Pi และล็อกอินบัญชีเดิมก่อนเริ่มแอป")
if not mt.initialize(str(exe), timeout=15000):
raise RuntimeError(f"MT5 initialize: {mt.last_error()}")
terminal = mt.terminal_info()
if terminal is None or Path(terminal.data_path).resolve() != self.settings.data_path.resolve():
raise RuntimeError("MT5 data folder ไม่ตรงกับบัญชีที่กำหนด")
if not terminal.connected:
raise RuntimeError("MT5 ยังไม่เชื่อมต่อ server")
account = mt.account_info()
if account is None:
raise RuntimeError(f"อ่านบัญชีไม่ได้: {mt.last_error()}")
identity = {"login": int(account.login), "server": account.server}
pinned = self.store.get("pinned_account")
if pinned is None:
self.store.put("pinned_account", identity)
elif pinned != identity:
raise RuntimeError("บัญชี MT5 เปลี่ยนจากบัญชีที่ผูกไว้ แอปหยุดการจัดการคำสั่ง")
return terminal, account
def snapshot(self):
with self.lock:
mt = self.api
terminal, account = self.connect()
positions, orders = mt.positions_get(), mt.orders_get()
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)
if deals is None:
raise RuntimeError(f"อ่านประวัติไม่ได้: {mt.last_error()}")
history_orders = mt.history_orders_get(now - timedelta(days=120), 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]
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",
)}
account_data["login_masked"] = "***" + str(account.login)[-4:]
market_value = sum(p['volume'] * p['price_current'] for p in pos)
mark_equity = account.balance + market_value - getattr(account, "liabilities", 0)
differences = abs(mark_equity - account.equity)
account_data.update({"position_market_value": market_value,
"equity_from_positions": mark_equity,
"equity_difference": mark_equity - account.equity})
quotes = {}
for symbol in {p['symbol'] for p in pos}:
quotes[symbol] = self.quote(symbol)
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],
"quotes": quotes,
"terminal": {k: getattr(terminal, k, None) for k in (
"connected", "trade_allowed", "tradeapi_disabled", "build", "name")},
"warnings": ([f"Equity จาก server กับมูลค่าหุ้นรวมต่างกัน {differences:,.2f} บาท; ใช้เงินว่างจากโบรกเกอร์เป็นงบ"]
if differences > .02 else []),
}
self.store.put("snapshot", result)
self.store.reconcile(result, self.settings.magic)
return result
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
return {
"symbol": symbol, "bid": float(info.bid), "ask": float(info.ask), "last": float(info.last),
"time": int(tick.time if tick else info.time),
"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,
}
def symbols(self):
with self.lock:
self.connect()
values = self.api.symbols_get()
if values is None:
raise RuntimeError(f"อ่านรายชื่อหุ้นไม่ได้: {self.api.last_error()}")
return values
def history(self, symbol, count):
with self.lock:
self.connect()
for attempt in range(3):
data = self.api.copy_rates_from_pos(symbol, self.api.TIMEFRAME_D1, 0, count)
if data is not None and len(data):
return data
if attempt == 0:
self.api.symbol_select(symbol, True)
time.sleep(.3)
raise RuntimeError(f"{symbol}: ไม่มี D1 history ({self.api.last_error()})")
def _validate_order(self, request):
mt = self.api
terminal, account = self.connect()
if not (terminal.trade_allowed and not terminal.tradeapi_disabled
and account.trade_allowed and account.trade_expert):
raise ValueError("บัญชีหรือ MT5 ไม่อนุญาตให้ส่งคำสั่งผ่านโปรแกรม")
symbol = request['symbol']
for intent in self.store.unresolved():
prior = json.loads(intent['request'])
if (intent['status'] in ('unknown', 'sending') and prior.get('symbol') == symbol
and prior.get('comment') != request.get('comment')):
raise ValueError('หุ้นนี้มีคำสั่งที่ยังไม่ทราบผล ตรวจประวัติ MT5 ก่อนส่งคำสั่งใหม่')
info = mt.symbol_info(symbol)
if info is None or "Common Stock" not in info.path or info.trade_contract_size != 1:
raise ValueError("รองรับเฉพาะหุ้นสามัญที่ 1 volume เท่ากับ 1 หุ้น")
volume, price = float(request['volume']), float(request['price'])
if not math.isfinite(volume) or volume < 100 or volume % 100 or volume > info.volume_max:
raise ValueError("จำนวนต้องเป็นจำนวนเต็มครั้งละ 100 หุ้น")
if not math.isfinite(price) or price <= 0:
raise ValueError("ราคาไม่ถูกต้อง")
tick_size = ThaiMarketRules().tick_size(price)
if not math.isclose(price / tick_size, round(price / tick_size), abs_tol=1e-7):
raise ValueError(f"ราคาต้องตรงช่วงราคา {tick_size:g} บาท")
if info.trade_mode in (mt.SYMBOL_TRADE_MODE_DISABLED,):
raise ValueError("หุ้นนี้ถูกปิดการซื้อขาย")
orders = mt.orders_get()
positions = mt.positions_get(symbol=symbol)
if orders is None or positions is None:
raise ValueError("อ่านหุ้นหรือคำสั่งค้างไม่ได้")
if request['type'] == mt.ORDER_TYPE_BUY_LIMIT:
if info.trade_mode in (mt.SYMBOL_TRADE_MODE_SHORTONLY, mt.SYMBOL_TRADE_MODE_CLOSEONLY):
raise ValueError("หุ้นนี้ไม่อนุญาตเปิดสถานะซื้อ")
reserved = sum(o.volume_current * o.price_open for o in orders if o.type in (2, 4, 6))
budget = max(0., min(account.balance, account.margin_free) - reserved)
cost = volume * price * (1 + self.settings.fee_reserve_pct / 100)
if cost > budget + .005:
raise ValueError(f"เงินว่างไม่พอ ต้องใช้รวมเงินเผื่อค่าธรรมเนียม {cost:,.2f} บาท มี {budget:,.2f}")
else:
held = sum(p.volume for p in positions if p.type == mt.POSITION_TYPE_BUY)
reserved = sum(o.volume_current for o in orders
if o.symbol == symbol and o.type in (3, 5, 7))
if volume > held - reserved:
raise ValueError("จำนวนขายเกินหุ้นที่มีหลังหักคำสั่งขายค้าง")
return account
def preview(self, symbol, side, quantity, price, signals):
with self.lock:
mt = self.api
side = str(side).upper()
if side not in ("BUY", "SELL"):
raise ValueError("เลือกรายการซื้อหรือขาย")
_, account = self.connect()
if side == 'BUY':
row = next((s for s in signals if s['symbol'] == symbol), None)
if row is None or int(row.get('stale_sessions', 999)):
raise ValueError("ไม่มีสัญญาณซื้อที่ข้อมูลครบสำหรับหุ้นนี้")
reference = float(row['reference_close'])
if float(price) > reference * (1 + self.settings.max_premium_pct / 100) + 1e-8:
raise ValueError("ราคาสูงเกินส่วนต่างที่กำหนดจากราคาสัญญาณ ใช้ข้ามรอบนี้ได้")
ident = uuid.uuid4().hex
request = {
"action": mt.TRADE_ACTION_PENDING, "symbol": symbol,
"type": mt.ORDER_TYPE_BUY_LIMIT if side == 'BUY' else mt.ORDER_TYPE_SELL_LIMIT,
"volume": float(quantity), "price": float(price),
"type_time": mt.ORDER_TIME_DAY, "type_filling": mt.ORDER_FILLING_RETURN,
"magic": self.settings.magic, "comment": "PTMT5:" + ident[:12],
}
self._validate_order(request)
result = mt.order_check(request)
if result is None or result.retcode != 0:
raise ValueError(f"โบรกเกอร์ตรวจคำสั่งไม่ผ่าน: {result.comment if result else mt.last_error()}")
self.store.create_intent(ident, account.login, time.time(), request)
self.store.put('intent_context:' + ident, {
'signal_day': row.get('signal_as_of') if side == 'BUY' else None,
})
return {"id": ident, "request": request, "check": result.comment,
"expires_in": 60, "live_enabled": self.settings.live_orders}
def submit(self, ident):
with self.lock:
if not self.settings.live_orders:
raise ValueError("การส่งคำสั่งจริงยังปิดอยู่")
_, account = self.connect()
request = self.store.claim_intent(ident, account.login, time.time() - 60)
try:
self._validate_order(request)
check = self.api.order_check(request)
if check is None or check.retcode != 0:
raise ValueError(f"ตรวจคำสั่งซ้ำไม่ผ่าน: {check.comment if check else self.api.last_error()}")
except Exception as exc:
self.store.finish_intent(ident, "rejected", {"error": str(exc)})
raise
# Never automatically retry a send: an IPC/network error may happen
# after the broker has accepted it. Reconcile tickets/history first.
try:
result = self.api.order_send(request)
if result is None:
raise RuntimeError(f"ไม่ทราบผลคำสั่ง: {self.api.last_error()}")
result_data = result._asdict()
result_data['request'] = dict(request)
status = ("accepted" if result.retcode in (
self.api.TRADE_RETCODE_DONE, self.api.TRADE_RETCODE_PLACED,
self.api.TRADE_RETCODE_DONE_PARTIAL) else "rejected")
self.store.finish_intent(ident, status, result_data)
self.store.event("order_send", {"intent": ident, "status": status, "result": result_data})
return {"status": status, "result": result_data}
except Exception as exc:
self.store.finish_intent(ident, "unknown", {"error": str(exc)})
raise
def manage_pending(self, ticket, *, price=None):
with self.lock:
if not self.settings.live_orders:
raise ValueError("การส่งคำสั่งจริงยังปิดอยู่")
self.connect()
mt = self.api
orders = mt.orders_get(ticket=int(ticket))
if orders is None or len(orders) != 1 or orders[0].magic != self.settings.magic:
raise ValueError("จัดการได้เฉพาะคำสั่งค้างที่แอปนี้เป็นผู้ส่ง")
order = orders[0]
request = {"action": mt.TRADE_ACTION_REMOVE, "order": int(ticket)}
if price is not None:
raise ValueError("เปลี่ยนราคาโดยยกเลิกคำสั่งเดิมแล้วตรวจคำสั่งใหม่ เพื่อคำนวณงบซ้ำ")
# A durable token also prevents repeated cancellation sends.
ident = uuid.uuid4().hex
self.store.create_intent(ident, self.store.get('pinned_account')['login'], time.time(), request)
self.store.claim_intent(ident, self.store.get('pinned_account')['login'], time.time() - 60)
result = mt.order_send(request)
if result is None:
self.store.finish_intent(ident, 'unknown', {"error": str(mt.last_error())})
raise ValueError("ไม่ทราบผลยกเลิก ตรวจคำสั่งค้างก่อนทำซ้ำ")
data = result._asdict()
data['request'] = request
self.store.finish_intent(ident, 'accepted' if result.retcode == mt.TRADE_RETCODE_DONE else 'rejected', data)
self.store.event('cancel', data)
return data
+68
View File
@@ -0,0 +1,68 @@
from dataclasses import dataclass
from datetime import datetime, timedelta
import os
from pathlib import Path
from zoneinfo import ZoneInfo
ROOT = Path(__file__).resolve().parent
REPO = ROOT.parent
TZ = ZoneInfo("Asia/Bangkok")
@dataclass(frozen=True)
class Settings:
data_path: Path
port: int = 18901
live_orders: bool = False
magic: int = 1061501
model_start: str = "2026-01-01"
history_bars: int = 1000
eod_hour: int = 20
eod_minute: int = 30
max_premium_pct: float = 2.0
fee_reserve_pct: float = 0.2
refresh_seconds: int = 60
state_dir: Path = ROOT / "data"
@property
def warmup_start(self):
return (datetime.fromisoformat(self.model_start) - timedelta(days=700)).date().isoformat()
def closed_through(self, now=None):
now = (now or datetime.now(TZ)).astimezone(TZ)
day = now.date()
if (now.hour, now.minute) < (self.eod_hour, self.eod_minute):
day -= timedelta(days=1)
return day.isoformat()
@classmethod
def load(cls):
values = {}
env = ROOT / ".env"
if env.exists():
for raw in env.read_text(encoding="utf-8-sig").splitlines():
if raw.strip() and not raw.lstrip().startswith("#") and "=" in raw:
key, value = raw.split("=", 1)
values[key.strip()] = value.strip().strip('"').strip("'")
values.update({k: v for k, v in os.environ.items() if k.startswith("MT5_")})
path = values.get("MT5_DATA_PATH", "")
if not path:
raise ValueError("Set MT5_DATA_PATH in mt5_app/.env")
config = cls(
data_path=Path(path).resolve(),
port=int(values.get("MT5_PORT", 18901)),
live_orders=values.get("MT5_ENABLE_LIVE_ORDERS", "false").lower() == "true",
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)),
eod_hour=int(values.get("MT5_EOD_HOUR", 20)),
eod_minute=int(values.get("MT5_EOD_MINUTE", 30)),
max_premium_pct=float(values.get("MT5_MAX_ENTRY_PREMIUM_PCT", 2)),
fee_reserve_pct=float(values.get("MT5_FEE_RESERVE_PCT", .2)),
refresh_seconds=int(values.get("MT5_REFRESH_SECONDS", 60)),
)
if not 1024 <= config.port <= 65535 or config.history_bars < 700:
raise ValueError("Invalid port or fewer than 700 history bars")
if not 0 <= config.max_premium_pct <= 20 or not 0 <= config.fee_reserve_pct <= 5:
raise ValueError("Invalid price premium or fee reserve")
return config
+97
View File
@@ -0,0 +1,97 @@
<!doctype html>
<html lang="th">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>PrimeThai · MT5 Desk</title>
<style>
:root{color-scheme:dark;--bg:#0b1018;--panel:#131c28;--line:#253348;--ink:#edf3fc;--muted:#9aaac0;--green:#70dfbb;--red:#ff8f9d;--amber:#f7cc7e}
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.65 system-ui,"Segoe UI",sans-serif}main{max-width:1450px;margin:auto;padding:30px}header{display:flex;justify-content:space-between;align-items:center;gap:15px;margin-bottom:20px}.eyebrow{color:var(--green);font-size:12px;letter-spacing:2px}h1{font-size:28px;letter-spacing:-1px;margin:3px 0}h2{font-size:18px;margin:0 0 8px}p{margin:6px 0}.muted,.small{color:var(--muted)}.small{font-size:12px}.actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap}button,a.button{border:1px solid var(--line);background:#1b293a;color:var(--ink);border-radius:8px;padding:9px 13px;cursor:pointer;font:inherit;text-decoration:none}button:hover{border-color:var(--green)}button:disabled{opacity:.45;cursor:default}.primary{background:#2c745f;color:#fff;border-color:#48937a}.danger{background:#603040;color:#fff}.mini{font-size:12px;padding:5px 8px}.badge{font-size:12px;border:1px solid var(--line);border-radius:30px;padding:5px 10px;color:var(--muted)}.positive{color:var(--green)}.negative{color:var(--red)}.warning{color:var(--amber)}
.banner{background:#152235;border:1px solid #2a4464;border-radius:10px;padding:14px 18px;margin:14px 0}.banner.warning{background:#302719;border-color:#69502b}.banner.error{background:#311d29;border-color:#743c4c;color:var(--red)}.metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin:22px 0}.metric,.panel{background:var(--panel);border:1px solid var(--line);border-radius:12px}.metric{padding:18px}.metric strong{display:block;font-size:27px;margin:8px 0 2px;font-variant-numeric:tabular-nums}.label{color:var(--muted);font-size:13px}.panel{padding:20px;margin:16px 0}.panel-head{display:flex;justify-content:space-between;gap:16px;align-items:center;margin-bottom:16px}nav{display:flex;gap:8px;border-bottom:1px solid var(--line);padding-bottom:12px;overflow:auto}nav button{white-space:nowrap;background:transparent}nav button.active{background:#203e3a;border-color:#468c75;color:var(--green)}[hidden]{display:none!important}.scroll{overflow:auto}table{width:100%;border-collapse:collapse;white-space:nowrap;font-size:13px}th,td{padding:12px 10px;border-bottom:1px solid var(--line);text-align:left}th{font-size:12px;color:var(--muted);font-weight:500}td.num,th.num{text-align:right;font-variant-numeric:tabular-nums}.symbol{font-weight:700;color:#fff}.empty{text-align:center;color:var(--muted);padding:38px}.two{display:grid;grid-template-columns:1fr 1fr;gap:16px}.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}label{color:var(--muted);font-size:13px;display:block}input{display:block;width:100%;border:1px solid var(--line);background:#0b1420;color:#fff;padding:10px;border-radius:7px;font:inherit;margin:5px 0 12px}dialog{background:var(--panel);color:var(--ink);border:1px solid #54738e;border-radius:14px;padding:25px;max-width:620px;width:calc(100% - 28px)}dialog::backdrop{background:#000a}.toast{position:fixed;right:22px;bottom:22px;background:#263d38;border:1px solid var(--green);padding:14px 20px;border-radius:10px;max-width:550px;z-index:10}.toast.error{background:#472534;border-color:var(--red)}progress{height:5px;width:100%;accent-color:var(--green)}.chart{height:220px;width:100%;display:block}details{margin:10px 0}summary{cursor:pointer;color:var(--muted)}footer{margin:24px 0;font-size:12px;color:var(--muted)}
@media(max-width:850px){main{padding:18px}header,.panel-head{align-items:flex-start;flex-direction:column}.metrics{grid-template-columns:1fr 1fr}.two{grid-template-columns:1fr}.grid{grid-template-columns:1fr}.metric strong{font-size:22px}h1{font-size:24px}}
</style>
</head>
<body><main>
<header><div><div class="eyebrow">PRIMETHAI / LOCAL MT5 DESK</div><h1>ดูแลพอร์ตจากบัญชีจริง</h1><div class="small" id="connection">กำลังอ่านข้อมูล MT5…</div></div><div class="actions"><span class="badge" id="live-state">อ่านพอร์ต</span><button id="trading-mode">เปิดการส่งจริง</button><button id="sync">อัปเดตพอร์ต</button><button id="research-refresh">คำนวณสัญญาณใหม่</button></div></header>
<div class="banner" id="job"><span id="job-message">กำลังเริ่มแอป</span><progress id="job-progress" hidden></progress></div>
<div class="banner warning" id="warnings" hidden></div>
<section class="metrics">
<article class="metric"><div class="label">Equity ที่โบรกเกอร์รายงาน</div><strong id="equity">—</strong><div class="small" id="equity-note">จากบัญชี MT5</div></article>
<article class="metric"><div class="label">เงินว่างสำหรับแผนซื้อ</div><strong id="cash">—</strong><div class="small">หักคำสั่งซื้อค้างและเผื่อค่าธรรมเนียมในแผน</div></article>
<article class="metric"><div class="label">กำไร / ขาดทุนค้าง</div><strong id="profit">—</strong><div class="small">ตาม MT5 · ยังไม่รวมค่าธรรมเนียมซื้อขาย</div></article>
<article class="metric"><div class="label">หุ้นที่ถือ / คำสั่งค้าง</div><strong id="counts">—</strong><div class="small" id="asof">กำลังตรวจวันสัญญาณ</div></article>
</section>
<nav><button data-page="signals" class="active">สัญญาณและแผนวันนี้</button><button data-page="portfolio">พอร์ตและคำสั่งจริง</button><button data-page="compare">เทียบ MT5 กับระบบเดิม</button><button data-page="backtest">ผล Backtest</button><button data-page="history">ประวัติและสถานะ</button></nav>
<section data-content="signals">
<article class="panel"><div class="panel-head"><div><h2>Donchian 55/20 + EMA 50/200</h2><p class="small">ซื้อเมื่อโมเดลใดโมเดลหนึ่งเลือกหุ้น · ขนาดขั้นต่ำ 100 หุ้น · ต้นทุนและจำนวนที่ถืออ่านจาก MT5</p></div><span class="badge" id="signal-date">กำลังอ่านข้อมูล</span></div>
<div class="scroll"><table><thead><tr><th>หุ้น / ลำดับ</th><th>โมเดล</th><th class="num">ถืออยู่</th><th class="num">ราคาสัญญาณ</th><th class="num">เสนอขายล่าสุด</th><th class="num">ต่างจากสัญญาณ</th><th class="num">จำนวนในแผน</th><th>การจัดสรร</th><th>จัดการ</th></tr></thead><tbody id="signals-table"></tbody></table></div>
<p class="small" style="margin-top:14px" id="plan-note">การข้ามไม่เปลี่ยนเงินสดหรือหุ้นจริง ระบบจะนำงบในแผนไปพิจารณาตัวถัดไป และคืนรายการเมื่อมีสัญญาณวันใหม่</p></article>
</section>
<section data-content="portfolio" hidden>
<article class="panel"><div class="panel-head"><div><h2>หุ้นที่ถือจริง</h2><p class="small">ต้นทุนและผลซื้อขายดึงจากโบรกเกอร์ ไม่สร้างรายการซื้อประมาณการเพิ่ม</p></div></div><div class="scroll"><table><thead><tr><th>หุ้น</th><th class="num">จำนวน</th><th class="num">ต้นทุนต่อหุ้น</th><th class="num">ราคาประเมิน</th><th class="num">กำไรค้าง</th><th>ที่มาของรายการ</th></tr></thead><tbody id="holdings-table"></tbody></table></div></article>
<article class="panel"><h2>คำสั่งที่ยังรอจับคู่</h2><p class="small">แสดงทุกคำสั่งในบัญชี ยกเลิกได้เฉพาะคำสั่งที่แอปนี้ส่ง</p><div class="scroll"><table><thead><tr><th>หุ้น</th><th>ประเภท</th><th class="num">เหลือ</th><th class="num">ราคา</th><th>เจ้าของคำสั่ง</th><th>จัดการ</th></tr></thead><tbody id="orders-table"></tbody></table></div></article>
</section>
<section data-content="compare" hidden>
<article class="panel"><div class="panel-head"><div><h2>สัญญาณจากสองแหล่งข้อมูลตรงกันหรือไม่</h2><p class="small">ใช้วันสิ้นสุดเดียวกัน ช่วง warm-up เดียวกัน และกฎกลยุทธ์ชุดเดียวกัน</p></div><span class="badge" id="compare-date">รอการเปรียบเทียบ</span></div><p id="compare-summary">กำลังจัดเตรียมข้อมูล…</p><div class="scroll"><table><thead><tr><th>ข้อมูลที่เทียบ</th><th class="num">จำนวนแท่งที่เทียบ</th><th class="num">ตรงกัน</th><th class="num">แตกต่าง</th><th class="num">ตรงกัน (%)</th></tr></thead><tbody id="data-compare-table"></tbody></table></div><p class="small" id="compare-coverage"></p></article>
<article class="panel"><h2>รายชื่อ โมเดล และลำดับจัดสรรงบ</h2><div class="scroll"><table><thead><tr><th>หุ้น</th><th>MT5</th><th>SiamChart / ระบบเดิม</th><th>โมเดล</th><th class="num">ลำดับ MT5</th><th class="num">ลำดับเดิม</th><th class="num">คะแนน MT5</th><th class="num">คะแนนเดิม</th></tr></thead><tbody id="signal-compare-table"></tbody></table></div><button class="mini" id="download-compare" style="margin-top:14px">ดาวน์โหลดรายงานเปรียบเทียบ</button><details><summary>ตัวอย่างราคาปิดที่แตกต่าง</summary><div class="scroll"><table><thead><tr><th>วัน</th><th>หุ้น</th><th class="num">MT5</th><th class="num">SiamChart</th></tr></thead><tbody id="difference-table"></tbody></table></div></details></article>
</section>
<section data-content="backtest" hidden>
<article class="panel"><h2>Backtest บนช่วงวันที่เดียวกัน</h2><p class="small">ทุนเริ่มต้น 10,000 บาท · ขั้นต่ำ 100 หุ้น · ใช้ commission และ slippage สมมติฐานเดิม · ผลจำลองไม่ใช่กำไรในบัญชีจริง</p><div class="scroll"><table><thead><tr><th>แหล่งข้อมูล</th><th>ช่วงเวลา</th><th class="num">ผลตอบแทน</th><th class="num">ขาดทุนสูงสุด</th><th class="num">จำนวน fills</th></tr></thead><tbody id="backtest-table"></tbody></table></div><svg id="equity-chart" class="chart" role="img" aria-label="เปรียบเทียบมูลค่าพอร์ตจำลอง"></svg><p class="small">เส้นสีเขียว = MT5 · เส้นสีทอง = SiamChart · ใช้เฉพาะช่วงวันร่วมกัน</p></article>
<article class="panel"><h2>Backtest จาก MT5 ถึงวันล่าสุด</h2><div id="latest-backtest"></div></article>
</section>
<section data-content="history" hidden>
<article class="panel"><h2>ประวัติซื้อขายจริงล่าสุด</h2><div class="scroll"><table><thead><tr><th>เวลาไทย</th><th>หุ้น</th><th>รายการ</th><th class="num">จำนวน</th><th class="num">ราคาจริง</th><th class="num">ค่าธรรมเนียม</th><th class="num">กำไรที่รับรู้</th></tr></thead><tbody id="deals-table"></tbody></table></div></article>
<article class="panel"><h2>คำสั่งที่ตรวจหรือส่งจากแอปนี้</h2><p class="small">หากขึ้น unknown หรือ sending ค้าง ให้ตรวจบัญชี MT5 ก่อน แอปจะไม่ส่งคำสั่งเดิมซ้ำอัตโนมัติ</p><div class="scroll"><table><thead><tr><th>เวลา</th><th>หุ้น</th><th>สถานะ</th><th>รายละเอียด</th></tr></thead><tbody id="intents-table"></tbody></table></div></article>
<article class="panel"><h2>ข้อมูลที่เก็บในเครื่อง</h2><p id="history-state">กำลังตรวจประวัติราคา…</p><p class="small">ราคาหลักเป็น MT5 D1 และ real volume · ดัชนี SET มาจาก MT5 · ปันผลและแตกหุ้นอ้างอิงข้อมูลเดิมที่มีอยู่ · ข้อมูลส่วนตัวเก็บแยกในแอป MT5</p><details><summary>ข้อมูลที่ยังดึงไม่ได้</summary><pre id="history-errors" style="white-space:pre-wrap;font-size:12px"></pre></details></article>
</section>
<footer>แอป MT5 แยกจากระบบเดิม · ดึงพอร์ตอัตโนมัติ และคำนวณสัญญาณหลังมีราคาปิดวันใหม่ · ทุกคำสั่งจริงต้องตรวจและยืนยันรายครั้ง</footer>
</main>
<dialog id="order-dialog"><h2 id="order-title">ตรวจคำสั่ง</h2><p class="small">ส่งเป็น Limit มีผลภายในวัน ตามราคาและจำนวนที่ยืนยัน ผลจับคู่จริงจะอ่านกลับจาก MT5</p><div class="grid"><label>หุ้น<input id="order-symbol" readonly></label><label>จำนวนหุ้น<input id="order-quantity" type="number" min="100" step="100"></label><label>ราคา Limit<input id="order-price" type="number" min="0.01" step="0.01"></label></div><div class="banner" id="preview-result" hidden></div><div class="actions"><button id="preview-order">ตรวจคำสั่งกับโบรกเกอร์</button><button class="danger" id="send-order" hidden>ยืนยันส่งคำสั่งจริง</button><button id="close-dialog">ปิด</button></div><p class="small" id="live-help"></p></dialog>
<div id="toast" class="toast" hidden></div>
<script>
const TOKEN='__APP_TOKEN__';const $=id=>document.getElementById(id);let state=null,loading=false,preview=null,currentSide=null,toastTimer;
const money=v=>v==null?'—':Number(v).toLocaleString('th-TH',{minimumFractionDigits:2,maximumFractionDigits:2});
const num=v=>Number(v||0).toLocaleString('th-TH');const pct=v=>v==null?'—':(v>=0?'+':'')+Number(v).toFixed(2)+'%';
const timestamp=v=>v?new Date(typeof v==='number'?v*1000:v).toLocaleString('th-TH',{timeZone:'Asia/Bangkok'}):'—';
const labels={BUY:'ซื้อเพิ่ม',SELL:'พิจารณาขาย',HOLD:'ถือ',BUDGET:'งบไม่พอ',SKIPPED:'ข้ามรอบนี้',PENDING:'รอคำสั่งเดิม',WAIT:'รอข้อมูล'};
function toast(message,error=false){clearTimeout(toastTimer);$('toast').textContent=message;$('toast').className='toast'+(error?' error':'');$('toast').hidden=false;toastTimer=setTimeout(()=>$('toast').hidden=true,10000);}
async function api(path,body){const r=await fetch('/api/'+path,{method:body===undefined?'GET':'POST',headers:{'X-App-Token':TOKEN,'Content-Type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)})});const result=await r.json();if(!r.ok)throw new Error(result.error||'คำขอไม่สำเร็จ');return result;}
function button(text,fn,cls='mini'){const b=document.createElement('button');b.textContent=text;b.className=cls;b.onclick=async()=>{b.disabled=true;try{await fn();}catch(e){toast(e.message,true);}finally{b.disabled=false;}};return b;}
function cell(text,cls=''){const td=document.createElement('td');td.textContent=text==null?'—':String(text);td.className=cls;return td;}
function table(id,rows,columns){const body=$(id);body.replaceChildren();if(!rows?.length){const tr=document.createElement('tr');const td=cell('ยังไม่มีรายการ','empty');td.colSpan=columns.length;tr.append(td);body.append(tr);return;}for(const row of rows){const tr=document.createElement('tr');for(const col of columns){const value=col(row);if(value instanceof Node)tr.append(value);else tr.append(cell(value));}body.append(tr);}}
const n=v=>cell(money(v),'num');const p=v=>cell(pct(v),'num '+(v>=0?'positive':'negative'));
function chart(left,right){const svg=$('equity-chart');svg.replaceChildren();const all=[...(left||[]),...(right||[])];if(all.length<2)return;const days=[...new Set(all.map(r=>r.day))].sort();const lo=Math.min(...all.map(r=>r.equity)),hi=Math.max(...all.map(r=>r.equity));svg.setAttribute('viewBox','0 0 1000 220');for(const [series,color] of [[left,'#70dfbb'],[right,'#f7cc7e']]){if(!series?.length)continue;const line=document.createElementNS('http://www.w3.org/2000/svg','polyline');line.setAttribute('points',series.map(r=>`${25+950*days.indexOf(r.day)/Math.max(1,days.length-1)},${195-170*(r.equity-lo)/Math.max(1,hi-lo)}`).join(' '));line.setAttribute('fill','none');line.setAttribute('stroke',color);line.setAttribute('stroke-width','2');svg.append(line);}}
function render(d){state=d;const s=d.snapshot||{},a=s.account||{},r=d.research||{},c=r.comparison||{},job=d.job||{};
const paused=(!r.data_quality?.calendar_source)||(job.running&&['history','archive','signals','comparison'].includes(job.stage));const planRows=(d.plan?.rows||[]).map(x=>paused?{...x,action:'WAIT',quantity:0,reason:'รอคำนวณและตรวจข้อมูลให้เสร็จก่อน'}:x);$('sync').disabled=!!job.running;$('research-refresh').disabled=!!job.running;$('trading-mode').disabled=paused&&!d.live_enabled;
$('connection').textContent=(a.server||'ยังไม่เชื่อมต่อ')+' · '+(a.login_masked||'')+' · อัปเดต '+timestamp(s.updated_at);
$('live-state').textContent=d.live_enabled?'เปิดการส่งคำสั่งจริง · ยืนยันรายครั้ง':'โหมดอ่านพอร์ตและตรวจคำสั่ง';$('live-state').className='badge '+(d.live_enabled?'warning':'positive');
$('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;}
const warnings=[...(s.warnings||[])];if(d.connection_error)warnings.push('อ่าน MT5 ล่าสุดไม่สำเร็จ: '+d.connection_error.message+' · ข้อมูลที่เห็นเป็นข้อมูลก่อนหน้า');if(d.history?.failures?.length)warnings.push('ยังดึงประวัติไม่ได้ '+d.history.failures.length+' หุ้น ดูรายละเอียดในประวัติและสถานะ');if(c.as_of&&r.signal_as_of!==c.as_of)warnings.push('สัญญาณ MT5 ถึง '+r.signal_as_of+'; ข้อมูลเดิมเทียบได้ถึง '+c.as_of+' จึงแสดงผลเทียบเฉพาะวันร่วมกัน');$('warnings').hidden=!warnings.length;$('warnings').textContent=warnings.join(' · ');
$('equity').textContent=money(a.equity);$('equity-note').textContent=Math.abs(a.equity_difference||0)>.02?'ยอดต่างจากรวมราคาหุ้น '+money(a.equity_difference)+' บาท':'ตรงกับยอดเงินสดและมูลค่าหุ้น';$('cash').textContent=money(d.plan?.cash_budget);$('profit').textContent=money(a.profit);$('profit').className=a.profit>=0?'positive':'negative';$('counts').textContent=num(s.positions?.length)+' / '+num(s.orders?.length);$('asof').textContent='สัญญาณจากราคาปิด '+(r.signal_as_of||'กำลังคำนวณ');$('signal-date').textContent=r.signal_as_of||'รอประวัติราคา';
table('signals-table',planRows,[x=>cell(x.symbol+(x.rank?' · #'+x.rank:''),'symbol'),x=>x.source_model?.replaceAll('donchian_55_20','Donchian').replaceAll('ema50_200_cross','EMA')||'นอกเป้าหมาย',x=>cell(num(x.held),'num'),x=>n(x.reference_close),x=>{const td=n(x.ask);td.title='ราคาเสนอ ณ '+timestamp(x.quote_time);return td;},x=>cell(pct(x.premium_pct),'num '+(x.premium_pct>state.max_premium_pct?'warning':'muted')),x=>cell(num(x.quantity),'num'),x=>{const td=cell(labels[x.action]||x.action,x.action==='BUY'?'positive':x.action==='SELL'?'warning':'muted');td.title=x.reason||'';return td;},x=>{const td=document.createElement('td');const group=document.createElement('div');group.className='actions';if(['BUY','SELL'].includes(x.action))group.append(button(x.action==='BUY'?'ซื้อเพิ่ม':'ตรวจขาย',()=>openOrder(x),x.action==='BUY'?'mini primary':'mini'));if(!paused&&x.source_model&&x.action!=='PENDING')group.append(button(x.action==='SKIPPED'?'กลับมาพิจารณา':'ซื้อไม่ทัน',async()=>{await api('skip',{symbol:x.symbol,skip:x.action!=='SKIPPED'});await load();}));td.append(group);return td;}]);
table('holdings-table',s.positions,[x=>cell(x.symbol,'symbol'),x=>cell(num(x.volume),'num'),x=>n(x.price_open),x=>n(x.price_current),x=>cell(money(x.profit),'num '+(x.profit>=0?'positive':'negative')),x=>x.magic===d.app_magic?'แอป MT5 นี้':x.magic?'โปรแกรมอื่น':'รายการเดิม / ทำเอง']);
table('orders-table',s.orders,[x=>x.symbol,x=>({2:'Buy Limit',3:'Sell Limit',4:'Buy Stop',5:'Sell Stop'})[x.type]||x.type,x=>num(x.volume_current),x=>money(x.price_open),x=>x.magic===d.app_magic?'แอปนี้':'ภายนอกแอป',x=>{const td=document.createElement('td');if(x.magic===d.app_magic&&d.live_enabled)td.append(button('ยกเลิก',async()=>{if(!confirm(`ยกเลิกคำสั่ง ${x.symbol} #${x.ticket} จริงหรือไม่?`))return;await api('cancel',{ticket:x.ticket,confirm:'CANCEL_LIVE'});toast('ส่งคำขอยกเลิกแล้ว ตรวจสถานะจาก MT5');await load();}));else td.textContent='—';return td;}]);
$('compare-date').textContent=c.as_of||'กำลังเปรียบเทียบ';$('compare-summary').textContent=c.error||(!c.as_of?'รอประวัติ MT5 ครบก่อนคำนวณ':(c.same_signal_membership_and_model?'รายชื่อหุ้นและโมเดลตรงกัน':'พบความต่างของรายชื่อหุ้นหรือโมเดล')+` · MT5 ${c.mt5_count} ตัว / เดิม ${c.siamchart_count} ตัว · หุ้นร่วมกัน ${c.common_signal_count} ตัว · ลำดับคะแนน${c.same_rankings?'ตรงกัน':'ต่างกัน'}`);
table('data-compare-table',Object.entries(c.ohlcv||{}).map(([field,x])=>({field,...x})),[x=>x.field,x=>num(x.compared),x=>num(x.matched),x=>num(x.different),x=>money(x.match_pct)]);
$('compare-coverage').textContent=c.as_of?`${num(c.shared_sessions)} วันร่วมกัน · ${num(c.shared_symbols)} หุ้นร่วมกัน · SET ต่างกัน ${num(c.set_different)} วัน · ไม่มีใน MT5 ${num(c.missing_from_mt5?.length)} หุ้น · แท่งขาดจาก MT5 ${num(c.bars_only_siamchart)} แท่ง · เป้าหมายย้อนหลังต่างกัน ${num(c.historical_target_days_different)} จาก ${num(c.historical_target_days_compared)} วัน`:'';
table('signal-compare-table',c.signals,[x=>x.symbol,x=>x.mt5||'ไม่เลือก',x=>x.siamchart||'ไม่เลือก',x=>cell(x.same?'ตรงกัน':'ต่างกัน',x.same?'positive':'warning'),x=>x.mt5_rank||'—',x=>x.siamchart_rank||'—',x=>n(x.mt5_allocation_score),x=>n(x.siamchart_allocation_score)]);
table('difference-table',c.close_difference_samples,[x=>x.day,x=>x.symbol,x=>n(x.mt5),x=>n(x.siamchart)]);
const bs=[['MT5',c.backtest_mt5],['SiamChart',c.backtest_siamchart]].filter(x=>x[1]);table('backtest-table',bs,[x=>x[0],x=>x[1].metrics.start+' – '+x[1].metrics.end,x=>p(x[1].metrics.total_return*100),x=>p(x[1].metrics.max_drawdown*100),x=>num(x[1].metrics.fills_full_run)]);chart(c.backtest_mt5?.curve,c.backtest_siamchart?.curve);
const latest=r.backtest_mt5_latest?.metrics;$('latest-backtest').textContent=latest?`${latest.start} – ${latest.end} · ผลตอบแทน ${pct(latest.total_return*100)} · ขาดทุนสูงสุด ${pct(latest.max_drawdown*100)} · มูลค่าปลายงวด ${money(latest.ending_equity||latest.equity_end)} บาท`:'รอการคำนวณ';
const deals=(s.deals||[]).filter(x=>[0,1].includes(x.type)).slice(-40).reverse();table('deals-table',deals,[x=>timestamp(x.time),x=>x.symbol,x=>x.type===0?'ซื้อ':'ขาย',x=>num(x.volume),x=>n(x.price),x=>n(-(x.commission+x.fee)),x=>n(x.profit)]);
table('intents-table',d.intents,[x=>timestamp(x.created),x=>{try{return JSON.parse(x.request).symbol||'ยกเลิก';}catch{return '—';}},x=>x.status,x=>{try{const z=JSON.parse(x.result||'{}');return z.comment||z.error||'ตรวจคำสั่งแล้ว ยังไม่ส่ง';}catch{return '—';}}]);
const h=d.history?.bar_summary;$('history-state').textContent=h?`เก็บ ${num(h.rows)} แท่ง · ${num(h.symbols)} สัญลักษณ์ · ${h.first_day} ถึง ${h.last_day}`:'กำลังดาวน์โหลดประวัติครั้งแรก';$('history-errors').textContent=JSON.stringify(d.history?.failures||[],null,2);
}
async function load(){if(loading)return;loading=true;try{render(await api('state'));}catch(e){$('job-message').textContent='อ่านแอปไม่สำเร็จ: '+e.message;$('job').className='banner error';}finally{loading=false;}}
function openOrder(row){currentSide=row.action;preview=null;$('order-title').textContent=(currentSide==='BUY'?'ซื้อ ':'ขาย ')+row.symbol;$('order-symbol').value=row.symbol;$('order-quantity').value=row.quantity;$('order-price').value=row.limit_price||row.current||'';$('preview-result').hidden=true;$('send-order').hidden=true;$('live-help').textContent=state.live_enabled?'ทุกคำสั่งส่งเข้าบัญชีจริง โปรดตรวจจำนวนและราคา':'ขณะนี้ตรวจคำสั่งได้ แต่การส่งคำสั่งจริงยังปิดอยู่';$('order-dialog').showModal();}
for(const id of ['order-quantity','order-price'])$(id).oninput=()=>{preview=null;$('send-order').hidden=true;$('preview-result').hidden=true;};
$('preview-order').onclick=async()=>{try{preview=await api('preview',{symbol:$('order-symbol').value,side:currentSide,quantity:Number($('order-quantity').value),price:Number($('order-price').value)});$('preview-result').textContent=`ตรวจผ่าน: ${currentSide==='BUY'?'ซื้อ':'ขาย'} ${preview.request.symbol} ${num(preview.request.volume)} หุ้น ราคา ${money(preview.request.price)} · ยืนยันภายใน 60 วินาที`;$('preview-result').className='banner';$('preview-result').hidden=false;$('send-order').hidden=!preview.live_enabled;}catch(e){$('preview-result').textContent=e.message;$('preview-result').className='banner error';$('preview-result').hidden=false;}};
$('send-order').onclick=async()=>{if(!preview||!confirm('ยืนยันส่งคำสั่งนี้เข้าบัญชีจริงหรือไม่?'))return;$('send-order').disabled=true;try{const result=await api('submit',{id:preview.id,confirm:'SEND_LIVE'});toast(result.status==='accepted'?'โบรกเกอร์รับคำสั่งแล้ว รอผลจับคู่ในหน้าพอร์ต':'โบรกเกอร์ไม่รับคำสั่ง: '+(result.result?.comment||result.status),result.status!=='accepted');$('order-dialog').close();await load();}catch(e){toast(e.message,true);}finally{preview=null;$('send-order').disabled=false;$('send-order').hidden=true;}};
$('close-dialog').onclick=()=>$('order-dialog').close();
$('sync').onclick=async()=>{try{await api('refresh',{});await load();}catch(e){toast(e.message,true);}};
$('trading-mode').onclick=async()=>{const enable=!state?.live_enabled;const message=enable?`เปิดให้แอปส่งคำสั่งเข้าบัญชีจริง ${state?.snapshot?.account?.login_masked||''} สำหรับรอบเปิดแอปนี้หรือไม่?\n\nแต่ละคำสั่งยังต้องตรวจและยืนยันรายครั้ง`: 'ปิดการส่งคำสั่งใหม่จากแอปหรือไม่? คำสั่งที่โบรกเกอร์รับไปแล้วยังรอจับคู่ตามเดิม';if(!confirm(message))return;try{await api('trading',{enabled:enable,confirm:enable?'ENABLE_LIVE':'DISABLE_LIVE'});await load();}catch(e){toast(e.message,true);}};
$('research-refresh').onclick=async()=>{try{await api('refresh',{research:true});await load();}catch(e){toast(e.message,true);}};
document.querySelectorAll('nav button').forEach(b=>b.onclick=()=>{document.querySelectorAll('nav button').forEach(x=>x.classList.toggle('active',x===b));document.querySelectorAll('[data-content]').forEach(x=>x.hidden=x.dataset.content!==b.dataset.page);});
$('download-compare').onclick=()=>{const blob=new Blob([JSON.stringify(state?.research?.comparison||{},null,2)],{type:'application/json'});const a=document.createElement('a');const url=URL.createObjectURL(blob);a.href=url;a.download='mt5-comparison.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
load();setInterval(load,5000);
</script></body></html>
+4
View File
@@ -0,0 +1,4 @@
# Install from the repository root with: python -m pip install -r mt5_app/requirements.txt
MetaTrader5==5.0.6231
numpy==2.5.3
pandas==3.0.5
+316
View File
@@ -0,0 +1,316 @@
"""MT5-only prices; unchanged PrimeThai rules; comparisons on identical dates."""
from collections import defaultdict
from datetime import datetime, timedelta, timezone
import csv
import hashlib
import io
import json
import math
from pathlib import Path
import re
import time
import zipfile
import numpy as np
import pandas as pd
from primethai.config import TradingCosts
from primethai.model_lab import (
_features, build_model_targets, build_union_target_weights,
build_next_session_union_signals, load_market_panel,
simulate_board_lots, calculate_model_metrics,
)
from .config import REPO, TZ
from .store import now_iso
MODELS = ("donchian_55_20", "ema50_200_cross")
EOD = re.compile(r"set-history_EOD_(\d{4}-\d{2}-\d{2})\.csv$", re.I)
def plain(value):
if isinstance(value, dict):
return {str(k): plain(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [plain(v) for v in value]
if isinstance(value, (datetime, pd.Timestamp)):
return value.isoformat()
if hasattr(value, 'item'):
return plain(value.item())
if isinstance(value, float) and not math.isfinite(value):
return None
return value
def download_history(broker, store, settings, progress, *, force=False):
through = settings.closed_through()
if store.get('history_checked_through') == through and not force:
progress('history', 'ใช้ประวัติ MT5 ที่เก็บไว้แล้ว', 1, 1)
return store.get('history_download', {})
symbols = [s.name for s in broker.symbols()
if 'Common Stock' in s.path and s.path.split('\\')[0] in ('SET', 'MAI')
and re.fullmatch(r'[A-Z0-9]{1,5}', s.name)]
symbols = sorted(set(symbols) | {'SET'})
previous_record = store.get('history_download', {})
previous = set(previous_record.get('successful_symbols', []))
successful, failures, zero_volume = [], [], []
for number, symbol in enumerate(symbols, 1):
progress('history', f'อ่าน D1 {symbol} · {number}/{len(symbols)}', number, len(symbols))
try:
symbol_state = store.get('history_symbol:' + symbol, {})
if (symbol_state.get('through') == through
or (symbol in previous and previous_record.get('through') == through)) and not force:
successful.append(symbol)
if symbol in previous_record.get('zero_real_volume', []):
zero_volume.append(symbol)
continue
prior_day = symbol_state.get('through', previous_record.get('through'))
gap = (datetime.fromisoformat(through) - datetime.fromisoformat(prior_day)).days if prior_day else 999
count = settings.history_bars if force or symbol not in previous or gap > 20 else 30
rates = broker.history(symbol, count)
rows = []
for r in rates:
# D1 timestamps label the exchange session. MT5 stores them as
# UTC; do not use the workstation timezone to shift the date.
day = datetime.fromtimestamp(int(r['time']), timezone.utc).date().isoformat()
prices = [float(r[c]) for c in ('open', 'high', 'low', 'close')]
if day < settings.warmup_start or day > through:
continue
if not all(math.isfinite(p) and p > 0 for p in prices):
continue
rows.append((symbol, day, *prices, float(r['real_volume']), float(r['tick_volume'])))
if not rows:
raise ValueError('ไม่มีแท่งปิดในช่วงที่ต้องใช้')
if symbol != 'SET' and all(r[6] <= 0 for r in rows):
zero_volume.append(symbol)
store.save_bars(rows)
store.put('history_symbol:' + symbol, {'through': through, 'rows': len(rows), 'checked_at': now_iso()})
successful.append(symbol)
except Exception as exc:
failures.append({'symbol': symbol, 'error': str(exc)})
result = {'checked_at': now_iso(), 'through': through, 'requested': len(symbols),
'successful_symbols': successful, 'failures': failures, 'zero_real_volume': zero_volume,
'bar_summary': store.bar_summary()}
store.put('history_download', result)
if 'SET' not in successful:
raise ValueError('ไม่มีข้อมูล SET จาก MT5 จึงยังคำนวณ market filter ไม่ได้')
# Retry incomplete downloads on the next scheduled pass.
if not failures:
store.put('history_checked_through', through)
return result
def export_archive(store, settings):
path = settings.state_dir / 'mt5_eod.zip'
rows = store.bars(settings.warmup_start, settings.closed_through())
by_day = defaultdict(list)
for r in rows:
by_day[r['day']].append(r)
if not by_day:
raise ValueError('ยังไม่มีประวัติราคาที่ปิดแล้ว')
# Some individual MT5 symbols contain bars on market holidays. A session
# without a SET bar must not enter the common calendar: it would introduce
# a missing benchmark observation and invalidate its 200-session average.
sessions = {r['day'] for r in rows if r['symbol'] == 'SET'}
if not sessions or max(by_day) > max(sessions):
raise ValueError('ดัชนี SET ยังไม่ถึงวันล่าสุดของหุ้น รอข้อมูลก่อนคำนวณสัญญาณ')
excluded = sorted(set(by_day) - sessions)
quality = {'calendar_source': 'MT5 SET D1',
'excluded_non_session_days': [
{'day': day, 'rows': len(by_day[day]),
'symbols': [r['symbol'] for r in by_day[day]]} for day in excluded],
'raw_rows_retained': True}
store.put('data_quality', quality)
temporary = path.with_suffix('.tmp')
with zipfile.ZipFile(temporary, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
for day, records in sorted(by_day.items()):
if day not in sessions:
continue
out = io.StringIO(newline='')
writer = csv.writer(out)
writer.writerow(['<TICKER>', '<DTYYYYMMDD>', '<OPEN>', '<HIGH>', '<LOW>', '<CLOSE>', '<VOL>'])
for r in records:
writer.writerow([r['symbol'], day.replace('-', ''), r['open'], r['high'], r['low'], r['close'], r['volume']])
archive.writestr(f'set-history_EOD_{day}.csv', out.getvalue())
temporary.replace(path)
return path, max(sessions)
def legacy_archives():
base = REPO / 'data/raw/siamchart'
return [p for p in (base / 'set-archive_EOD_1970-LAST.zip', base / 'set-archive_EOD.zip',
base / 'set-archive_EOD_LAST.zip') if p.is_file()]
def latest_archive_date(paths):
dates = []
for path in paths:
with zipfile.ZipFile(path) as archive:
dates.extend(m.group(1) for name in archive.namelist() if (m := EOD.search(Path(name).name)))
return max(dates) if dates else None
def panel_for(paths, settings, through):
end = (datetime.fromisoformat(through) + timedelta(days=1)).date().isoformat()
panel = load_market_panel(
paths, start=settings.warmup_start, end=end,
action_dir=REPO / 'data/raw/actions',
set_index_csv=settings.state_dir / 'NO_EXTERNAL_SET_FALLBACK.csv',
set_reference=REPO / 'data/reference/set_actions_2025_2026_h1.csv',
)
if len(panel.dates) < 253 or not math.isfinite(float(panel.set_close.iloc[-1])):
raise ValueError('ประวัติ warm-up ไม่พอ หรือไม่มีดัชนี SET ในวันล่าสุด จึงไม่ออกสัญญาณใหม่')
return panel
def calculate(panel, settings):
features = _features(panel)
signals = build_next_session_union_signals(panel, features, start=settings.model_start,
initial_equity=10_000., board_lot=100)
targets = [build_model_targets(panel, features, model=m, start=settings.model_start) for m in MODELS]
return features, plain(signals.to_dict('records')), build_union_target_weights(*targets)
def backtest(panel, targets, settings):
curve, execution = simulate_board_lots(panel, targets.gt(0), target_weights=targets,
initial_equity=10_000., board_lot=100, max_positions=20,
costs=TradingCosts())
end = (panel.dates[-1] + pd.Timedelta(days=1)).date().isoformat()
metrics, _ = calculate_model_metrics(curve, start=settings.model_start, end=end, execution=execution)
cropped = curve.loc[curve.index >= settings.model_start]
metrics['ending_equity'] = float(cropped['equity'].iloc[-1])
return plain({'metrics': metrics,
'curve': [{'day': str(day.date()), 'equity': float(r.equity)} for day, r in cropped.iterrows()],
'initial_equity': 10_000, 'costs': {'commission_rate': .0015, 'slippage_bps': 5}})
def compare_panels(left, right, left_signals, right_signals, left_features, right_features):
days = left.dates.intersection(right.dates)
symbols = sorted(set(left.symbols) & set(right.symbols))
missing_left = sorted(set(right.symbols) - set(left.symbols))
missing_right = sorted(set(left.symbols) - set(right.symbols))
fields, samples = {}, []
for field in ('open', 'high', 'low', 'close', 'volume'):
a = getattr(left, field).reindex(index=days, columns=symbols).to_numpy()
b = getattr(right, field).reindex(index=days, columns=symbols).to_numpy()
mask = (left.has_bar.reindex(index=days, columns=symbols).to_numpy()
& right.has_bar.reindex(index=days, columns=symbols).to_numpy())
matches = np.isclose(a, b, atol=1e-6, rtol=1e-8) & mask
differences = mask & ~matches
fields[field] = {'compared': int(mask.sum()), 'matched': int(matches.sum()),
'different': int(differences.sum()),
'match_pct': float(matches.sum() / mask.sum() * 100) if mask.any() else None}
if field == 'close':
for i, j in list(zip(*np.where(differences)))[-80:]:
samples.append({'day': str(days[i].date()), 'symbol': symbols[j],
'mt5': float(a[i, j]), 'siamchart': float(b[i, j])})
ls = {s['symbol']: s for s in left_signals}
rs = {s['symbol']: s for s in right_signals}
lr = {r['symbol']: i + 1 for i, r in enumerate(left_signals)}
rr = {r['symbol']: i + 1 for i, r in enumerate(right_signals)}
signals = []
for s in sorted(set(ls) | set(rs)):
a, b = ls.get(s, {}), rs.get(s, {})
same = a.get('source_model', '') == b.get('source_model', '')
row = {'symbol': s, 'mt5': a.get('source_model', ''), 'siamchart': b.get('source_model', ''),
'same': same, 'mt5_rank': lr.get(s), 'siamchart_rank': rr.get(s),
'rank_same': lr.get(s) == rr.get(s)}
for field in ('target_weight', 'allocation_score', 'reference_close'):
row['mt5_' + field] = a.get(field)
row['siamchart_' + field] = b.get(field)
row['same_' + field] = (field in a and field in b and
math.isclose(float(a[field]), float(b[field]), abs_tol=1e-6, rel_tol=1e-8))
signals.append(row)
set_left = left.set_close.reindex(days).to_numpy()
set_right = right.set_close.reindex(days).to_numpy()
set_mask = np.isfinite(set_left) & np.isfinite(set_right)
same_signals = all(s['same'] for s in signals)
latest_common = str(days[-1].date()) if len(days) else None
universe_left = set(left_features['universe'].iloc[-1].loc[lambda v: v].index)
universe_right = set(right_features['universe'].iloc[-1].loc[lambda v: v].index)
left_mask = left.has_bar.reindex(index=days, columns=symbols).to_numpy()
right_mask = right.has_bar.reindex(index=days, columns=symbols).to_numpy()
return plain({
'as_of': latest_common, 'same_signal_membership_and_model': same_signals,
'same_rankings': all(s['rank_same'] for s in signals),
'same_allocation_scores': all(s['same_allocation_score'] for s in signals),
'same_target_weights': all(s['same_target_weight'] for s in signals),
'shared_sessions': len(days), 'shared_symbols': len(symbols), 'ohlcv': fields,
'bars_only_mt5': int((left_mask & ~right_mask).sum()),
'bars_only_siamchart': int((right_mask & ~left_mask).sum()),
'sessions_only_mt5': [str(d.date()) for d in left.dates.difference(right.dates)],
'sessions_only_siamchart': [str(d.date()) for d in right.dates.difference(left.dates)],
'missing_from_mt5': missing_left, 'missing_from_siamchart': missing_right,
'set_compared': int(set_mask.sum()),
'set_different': int((set_mask & ~np.isclose(set_left, set_right, atol=1e-6, rtol=1e-8)).sum()),
'market_filter_mt5': {'close': float(left.set_close.iloc[-1]),
'sma200': float(left.set_close.rolling(200).mean().iloc[-1]),
'up': bool(left_features['market_up'].iloc[-1])},
'market_filter_siamchart': {'close': float(right.set_close.iloc[-1]),
'sma200': float(right.set_close.rolling(200).mean().iloc[-1]),
'up': bool(right_features['market_up'].iloc[-1])},
'signals': signals, 'mt5_count': len(ls), 'siamchart_count': len(rs),
'common_signal_count': len(set(ls) & set(rs)),
'latest_universe_mt5_only': sorted(universe_left - universe_right),
'latest_universe_siamchart_only': sorted(universe_right - universe_left),
'close_difference_samples': samples,
'notes': [
'ใช้กฎเดิม ช่วง warm-up เดียวกัน ข้อมูลปิดแล้ว และข้อมูลปันผล/แตกหุ้นชุดเดียวกัน',
'volume ใช้ real_volume เป็นจำนวนหุ้น ไม่ใช้ tick_volume แทน',
'MT5 แสดงหุ้นที่โบรกเกอร์มีในปัจจุบัน อาจไม่มีหุ้นที่เพิกถอนในประวัติเดิม',
'รายงานความต่างตามข้อมูลจริง ไม่มีการปรับราคา/volume ให้ดูตรงกัน',
],
})
def run_research(store, settings, progress):
progress('archive', 'เตรียมราคาจาก MT5 ที่เก็บในเครื่อง', 0, 1)
archive, through = export_archive(store, settings)
progress('signals', 'คำนวณ Donchian 55/20 และ EMA 50/200 จาก MT5', 0, 1)
current = panel_for([archive], settings, through)
features, signals, targets = calculate(current, settings)
output = {'updated_at': now_iso(), 'signal_as_of': str(current.dates[-1].date()),
'signals': signals, 'sessions': len(current.dates), 'symbols': len(current.symbols),
'history_issues': current.issues, 'warmup_start': settings.warmup_start,
'data_quality': store.get('data_quality', {}),
'model_start': settings.model_start,
'market_filter': {'set_close': float(current.set_close.iloc[-1]),
'sma200': float(current.set_close.rolling(200).mean().iloc[-1]),
'up': bool(features['market_up'].iloc[-1])},
'strategy_sha256': hashlib.sha256((REPO / 'primethai/model_lab.py').read_bytes()).hexdigest(),
'actions_note': 'ราคาจาก MT5; การปรับปันผล/แตกหุ้นใช้อ้างอิงที่มีอยู่ในโครงการเดิม',
'backtest_mt5_latest': backtest(current, targets, settings)}
archives = legacy_archives()
legacy_day = latest_archive_date(archives)
if legacy_day:
common_day = min(through, legacy_day)
progress('comparison', f'เทียบสองแหล่งข้อมูลถึงวันเดียวกัน {common_day}', 0, 1)
lp = panel_for([archive], settings, common_day)
rp = panel_for(archives, settings, common_day)
# Never label comparisons as equal-date if a whole market session is missing.
actual_common = min(lp.dates[-1], rp.dates[-1]).date().isoformat()
if str(lp.dates[-1].date()) != actual_common:
lp = panel_for([archive], settings, actual_common)
if str(rp.dates[-1].date()) != actual_common:
rp = panel_for(archives, settings, actual_common)
lf, ls, lt = calculate(lp, settings)
rf, rs, rt = calculate(rp, settings)
comparison = compare_panels(lp, rp, ls, rs, lf, rf)
comparison.update({'legacy_latest': legacy_day, 'mt5_latest': output['signal_as_of'],
'data_quality': output['data_quality'],
'backtest_mt5': backtest(lp, lt, settings),
'backtest_siamchart': backtest(rp, rt, settings)})
shared = lt.index.intersection(rt.index)
names = sorted(set(lt.columns) | set(rt.columns))
different_holdings = (lt.reindex(index=shared, columns=names, fill_value=0).gt(0)
!= rt.reindex(index=shared, columns=names, fill_value=0).gt(0))
comparison['historical_target_days_compared'] = len(shared[shared >= settings.model_start])
comparison['historical_target_days_different'] = int(different_holdings.loc[shared >= settings.model_start].any(axis=1).sum())
output['comparison'] = comparison
(settings.state_dir / 'comparison.json').write_text(json.dumps(plain(comparison), ensure_ascii=False, indent=2), encoding='utf-8')
pd.DataFrame(comparison['signals']).to_csv(settings.state_dir / 'signal_comparison.csv', index=False)
else:
output['comparison'] = {'error': 'ไม่พบไฟล์ SiamChart เดิมสำหรับเทียบ; สัญญาณหลักยังใช้ MT5'}
output = plain(output)
store.put('research', output)
(settings.state_dir / 'research.json').write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
return output
+17
View File
@@ -0,0 +1,17 @@
param([int]$Port = 18901)
$ErrorActionPreference = 'Stop'
$taskRoot = Split-Path $PSScriptRoot -Parent
Set-Location -LiteralPath $taskRoot
$taskPython = Join-Path $PSScriptRoot '.venv\Scripts\python.exe'
if (-not (Test-Path -LiteralPath $taskPython)) {
$taskPython = Join-Path $taskRoot '.venv\Scripts\python.exe'
}
if (-not (Test-Path -LiteralPath $taskPython)) {
throw 'Run mt5_app/setup.ps1 first. See mt5_app/README.md.'
}
$env:PYTHONIOENCODING = 'utf-8'
$env:MT5_PORT = "$Port"
if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot '.env'))) {
Copy-Item -LiteralPath (Join-Path $PSScriptRoot '.env.example') -Destination (Join-Path $PSScriptRoot '.env')
}
& $taskPython -m mt5_app serve
+222
View File
@@ -0,0 +1,222 @@
from datetime import datetime, timedelta
from dataclasses import replace
import logging
import math
import threading
import time
from .broker import Broker
from .config import TZ
from .research import download_history, run_research
from .store import Store, now_iso
def make_plan(snapshot, research, skipped, settings):
account = snapshot.get('account', {})
positions = {p['symbol']: p for p in snapshot.get('positions', [])}
signals = {s['symbol']: s for s in research.get('signals', [])}
model_ready = bool(research.get('signal_as_of'))
orders = snapshot.get('orders', [])
# Conservative cash sizing; never use the full equity as free buying power.
reserved = sum(float(o['volume_current']) * float(o['price_open']) for o in orders if o['type'] in (2, 4, 6))
cash = max(0., min(float(account.get('balance', 0)), float(account.get('margin_free', 0))) - reserved)
equity = min(float(account.get('equity', 0)), float(account.get('equity_from_positions', 0)))
rows = []
for symbol in sorted(set(signals) | set(positions)):
signal, position = signals.get(symbol, {}), positions.get(symbol, {})
held = int(position.get('volume', 0))
close = float(signal.get('reference_close', 0))
quote = snapshot.get('quotes', {}).get(symbol) or {}
ask = float(quote.get('ask') or 0)
limit = close
premium = ((ask / close - 1) * 100) if ask > 0 and close > 0 else None
desired_total = int(equity * float(signal.get('target_weight', 0)) / close / 100) * 100 if close > 0 else 0
desired = max(0, desired_total - held) if held else max(100, desired_total)
stale = int(signal.get('stale_sessions', 999))
action, reason = ('HOLD', 'ยังอยู่ในสัญญาณ') if held else ('WAIT', '')
if not model_ready:
action, reason = 'WAIT', 'กำลังเตรียมสัญญาณ ยังไม่ประเมินซื้อขายหุ้นที่ถือ'
elif any(o['symbol'] == symbol for o in orders):
action, reason = 'PENDING', 'มีคำสั่งค้างอยู่แล้ว'
elif not signal and held:
action, reason = 'SELL', 'ไม่มีในเป้าหมาย Donchian/EMA ล่าสุด ตรวจรายการก่อนส่งขาย'
desired = held
elif symbol in skipped:
action, reason = 'SKIPPED', 'ข้ามเฉพาะรอบสัญญาณนี้'
elif stale:
action, reason = 'WAIT', 'ราคาสัญญาณของหุ้นนี้ไม่ครบถึงวันล่าสุด'
elif desired > 0:
action = 'CANDIDATE'
rows.append({**signal, 'symbol': symbol, 'held': held, 'average_cost': position.get('price_open'),
'current': position.get('price_current'), 'profit': position.get('profit'),
'ask': ask or None, 'bid': quote.get('bid'), 'quote_time': quote.get('time'),
'premium_pct': premium, 'limit_price': limit if limit > 0 else position.get('price_current'),
'desired_quantity': desired, 'quantity': 0, 'action': action, 'reason': reason})
candidates = sorted([r for r in rows if r['action'] == 'CANDIDATE'],
key=lambda r: (-int(r.get('model_agreement', 0)), -float(r.get('allocation_score', 0)), r['symbol']))
remaining = cash
for rank, r in enumerate(candidates, 1):
r['rank'] = rank
unit_cost = r['limit_price'] * (1 + settings.fee_reserve_pct / 100)
affordable = int(max(0, remaining) / unit_cost / 100) * 100
qty = min(r['desired_quantity'], affordable)
if not qty:
r.update(action='BUDGET', reason='เงินว่างไม่พอสำหรับ 100 หุ้น รวมเงินเผื่อค่าธรรมเนียม')
else:
remaining -= qty * unit_cost
r.update(action='BUY', quantity=qty, reason='จัดสรรตามคะแนนและเงินว่างจริง')
for r in rows:
if r['action'] == 'SELL':
r['quantity'] = r['held'] // 100 * 100
order = {'SELL': 0, 'BUY': 1, 'BUDGET': 2, 'SKIPPED': 3, 'PENDING': 4, 'HOLD': 5, 'WAIT': 6}
rows.sort(key=lambda r: (order.get(r['action'], 9), r.get('rank', 999), r['symbol']))
return {'rows': rows, 'cash_budget': cash, 'cash_remaining_after_plan': remaining,
'pending_buy_reserve': reserved, 'signal_as_of': research.get('signal_as_of')}
class Desk:
def __init__(self, settings, broker=None):
self.settings = settings
self.store = Store(settings.state_dir)
self.broker = broker or Broker(settings, self.store)
self._job_lock = threading.Lock()
self.stop = threading.Event()
self.log = logging.getLogger('mt5desk')
def progress(self, stage, message, done=0, total=1):
self.store.put('job', {'running': True, 'stage': stage, 'message': message,
'done': done, 'total': total, 'updated_at': now_iso()})
def update_quotes(self, snapshot, research):
for signal in research.get('signals', []):
quote = self.broker.quote(signal['symbol'])
if quote:
snapshot.setdefault('quotes', {})[signal['symbol']] = quote
self.store.put('snapshot', snapshot)
def refresh(self, research=False):
if not self._job_lock.acquire(blocking=False):
return False
def work():
try:
self.progress('portfolio', 'อ่านพอร์ตจริงและคำสั่งค้างจาก MT5')
snapshot = self.broker.snapshot()
self.store.put('connection_error', None)
model = self.store.get('research', {})
previous = self.store.get('history_download', {})
last_attempt = previous.get('checked_at')
retry_due = (not last_attempt or time.time() - datetime.fromisoformat(last_attempt).timestamp() >= 600)
needs_new_day = previous.get('through') != self.settings.closed_through()
incomplete = self.store.get('history_checked_through') != self.settings.closed_through()
if research or not model or needs_new_day or (incomplete and retry_due):
download_history(self.broker, self.store, self.settings, self.progress)
model = run_research(self.store, self.settings, self.progress)
snapshot = self.broker.snapshot()
self.progress('quotes', 'อ่านราคาเสนอซื้อขายของหุ้นในแผน')
self.update_quotes(snapshot, model)
self.store.put('job', {'running': False, 'stage': 'complete', 'message': 'พร้อมใช้งาน', 'updated_at': now_iso()})
except Exception as exc:
self.log.exception('refresh_failed')
self.store.put('connection_error', {'message': str(exc), 'at': now_iso()})
self.store.put('job', {'running': False, 'stage': 'failed', 'message': str(exc), 'updated_at': now_iso()})
finally:
self._job_lock.release()
threading.Thread(target=work, daemon=True, name='mt5-refresh').start()
return True
def state(self):
snap = self.store.get('snapshot', {})
model = self.store.get('research', {})
day = model.get('signal_as_of', '')
history = self.store.get('history_download', {})
job = self.store.get('job', {})
plan = make_plan(snap, model, self.store.skipped(day), self.settings)
if (not model.get('data_quality', {}).get('calendar_source')
or (job.get('running') and job.get('stage') in ('history', 'archive', 'signals', 'comparison'))):
for row in plan['rows']:
row.update(action='WAIT', quantity=0, reason='รอการตรวจปฏิทินข้อมูล MT5 ให้ครบ')
return {'snapshot': snap, 'plan': plan,
'research': model, 'job': job,
'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,
'max_premium_pct': self.settings.max_premium_pct,
'intents': self.store.intents()}
def skip(self, symbol, skip):
model = self.store.get('research', {})
if symbol not in {s['symbol'] for s in model.get('signals', [])}:
raise ValueError('หุ้นนี้ไม่ได้อยู่ในสัญญาณรอบปัจจุบัน')
self.store.skip(symbol, model['signal_as_of'], skip)
self.store.event('skip' if skip else 'restore', {'symbol': symbol, 'as_of': model['signal_as_of']})
def set_live(self, enabled):
with self.broker.lock:
terminal, account = self.broker.connect()
if enabled and not (terminal.trade_allowed and not terminal.tradeapi_disabled
and account.trade_allowed and account.trade_expert):
raise ValueError('MT5 หรือบัญชียังไม่อนุญาตให้ส่งคำสั่งผ่านโปรแกรม')
self.settings = replace(self.settings, live_orders=bool(enabled))
self.broker.settings = self.settings
self.store.event('trading_mode', {'live_enabled': bool(enabled)})
return {'live_enabled': bool(enabled)}
def preview(self, payload):
job = self.store.get('job', {})
if job.get('running') and job.get('stage') in ('history', 'archive', 'signals', 'comparison'):
raise ValueError('รอการคำนวณสัญญาณให้เสร็จก่อนตรวจคำสั่งซื้อขาย')
if not self.store.get('research', {}).get('signal_as_of'):
raise ValueError('ยังไม่มีสัญญาณที่คำนวณสำเร็จ')
if not self.store.get('research', {}).get('data_quality', {}).get('calendar_source'):
raise ValueError('สัญญาณยังไม่ผ่านการตรวจปฏิทินข้อมูล MT5 กรุณาคำนวณใหม่ก่อน')
symbol, side = str(payload.get('symbol', '')).upper(), str(payload.get('side', '')).upper()
snapshot = self.broker.snapshot() # Recheck actual buying power and holdings now.
self.update_quotes(snapshot, self.store.get('research', {}))
self.store.put('connection_error', None)
state = self.state()
row = next((r for r in state['plan']['rows'] if r['symbol'] == symbol), None)
qty, price = float(payload.get('quantity', 0)), float(payload.get('price', 0))
if side == 'BUY':
if not row or row['action'] != 'BUY' or qty > row['quantity']:
raise ValueError('จำนวนซื้อเกินแผนปัจจุบัน หรือหุ้นถูกข้ามไปแล้ว')
signal_date = datetime.fromisoformat(state['plan']['signal_as_of']).date()
if (datetime.now(TZ).date() - signal_date).days > 4:
raise ValueError('สัญญาณเก่าเกินไป อัปเดตข้อมูลก่อนส่งคำสั่ง')
return self.broker.preview(symbol, side, qty, price, state['research'].get('signals', []))
def submit(self, ident):
job = self.store.get('job', {})
if job.get('running') and job.get('stage') in ('history', 'archive', 'signals', 'comparison'):
raise ValueError('รอการคำนวณให้เสร็จ แล้วตรวจคำสั่งใหม่ก่อนส่ง')
# Recheck skips and new signal dates, in addition to broker-side validation.
intents = {r['id']: r for r in self.store.intents()}
intent = intents.get(ident)
if not intent:
raise ValueError('ไม่พบตัวอย่างคำสั่ง')
import json
request = json.loads(intent['request'])
if request['type'] == self.broker.api.ORDER_TYPE_BUY_LIMIT:
state = self.state()
context = self.store.get('intent_context:' + ident, {})
if context.get('signal_day') != state['plan']['signal_as_of']:
raise ValueError('วันสัญญาณเปลี่ยนแล้ว สร้างตัวอย่างคำสั่งใหม่')
row = next((r for r in state['plan']['rows'] if r['symbol'] == request['symbol']), None)
if not row or row['action'] != 'BUY' or request['volume'] > row['quantity']:
raise ValueError('แผนเปลี่ยนหรือหุ้นถูกข้ามแล้ว สร้างตัวอย่างใหม่')
result = self.broker.submit(ident)
self.refresh()
return result
def scheduler(self):
self.refresh()
while not self.stop.wait(max(30, self.settings.refresh_seconds)):
last = self.store.get('job', {})
# Avoid hammering the terminal with large history retries on errors.
if last.get('stage') == 'failed':
try:
elapsed = time.time() - datetime.fromisoformat(last['updated_at']).timestamp()
if elapsed < 600:
continue
except (KeyError, ValueError):
pass
self.refresh()
+14
View File
@@ -0,0 +1,14 @@
$ErrorActionPreference = 'Stop'
$taskRoot = Split-Path $PSScriptRoot -Parent
Set-Location -LiteralPath $taskRoot
$taskEnvironment = Join-Path $PSScriptRoot '.venv'
if (-not (Test-Path -LiteralPath (Join-Path $taskEnvironment 'Scripts\python.exe'))) {
python -m venv $taskEnvironment
if ($LASTEXITCODE -ne 0) { throw 'Could not create the dedicated Python environment.' }
}
& (Join-Path $taskEnvironment 'Scripts\python.exe') -m pip install -r (Join-Path $PSScriptRoot 'requirements.txt')
if ($LASTEXITCODE -ne 0) { throw 'Could not install the MT5 app requirements.' }
if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot '.env'))) {
Copy-Item -LiteralPath (Join-Path $PSScriptRoot '.env.example') -Destination (Join-Path $PSScriptRoot '.env')
}
Write-Output 'Ready. Open and log in to the Pi MT5 terminal, then run mt5_app/run.ps1.'
+135
View File
@@ -0,0 +1,135 @@
from contextlib import contextmanager
from datetime import datetime, timezone
import json
from pathlib import Path
import sqlite3
def now_iso():
return datetime.now(timezone.utc).isoformat()
class Store:
def __init__(self, directory: Path):
directory.mkdir(parents=True, exist_ok=True)
self.path = directory / "mt5.sqlite3"
with self.connect() as db:
db.executescript("""
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS bars (
symbol TEXT, day TEXT, open REAL, high REAL, low REAL, close REAL,
volume REAL, tick_volume REAL, PRIMARY KEY(symbol,day));
CREATE TABLE IF NOT EXISTS decisions (
symbol TEXT, signal_day TEXT, PRIMARY KEY(symbol,signal_day));
CREATE TABLE IF NOT EXISTS intents (
id TEXT PRIMARY KEY, account TEXT NOT NULL, created REAL NOT NULL,
status TEXT NOT NULL, request TEXT NOT NULL, result TEXT);
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY, time TEXT NOT NULL, kind TEXT NOT NULL, payload TEXT NOT NULL);
""")
@contextmanager
def connect(self):
db = sqlite3.connect(self.path, timeout=15)
db.row_factory = sqlite3.Row
try:
with db:
yield db
finally:
db.close()
def get(self, key, default=None):
with self.connect() as db:
row = db.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
return json.loads(row[0]) if row else default
def put(self, key, value):
with self.connect() as db:
db.execute("INSERT OR REPLACE INTO meta VALUES (?,?)", (key, json.dumps(value, allow_nan=False)))
def event(self, kind, payload):
with self.connect() as db:
db.execute("INSERT INTO events(time,kind,payload) VALUES (?,?,?)",
(now_iso(), kind, json.dumps(payload, allow_nan=False)))
def save_bars(self, rows):
with self.connect() as db:
db.executemany("INSERT OR REPLACE INTO bars VALUES (?,?,?,?,?,?,?,?)", rows)
def bars(self, start, end):
with self.connect() as db:
return [dict(row) for row in db.execute(
"SELECT * FROM bars WHERE day>=? AND day<=? ORDER BY day,symbol", (start, end))]
def bar_summary(self):
with self.connect() as db:
return dict(db.execute("SELECT count(*) AS rows, count(DISTINCT symbol) AS symbols, "
"min(day) AS first_day,max(day) AS last_day FROM bars").fetchone())
def skipped(self, day):
with self.connect() as db:
return {r[0] for r in db.execute("SELECT symbol FROM decisions WHERE signal_day=?", (day,))}
def skip(self, symbol, day, skip=True):
with self.connect() as db:
if skip:
db.execute("INSERT OR IGNORE INTO decisions VALUES (?,?)", (symbol, day))
else:
db.execute("DELETE FROM decisions WHERE symbol=? AND signal_day=?", (symbol, day))
def create_intent(self, ident, account, created, request):
with self.connect() as db:
db.execute("INSERT INTO intents(id,account,created,status,request) VALUES (?,?,?,'preview',?)",
(ident, str(account), created, json.dumps(request)))
def claim_intent(self, ident, account, cutoff):
with self.connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT * FROM intents WHERE id=?", (ident,)).fetchone()
if not row or row['status'] != 'preview' or row['account'] != str(account) or row['created'] < cutoff:
raise ValueError("คำสั่งหมดอายุ ถูกใช้ไปแล้ว หรือบัญชีเปลี่ยน กรุณาสร้างตัวอย่างใหม่")
db.execute("UPDATE intents SET status='sending' WHERE id=?", (ident,))
return json.loads(row['request'])
def finish_intent(self, ident, status, result):
with self.connect() as db:
db.execute("UPDATE intents SET status=?,result=? WHERE id=?",
(status, json.dumps(result), ident))
def intents(self):
with self.connect() as db:
return [dict(r) for r in db.execute("SELECT id,created,status,request,result FROM intents ORDER BY created DESC LIMIT 30")]
def unresolved(self):
with self.connect() as db:
return [dict(r) for r in db.execute("SELECT * FROM intents WHERE status IN ('sending','unknown')")]
def reconcile(self, snapshot, magic):
"""Resolve send uncertainty from broker tickets/deals, never by resending."""
with self.connect() as db:
intents = db.execute("SELECT * FROM intents WHERE status IN ('sending','unknown','accepted','partial')").fetchall()
for intent in intents:
request = json.loads(intent['request'])
comment = request.get('comment')
if not comment:
continue
deals = [d for d in snapshot.get('deals', []) if d.get('magic') == magic and d.get('comment') == comment]
pending = [o for o in snapshot.get('orders', []) if o.get('magic') == magic and o.get('comment') == comment]
history = [o for o in snapshot.get('history_orders', []) if o.get('magic') == magic and o.get('comment') == comment]
volume = sum(float(d.get('volume', 0)) for d in deals if d.get('type') in (0, 1))
status = None
if volume >= float(request.get('volume', float('inf'))) - 1e-8:
status = 'filled'
elif volume > 0:
status = 'partial' if pending else 'partial_closed'
elif pending:
status = 'accepted'
elif history and history[-1].get('state') in (2, 5, 6):
# MT5 ORDER_STATE_CANCELED, REJECTED, EXPIRED.
status = {2: 'cancelled', 5: 'rejected', 6: 'expired'}[history[-1]['state']]
if status:
prior = json.loads(intent['result'] or '{}')
prior['broker_reconciliation'] = {'status': status, 'filled_volume': volume, 'at': now_iso()}
db.execute("UPDATE intents SET status=?,result=? WHERE id=?",
(status, json.dumps(prior), intent['id']))
+215
View File
@@ -0,0 +1,215 @@
"""All execution tests use a fake terminal. Never connect to or trade a live account."""
from datetime import datetime
import io
import json
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace as NS
import unittest
from unittest.mock import Mock
from mt5_app.app import handler_for
from mt5_app.broker import Broker
from mt5_app.config import ROOT, Settings, TZ
from mt5_app.service import make_plan
from mt5_app.store import Store
class FakeAPI:
TRADE_ACTION_PENDING = 5
TRADE_ACTION_REMOVE = 8
ORDER_TYPE_BUY_LIMIT = 2
ORDER_TYPE_SELL_LIMIT = 3
ORDER_TYPE_SELL_STOP = 5
POSITION_TYPE_BUY = 0
ORDER_TIME_DAY = 1
ORDER_FILLING_RETURN = 2
SYMBOL_TRADE_MODE_DISABLED = 0
SYMBOL_TRADE_MODE_SHORTONLY = 2
SYMBOL_TRADE_MODE_CLOSEONLY = 3
TRADE_RETCODE_DONE = 10009
TRADE_RETCODE_PLACED = 10008
TRADE_RETCODE_DONE_PARTIAL = 10010
def __init__(self, path):
self.path = path
self.cash = 10_000
self.position_volume = 100
self.orders = []
self.sent = []
self.fail_send = False
self.login = 123
def terminal_info(self):
return NS(data_path=str(self.path), connected=True, trade_allowed=True, tradeapi_disabled=False)
def account_info(self):
return NS(login=self.login, server='TEST', balance=self.cash, margin_free=self.cash,
trade_allowed=True, trade_expert=True)
def symbol_info(self, name):
return NS(path='SET\\Common Stock\\' + name, trade_contract_size=1, volume_max=1e6, trade_mode=1)
def orders_get(self, **kwargs):
return self.orders
def positions_get(self, **kwargs):
return [NS(type=0, volume=self.position_volume)]
def order_check(self, request):
return NS(retcode=0, comment='Test passed')
def order_send(self, request):
self.sent.append(request)
if self.fail_send:
return None
return NS(retcode=10008, _asdict=lambda: {'retcode': 10008, 'comment': 'Placed', 'order': 456})
def last_error(self):
return (-1, 'fake lost connection')
class DeskTests(unittest.TestCase):
def setUp(self):
self.tmp = TemporaryDirectory(prefix='test_', dir=ROOT / 'data')
self.directory = Path(self.tmp.name)
self.settings = Settings(data_path=self.directory, live_orders=True, state_dir=self.directory)
self.store = Store(self.directory)
self.api = FakeAPI(self.directory)
self.broker = Broker(self.settings, self.store, api=self.api)
self.signals = [{'symbol': 'AAA', 'reference_close': 10, 'stale_sessions': 0}]
def tearDown(self):
self.tmp.cleanup()
def test_account_change_is_blocked(self):
self.broker.connect()
self.api.login = 999
with self.assertRaisesRegex(RuntimeError, 'บัญชี MT5 เปลี่ยน'):
self.broker.connect()
self.assertFalse(self.api.sent)
def test_wrong_terminal_folder_is_blocked(self):
self.api.path = self.directory / 'other'
with self.assertRaisesRegex(RuntimeError, 'folder'):
self.broker.connect()
def test_preview_never_sends_and_submit_is_single_use(self):
preview = self.broker.preview('AAA', 'BUY', 100, 10, self.signals)
self.assertFalse(self.api.sent)
result = self.broker.submit(preview['id'])
self.assertEqual(result['status'], 'accepted')
with self.assertRaises(ValueError):
self.broker.submit(preview['id'])
self.assertEqual(len(self.api.sent), 1)
def test_send_uncertainty_cannot_be_retried(self):
preview = self.broker.preview('AAA', 'BUY', 100, 10, self.signals)
self.api.fail_send = True
with self.assertRaises(RuntimeError):
self.broker.submit(preview['id'])
self.assertEqual(self.store.intents()[0]['status'], 'unknown')
with self.assertRaises(ValueError):
self.broker.submit(preview['id'])
self.assertEqual(len(self.api.sent), 1)
with self.assertRaisesRegex(ValueError, 'ไม่ทราบผล'):
self.broker.preview('AAA', 'BUY', 100, 10, self.signals)
def test_reconciliation_resolves_uncertain_send_from_broker_fill(self):
preview = self.broker.preview('AAA', 'BUY', 100, 10, self.signals)
self.api.fail_send = True
with self.assertRaises(RuntimeError):
self.broker.submit(preview['id'])
request = preview['request']
self.store.reconcile({'deals': [{'magic': self.settings.magic, 'comment': request['comment'],
'volume': 100, 'type': 0}], 'orders': []}, self.settings.magic)
self.assertEqual(self.store.intents()[0]['status'], 'filled')
self.assertEqual(len(self.api.sent), 1)
def test_live_off_blocks_send(self):
broker = Broker(Settings(data_path=self.directory, state_dir=self.directory), self.store, self.api)
preview = broker.preview('AAA', 'BUY', 100, 10, self.signals)
with self.assertRaisesRegex(ValueError, 'ปิดอยู่'):
broker.submit(preview['id'])
self.assertFalse(self.api.sent)
def test_bad_lots_prices_and_chasing_are_blocked(self):
for quantity, price in [(1, 10), (150, 10), (100, float('nan')), (100, 10.01), (100, 11)]:
with self.subTest(quantity=quantity, price=price), self.assertRaises(ValueError):
self.broker.preview('AAA', 'BUY', quantity, price, self.signals)
self.assertFalse(self.api.sent)
def test_sell_cannot_open_short_or_sell_reserved_shares(self):
with self.assertRaises(ValueError):
self.broker.preview('AAA', 'SELL', 200, 10, [])
self.api.orders = [NS(symbol='AAA', type=3, volume_current=100)]
with self.assertRaises(ValueError):
self.broker.preview('AAA', 'SELL', 100, 10, [])
def test_cash_is_checked_again_after_preview(self):
preview = self.broker.preview('AAA', 'BUY', 100, 10, self.signals)
self.api.cash = 100
with self.assertRaises(ValueError):
self.broker.submit(preview['id'])
self.assertFalse(self.api.sent)
def test_foreign_pending_order_cannot_be_cancelled(self):
self.api.orders = [NS(magic=539141)]
with self.assertRaises(ValueError):
self.broker.manage_pending(123)
self.assertFalse(self.api.sent)
def test_skip_reallocates_cash_but_never_changes_the_portfolio(self):
snapshot = {'account': {'balance': 10_000, 'margin_free': 10_000, 'equity': 10_000,
'equity_from_positions': 10_000}, 'positions': [], 'orders': []}
research = {'signal_as_of': '2026-10-15', 'signals': [
{'symbol': 'AAA', 'target_weight': .5, 'reference_close': 80,
'stale_sessions': 0, 'allocation_score': 1, 'model_agreement': 2},
{'symbol': 'BBB', 'target_weight': .5, 'reference_close': 30,
'stale_sessions': 0, 'allocation_score': .5, 'model_agreement': 1},
]}
initial = {r['symbol']: r for r in make_plan(snapshot, research, set(), self.settings)['rows']}
after = {r['symbol']: r for r in make_plan(snapshot, research, {'AAA'}, self.settings)['rows']}
self.assertEqual(initial['AAA']['action'], 'BUY')
self.assertEqual(initial['BBB']['action'], 'BUDGET')
self.assertEqual(after['AAA']['action'], 'SKIPPED')
self.assertEqual(after['BBB']['action'], 'BUY')
self.assertEqual(after['BBB']['quantity'], 100)
self.assertEqual(snapshot['account']['balance'], 10_000)
self.store.skip('AAA', '2026-10-15')
self.assertEqual(self.store.skipped('2026-10-16'), set())
def test_first_loading_state_never_generates_sell_signals(self):
snapshot = {'account': {'balance': 100, 'margin_free': 100},
'positions': [{'symbol': 'AAA', 'volume': 100, 'price_current': 10}], 'orders': []}
plan = make_plan(snapshot, {}, set(), self.settings)
self.assertEqual(plan['rows'][0]['action'], 'WAIT')
self.assertEqual(plan['rows'][0]['quantity'], 0)
def test_unclosed_daily_bar_cutoff(self):
self.assertEqual(self.settings.closed_through(datetime(2026, 10, 15, 15, 0, tzinfo=TZ)), '2026-10-14')
self.assertEqual(self.settings.closed_through(datetime(2026, 10, 15, 21, 0, tzinfo=TZ)), '2026-10-15')
class LocalHTTPTests(unittest.TestCase):
def handler(self, host, origin, token):
desk = Mock()
handler = handler_for(desk, 'secret', 18901).__new__(handler_for(desk, 'secret', 18901))
handler.path = '/api/submit'
handler.headers = {'Host': host, 'Origin': origin, 'X-App-Token': token, 'Content-Length': '2'}
handler.rfile = io.BytesIO(b'{}')
handler.respond = Mock()
return handler, desk
def test_remote_host_origin_or_missing_token_cannot_submit(self):
for host, origin, token in [('evil.test:18901', 'http://evil.test:18901', 'secret'),
('127.0.0.1:18901', 'http://evil.test', 'secret'),
('127.0.0.1:18901', 'http://127.0.0.1:18901', '')]:
handler, desk = self.handler(host, origin, token)
handler.do_POST()
self.assertEqual(handler.respond.call_args.args[0], 403)
desk.submit.assert_not_called()
if __name__ == '__main__':
unittest.main()
+80
View File
@@ -0,0 +1,80 @@
from datetime import datetime, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace
import unittest
import zipfile
from unittest.mock import patch
import numpy as np
import pandas as pd
from mt5_app.config import ROOT, Settings
from mt5_app.research import download_history, export_archive, run_research
from mt5_app.store import Store
class ResearchTests(unittest.TestCase):
def setUp(self):
self.tmp = TemporaryDirectory(prefix='research_test_', dir=ROOT / 'data')
self.settings = Settings(data_path=Path(self.tmp.name), state_dir=Path(self.tmp.name))
self.store = Store(self.settings.state_dir)
def tearDown(self):
self.tmp.cleanup()
def test_identical_prices_and_rules_produce_identical_comparison_and_backtest(self):
days = pd.bdate_range('2024-02-01', periods=620)
rows = []
for i, day in enumerate(days):
for symbol, start, slope in [('SET', 1000, 1), ('AAA', 10, .1), ('BBB', 20, .15)]:
price = start + i * slope
rows.append((symbol, str(day.date()), price, price + .005, price - .005, price, 2_000_000, 200))
self.store.save_bars(rows)
archive, _ = export_archive(self.store, self.settings)
with patch('mt5_app.research.legacy_archives', return_value=[archive]):
result = run_research(self.store, self.settings, lambda *args: None)
comparison = result['comparison']
self.assertTrue(comparison['same_signal_membership_and_model'])
self.assertTrue(comparison['same_rankings'])
self.assertTrue(comparison['same_allocation_scores'])
self.assertEqual(comparison['ohlcv']['close']['different'], 0)
self.assertEqual(comparison['ohlcv']['volume']['different'], 0)
self.assertEqual(comparison['historical_target_days_different'], 0)
self.assertEqual(comparison['backtest_mt5']['metrics']['total_return'],
comparison['backtest_siamchart']['metrics']['total_return'])
self.assertTrue((self.settings.state_dir / 'comparison.json').is_file())
def test_real_volume_is_preserved_and_unfinished_today_is_not_imported(self):
rows = np.array([
(int(datetime(2026, 10, 14, tzinfo=timezone.utc).timestamp()), 10., 11., 9., 10., 99, 0, 100_000),
(int(datetime(2026, 10, 15, tzinfo=timezone.utc).timestamp()), 11., 12., 10., 11., 123, 0, 200_000),
], dtype=[('time', 'i8'), ('open', 'f8'), ('high', 'f8'), ('low', 'f8'), ('close', 'f8'),
('tick_volume', 'u8'), ('spread', 'i4'), ('real_volume', 'u8')])
broker = SimpleNamespace(symbols=lambda: [SimpleNamespace(name='AAA', path='SET\\Common Stock\\AAA')],
history=lambda *args: rows)
with patch.object(Settings, 'closed_through', return_value='2026-10-14'):
download_history(broker, self.store, self.settings, lambda *args: None)
stored = self.store.bars('2026-10-01', '2026-10-31')
self.assertEqual({r['day'] for r in stored}, {'2026-10-14'})
self.assertEqual(stored[0]['volume'], 100_000)
self.assertEqual(stored[0]['tick_volume'], 99)
def test_stock_bar_without_set_session_is_quarantined_not_forward_filled(self):
self.store.save_bars([
('SET', '2026-03-02', 1000, 1001, 999, 1000, 0, 1),
('AAA', '2026-03-02', 10, 10, 10, 10, 100, 1),
('AAA', '2026-03-03', 11, 11, 11, 11, 100, 1),
('SET', '2026-03-04', 1001, 1002, 1000, 1001, 0, 1),
('AAA', '2026-03-04', 11, 11, 11, 11, 100, 1),
])
archive, _ = export_archive(self.store, self.settings)
with zipfile.ZipFile(archive) as z:
self.assertEqual(len(z.namelist()), 2)
self.assertFalse(any('2026-03-03' in name for name in z.namelist()))
self.assertEqual(self.store.bar_summary()['rows'], 5) # Raw evidence is retained.
self.assertEqual(self.store.get('data_quality')['excluded_non_session_days'][0]['day'], '2026-03-03')
if __name__ == '__main__':
unittest.main()