Files

341 lines
21 KiB
Python

"""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
from .market import Market
class Broker:
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 normalized_times(self, value):
"""Convert explicitly configured broker-clock epochs to actual UTC.
Preserve raw fields for auditing. D1 bar dates are session labels and
deliberately do not pass through this conversion.
"""
data = value._asdict() if hasattr(value, '_asdict') else dict(value)
offset = self.settings.server_utc_offset_minutes * 60
if not offset:
return data
raw = {}
for key, stamp in list(data.items()):
if (key == 'time' or key.startswith('time_')) and isinstance(stamp, (int, float)) and stamp > 0:
raw[key] = stamp
data[key] = stamp - offset * (1000 if key.endswith('_msc') else 1)
if raw:
data['_broker_times'] = raw
return data
def require_execution_ready(self, request):
self.market.require_open()
# Require a current exchange feed AND a current stock quote. Calendar
# 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:
raise ValueError(f'{symbol}: อ่านราคา MT5 ไม่ได้ หยุดส่งคำสั่ง')
if age < -5:
raise ValueError(f'{symbol}: เวลาราคาอยู่ล่วงหน้า {abs(age):,.0f} วินาที '
f'(server UTC offset={self.settings.server_utc_offset_minutes} นาที) หยุดส่งคำสั่ง')
if age > 120:
raise ValueError(f'{symbol}: ราคา MT5 อายุ {age:,.0f} วินาที เกิน 120 วินาที หยุดส่งคำสั่ง')
if symbol != 'SET':
side_price = quote['ask'] if request['type'] == self.api.ORDER_TYPE_BUY_LIMIT else quote['bid']
if not math.isfinite(side_price) or side_price <= 0:
raise ValueError(f'{symbol}: ไม่มีราคาเสนอซื้อขายที่ใช้งานได้')
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)
# Query boundaries use the same encoded server clock as the broker
# records; otherwise today's latest fills can be missing for hours.
broker_now = now + timedelta(minutes=self.settings.server_utc_offset_minutes)
deals = mt.history_deals_get(broker_now - timedelta(days=120), broker_now)
if deals is None:
raise RuntimeError(f"อ่านประวัติไม่ได้: {mt.last_error()}")
history_orders = mt.history_orders_get(broker_now - timedelta(days=120), broker_now)
if history_orders is None:
raise RuntimeError(f"อ่านประวัติคำสั่งไม่ได้: {mt.last_error()}")
pos = [self.normalized_times(p) for p in positions]
pending = [self.normalized_times(o) for o in orders]
account_data = {k: getattr(account, k, None) for k in (
"balance", "equity", "profit", "margin_free", "margin", "assets", "liabilities",
"currency", "server", "trade_allowed", "trade_expert", "margin_mode",
)}
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": [self.normalized_times(d) for d in deals],
"history_orders": [self.normalized_times(o) for o in history_orders],
"quotes": quotes,
"terminal": {k: getattr(terminal, k, None) for k in (
"connected", "trade_allowed", "tradeapi_disabled", "build", "name")},
"server_utc_offset_minutes": self.settings.server_utc_offset_minutes,
"warnings": ([f"Equity จาก server กับมูลค่าหุ้นรวมต่างกัน {differences:,.2f} บาท; ใช้เงินว่างจากโบรกเกอร์เป็นงบ"]
if differences > .02 else []),
}
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)
if info is None:
return None
if not getattr(info, 'visible', True) or not getattr(info, 'select', True):
if not self.api.symbol_select(symbol, True):
raise ValueError(f'{symbol}: เปิดรับราคาใน Market Watch ไม่สำเร็จ: {self.api.last_error()}')
info = self.api.symbol_info(symbol)
if info is None:
return None
tick = self.api.symbol_info_tick(symbol)
raw_time = int(tick.time if tick else info.time)
offset = self.settings.server_utc_offset_minutes * 60
return {
"symbol": symbol, "bid": float(info.bid), "ask": float(info.ask), "last": float(info.last),
"time": raw_time - offset if raw_time else 0,
"time_raw": raw_time, "server_utc_offset_minutes": self.settings.server_utc_offset_minutes,
"contract_size": float(info.trade_contract_size), "volume_step": float(info.volume_step),
"volume_min": float(info.volume_min), "trade_mode": int(info.trade_mode),
"path": info.path,
}
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("การส่งคำสั่งจริงยังปิดอยู่")
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
# 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.market.require_open()
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)
self.market.require_open()
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