Files

398 lines
26 KiB
Python

from datetime import datetime
from dataclasses import replace
import logging
import math
import json
import threading
import time
from .broker import Broker
from .research import download_history, run_research
from .store import Store, now_iso
from .runtime import read_status
from primethai.config import ThaiMarketRules
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')
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,
'done': done, 'total': total, 'updated_at': now_iso()})
def update_quotes(self, snapshot, research):
benchmark = self.broker.quote('SET')
if benchmark:
snapshot.setdefault('quotes', {})['SET'] = benchmark
for signal in research.get('signals', []):
quote = self.broker.quote(signal['symbol'])
if quote:
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()
or self.store.last_bar_day('SET', self.settings.closed_through())
!= self.settings.closed_through())
model_due = model.get('signal_as_of') != self.settings.closed_through()
if research or not model or needs_new_day or ((incomplete or model_due) and retry_due):
before = self.store.bar_summary()
download_history(self.broker, self.store, self.settings, self.progress)
if research or not model or needs_new_day or model_due 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)
pending = model.get('signal_as_of') != self.settings.closed_through()
message = (f'พอร์ตอัปเดตแล้ว แต่สัญญาณถึง {model.get("signal_as_of", "ยังไม่มี")} '
f'รอข้อมูล/คำนวณถึง {self.settings.closed_through()}' if pending else 'พร้อมใช้งาน')
self.store.put('job', {'running': False, 'stage': 'waiting_data' if pending else 'complete',
'message': 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 model.get('signal_as_of') != self.settings.closed_through()
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,
'runtime': read_status(self.settings.state_dir / 'runtime.json'),
'supervisor': read_status(self.settings.state_dir / 'supervisor.json'),
'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,
'server_utc_offset_minutes': self.settings.server_utc_offset_minutes,
'automation': self.auto_status(), 'executions': self.store.executions(),
'max_premium_pct': self.settings.max_premium_pct,
'intents': self.store.intents()}
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
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, *, automatic=False):
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 กรุณาคำนวณใหม่ก่อน')
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('จำนวนซื้อเกินแผนปัจจุบัน หรือหุ้นถูกข้ามไปแล้ว')
# 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('รอการคำนวณให้เสร็จ แล้วตรวจคำสั่งใหม่ก่อนส่ง')
# 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('ไม่พบตัวอย่างคำสั่ง')
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()
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() # A running automatic cycle owns _job_lock; its next snapshot handles this.
return result
def scheduler(self):
self.refresh()
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':
try:
elapsed = time.time() - datetime.fromisoformat(last['updated_at']).timestamp()
if elapsed < 600:
continue
except (KeyError, ValueError):
pass
self.refresh()
last_refresh = time.monotonic()