diff --git a/mt5_app/.env.example b/mt5_app/.env.example
index 4cd6257..eb828d9 100644
--- a/mt5_app/.env.example
+++ b/mt5_app/.env.example
@@ -2,6 +2,11 @@
MT5_DATA_PATH=C:\Users\YOUR_WINDOWS_USER\AppData\Roaming\MetaQuotes\Terminal\YOUR_PI_TERMINAL_ID
MT5_PORT=18901
MT5_ENABLE_LIVE_ORDERS=false
+# Automatic execution requires both live=true and auto=true. YYYY-MM-DD in Bangkok time.
+MT5_AUTO_TRADE=false
+MT5_AUTO_START_DATE=
+# Empty end date means every trading day until paused.
+MT5_AUTO_END_DATE=
MT5_MAGIC=1061501
MT5_MODEL_START=2026-01-01
MT5_HISTORY_BARS=1000
diff --git a/mt5_app/README.md b/mt5_app/README.md
index ae11d24..728c4c0 100644
--- a/mt5_app/README.md
+++ b/mt5_app/README.md
@@ -40,7 +40,7 @@
ใช้ OHLC และ `real_volume` ของหุ้นสามัญ SET/MAI กับดัชนี SET จาก MT5 ปริมาณ tick ไม่ได้ใช้แทนจำนวนหุ้น Donchian ต้องใช้ high/low; โมเดลยังใช้ปันผลและแตกหุ้นจากไฟล์อ้างอิงเดิมที่มีอยู่ ข้อมูล corporate actions ดังกล่าวไม่ได้ดึงจาก MT5 และอาจครอบคลุมไม่ครบ
-ประวัติครั้งแรกขอ 1,000 แท่งต่อหุ้น จากนั้นดึงเพิ่มช่วงล่าสุด ใช้แท่งวันนี้เป็น EOD หลัง 20:30 เวลาไทยเท่านั้น ก่อนเวลานั้นใช้วันก่อนหน้า เก็บข้อมูลไว้ในเครื่องและลองใหม่เมื่อดาวน์โหลดไม่สำเร็จ หุ้นที่ข้อมูลล่าสุดไม่ครบจะแสดงรอข้อมูล
+ประวัติครั้งแรกขอ 1,000 แท่งต่อหุ้น จากนั้นดึงเพิ่มช่วงล่าสุด ใช้แท่งวันนี้เป็น EOD หลัง 20:30 เวลาไทยเท่านั้น ก่อนเวลานั้นใช้วันทำการก่อนหน้า โดยข้ามเสาร์–อาทิตย์และวันหยุด ไม่ใช้ข้อมูลระหว่างวันแทนแท่งปิดใน Donchian/EMA เก็บข้อมูลไว้ในเครื่องและลองใหม่เมื่อดาวน์โหลดไม่สำเร็จ หุ้นที่ข้อมูลล่าสุดไม่ครบจะแสดงรอข้อมูล
ใช้วันที่มีแท่ง SET เป็นปฏิทินซื้อขายร่วมกัน แท่งหุ้นในวันที่ไม่มี SET จะถูกแยกออกจากการคำนวณและรายงานใน `data_quality` แต่เก็บหลักฐานดิบไว้ใน SQLite หาก SET ยังไม่ถึงวันล่าสุดของหุ้น จะพักการคำนวณแทนการเติมดัชนีเอง วิธีนี้ป้องกันแท่งวันหยุดของหุ้นบางตัวทำให้ค่าเฉลี่ย SET 200 วันขาดข้อมูล
@@ -52,7 +52,7 @@ Equity ที่โบรกเกอร์รายงานกับผลร
## คำสั่งจริง
-ค่าเริ่มต้นอ่านพอร์ตและตรวจคำสั่งเท่านั้น เปิดส่งจริงได้จากปุ่มในหน้าจอสำหรับรอบเปิดแอปนี้ ทุกคำสั่งยังต้องกดตรวจและยืนยันรายครั้ง ปิดแอปแล้วเปิดใหม่จะกลับตาม `.env` ค่า `MT5_ENABLE_LIVE_ORDERS=false` จึงปิดการส่งจริงเมื่อเริ่มแอป
+ค่าเริ่มต้นใน `.env.example` อ่านพอร์ตและตรวจคำสั่งเท่านั้น คำสั่งที่กดเองต้องตรวจและยืนยันรายครั้ง ส่วนรอบอัตโนมัติเปิดแยกตามการตั้งค่าด้านล่าง ทุกเส้นทางส่งจริง รวมถึงปุ่มส่ง/ยกเลิก ถูกกั้นด้วยเวลาตลาด
- รองรับ Buy Limit, Sell Limit และยกเลิกคำสั่งที่แอปนี้ส่ง ใช้ `ORDER_TIME_DAY` และ `ORDER_FILLING_RETURN` การรองรับจริงขึ้นกับ server และ `order_check`
- ไม่มีการเปิด Short ขายได้ไม่เกินหุ้นหลังหักคำสั่งขายค้าง
@@ -64,7 +64,32 @@ Equity ที่โบรกเกอร์รายงานกับผลร
- โบรกเกอร์รับคำสั่งไม่เท่ากับซื้อขายสำเร็จ ดูคำสั่งค้างและประวัติ fills จาก MT5
- เปลี่ยนราคาโดยยกเลิกคำสั่งเดิม แล้วตรวจและยืนยันคำสั่งใหม่เพื่อประเมินงบซ้ำ
-ไม่เปิดอัตโนมัติซื้อขายตามเวลา ทุกคำสั่งต้องยืนยันใน UI ไม่มีการส่งคำสั่งเงินจริงในการทดสอบของโครงการ
+## ส่งคำสั่งจริงอัตโนมัติ
+
+ตั้งค่าใน `mt5_app/.env` แล้วเริ่มแอปใหม่:
+
+```dotenv
+MT5_ENABLE_LIVE_ORDERS=true
+MT5_AUTO_TRADE=true
+MT5_AUTO_START_DATE=2026-10-19
+MT5_AUTO_END_DATE=
+```
+
+วันสิ้นสุดว่างหมายถึงทำต่อทุกวันทำการจนกดหยุด ใช้พอร์ตและเงินว่างจากบัญชีที่ผูกไว้ ผู้ใช้อนุญาตให้เริ่ม 19 ต.ค. 2026 หลังตรวจพบว่าวันที่ 16 ต.ค. เป็นวันหยุดพิเศษ จึงไม่มีคำสั่งในวันที่ 16
+
+- อ่านพอร์ต/เงินสด/ราคาประมาณทุก 60 วินาที คำนวณสัญญาณเมื่อมีแท่งปิดวันทำการใหม่หลัง 20:30 น.
+- ตรวจรอบอัตโนมัติทุก 15 วินาที ส่งเฉพาะ **10:05 ≤ เวลา < 12:25 และ 14:05 ≤ เวลา < 16:25** ตาม Asia/Bangkok เว้นช่วงประมูลเปิด/ปิด พักเที่ยง วันหยุด และกลางคืน
+- เวลาตลาดหุ้นสามัญจริง: เปิดสุ่ม 09:55–10:00 ถึง 12:30; รอบบ่ายรับประมูล 13:30 เปิดสุ่ม 13:55–14:00 ถึง 16:30 ก่อนประมูลปิด แอปใช้ช่วงที่แคบกว่าเพื่อเว้นรอยต่อ
+- `market_calendar.json` เก็บปฏิทินที่ตรวจจาก SET/ก.ล.ต. รวมประกาศ สธ. 6/2569 วันที่ 16 ต.ค. หากปีนั้นไม่มีปฏิทินจะหยุดส่ง ต้องเพิ่มปฏิทินจากประกาศทางการก่อนเริ่มปีใหม่ วันหยุดฉุกเฉินสามารถเพิ่มในไฟล์นี้ได้และมีผลทันที
+- ต้องมีสัญญาณถึงวันทำการก่อนหน้าและราคา SET/หุ้นจาก MT5 อายุไม่เกิน 120 วินาที พร้อมสิทธิ์ส่งโปรแกรมและกำลังซื้อจริง มิฉะนั้นพักพร้อมแสดงเหตุผล ไม่ใช้นาฬิกาหรือ trade_mode เพียงอย่างเดียวตัดสินว่าตลาดเปิด
+- ซื้อ Limit ไม่เกินราคาปิดสัญญาณ หาก ask สูงกว่าราคานั้นจะรอและประเมินตัวถัดไป ไม่ไล่ราคา ขายเมื่อหลุดเป้าหมายทั้งสองโมเดล โดยใช้ Sell Limit ที่ bid ล่าสุดและต้องมีแท่งหุ้นที่ถือครบถึงวันสัญญาณ
+- ก่อนแต่ละคำสั่ง อ่านพอร์ต เงินสด และคำสั่งค้างใหม่ ไม่ถือว่าเงินจากคำสั่งขายที่ยังไม่จับคู่พร้อมซื้อได้ การรับคำสั่งไม่รับประกันว่าจะจับคู่
+- จองรอบใน SQLite ก่อนเตรียมคำสั่ง จำกัดหนึ่งครั้งต่อหุ้นต่อวัน แม้รีสตาร์ต หากล้มเหลว/ไม่ทราบผลจะเก็บสถานะ `needs_review` และไม่ส่งหุ้นนั้นซ้ำในวันเดียวกัน ส่วน unresolved จะกันข้ามวันด้วยจนตรวจพบผลจริง
+- หน้าแรกแสดงเวลาตลาด วันเริ่ม รอบอ่านพอร์ต รอบวิเคราะห์ และผลตรวจแผนล่าสุด รวมถึงปุ่ม **หยุดส่งอัตโนมัติ** ที่จำสถานะข้ามการเริ่มแอปใหม่ การปิดส่งจริงจะหยุดรอบอัตโนมัติด้วย
+- การหยุดไม่ยกเลิกคำสั่งที่โบรกเกอร์รับแล้ว และไม่สามารถเรียกคืนคำสั่งที่กำลังส่งผ่าน IPC ได้ คำสั่ง Limit ใช้ DAY ยกเลิกเองได้เฉพาะคำสั่งของแอปนี้ในเวลาที่อนุญาต
+- ต้องเปิดเครื่อง แอป และ MT5 ของ Pi ที่ล็อกอินบัญชีเดิมค้างไว้ พร้อมเปิดสิทธิ์การเทรดผ่าน Python และไม่ให้เครื่อง Sleep แอปไม่ได้ตั้งเปิดเครื่อง/เริ่มโปรแกรมหลัง Windows restart ให้อัตโนมัติ
+
+ปฏิทินอ้างอิง: [เวลาตลาด SET](https://www.set.or.th/en/market/information/trading-procedure/trading-hours), [วันหยุด ก.ล.ต.](https://www.sec.or.th/TH/Pages/AboutUs/Holiday.aspx), [ประกาศวันหยุดเพิ่มเติม 16 ต.ค.](https://www.sec.or.th/TH/Documents/11162p_r.pdf)
## การเปรียบเทียบ
diff --git a/mt5_app/__main__.py b/mt5_app/__main__.py
index f0a7231..51d5d3e 100644
--- a/mt5_app/__main__.py
+++ b/mt5_app/__main__.py
@@ -1,9 +1,14 @@
import argparse
import json
+import sys
from .config import Settings
def main():
+ if hasattr(sys.stdout, 'reconfigure'):
+ sys.stdout.reconfigure(encoding='utf-8')
+ if hasattr(sys.stderr, 'reconfigure'):
+ sys.stderr.reconfigure(encoding='utf-8')
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')
@@ -18,6 +23,7 @@ def main():
if args.command == 'status':
state = desk.state()
print(json.dumps({'job': state['job'], 'history': state['history'],
+ 'automation': state['automation'],
'signal_as_of': state['research'].get('signal_as_of')}, ensure_ascii=False, indent=2))
else:
from .research import download_history, run_research
diff --git a/mt5_app/app.py b/mt5_app/app.py
index f2aa867..f5000ca 100644
--- a/mt5_app/app.py
+++ b/mt5_app/app.py
@@ -83,6 +83,11 @@ def handler_for(desk, token, port):
if enabled and body.get('confirm') != 'ENABLE_LIVE':
raise ValueError('ต้องยืนยันเปิดส่งคำสั่งเข้าบัญชีจริง')
self.respond(200, desk.set_live(enabled))
+ elif path == '/api/automation':
+ paused = body.get('paused') is not False
+ if not paused and body.get('confirm') != 'ENABLE_AUTO':
+ raise ValueError('ต้องยืนยันการส่งคำสั่งจริงอัตโนมัติ')
+ self.respond(200, desk.pause_auto(paused))
elif path == '/api/preview':
self.respond(200, desk.preview(body))
elif path == '/api/submit':
@@ -124,7 +129,8 @@ def run(settings, *, auto_refresh=True):
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)
+ print(f'Live orders: {settings.live_orders}; automatic: {settings.auto_trade}; start: {settings.auto_start or "not scheduled"}.', flush=True)
+ print('SET common stocks only; Bangkok windows 10:05-12:25 and 14:05-16:25; holidays blocked.', flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
diff --git a/mt5_app/broker.py b/mt5_app/broker.py
index 9b50341..0830ea4 100644
--- a/mt5_app/broker.py
+++ b/mt5_app/broker.py
@@ -10,16 +10,33 @@ import uuid
from primethai.config import ThaiMarketRules
from .store import now_iso
+from .market import Market
class Broker:
- def __init__(self, settings, store, api=None):
+ def __init__(self, settings, store, api=None, market=None):
if api is None:
import MetaTrader5 as api
self.api = api
self.settings = settings
self.store = store
self.lock = threading.RLock()
+ self.market = market or Market()
+
+ def require_execution_ready(self, request):
+ self.market.require_open()
+ # Require a current exchange feed AND a current stock quote. Calendar
+ # time alone cannot establish that a terminal/feed is actually live.
+ now = self.market.now().timestamp()
+ for symbol in ('SET', request['symbol']):
+ quote = self.quote(symbol)
+ age = now - float((quote or {}).get('time', 0))
+ if quote is None or not -5 <= age <= 120:
+ raise ValueError(f'{symbol}: ราคาจาก MT5 ไม่สดภายใน 120 วินาที หยุดส่งคำสั่ง')
+ if symbol != 'SET':
+ side_price = quote['ask'] if request['type'] == self.api.ORDER_TYPE_BUY_LIMIT else quote['bid']
+ if not math.isfinite(side_price) or side_price <= 0:
+ raise ValueError(f'{symbol}: ไม่มีราคาเสนอซื้อขายที่ใช้งานได้')
def connect(self):
mt = self.api
@@ -219,13 +236,22 @@ class Broker:
with self.lock:
if not self.settings.live_orders:
raise ValueError("การส่งคำสั่งจริงยังปิดอยู่")
+ self.market.require_open()
_, account = self.connect()
request = self.store.claim_intent(ident, account.login, time.time() - 60)
try:
self._validate_order(request)
+ self.require_execution_ready(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()}")
+ self.market.require_open()
+ if self.store.get('intent_context:' + ident, {}).get('automatic'):
+ day = self.market.now().date().isoformat()
+ if (self.store.get('auto_paused', False) or not self.settings.auto_trade
+ or not self.settings.auto_start or day < self.settings.auto_start
+ or (self.settings.auto_end and day > self.settings.auto_end)):
+ raise ValueError('หยุดส่งอัตโนมัติ หรืออยู่นอกช่วงวันที่อนุญาต')
except Exception as exc:
self.store.finish_intent(ident, "rejected", {"error": str(exc)})
raise
@@ -251,6 +277,7 @@ class Broker:
with self.lock:
if not self.settings.live_orders:
raise ValueError("การส่งคำสั่งจริงยังปิดอยู่")
+ self.market.require_open()
self.connect()
mt = self.api
orders = mt.orders_get(ticket=int(ticket))
@@ -264,6 +291,7 @@ class Broker:
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)
+ self.market.require_open()
result = mt.order_send(request)
if result is None:
self.store.finish_intent(ident, 'unknown', {"error": str(mt.last_error())})
diff --git a/mt5_app/config.py b/mt5_app/config.py
index 13d5e56..3baf36e 100644
--- a/mt5_app/config.py
+++ b/mt5_app/config.py
@@ -14,6 +14,9 @@ class Settings:
data_path: Path
port: int = 18901
live_orders: bool = False
+ auto_trade: bool = False
+ auto_start: str = ""
+ auto_end: str = ""
magic: int = 1061501
model_start: str = "2026-01-01"
history_bars: int = 1000
@@ -29,10 +32,13 @@ class Settings:
return (datetime.fromisoformat(self.model_start) - timedelta(days=700)).date().isoformat()
def closed_through(self, now=None):
+ from .market import Market
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)
+ market = Market()
+ if ((now.hour, now.minute) < (self.eod_hour, self.eod_minute)
+ or market.reason(day)):
+ day = market.previous_session(day)
return day.isoformat()
@classmethod
@@ -52,6 +58,9 @@ class Settings:
data_path=Path(path).resolve(),
port=int(values.get("MT5_PORT", 18901)),
live_orders=values.get("MT5_ENABLE_LIVE_ORDERS", "false").lower() == "true",
+ auto_trade=values.get("MT5_AUTO_TRADE", "false").lower() == "true",
+ auto_start=values.get("MT5_AUTO_START_DATE", ""),
+ auto_end=values.get("MT5_AUTO_END_DATE", ""),
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)),
@@ -65,4 +74,11 @@ class Settings:
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")
+ if config.auto_trade and (not config.live_orders or not config.auto_start):
+ raise ValueError("Automatic execution requires live orders and an explicit start date")
+ for day in (config.auto_start, config.auto_end):
+ if day:
+ datetime.strptime(day, '%Y-%m-%d')
+ if config.auto_end and config.auto_end < config.auto_start:
+ raise ValueError("Automatic execution end date precedes start date")
return config
diff --git a/mt5_app/index.html b/mt5_app/index.html
index b19c021..e682f3d 100644
--- a/mt5_app/index.html
+++ b/mt5_app/index.html
@@ -13,6 +13,7 @@
+สถานะตลาดและรอบส่งคำสั่ง
กำลังอ่านเวลาตลาด…
Equity ที่โบรกเกอร์รายงาน
—จากบัญชี MT5
@@ -39,11 +40,12 @@
Backtest จาก MT5 ถึงวันล่าสุด
+รอบส่งคำสั่งอัตโนมัติ
ส่งได้หนึ่งครั้งต่อหุ้นต่อวัน แม้เริ่มแอปใหม่ · คำสั่งที่ไม่ทราบผลหรือส่งไม่ผ่านต้องตรวจสอบก่อน · Limit มีผลภายในวัน
ประวัติซื้อขายจริงล่าสุด
คำสั่งที่ตรวจหรือส่งจากแอปนี้
หากขึ้น unknown หรือ sending ค้าง ให้ตรวจบัญชี MT5 ก่อน แอปจะไม่ส่งคำสั่งเดิมซ้ำอัตโนมัติ
ข้อมูลที่เก็บในเครื่อง
กำลังตรวจประวัติราคา…
ราคาหลักเป็น MT5 D1 และ real volume · ดัชนี SET มาจาก MT5 · ปันผลและแตกหุ้นอ้างอิงข้อมูลเดิมที่มีอยู่ · ข้อมูลส่วนตัวเก็บแยกในแอป MT5
ข้อมูลที่ยังดึงไม่ได้
-
+
@@ -63,7 +65,13 @@ function chart(left,right){const svg=$('equity-chart');svg.replaceChildren();con
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');
+ $('live-state').textContent=d.live_enabled?'เปิดการส่งคำสั่งจริง':'โหมดอ่านพอร์ตและตรวจคำสั่ง';$('live-state').className='badge '+(d.live_enabled?'warning':'positive');
+ const auto=d.automation||{},market=auto.market||{};
+ $('market-status').textContent=(market.message||'รอข้อมูลตลาด')+' · เวลาไทย '+timestamp(market.now);
+ $('auto-status').textContent=auto.message||'ยังไม่ตั้งรอบอัตโนมัติ';
+ $('auto-details').textContent=`เริ่ม ${auto.start_date||'ยังไม่กำหนด'}${auto.end_date?' ถึง '+auto.end_date:' · ทุกวันทำการ'} · ส่งเฉพาะ ${market.order_windows||'—'} น. · ตรวจรอบทุก ${auto.interval_seconds||15} วินาที · อ่านพอร์ตทุก ${auto.portfolio_seconds||60} วินาที · คำนวณราคาปิดหลัง ${auto.eod_time||'20:30'} น. · ปฏิทินยืนยันปี ${(market.calendar_years||[]).join(', ')} (ปีที่ไม่มีปฏิทินจะหยุดส่ง)`;
+ $('auto-cycle').textContent=(auto.last_cycle?'ตรวจแผนล่าสุด '+timestamp(auto.last_cycle.at)+' · '+auto.last_cycle.message:'ยังไม่ถึงรอบส่งอัตโนมัติ')+' · วิเคราะห์สัญญาณล่าสุด '+timestamp(r.updated_at);
+ $('pause-auto').textContent=auto.paused?'เปิดรอบอัตโนมัติต่อ':'หยุดส่งอัตโนมัติ';$('pause-auto').disabled=!auto.enabled&&!auto.paused;
$('trading-mode').textContent=d.live_enabled?'ปิดการส่งจริง':'เปิดการส่งจริง';
$('job-message').textContent=job.message||'รออ่านพอร์ต';$('job').className='banner'+(job.stage==='failed'?' error':'');$('job-progress').hidden=!job.running;if(job.running){$('job-progress').max=job.total||1;$('job-progress').value=job.done||0;}
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(' · ');
@@ -80,6 +88,7 @@ function render(d){state=d;const s=d.snapshot||{},a=s.account||{},r=d.research||
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 '—';}}]);
+ table('executions-table',d.executions,[x=>x.day,x=>x.symbol,x=>x.side==='BUY'?'ซื้อ':'ขาย',x=>x.status,x=>{try{const z=JSON.parse(x.detail||'{}');return z.error||z.result?.comment||z.status||'จองรอบแล้ว';}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;}}
@@ -89,7 +98,8 @@ $('preview-order').onclick=async()=>{try{preview=await api('preview',{symbol:$('
$('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);}};
+$('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);}};
+$('pause-auto').onclick=async()=>{const paused=!state?.automation?.paused;if(!paused&&!confirm('เปิดส่งคำสั่งจริงอัตโนมัติตามสัญญาณและเงินว่าง ทุกวันทำการตั้งแต่วันที่กำหนด โดยไม่ต้องยืนยันแต่ละรายการหรือไม่?'))return;try{await api('automation',{paused,confirm:paused?'PAUSE_AUTO':'ENABLE_AUTO'});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);};
diff --git a/mt5_app/market.py b/mt5_app/market.py
new file mode 100644
index 0000000..882fd82
--- /dev/null
+++ b/mt5_app/market.py
@@ -0,0 +1,90 @@
+"""SET common-stock calendar and conservative order windows, in Bangkok time.
+
+An unknown calendar year blocks execution. A historical bar is never evidence
+that today's exchange is open. Emergency holidays can be added to the JSON.
+"""
+from datetime import datetime, time, timedelta
+import json
+
+from .config import ROOT, TZ
+
+
+class Market:
+ def __init__(self, clock=None):
+ self.clock = clock or (lambda: datetime.now(TZ))
+
+ def now(self):
+ return self.clock().astimezone(TZ)
+
+ def calendar(self):
+ return json.loads((ROOT / 'market_calendar.json').read_text(encoding='utf-8'))
+
+ def reason(self, day):
+ calendar = self.calendar()
+ if day.year not in calendar['years']:
+ return 'ยังไม่มีปฏิทินตลาดที่ยืนยันสำหรับปีนี้ หยุดส่งคำสั่ง'
+ if day.isoformat() in calendar['holidays']:
+ return calendar['holidays'][day.isoformat()]
+ return 'วันเสาร์–อาทิตย์' if day.weekday() >= 5 else None
+
+ def previous_session(self, day):
+ for _ in range(370):
+ day -= timedelta(days=1)
+ if day.year not in self.calendar()['years']:
+ raise ValueError('ปฏิทินตลาดไม่ครอบคลุมวันสัญญาณ')
+ if not self.reason(day):
+ return day
+ raise ValueError('ไม่พบวันทำการก่อนหน้า')
+
+ def status(self, now=None):
+ now = (now or self.now()).astimezone(TZ)
+ reason = self.reason(now.date())
+ minute = now.hour * 60 + now.minute
+ continuous = not reason and (600 <= minute < 750 or 840 <= minute < 990)
+ # Leave five minutes on both sides; no opening/closing auctions.
+ allowed = not reason and (605 <= minute < 745 or 845 <= minute < 985)
+ if reason:
+ phase = 'holiday'
+ elif continuous:
+ phase = 'morning' if minute < 750 else 'afternoon'
+ reason = 'ซื้อขายช่วงเช้า' if minute < 750 else 'ซื้อขายช่วงบ่าย'
+ if not allowed:
+ reason += ' · นอกช่วงส่งคำสั่งของแอป'
+ elif 750 <= minute < 840:
+ phase, reason = 'intermission', 'พักกลางวัน / รอเปิดรอบบ่าย'
+ elif minute < 600:
+ phase, reason = 'before_open', 'ก่อนเปิดตลาด / ช่วงประมูลเปิด'
+ else:
+ phase, reason = 'closed', 'สิ้นสุดช่วงซื้อขาย / ประมูลปิด / นอกเวลาตลาด'
+ next_window = None
+ for offset in range(370):
+ day = now.date() + timedelta(days=offset)
+ if day.year not in self.calendar()['years']:
+ break
+ if self.reason(day):
+ continue
+ for start, end in ((time(10, 5), time(12, 25)), (time(14, 5), time(16, 25))):
+ begin = datetime.combine(day, start, TZ)
+ finish = datetime.combine(day, end, TZ)
+ if now < finish:
+ next_window = max(now, begin).isoformat()
+ break
+ if next_window:
+ break
+ return {'now': now.isoformat(), 'date': now.date().isoformat(), 'phase': phase,
+ 'message': reason, 'continuous': bool(continuous), 'order_allowed': bool(allowed),
+ 'next_window': next_window, 'timezone': 'Asia/Bangkok',
+ 'order_windows': '10:05–12:25 และ 14:05–16:25',
+ 'calendar_verified_at': self.calendar()['verified_at'],
+ 'calendar_years': self.calendar()['years']}
+
+ def require_open(self):
+ status = self.status()
+ if not status['order_allowed']:
+ raise ValueError('ยังส่งคำสั่งไม่ได้: ' + status['message'])
+ return status
+
+ def require_signal(self, signal_day):
+ expected = self.previous_session(self.now().date()).isoformat()
+ if signal_day != expected:
+ raise ValueError(f'ต้องใช้สัญญาณราคาปิด {expected}; ขณะนี้เป็น {signal_day or "ไม่มีข้อมูล"}')
diff --git a/mt5_app/market_calendar.json b/mt5_app/market_calendar.json
new file mode 100644
index 0000000..308c2af
--- /dev/null
+++ b/mt5_app/market_calendar.json
@@ -0,0 +1,32 @@
+{
+ "verified_at": "2026-10-15",
+ "years": [2026],
+ "sources": [
+ "https://www.set.or.th/en/market/information/trading-procedure/trading-hours",
+ "https://media.set.or.th/set/Documents/2025/Nov/SET-Calendar-2026-EN.pdf",
+ "https://www.sec.or.th/TH/Pages/AboutUs/Holiday.aspx",
+ "https://www.sec.or.th/TH/Documents/11162p_r.pdf"
+ ],
+ "holidays": {
+ "2026-01-01": "วันขึ้นปีใหม่",
+ "2026-01-02": "วันหยุดพิเศษ",
+ "2026-03-03": "วันมาฆบูชา",
+ "2026-04-06": "วันจักรี",
+ "2026-04-13": "วันสงกรานต์",
+ "2026-04-14": "วันสงกรานต์",
+ "2026-04-15": "วันสงกรานต์",
+ "2026-05-01": "วันแรงงาน",
+ "2026-05-04": "วันฉัตรมงคล",
+ "2026-06-01": "ชดเชยวันวิสาขบูชา",
+ "2026-06-03": "วันเฉลิมพระชนมพรรษาสมเด็จพระราชินี",
+ "2026-07-28": "วันเฉลิมพระชนมพรรษาพระบาทสมเด็จพระเจ้าอยู่หัว",
+ "2026-07-29": "วันอาสาฬหบูชา",
+ "2026-08-12": "วันแม่แห่งชาติ",
+ "2026-10-13": "วันนวมินทรมหาราช",
+ "2026-10-16": "วันหยุดพิเศษ รองรับการประชุม World Bank / IMF (ก.ล.ต. สธ. 6/2569)",
+ "2026-10-23": "วันปิยมหาราช",
+ "2026-12-07": "ชดเชยวันพ่อแห่งชาติ",
+ "2026-12-10": "วันรัฐธรรมนูญ",
+ "2026-12-31": "วันสิ้นปี"
+ }
+}
diff --git a/mt5_app/service.py b/mt5_app/service.py
index ea29ce4..52bfdb8 100644
--- a/mt5_app/service.py
+++ b/mt5_app/service.py
@@ -1,14 +1,15 @@
-from datetime import datetime, timedelta
+from datetime import datetime
from dataclasses import replace
import logging
import math
+import json
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
+from primethai.config import ThaiMarketRules
def make_plan(snapshot, research, skipped, settings):
@@ -82,6 +83,141 @@ class Desk:
self._job_lock = threading.Lock()
self.stop = threading.Event()
self.log = logging.getLogger('mt5desk')
+ self.market = self.broker.market
+
+ def auto_status(self):
+ market = self.market.status()
+ day = market['date']
+ paused = self.store.get('auto_paused', False)
+ enabled = self.settings.auto_trade and self.settings.live_orders and not paused
+ authorized = (enabled and self.settings.auto_start and day >= self.settings.auto_start
+ and (not self.settings.auto_end or day <= self.settings.auto_end))
+ if paused:
+ message = 'หยุดส่งอัตโนมัติแล้ว'
+ elif not enabled:
+ message = 'การส่งอัตโนมัติยังปิดอยู่'
+ elif day < self.settings.auto_start:
+ message = 'ตั้งเวลาเริ่มส่งจริง ' + self.settings.auto_start
+ elif self.settings.auto_end and day > self.settings.auto_end:
+ message = 'สิ้นสุดช่วงที่อนุญาตให้ส่งอัตโนมัติ'
+ elif not market['order_allowed']:
+ message = 'รอเวลาตลาด: ' + market['message']
+ else:
+ message = 'พร้อมตรวจแผนและส่งคำสั่งจริงตามสัญญาณ'
+ return {'enabled': bool(enabled), 'paused': bool(paused), 'authorized_today': bool(authorized),
+ 'can_run': bool(authorized and market['order_allowed']), 'message': message,
+ 'start_date': self.settings.auto_start, 'end_date': self.settings.auto_end or None,
+ 'last_cycle': self.store.get('auto_cycle'), 'market': market,
+ 'interval_seconds': 15, 'portfolio_seconds': max(30, self.settings.refresh_seconds),
+ 'eod_time': f'{self.settings.eod_hour:02}:{self.settings.eod_minute:02}'}
+
+ def pause_auto(self, paused):
+ # Do not wait for the broker lock: pause must interrupt a long cycle
+ # between orders. It cannot retract an IPC send already in progress.
+ if not paused and not (self.settings.auto_trade and self.settings.live_orders):
+ raise ValueError('ต้องตั้งค่าเปิดส่งจริงและรอบอัตโนมัติใน .env ก่อน')
+ self.store.put('auto_paused', bool(paused))
+ self.store.event('auto_pause', {'paused': bool(paused)})
+ return self.auto_status()
+
+ def automatic_plan(self, snapshot, model):
+ skipped = self.store.skipped(model.get('signal_as_of', ''))
+ now = self.market.now().timestamp()
+ price_wait = set()
+ for signal in model.get('signals', []):
+ quote = snapshot.get('quotes', {}).get(signal['symbol']) or {}
+ ask = float(quote.get('ask') or 0)
+ age = now - float(quote.get('time') or 0)
+ if (ask <= 0 or ask > float(signal.get('reference_close') or 0) + 1e-8
+ or not -5 <= age <= 120):
+ price_wait.add(signal['symbol'])
+ plan = make_plan(snapshot, model, skipped | price_wait, self.settings)
+ for row in plan['rows']:
+ if row['symbol'] in price_wait - skipped and row['action'] == 'SKIPPED':
+ row.update(action='WAIT', reason='รอราคาสดและราคาเสนอขายไม่เกินราคาสัญญาณ')
+ return plan
+
+ def automatic_cycle(self):
+ if not self.auto_status()['can_run'] or not self._job_lock.acquire(blocking=False):
+ return
+ results = []
+ try:
+ with self.broker.lock:
+ if not self.auto_status()['can_run']:
+ return
+ model = self.store.get('research', {})
+ self.market.require_signal(model.get('signal_as_of'))
+ if not model.get('data_quality', {}).get('calendar_source'):
+ raise ValueError('ข้อมูลยังไม่ผ่านการตรวจปฏิทิน MT5')
+ snapshot = self.broker.snapshot()
+ self.update_quotes(snapshot, model)
+ # Release cash assigned to an unaffordable entry price so a
+ # lower-ranked, actionable stock can be considered this cycle.
+ plan = self.automatic_plan(snapshot, model)
+ candidates = [r['symbol'] for r in plan['rows'] if r['action'] in ('BUY', 'SELL') and r['quantity'] >= 100]
+ for symbol in candidates:
+ if not self.auto_status()['can_run']:
+ break
+ # Re-read buying power after every preceding submission.
+ snapshot = self.broker.snapshot()
+ self.update_quotes(snapshot, model)
+ plan = self.automatic_plan(snapshot, model)
+ row = next(r for r in plan['rows'] if r['symbol'] == symbol)
+ side = row['action']
+ if side not in ('BUY', 'SELL') or row['quantity'] < 100:
+ continue
+ quote = snapshot.get('quotes', {}).get(symbol) or {}
+ if side == 'BUY':
+ # Keep the EOD recommendation as the ceiling; no chase.
+ if not quote.get('ask') or quote['ask'] > row['limit_price'] + 1e-8:
+ results.append({'symbol': symbol, 'status': 'waiting_price',
+ 'message': 'รอราคาเสนอขายไม่เกินราคาสัญญาณ'})
+ continue
+ price = row['limit_price']
+ else:
+ # An absent target is actionable only with complete data
+ # for the held stock through the same signal session.
+ if self.store.last_bar_day(symbol, model['signal_as_of']) != model['signal_as_of']:
+ raise ValueError(symbol + ': ข้อมูลหุ้นที่ถือไม่ครบ ไม่ส่งขายจากข้อมูลที่หาย')
+ bid = float(quote.get('bid') or 0)
+ if bid <= 0:
+ continue
+ tick = ThaiMarketRules().tick_size(bid)
+ price = round(math.ceil(bid / tick - 1e-8) * tick, 4)
+ day = self.market.now().date().isoformat()
+ request = {'symbol': symbol, 'type': (self.broker.api.ORDER_TYPE_BUY_LIMIT if side == 'BUY'
+ else self.broker.api.ORDER_TYPE_SELL_LIMIT)}
+ self.broker.require_execution_ready(request)
+ if not self.store.claim_execution(day, symbol, side):
+ continue
+ preview = None
+ try:
+ preview = self.preview({'symbol': symbol, 'side': side,
+ 'quantity': row['quantity'], 'price': price}, automatic=True)
+ context = self.store.get('intent_context:' + preview['id'], {})
+ self.store.put('intent_context:' + preview['id'], {**context, 'automatic': True})
+ self.store.finish_execution(day, symbol, 'prepared', {}, preview['id'])
+ if not self.auto_status()['can_run']:
+ raise ValueError('หยุดรอบอัตโนมัติ หรือสิ้นสุดช่วงส่งคำสั่ง')
+ result = self.submit(preview['id'])
+ self.store.finish_execution(day, symbol, result['status'], result, preview['id'])
+ results.append({'symbol': symbol, 'side': side, **result})
+ except Exception as exc:
+ self.store.finish_execution(day, symbol, 'needs_review', {'error': str(exc)},
+ preview['id'] if preview else None)
+ self.log.exception('auto_order_failed symbol=%s side=%s', symbol, side)
+ # Stop the cycle after any ambiguous or rejected send.
+ raise
+ message = ('ตรวจแผนแล้ว ไม่มีรายการซื้อขายที่ส่งได้ตามงบและสัญญาณ' if not candidates
+ else 'ตรวจแผนแล้ว ดูผลส่งคำสั่ง / รายการรอราคาในประวัติ')
+ self.store.put('auto_cycle', {'at': now_iso(), 'status': 'complete', 'message': message,
+ 'candidates': len(candidates), 'results': results})
+ self.store.put('connection_error', None)
+ except Exception as exc:
+ self.log.exception('automatic_cycle_failed')
+ self.store.put('auto_cycle', {'at': now_iso(), 'status': 'blocked', 'message': str(exc), 'results': results})
+ finally:
+ self._job_lock.release()
def progress(self, stage, message, done=0, total=1):
self.store.put('job', {'running': True, 'stage': stage, 'message': message,
@@ -109,8 +245,10 @@ class Desk:
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):
+ before = self.store.bar_summary()
download_history(self.broker, self.store, self.settings, self.progress)
- model = run_research(self.store, self.settings, self.progress)
+ if research or not model or needs_new_day or self.store.bar_summary() != before:
+ model = run_research(self.store, self.settings, self.progress)
snapshot = self.broker.snapshot()
self.progress('quotes', 'อ่านราคาเสนอซื้อขายของหุ้นในแผน')
self.update_quotes(snapshot, model)
@@ -140,6 +278,7 @@ class Desk:
'connection_error': self.store.get('connection_error'),
'history': {k: v for k, v in history.items() if k != 'successful_symbols'},
'live_enabled': self.settings.live_orders, 'app_magic': self.settings.magic,
+ 'automation': self.auto_status(), 'executions': self.store.executions(),
'max_premium_pct': self.settings.max_premium_pct,
'intents': self.store.intents()}
@@ -158,10 +297,12 @@ class Desk:
raise ValueError('MT5 หรือบัญชียังไม่อนุญาตให้ส่งคำสั่งผ่านโปรแกรม')
self.settings = replace(self.settings, live_orders=bool(enabled))
self.broker.settings = self.settings
+ if not enabled:
+ self.store.put('auto_paused', True)
self.store.event('trading_mode', {'live_enabled': bool(enabled)})
return {'live_enabled': bool(enabled)}
- def preview(self, payload):
+ def preview(self, payload, *, automatic=False):
job = self.store.get('job', {})
if job.get('running') and job.get('stage') in ('history', 'archive', 'signals', 'comparison'):
raise ValueError('รอการคำนวณสัญญาณให้เสร็จก่อนตรวจคำสั่งซื้อขาย')
@@ -169,22 +310,25 @@ class Desk:
raise ValueError('ยังไม่มีสัญญาณที่คำนวณสำเร็จ')
if not self.store.get('research', {}).get('data_quality', {}).get('calendar_source'):
raise ValueError('สัญญาณยังไม่ผ่านการตรวจปฏิทินข้อมูล MT5 กรุณาคำนวณใหม่ก่อน')
+ self.market.require_signal(self.store.get('research', {}).get('signal_as_of'))
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()
+ if automatic:
+ state['plan'] = self.automatic_plan(snapshot, state['research'])
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('สัญญาณเก่าเกินไป อัปเดตข้อมูลก่อนส่งคำสั่ง')
+ # Freshness follows exchange sessions, including long holidays;
+ # require_signal() above already checks the exact prior session.
return self.broker.preview(symbol, side, qty, price, state['research'].get('signals', []))
def submit(self, ident):
+ self.market.require_signal(self.store.get('research', {}).get('signal_as_of'))
job = self.store.get('job', {})
if job.get('running') and job.get('stage') in ('history', 'archive', 'signals', 'comparison'):
raise ValueError('รอการคำนวณให้เสร็จ แล้วตรวจคำสั่งใหม่ก่อนส่ง')
@@ -193,23 +337,38 @@ class Desk:
intent = intents.get(ident)
if not intent:
raise ValueError('ไม่พบตัวอย่างคำสั่ง')
- import json
request = json.loads(intent['request'])
+ context = self.store.get('intent_context:' + ident, {})
+ if context.get('automatic'):
+ state = self.state()
+ auto_plan = self.automatic_plan(state['snapshot'], state['research'])
+ row = next((r for r in auto_plan['rows'] if r['symbol'] == request['symbol']), None)
+ side = 'BUY' if request['type'] == self.broker.api.ORDER_TYPE_BUY_LIMIT else 'SELL'
+ if not row or row['action'] != side or request['volume'] > row['quantity']:
+ raise ValueError('แผนอัตโนมัติเปลี่ยนแล้ว หยุดส่งรายการนี้')
if request['type'] == self.broker.api.ORDER_TYPE_BUY_LIMIT:
state = self.state()
- context = self.store.get('intent_context:' + ident, {})
+ if context.get('automatic'):
+ state['plan'] = self.automatic_plan(state['snapshot'], state['research'])
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()
+ self.refresh() # A running automatic cycle owns _job_lock; its next snapshot handles this.
return result
def scheduler(self):
self.refresh()
- while not self.stop.wait(max(30, self.settings.refresh_seconds)):
+ last_refresh = time.monotonic()
+ while not self.stop.wait(15):
+ try:
+ self.automatic_cycle()
+ except Exception:
+ self.log.exception('automatic_scheduler_failed')
+ if time.monotonic() - last_refresh < max(30, self.settings.refresh_seconds):
+ continue
last = self.store.get('job', {})
# Avoid hammering the terminal with large history retries on errors.
if last.get('stage') == 'failed':
@@ -220,3 +379,4 @@ class Desk:
except (KeyError, ValueError):
pass
self.refresh()
+ last_refresh = time.monotonic()
diff --git a/mt5_app/store.py b/mt5_app/store.py
index 097d57a..4a2cb94 100644
--- a/mt5_app/store.py
+++ b/mt5_app/store.py
@@ -27,6 +27,9 @@ class Store:
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);
+ CREATE TABLE IF NOT EXISTS executions (
+ day TEXT, symbol TEXT, side TEXT, status TEXT, intent TEXT,
+ updated_at TEXT, detail TEXT, PRIMARY KEY(day,symbol));
""")
@contextmanager
@@ -53,6 +56,24 @@ class Store:
db.execute("INSERT INTO events(time,kind,payload) VALUES (?,?,?)",
(now_iso(), kind, json.dumps(payload, allow_nan=False)))
+ def claim_execution(self, day, symbol, side):
+ # Reserve BEFORE any preparation or send. A crash consumes the daily
+ # attempt too. Neither restart nor a missing broker response resends it.
+ with self.connect() as db:
+ return bool(db.execute(
+ "INSERT OR IGNORE INTO executions VALUES (?,?,?,'preparing',NULL,?,NULL)",
+ (day, symbol, side, now_iso())).rowcount)
+
+ def finish_execution(self, day, symbol, status, detail, intent=None):
+ with self.connect() as db:
+ db.execute('UPDATE executions SET status=?,detail=?,intent=?,updated_at=? WHERE day=? AND symbol=?',
+ (status, json.dumps(detail), intent, now_iso(), day, symbol))
+
+ def executions(self, limit=100):
+ with self.connect() as db:
+ return [dict(r) for r in db.execute(
+ 'SELECT * FROM executions ORDER BY updated_at DESC LIMIT ?', (limit,))]
+
def save_bars(self, rows):
with self.connect() as db:
db.executemany("INSERT OR REPLACE INTO bars VALUES (?,?,?,?,?,?,?,?)", rows)
@@ -67,6 +88,11 @@ class Store:
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 last_bar_day(self, symbol, through):
+ with self.connect() as db:
+ return db.execute('SELECT max(day) FROM bars WHERE symbol=? AND day<=?',
+ (symbol, through)).fetchone()[0]
+
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,))}
diff --git a/mt5_app/tests/test_desk.py b/mt5_app/tests/test_desk.py
index c3da197..4ca9f03 100644
--- a/mt5_app/tests/test_desk.py
+++ b/mt5_app/tests/test_desk.py
@@ -13,6 +13,10 @@ 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
+from mt5_app.market import Market
+
+
+FAKE_NOW = datetime(2026, 10, 19, 10, 10, tzinfo=TZ)
class FakeAPI:
@@ -48,7 +52,11 @@ class FakeAPI:
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)
+ return NS(path='SET\\Common Stock\\' + name, trade_contract_size=1, volume_max=1e6, trade_mode=1,
+ bid=10., ask=10., last=10., time=int(FAKE_NOW.timestamp()), volume_step=100, volume_min=1)
+
+ def symbol_info_tick(self, name):
+ return NS(time=int(FAKE_NOW.timestamp()))
def orders_get(self, **kwargs):
return self.orders
@@ -76,7 +84,7 @@ class DeskTests(unittest.TestCase):
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.broker = Broker(self.settings, self.store, api=self.api, market=Market(clock=lambda: FAKE_NOW))
self.signals = [{'symbol': 'AAA', 'reference_close': 10, 'stale_sessions': 0}]
def tearDown(self):