76 lines
2.5 KiB
Python
76 lines
2.5 KiB
Python
import uuid
|
|
from decimal import Decimal
|
|
from typing import List, Optional
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
from app.models.entities import MarketModel, OrderModel, MarketStatus
|
|
from app.domains.ledger.service import LedgerService
|
|
|
|
class MarketService:
|
|
"""预测市场领域服务"""
|
|
|
|
def __init__(self, session: AsyncSession):
|
|
self.session = session
|
|
|
|
async def list_markets(self, category: Optional[str] = None, status: Optional[str] = None) -> List[MarketModel]:
|
|
stmt = select(MarketModel)
|
|
if category:
|
|
stmt = stmt.where(MarketModel.category == category)
|
|
if status:
|
|
stmt = stmt.where(MarketModel.status == status)
|
|
stmt = stmt.order_by(MarketModel.created_at.desc())
|
|
result = await self.session.execute(stmt)
|
|
return list(result.scalars().all())
|
|
|
|
async def get_market(self, market_address: str) -> Optional[MarketModel]:
|
|
stmt = select(MarketModel).where(MarketModel.market_address == market_address.lower())
|
|
result = await self.session.execute(stmt)
|
|
return result.scalar_one_or_none()
|
|
|
|
class TradingService:
|
|
"""交易撮合与下单领域服务"""
|
|
|
|
def __init__(self, session: AsyncSession):
|
|
self.session = session
|
|
self.ledger_service = LedgerService(session)
|
|
|
|
async def place_order(
|
|
self,
|
|
user_address: str,
|
|
market_address: str,
|
|
outcome_index: int,
|
|
side: str,
|
|
amount: Decimal,
|
|
price: Optional[Decimal] = None
|
|
) -> OrderModel:
|
|
"""执行下单流程"""
|
|
order_id = str(uuid.uuid4())
|
|
fee = amount * Decimal("0.006") # 0.6% protocol fee
|
|
|
|
# 1. 记账并扣款/冻结 (若提供 vault_address 则关联金库)
|
|
await self.ledger_service.record_trade(
|
|
address=user_address,
|
|
market_address=market_address,
|
|
order_id=order_id,
|
|
side=side,
|
|
amount=amount,
|
|
fee=fee
|
|
)
|
|
|
|
# 2. 生成订单记录
|
|
order = OrderModel(
|
|
order_id=order_id,
|
|
market_address=market_address.lower(),
|
|
user_address=user_address.lower(),
|
|
side=side,
|
|
outcome_index=outcome_index,
|
|
amount=amount,
|
|
price=price,
|
|
status="FILLED",
|
|
filled_amount=amount,
|
|
fee=fee
|
|
)
|
|
self.session.add(order)
|
|
await self.session.flush()
|
|
return order
|