"""Example strategy that runs on YOUR computer and trades through your hosted MT5: a moving-average crossover.

    pip install websockets
    set HOSTMT5_KEY=mc_...        (macOS/Linux: export HOSTMT5_KEY=mc_...)
    python sma_cross.py 1 EURUSD M5

Every closed candle: fast SMA crosses above slow SMA -> close sells, buy; crosses below -> close buys, sell.
Try it on a DEMO account first. This is an example, not trading advice."""
import os, sys
from hostmt5 import HostMT5

ACCOUNT, SYMBOL, TF = int(sys.argv[1]), sys.argv[2], sys.argv[3]
FAST, SLOW, LOTS = 10, 30, 0.01

acc = HostMT5(os.environ['HOSTMT5_KEY']).account(ACCOUNT)
closes = [b['close'] for b in acc.bars(SYMBOL, TF, count=SLOW + 5)[:-1]]       # history without the forming bar
sma = lambda n: sum(closes[-n:]) / n
print(f'{SYMBOL} {TF}: {len(closes)} bars loaded, fast {sma(FAST):.5f} slow {sma(SLOW):.5f}')


def position_side():
    ps = acc.positions(SYMBOL)
    return ps[0]['side'] if ps else None


for ev in acc.stream(candles=[(SYMBOL, TF)], account=False):
    if ev['type'] != 'candle' or not ev['closed']: continue                 # act once per finished bar
    was_above = sma(FAST) > sma(SLOW)
    closes.append(ev['bar']['close']); closes = closes[-500:]
    above = sma(FAST) > sma(SLOW)
    print(ev['bar']['time'], 'close', ev['bar']['close'], 'fast>slow' if above else 'fast<slow')
    if above == was_above: continue
    want = 'buy' if above else 'sell'
    if position_side() == want: continue
    acc.close_all(symbol=SYMBOL)                                            # flat first, then the new side
    t = acc.order(SYMBOL, want, LOTS, sl_pips=30, tp_pips=60, client_id=f"sma-{ev['bar']['time']}")   # client_id: a retry never doubles
    print('   ->', want, LOTS, 'ticket', t['ticket'], 'at', t['price'])
