Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/upbeat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
RemainingRequest,
UnprocessableEntityError,
UpbeatError,
ValidationError,
WebSocketClosedError,
WebSocketConnectionError,
WebSocketError,
Expand Down Expand Up @@ -137,6 +138,7 @@
"RemainingRequest",
"UnprocessableEntityError",
"UpbeatError",
"ValidationError",
"WebSocketClosedError",
"WebSocketConnectionError",
"WebSocketError",
Expand Down
28 changes: 26 additions & 2 deletions src/upbeat/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def __init__(
logger: Logger | None = None,
http_client: httpx.Client | None = None,
event_hooks: dict[str, list[Any]] | None = None,
validate_min_order: bool = False,
) -> None:
if (access_key is None) != (secret_key is None):
raise ValueError(
Expand All @@ -59,6 +60,7 @@ def __init__(
self._max_retries = max_retries
self._auto_throttle = auto_throttle
self._logger = logger
self._validate_min_order = validate_min_order
self._owns_http_client = http_client is None
self._closed = False

Expand All @@ -84,7 +86,11 @@ def accounts(self) -> AccountsAPI:

@cached_property
def orders(self) -> OrdersAPI:
return OrdersAPI(self._transport, self._credentials)
return OrdersAPI(
self._transport,
self._credentials,
validate_min_order=self._validate_min_order,
)

@cached_property
def deposits(self) -> DepositsAPI:
Expand Down Expand Up @@ -131,6 +137,7 @@ def with_options(
max_retries: int | None = None,
auto_throttle: bool | None = None,
logger: Logger | None = None,
validate_min_order: bool | None = None,
) -> Upbeat:
new = Upbeat.__new__(Upbeat)
new._credentials = self._credentials
Expand All @@ -141,6 +148,11 @@ def with_options(
auto_throttle if auto_throttle is not None else self._auto_throttle
)
new._logger = logger if logger is not None else self._logger
new._validate_min_order = (
validate_min_order
if validate_min_order is not None
else self._validate_min_order
)
new._owns_http_client = False
new._closed = False

Expand Down Expand Up @@ -176,6 +188,7 @@ def __init__(
logger: Logger | None = None,
http_client: httpx.AsyncClient | None = None,
event_hooks: dict[str, list[Any]] | None = None,
validate_min_order: bool = False,
) -> None:
if (access_key is None) != (secret_key is None):
raise ValueError(
Expand All @@ -193,6 +206,7 @@ def __init__(
self._max_retries = max_retries
self._auto_throttle = auto_throttle
self._logger = logger
self._validate_min_order = validate_min_order
self._owns_http_client = http_client is None
self._closed = False

Expand All @@ -218,7 +232,11 @@ def accounts(self) -> AsyncAccountsAPI:

@cached_property
def orders(self) -> AsyncOrdersAPI:
return AsyncOrdersAPI(self._transport, self._credentials)
return AsyncOrdersAPI(
self._transport,
self._credentials,
validate_min_order=self._validate_min_order,
)

@cached_property
def deposits(self) -> AsyncDepositsAPI:
Expand Down Expand Up @@ -269,6 +287,7 @@ def with_options(
max_retries: int | None = None,
auto_throttle: bool | None = None,
logger: Logger | None = None,
validate_min_order: bool | None = None,
) -> AsyncUpbeat:
new = AsyncUpbeat.__new__(AsyncUpbeat)
new._credentials = self._credentials
Expand All @@ -279,6 +298,11 @@ def with_options(
auto_throttle if auto_throttle is not None else self._auto_throttle
)
new._logger = logger if logger is not None else self._logger
new._validate_min_order = (
validate_min_order
if validate_min_order is not None
else self._validate_min_order
)
new._owns_http_client = False
new._closed = False

Expand Down
24 changes: 24 additions & 0 deletions src/upbeat/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,30 @@ def __init__(self, message: str) -> None:
self.message = message


# ── Validation errors ─────────────────────────────────────────────────


class ValidationError(UpbeatError):
"""Raised when client-side validation catches an invalid order before sending."""

market: str
total: str
min_total: str

def __init__(
self,
message: str,
*,
market: str,
total: str,
min_total: str,
) -> None:
super().__init__(message)
self.market = market
self.total = total
self.min_total = min_total


# ── API errors ───────────────────────────────────────────────────────────


Expand Down
91 changes: 91 additions & 0 deletions src/upbeat/api/orders.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
from __future__ import annotations

from decimal import Decimal
from typing import Any

from upbeat._auth import Credentials
from upbeat._base import _AsyncAPIResource, _SyncAPIResource
from upbeat._errors import ValidationError
from upbeat._http import AsyncTransport, SyncTransport
from upbeat.types.order import (
CancelAndNewOrderResponse,
CancelResult,
Expand All @@ -20,7 +24,54 @@ def _filter_params(**kwargs: Any) -> dict[str, Any]:
return {k: v for k, v in kwargs.items() if v is not None}


def _compute_bid_total(
price: str | None, volume: str | None, ord_type: str
) -> Decimal | None:
"""Return the total KRW value of a bid order, or None if indeterminate."""
if price is None:
return None
if ord_type == "limit":
return Decimal(price) * Decimal(volume) if volume is not None else None
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 volume is not None 가드가 잘 되어있어 Decimal(None) 호출이 방지됩니다. price에 잘못된 문자열이 올 경우 DecimalInvalidOperation이 발생하는데, 이는 호출자 입력 오류이므로 현재 동작(예외 전파)이 합리적입니다.

🤖 Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

감사합니다. 말씀대로 잘못된 문자열 입력 시 InvalidOperation 예외 전파가 호출자 책임이라 별도 처리 없이 두었습니다.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

동의합니다. 👍

🤖 Claude Code

return Decimal(price)


class OrdersAPI(_SyncAPIResource):
_validate_min_order: bool

def __init__(
self,
transport: SyncTransport,
credentials: Credentials | None,
*,
validate_min_order: bool = False,
) -> None:
super().__init__(transport, credentials)
self._validate_min_order = validate_min_order

def _check_min_order(
self,
market: str,
side: str,
price: str | None,
volume: str | None,
ord_type: str,
) -> None:
if not self._validate_min_order or side != "bid":
return
total = _compute_bid_total(price, volume, ord_type)
if total is None:
return
chance = self.get_chance(market=market)
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

매 주문마다 get_chance() API 호출이 발생합니다

validate_min_order=True일 때 create() 호출마다 /v1/orders/chance 요청이 추가로 나갑니다. 동일 마켓에 반복 주문하는 시나리오(예: DCA 전략)에서는 레이트 리밋 소진이 우려됩니다.

제안: 짧은 TTL의 per-market 캐시를 두면 불필요한 호출을 줄일 수 있습니다.

# 예시: 간단한 TTL 캐시
def _get_min_total(self, market: str) -> Decimal | None:
    now = time.monotonic()
    cached = self._min_total_cache.get(market)
    if cached and now - cached[1] < 60:
        return cached[0]
    chance = self.get_chance(market=market)
    ...

당장은 opt-in이라 급하지 않지만, strategies/ 쪽에서 활용할 때 병목이 될 수 있습니다.

🤖 Claude Code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이슈 #43 범위 외로 명시된 사항이라 이번 PR에서는 반영하지 않겠습니다. DCA 등 반복 주문 시나리오에서 병목이 될 수 있다는 점은 동의하므로, per-market TTL 캐시는 별도 이슈로 추적하면 좋겠습니다.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네, 이해합니다. 범위를 명확히 구분하는 게 맞습니다. 캐싱은 별도 이슈로 추적하면 충분할 것 같습니다. 👍

🤖 Claude Code

if chance.market.bid is not None:
min_total = Decimal(chance.market.bid.min_total)
if total < min_total:
raise ValidationError(
f"Order total {total} is below minimum {min_total} for {market}",
market=market,
total=str(total),
min_total=chance.market.bid.min_total,
)

def create(
self,
*,
Expand All @@ -33,6 +84,7 @@ def create(
time_in_force: str | None = None,
smp_type: str | None = None,
) -> OrderCreated:
self._check_min_order(market, side, price, volume, ord_type)
json_body = _filter_params(
market=market,
side=side,
Expand Down Expand Up @@ -60,6 +112,7 @@ def create_test(
time_in_force: str | None = None,
smp_type: str | None = None,
) -> OrderCreated:
self._check_min_order(market, side, price, volume, ord_type)
json_body = _filter_params(
market=market,
side=side,
Expand Down Expand Up @@ -244,6 +297,42 @@ def get_chance(self, *, market: str) -> OrderChance:


class AsyncOrdersAPI(_AsyncAPIResource):
_validate_min_order: bool

def __init__(
self,
transport: AsyncTransport,
credentials: Credentials | None,
*,
validate_min_order: bool = False,
) -> None:
super().__init__(transport, credentials)
self._validate_min_order = validate_min_order

async def _check_min_order(
self,
market: str,
side: str,
price: str | None,
volume: str | None,
ord_type: str,
) -> None:
if not self._validate_min_order or side != "bid":
return
total = _compute_bid_total(price, volume, ord_type)
if total is None:
return
chance = await self.get_chance(market=market)
if chance.market.bid is not None:
min_total = Decimal(chance.market.bid.min_total)
if total < min_total:
raise ValidationError(
f"Order total {total} is below minimum {min_total} for {market}",
market=market,
total=str(total),
min_total=chance.market.bid.min_total,
)

async def create(
self,
*,
Expand All @@ -256,6 +345,7 @@ async def create(
time_in_force: str | None = None,
smp_type: str | None = None,
) -> OrderCreated:
await self._check_min_order(market, side, price, volume, ord_type)
json_body = _filter_params(
market=market,
side=side,
Expand Down Expand Up @@ -283,6 +373,7 @@ async def create_test(
time_in_force: str | None = None,
smp_type: str | None = None,
) -> OrderCreated:
await self._check_min_order(market, side, price, volume, ord_type)
json_body = _filter_params(
market=market,
side=side,
Expand Down
Loading
Loading