From 33b14aaa2344b0fd95d1629627c3d135b24ae102 Mon Sep 17 00:00:00 2001 From: TheSiahxyz <164138827+TheSiahxyz@users.noreply.github.com> Date: Wed, 1 Apr 2026 15:56:35 +0900 Subject: feat: initial trading platform implementation Binance spot crypto trading platform with microservices architecture: - shared: Pydantic models, Redis Streams broker, asyncpg DB layer - data-collector: Binance WebSocket/REST market data collection - strategy-engine: Plugin-based strategy execution (RSI, Grid) - order-executor: Order execution with risk management - portfolio-manager: Position tracking and PnL calculation - backtester: Historical strategy testing with simulator - cli: Click-based CLI for all operations - Docker Compose orchestration with Redis and PostgreSQL - 24 test files covering all modules --- shared/tests/__init__.py | 0 shared/tests/test_broker.py | 66 +++++++++++++++++++++++++++++ shared/tests/test_db.py | 70 +++++++++++++++++++++++++++++++ shared/tests/test_events.py | 80 +++++++++++++++++++++++++++++++++++ shared/tests/test_models.py | 100 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 316 insertions(+) create mode 100644 shared/tests/__init__.py create mode 100644 shared/tests/test_broker.py create mode 100644 shared/tests/test_db.py create mode 100644 shared/tests/test_events.py create mode 100644 shared/tests/test_models.py (limited to 'shared/tests') diff --git a/shared/tests/__init__.py b/shared/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/shared/tests/test_broker.py b/shared/tests/test_broker.py new file mode 100644 index 0000000..d3a3569 --- /dev/null +++ b/shared/tests/test_broker.py @@ -0,0 +1,66 @@ +"""Tests for the Redis broker.""" +import pytest +import json +from unittest.mock import AsyncMock, MagicMock, patch + + +@pytest.mark.asyncio +async def test_broker_publish(): + """Test that publish calls xadd on the redis connection.""" + with patch("redis.asyncio.from_url") as mock_from_url: + mock_redis = AsyncMock() + mock_from_url.return_value = mock_redis + + from shared.broker import RedisBroker + broker = RedisBroker("redis://localhost:6379") + data = {"type": "CANDLE", "symbol": "BTCUSDT"} + await broker.publish("candles", data) + + mock_redis.xadd.assert_called_once() + call_args = mock_redis.xadd.call_args + assert call_args[0][0] == "candles" + payload = call_args[0][1] + assert "payload" in payload + parsed = json.loads(payload["payload"]) + assert parsed["type"] == "CANDLE" + + +@pytest.mark.asyncio +async def test_broker_subscribe_returns_messages(): + """Test that read parses xread response correctly.""" + with patch("redis.asyncio.from_url") as mock_from_url: + mock_redis = AsyncMock() + mock_from_url.return_value = mock_redis + + payload_data = {"type": "CANDLE", "symbol": "ETHUSDT"} + mock_redis.xread.return_value = [ + [ + b"candles", + [ + (b"1234567890-0", {b"payload": json.dumps(payload_data).encode()}), + ], + ] + ] + + from shared.broker import RedisBroker + broker = RedisBroker("redis://localhost:6379") + messages = await broker.read("candles", last_id="$") + + mock_redis.xread.assert_called_once() + assert len(messages) == 1 + assert messages[0]["type"] == "CANDLE" + assert messages[0]["symbol"] == "ETHUSDT" + + +@pytest.mark.asyncio +async def test_broker_close(): + """Test that close calls aclose on the redis connection.""" + with patch("redis.asyncio.from_url") as mock_from_url: + mock_redis = AsyncMock() + mock_from_url.return_value = mock_redis + + from shared.broker import RedisBroker + broker = RedisBroker("redis://localhost:6379") + await broker.close() + + mock_redis.aclose.assert_called_once() diff --git a/shared/tests/test_db.py b/shared/tests/test_db.py new file mode 100644 index 0000000..c31e487 --- /dev/null +++ b/shared/tests/test_db.py @@ -0,0 +1,70 @@ +"""Tests for the database layer.""" +import pytest +from decimal import Decimal +from datetime import datetime, timezone +from unittest.mock import AsyncMock, MagicMock, patch, call + + +def make_candle(): + from shared.models import Candle + return Candle( + symbol="BTCUSDT", + timeframe="1m", + open_time=datetime(2024, 1, 1, tzinfo=timezone.utc), + open=Decimal("50000"), + high=Decimal("51000"), + low=Decimal("49500"), + close=Decimal("50500"), + volume=Decimal("100"), + ) + + +@pytest.mark.asyncio +async def test_db_init_sql_creates_tables(): + """Verify that init_tables SQL references all required table names.""" + with patch("asyncpg.create_pool", new_callable=AsyncMock) as mock_pool: + mock_conn = AsyncMock() + mock_pool.return_value.__aenter__ = AsyncMock(return_value=mock_conn) + mock_pool.return_value.__aexit__ = AsyncMock(return_value=False) + + # Capture the SQL that gets executed + executed_sqls = [] + + async def capture_execute(sql, *args, **kwargs): + executed_sqls.append(sql) + + mock_conn.execute = capture_execute + + from shared.db import Database + db = Database("postgresql://trading:trading@localhost:5432/trading") + db._pool = mock_pool.return_value + await db.init_tables() + + combined_sql = " ".join(executed_sqls) + for table in ["candles", "signals", "orders", "trades", "positions", "portfolio_snapshots"]: + assert table in combined_sql, f"Table '{table}' not found in SQL" + + +@pytest.mark.asyncio +async def test_db_insert_candle(): + """Verify that insert_candle executes INSERT INTO candles.""" + with patch("asyncpg.create_pool", new_callable=AsyncMock) as mock_pool: + mock_conn = AsyncMock() + mock_pool.return_value.__aenter__ = AsyncMock(return_value=mock_conn) + mock_pool.return_value.__aexit__ = AsyncMock(return_value=False) + + executed = [] + + async def capture_execute(sql, *args, **kwargs): + executed.append((sql, args)) + + mock_conn.execute = capture_execute + + from shared.db import Database + db = Database("postgresql://trading:trading@localhost:5432/trading") + db._pool = mock_pool.return_value + candle = make_candle() + await db.insert_candle(candle) + + assert any("INSERT INTO candles" in sql for sql, _ in executed), \ + "Expected INSERT INTO candles" diff --git a/shared/tests/test_events.py b/shared/tests/test_events.py new file mode 100644 index 0000000..4bc7981 --- /dev/null +++ b/shared/tests/test_events.py @@ -0,0 +1,80 @@ +"""Tests for shared event types.""" +import pytest +from decimal import Decimal +from datetime import datetime, timezone + + +def make_candle(): + from shared.models import Candle + return Candle( + symbol="BTCUSDT", + timeframe="1m", + open_time=datetime(2024, 1, 1, tzinfo=timezone.utc), + open=Decimal("50000"), + high=Decimal("51000"), + low=Decimal("49500"), + close=Decimal("50500"), + volume=Decimal("100"), + ) + + +def make_signal(): + from shared.models import Signal, OrderSide + return Signal( + strategy="test", + symbol="BTCUSDT", + side=OrderSide.BUY, + price=Decimal("50000"), + quantity=Decimal("0.01"), + reason="test signal", + ) + + +def test_candle_event_serialize(): + """Test CandleEvent serializes to dict correctly.""" + from shared.events import CandleEvent, EventType + candle = make_candle() + event = CandleEvent(data=candle) + d = event.to_dict() + assert d["type"] == EventType.CANDLE + assert d["data"]["symbol"] == "BTCUSDT" + assert d["data"]["timeframe"] == "1m" + + +def test_candle_event_deserialize(): + """Test CandleEvent round-trips through to_dict/from_raw.""" + from shared.events import CandleEvent, EventType + candle = make_candle() + event = CandleEvent(data=candle) + d = event.to_dict() + restored = CandleEvent.from_raw(d) + assert restored.type == EventType.CANDLE + assert restored.data.symbol == "BTCUSDT" + assert restored.data.close == Decimal("50500") + + +def test_signal_event_serialize(): + """Test SignalEvent serializes to dict correctly.""" + from shared.events import SignalEvent, EventType + signal = make_signal() + event = SignalEvent(data=signal) + d = event.to_dict() + assert d["type"] == EventType.SIGNAL + assert d["data"]["symbol"] == "BTCUSDT" + assert d["data"]["strategy"] == "test" + + +def test_event_from_dict_dispatch(): + """Test Event.from_dict dispatches to correct class.""" + from shared.events import Event, CandleEvent, SignalEvent, EventType + candle = make_candle() + event = CandleEvent(data=candle) + d = event.to_dict() + restored = Event.from_dict(d) + assert isinstance(restored, CandleEvent) + + signal = make_signal() + s_event = SignalEvent(data=signal) + sd = s_event.to_dict() + restored_s = Event.from_dict(sd) + assert isinstance(restored_s, SignalEvent) diff --git a/shared/tests/test_models.py b/shared/tests/test_models.py new file mode 100644 index 0000000..f1d92ec --- /dev/null +++ b/shared/tests/test_models.py @@ -0,0 +1,100 @@ +"""Tests for shared models and settings.""" +import os +import pytest +from decimal import Decimal +from datetime import datetime, timezone +from unittest.mock import patch + + +def test_settings_defaults(): + """Test that Settings has correct defaults.""" + with patch.dict(os.environ, { + "BINANCE_API_KEY": "test_key", + "BINANCE_API_SECRET": "test_secret", + }): + from shared.config import Settings + settings = Settings() + assert settings.redis_url == "redis://localhost:6379" + assert settings.database_url == "postgresql://trading:trading@localhost:5432/trading" + assert settings.log_level == "INFO" + assert settings.risk_max_position_size == 0.1 + assert settings.risk_stop_loss_pct == 5.0 + assert settings.risk_daily_loss_limit_pct == 10.0 + assert settings.dry_run is True + + +def test_candle_creation(): + """Test Candle model creation.""" + from shared.models import Candle + now = datetime.now(timezone.utc) + candle = Candle( + symbol="BTCUSDT", + timeframe="1m", + open_time=now, + open=Decimal("50000.00"), + high=Decimal("51000.00"), + low=Decimal("49500.00"), + close=Decimal("50500.00"), + volume=Decimal("100.5"), + ) + assert candle.symbol == "BTCUSDT" + assert candle.timeframe == "1m" + assert candle.open == Decimal("50000.00") + assert candle.high == Decimal("51000.00") + assert candle.low == Decimal("49500.00") + assert candle.close == Decimal("50500.00") + assert candle.volume == Decimal("100.5") + + +def test_signal_creation(): + """Test Signal model creation.""" + from shared.models import Signal, OrderSide + signal = Signal( + strategy="rsi_strategy", + symbol="BTCUSDT", + side=OrderSide.BUY, + price=Decimal("50000.00"), + quantity=Decimal("0.01"), + reason="RSI oversold", + ) + assert signal.strategy == "rsi_strategy" + assert signal.symbol == "BTCUSDT" + assert signal.side == OrderSide.BUY + assert signal.price == Decimal("50000.00") + assert signal.quantity == Decimal("0.01") + assert signal.reason == "RSI oversold" + assert signal.id is not None + assert signal.created_at is not None + + +def test_order_creation(): + """Test Order model creation with defaults.""" + from shared.models import Order, OrderSide, OrderType, OrderStatus + import uuid + signal_id = str(uuid.uuid4()) + order = Order( + signal_id=signal_id, + symbol="BTCUSDT", + side=OrderSide.BUY, + type=OrderType.MARKET, + price=Decimal("50000.00"), + quantity=Decimal("0.01"), + ) + assert order.id is not None + assert order.signal_id == signal_id + assert order.status == OrderStatus.PENDING + assert order.filled_at is None + assert order.created_at is not None + + +def test_position_unrealized_pnl(): + """Test Position unrealized_pnl computed property.""" + from shared.models import Position + position = Position( + symbol="BTCUSDT", + quantity=Decimal("0.1"), + avg_entry_price=Decimal("50000"), + current_price=Decimal("51000"), + ) + # 0.1 * (51000 - 50000) = 100 + assert position.unrealized_pnl == Decimal("100") -- cgit v1.2.3