"""Exchange hours, currency conversion and the 'exchange closed' buy rule.""" from dataclasses import replace from datetime import datetime, timezone import pytest from app import demo, exchanges, main, marketdata from app.config import INSTRUMENTS from tests.test_bot import reset # noqa: F401 (shared fixture: clean account, mocked news) from tests.test_demo import trending_candles, yahoo_json EX = exchanges.EXCHANGES def utc(y, m, d, h, mi=0): return datetime(y, m, d, h, mi, tzinfo=timezone.utc) def test_amsterdam_hours_winter_and_summer(): # Tuesday 10 Nov 2026, CET (UTC+1): open 09:00 to 17:30 local assert not exchanges.is_open(EX["AEX"], utc(2026, 11, 10, 7, 59)) assert exchanges.is_open(EX["AEX"], utc(2026, 11, 10, 8, 0)) assert exchanges.is_open(EX["AEX"], utc(2026, 11, 10, 16, 29)) assert not exchanges.is_open(EX["AEX"], utc(2026, 11, 10, 16, 30)) # closing time is exclusive # Tuesday 7 Jul 2026, CEST (UTC+2): the same local hours are one UTC hour earlier assert not exchanges.is_open(EX["AEX"], utc(2026, 7, 7, 6, 59)) assert exchanges.is_open(EX["AEX"], utc(2026, 7, 7, 7, 0)) def test_weekend_closed_but_crypto_always_open(): sat = utc(2026, 11, 14, 11) assert not exchanges.is_open(EX["AEX"], sat) and not exchanges.is_open(EX["US"], sat) assert exchanges.is_open(EX["CRYPTO"], sat) def test_us_and_london_hours(): assert not exchanges.is_open(EX["US"], utc(2026, 11, 10, 14, 29)) # 09:29 New York (EST) assert exchanges.is_open(EX["US"], utc(2026, 11, 10, 14, 30)) assert exchanges.is_open(EX["LSE"], utc(2026, 11, 10, 8, 0)) # London is UTC in winter assert not exchanges.is_open(EX["LSE"], utc(2026, 11, 10, 16, 30)) # US and Europe change clocks on different dates: late March 2026, New York is on summer time # (UTC-4) while Amsterdam is not yet (UTC+1), so the gap shrinks to 5 hours instead of 6. assert exchanges.is_open(EX["US"], utc(2026, 3, 25, 13, 30)) assert exchanges.is_open(EX["AEX"], utc(2026, 3, 25, 8, 0)) def test_describe_lists_every_exchange(): d = {e["id"]: e for e in exchanges.describe(utc(2026, 11, 10, 15))} assert set(d) == set(EX) assert d["AEX"]["open"] and d["US"]["open"] and d["CRYPTO"]["hours"] == "24/7" assert d["AEX"]["hours"].startswith("09:00–17:30") def test_every_instrument_is_wired_consistently(): assert len(INSTRUMENTS) >= 20 for sym, inst in INSTRUMENTS.items(): ex = EX[inst.exchange] assert inst.yahoo.endswith(ex.yahoo_suffix) and inst.broker == ex.trade_via, sym assert inst.currency == ex.currency, sym assert INSTRUMENTS["SHEL"].yahoo == "SHEL.L" and INSTRUMENTS["SAP"].yahoo == "SAP.DE" assert INSTRUMENTS["ASML"].yahoo == "ASML.AS" and INSTRUMENTS["MC"].yahoo == "MC.PA" def test_currency_conversion(): rates = {"USD": 1.10, "GBP": 0.87} assert marketdata.to_eur(110, "USD", rates) == pytest.approx(100) assert marketdata.to_eur(2700, "GBp", rates) == pytest.approx(27 / 0.87) # pence -> pounds -> euros assert marketdata.to_eur(27, "GBP", rates) == pytest.approx(27 / 0.87) assert marketdata.to_eur(55, "EUR", rates) == 55 with pytest.raises(ValueError): marketdata.to_eur(1, "JPY", rates) # ---- the buy rule, with the clock pinned by passing the signal's own time ---- @pytest.fixture def hours_on(monkeypatch): monkeypatch.setattr(main, "settings", replace(main.settings, enforce_market_hours=True)) def test_buy_blocked_when_exchange_closed_but_sells_and_crypto_pass(hours_on): tue_10 = utc(2026, 11, 10, 9).timestamp() # 10:00 Amsterdam sat = utc(2026, 11, 14, 9).timestamp() assert main.process("ASML", "buy", 700, "t", at=tue_10)["decision"] == "executed" assert main.process("ASML", "sell", 710, "t", at=sat)["decision"] == "executed" # exits never blocked r = main.process("ADYEN", "buy", 1400, "t", at=sat) assert r["decision"] == "blocked" and "Euronext Amsterdam is closed" in r["reason"] assert main.process("BTCUSD", "buy", 67000, "t", at=sat)["decision"] == "executed" def test_simulated_demo_skips_the_hours_check(hours_on): sat = utc(2026, 11, 14, 9).timestamp() assert main.process("SAP", "buy", 220, "t", at=sat, enforce_hours=False)["decision"] == "executed" def test_london_pence_flow_into_the_fake_account_in_euros(): full = trending_candles(120) def fetch(sym): cur = "GBp" if sym.endswith(".L") else "EUR" if sym[-3:] in (".AS", ".PA", ".DE") else "USD" return marketdata.parse_chart(yahoo_json(full, cur), "1h", now=10**12) sim = demo.Simulator(main.process, main.paper.mark, mode="real", fetch=fetch, fx=lambda: {"USD": 1.1, "GBP": 0.87}) sim.run_once(main.paper.equity, main._held) last = full[-1][4] # close, quoted in pence assert sim.series["SHEL"].currency == "GBp" row = main.store.q("SELECT last_price FROM paper_positions WHERE symbol='SHEL'") # not held, so just check the conversion the simulator would use assert sim.to_eur(sim.series["SHEL"], last) == pytest.approx(last / 100 / 0.87) assert sim.to_eur(sim.series["SAP"], last) == pytest.approx(last) assert sim.to_eur(sim.series["SPY"], last) == pytest.approx(last / 1.1) assert row == [] def test_unknown_currency_becomes_a_feed_error_not_a_crash(): full = trending_candles(120) fetch = lambda sym: marketdata.parse_chart(yahoo_json(full, "JPY"), "1h", now=10**12) # noqa: E731 sim = demo.Simulator(main.process, main.paper.mark, mode="real", fetch=fetch, fx=lambda: {}) sim.run_once(main.paper.equity, main._held) assert "no EUR exchange rate" in sim.series["NVDA"].error