From c2785cfdaeb5cba2798f8681160c60524578c4bd Mon Sep 17 00:00:00 2001 From: Soju06 Date: Thu, 7 Nov 2024 15:39:17 +0900 Subject: [PATCH 1/3] =?UTF-8?q?Impl=20=ED=83=80=EC=9E=85=20Mixin=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=AA=85=EC=B9=AD=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pykis/adapter/account/balance.py | 10 +-- pykis/adapter/account/order.py | 18 ++-- pykis/adapter/account_product/order.py | 22 ++--- pykis/adapter/account_product/order_modify.py | 19 ++-- pykis/adapter/product/quote.py | 14 +-- pykis/adapter/websocket/execution.py | 10 +-- pykis/adapter/websocket/price.py | 38 +++----- pykis/api/account/balance.py | 88 +++++++++---------- pykis/api/account/order.py | 24 ++--- pykis/api/account/pending_order.py | 54 ++++++------ pykis/scope/account.py | 12 +-- pykis/scope/stock.py | 12 +-- 12 files changed, 156 insertions(+), 165 deletions(-) diff --git a/pykis/adapter/account/balance.py b/pykis/adapter/account/balance.py index ec8fb153..a5029219 100644 --- a/pykis/adapter/account/balance.py +++ b/pykis/adapter/account/balance.py @@ -9,7 +9,7 @@ __all__ = [ "KisQuotableAccount", - "KisQuotableAccountImpl", + "KisQuotableAccountMixin", ] @@ -36,7 +36,7 @@ def balance( KisAPIError: API 호출에 실패한 경우 ValueError: 계좌번호가 잘못된 경우 """ - raise NotImplementedError + ... def daily_orders( self: KisAccountProtocol, @@ -59,7 +59,7 @@ def daily_orders( KisAPIError: API 호출에 실패한 경우 ValueError: 계좌번호가 잘못된 경우 """ - raise NotImplementedError + ... def profits( self: KisAccountProtocol, @@ -84,10 +84,10 @@ def profits( KisAPIError: API 호출에 실패한 경우 ValueError: 계좌번호가 잘못된 경우 """ - raise NotImplementedError + ... -class KisQuotableAccountImpl: +class KisQuotableAccountMixin: """한국투자증권 잔고조회가능 프로토콜""" from pykis.api.account.balance import account_balance as balance # 잔고 조회 diff --git a/pykis/adapter/account/order.py b/pykis/adapter/account/order.py index eb50f89e..2b24861d 100644 --- a/pykis/adapter/account/order.py +++ b/pykis/adapter/account/order.py @@ -20,7 +20,7 @@ __all__ = [ "KisOrderableAccount", - "KisOrderableAccountImpl", + "KisOrderableAccountMixin", ] @@ -95,7 +95,7 @@ def buy( KisMarketNotOpenedError: 시장이 열리지 않은 경우 ValueError: 종목 코드가 올바르지 않은 경우 """ - raise NotImplementedError + ... def sell( self: "KisAccountProtocol", @@ -164,7 +164,7 @@ def sell( KisMarketNotOpenedError: 시장이 열리지 않은 경우 ValueError: 종목 코드가 올바르지 않은 경우 """ - raise NotImplementedError + ... def order( self: "KisAccountProtocol", @@ -269,7 +269,7 @@ def order( KisMarketNotOpenedError: 시장이 열리지 않은 경우 ValueError: 종목 코드가 올바르지 않은 경우 """ - raise NotImplementedError + ... def modify( self: "KisAccountProtocol", @@ -294,7 +294,7 @@ def modify( condition (ORDER_CONDITION, optional): 주문조건 execution (ORDER_EXECUTION_CONDITION, optional): 체결조건 """ - raise NotImplementedError + ... def cancel( self: "KisAccountProtocol", @@ -311,7 +311,7 @@ def cancel( account (str | KisAccountNumber): 계좌번호 order (KisOrderNumber): 주문번호 """ - raise NotImplementedError + ... def orderable_amount( self: "KisAccountProtocol", @@ -373,7 +373,7 @@ def orderable_amount( KisNotFoundError: 조회 결과가 없는 경우 ValueError: 주문조건이 잘못된 경우 """ - raise NotImplementedError + ... def pending_orders( self: "KisAccountProtocol", @@ -393,10 +393,10 @@ def pending_orders( KisAPIError: API 호출에 실패한 경우 ValueError: 계좌번호가 잘못된 경우 """ - raise NotImplementedError + ... -class KisOrderableAccountImpl: +class KisOrderableAccountMixin: """한국투자증권 주문가능 잔고 프로토콜""" from pykis.api.account.order import account_buy as buy # 매수 diff --git a/pykis/adapter/account_product/order.py b/pykis/adapter/account_product/order.py index 77dd7026..84c8b0f3 100644 --- a/pykis/adapter/account_product/order.py +++ b/pykis/adapter/account_product/order.py @@ -16,7 +16,7 @@ __all__ = [ "KisOrderableAccountProduct", - "KisOrderableAccountProductImpl", + "KisOrderableAccountProductMixin", ] @@ -123,7 +123,7 @@ def order( KisMarketNotOpenedError: 시장이 열리지 않은 경우 ValueError: 종목 코드가 올바르지 않은 경우 """ - raise NotImplementedError + ... def buy( self: "KisAccountProductProtocol", @@ -188,7 +188,7 @@ def buy( KisMarketNotOpenedError: 시장이 열리지 않은 경우 ValueError: 종목 코드가 올바르지 않은 경우 """ - raise NotImplementedError + ... def sell( self: "KisAccountProductProtocol", @@ -253,7 +253,7 @@ def sell( KisMarketNotOpenedError: 시장이 열리지 않은 경우 ValueError: 종목 코드가 올바르지 않은 경우 """ - raise NotImplementedError + ... def orderable_amount( self: "KisAccountProductProtocol", @@ -311,7 +311,7 @@ def orderable_amount( KisNotFoundError: 조회 결과가 없는 경우 ValueError: 주문조건이 잘못된 경우 """ - raise NotImplementedError + ... def pending_orders(self: "KisAccountProductProtocol") -> KisPendingOrders: """ @@ -324,7 +324,7 @@ def pending_orders(self: "KisAccountProductProtocol") -> KisPendingOrders: KisAPIError: API 호출에 실패한 경우 ValueError: 계좌번호가 잘못된 경우 """ - raise NotImplementedError + ... @property def quantity(self) -> ORDER_QUANTITY: @@ -334,7 +334,7 @@ def quantity(self) -> ORDER_QUANTITY: Returns: ORDER_QUANTITY: 보유수량 """ - raise NotImplementedError + ... @property def qty(self) -> ORDER_QUANTITY: @@ -344,7 +344,7 @@ def qty(self) -> ORDER_QUANTITY: Returns: ORDER_QUANTITY: 보유수량 """ - raise NotImplementedError + ... @property def orderable(self) -> ORDER_QUANTITY: @@ -354,7 +354,7 @@ def orderable(self) -> ORDER_QUANTITY: Returns: ORDER_QUANTITY: 주문 가능 수량 """ - raise NotImplementedError + ... @property def purchase_amount(self) -> ORDER_PRICE: @@ -364,10 +364,10 @@ def purchase_amount(self) -> ORDER_PRICE: Returns: ORDER_PRICE: 주문 가능 금액 """ - raise NotImplementedError + ... -class KisOrderableAccountProductImpl: +class KisOrderableAccountProductMixin: """한국투자증권 주문가능 상품""" from pykis.api.account.order import account_product_buy as buy # 매수 diff --git a/pykis/adapter/account_product/order_modify.py b/pykis/adapter/account_product/order_modify.py index 1cc82eee..b20a561f 100644 --- a/pykis/adapter/account_product/order_modify.py +++ b/pykis/adapter/account_product/order_modify.py @@ -12,6 +12,15 @@ KisOrderNumber, ) +__all__ = [ + "KisCancelableOrder", + "KisModifyableOrder", + "KisOrderableOrder", + "KisCancelableOrderMixin", + "KisModifyableOrderMixin", + "KisOrderableOrderMixin", +] + @runtime_checkable class KisCancelableOrder(Protocol): @@ -24,7 +33,7 @@ def cancel(self) -> "KisOrder": 국내주식주문 -> 주식주문(정정취소)[v1_국내주식-003] 국내주식주문 -> 해외주식 정정취소주문[v1_해외주식-003] """ - raise NotImplementedError + ... class KisModifyableOrder(Protocol): @@ -49,7 +58,7 @@ def modify( condition (ORDER_CONDITION, optional): 주문조건 execution (ORDER_EXECUTION_CONDITION, optional): 체결조건 """ - raise NotImplementedError + ... @runtime_checkable @@ -57,7 +66,7 @@ class KisOrderableOrder(KisCancelableOrder, KisModifyableOrder, Protocol): """주문 가능 주문 프로토콜""" -class KisCancelableOrderImpl: +class KisCancelableOrderMixin: """취소 가능 주문""" def cancel( @@ -74,7 +83,7 @@ def cancel( return cancel_order(self.kis, order=self) -class KisModifyableOrderImpl: +class KisModifyableOrderMixin: """정정 가능 주문""" def modify( @@ -108,5 +117,5 @@ def modify( ) -class KisOrderableOrderImpl(KisCancelableOrderImpl, KisModifyableOrderImpl): +class KisOrderableOrderMixin(KisCancelableOrderMixin, KisModifyableOrderMixin): """주문 가능 주문""" diff --git a/pykis/adapter/product/quote.py b/pykis/adapter/product/quote.py index 07e3d9b1..4c928d39 100644 --- a/pykis/adapter/product/quote.py +++ b/pykis/adapter/product/quote.py @@ -10,7 +10,7 @@ __all__ = [ "KisQuotableProduct", - "KisQuotableProductImpl", + "KisQuotableProductMixin", ] @@ -42,7 +42,7 @@ def daily_chart( KisNotFoundError: 조회 결과가 없는 경우 ValueError: 조회 파라미터가 올바르지 않은 경우 """ - raise NotImplementedError + ... def day_chart( self, @@ -69,7 +69,7 @@ def day_chart( KisNotFoundError: 조회 결과가 없는 경우 ValueError: 조회 파라미터가 올바르지 않은 경우 """ - raise NotImplementedError + ... def orderbook( self, @@ -89,7 +89,7 @@ def orderbook( KisNotFoundError: 조회 결과가 없는 경우 ValueError: 종목 코드가 올바르지 않은 경우 """ - raise NotImplementedError + ... def quote( self, @@ -109,7 +109,7 @@ def quote( KisNotFoundError: 조회 결과가 없는 경우 ValueError: 종목 코드가 올바르지 않은 경우 """ - raise NotImplementedError + ... def chart( self: KisProductProtocol, @@ -152,10 +152,10 @@ def chart( KisNotFoundError: 조회 결과가 없는 경우 ValueError: 조회 파라미터가 올바르지 않은 경우 """ - raise NotImplementedError + ... -class KisQuotableProductImpl: +class KisQuotableProductMixin: """한국투자증권 시세조회가능 상품 프로토콜""" from pykis.api.stock.daily_chart import product_daily_chart as daily_chart # 일봉 조회 diff --git a/pykis/adapter/websocket/execution.py b/pykis/adapter/websocket/execution.py index d3226d15..d8301d6e 100644 --- a/pykis/adapter/websocket/execution.py +++ b/pykis/adapter/websocket/execution.py @@ -11,7 +11,7 @@ __all__ = [ "KisRealtimeOrderableAccount", - "KisRealtimeOrderableAccountImpl", + "KisRealtimeOrderableAccountMixin", ] @@ -37,7 +37,7 @@ def on( where (KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeExecution]] | None, optional): 이벤트 필터. Defaults to None. once (bool, optional): 한번만 실행 여부. Defaults to False. """ - raise NotImplementedError + ... def once( self, @@ -55,10 +55,10 @@ def once( callback (Callable[[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeExecution]], None]): 콜백 함수 where (KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeExecution]] | None, optional): 이벤트 필터. Defaults to None. """ - raise NotImplementedError + ... -class KisRealtimeOrderableAccountImpl: +class KisRealtimeOrderableAccountMixin: """한국투자증권 실시간 주문가능 상품""" def on( @@ -120,7 +120,7 @@ def once( raise ValueError(f"Unknown event: {event}") -class KisRealtimeOrderableOrderImpl: +class KisRealtimeOrderableOrderMixin: """한국투자증권 실시간 주문 가능 주문""" def on( diff --git a/pykis/adapter/websocket/price.py b/pykis/adapter/websocket/price.py index 5e121423..1988489c 100644 --- a/pykis/adapter/websocket/price.py +++ b/pykis/adapter/websocket/price.py @@ -9,7 +9,7 @@ __all__ = [ "KisWebsocketQuotableProduct", - "KisWebsocketQuotableProductImpl", + "KisWebsocketQuotableProductMixin", ] @@ -39,16 +39,14 @@ def on( once (bool, optional): 한번만 실행할지 여부. Defaults to False. extended (bool, optional): 주간거래 시세 조회 여부 (나스닥, 뉴욕, 아멕스) """ - raise NotImplementedError + ... @overload def on( self, event: Literal["orderbook"], callback: Callable[[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]], None], - where: ( - KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] | None - ) = None, + where: KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] | None = None, once: bool = False, extended: bool = False, ) -> KisEventTicket[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]]: @@ -66,7 +64,7 @@ def on( once (bool, optional): 한번만 실행할지 여부. Defaults to False. extended (bool, optional): 주간거래 시세 조회 여부 (나스닥, 뉴욕, 아멕스) """ - raise NotImplementedError + ... def on( self, @@ -85,8 +83,7 @@ def on( ) -> ( KisEventTicket[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimePrice]] | KisEventTicket[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] - ): - raise NotImplementedError + ): ... @overload def once( @@ -108,16 +105,14 @@ def once( where (KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimePrice]] | None, optional): 이벤트 필터. Defaults to None. extended (bool, optional): 주간거래 시세 조회 여부 (나스닥, 뉴욕, 아멕스) """ - raise NotImplementedError + ... @overload def once( self, event: Literal["orderbook"], callback: Callable[[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]], None], - where: ( - KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] | None - ) = None, + where: KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] | None = None, extended: bool = False, ) -> KisEventTicket[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]]: """ @@ -133,7 +128,7 @@ def once( where (KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimePrice]] | None, optional): 이벤트 필터. Defaults to None. extended (bool, optional): 주간거래 시세 조회 여부 (나스닥, 뉴욕, 아멕스) """ - raise NotImplementedError + ... def once( self, @@ -151,11 +146,10 @@ def once( ) -> ( KisEventTicket[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimePrice]] | KisEventTicket[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] - ): - raise NotImplementedError + ): ... -class KisWebsocketQuotableProductImpl: +class KisWebsocketQuotableProductMixin: """한국투자증권 웹소켓 시세조회가능 상품""" @overload @@ -186,9 +180,7 @@ def on( self: "KisProductProtocol", event: Literal["orderbook"], callback: Callable[[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]], None], - where: ( - KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] | None - ) = None, + where: KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] | None = None, once: bool = False, extended: bool = False, ) -> KisEventTicket[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]]: @@ -270,16 +262,14 @@ def once( where (KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimePrice]] | None, optional): 이벤트 필터. Defaults to None. extended (bool, optional): 주간거래 시세 조회 여부 (나스닥, 뉴욕, 아멕스) """ - raise NotImplementedError + ... @overload def once( self: "KisProductProtocol", event: Literal["orderbook"], callback: Callable[[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]], None], - where: ( - KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] | None - ) = None, + where: KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]] | None = None, extended: bool = False, ) -> KisEventTicket[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimeOrderbook]]: """ @@ -295,7 +285,7 @@ def once( where (KisEventFilter[KisWebsocketClient, KisSubscriptionEventArgs[KisRealtimePrice]] | None, optional): 이벤트 필터. Defaults to None. extended (bool, optional): 주간거래 시세 조회 여부 (나스닥, 뉴욕, 아멕스) """ - raise NotImplementedError + ... def once( self: "KisProductProtocol", diff --git a/pykis/api/account/balance.py b/pykis/api/account/balance.py index b42b0819..97706c32 100644 --- a/pykis/api/account/balance.py +++ b/pykis/api/account/balance.py @@ -3,11 +3,11 @@ from pykis.adapter.account_product.order import ( KisOrderableAccountProduct, - KisOrderableAccountProductImpl, + KisOrderableAccountProductMixin, ) from pykis.adapter.websocket.price import ( KisWebsocketQuotableProduct, - KisWebsocketQuotableProductImpl, + KisWebsocketQuotableProductMixin, ) from pykis.api.account.order import ORDER_QUANTITY from pykis.api.base.account import KisAccountBase, KisAccountProtocol @@ -26,7 +26,7 @@ from pykis.client.page import KisPage from pykis.responses.dynamic import KisDynamic, KisList, KisObject, KisTransform from pykis.responses.response import KisAPIResponse, KisPaginationAPIResponse -from pykis.responses.types import KisAny, KisDecimal, KisInt, KisString +from pykis.responses.types import KisAny, KisDecimal, KisString from pykis.utils.cache import cached from pykis.utils.repr import kis_repr from pykis.utils.typing import Checkable @@ -54,67 +54,67 @@ class KisBalanceStock( @property def purchase_price(self) -> Decimal: """매입평균가""" - raise NotImplementedError + ... @property def current_price(self) -> Decimal: """현재가""" - raise NotImplementedError + ... @property def price(self) -> Decimal: """현재가""" - raise NotImplementedError + ... @property def quantity(self) -> ORDER_QUANTITY: """수량""" - raise NotImplementedError + ... @property def orderable(self) -> ORDER_QUANTITY: """매도가능수량""" - raise NotImplementedError + ... @property def qty(self) -> ORDER_QUANTITY: """수량""" - raise NotImplementedError + ... @property def purchase_amount(self) -> Decimal: """매입금액""" - raise NotImplementedError + ... @property def current_amount(self) -> Decimal: """평가금액""" - raise NotImplementedError + ... @property def amount(self) -> Decimal: """평가금액""" - raise NotImplementedError + ... @property def profit(self) -> Decimal: """손익금액""" - raise NotImplementedError + ... @property def profit_rate(self) -> Decimal: """손익률 (-100 ~ 100)""" - raise NotImplementedError + ... @property def rate(self) -> Decimal: """수익률 (-100 ~ 100)""" - raise NotImplementedError + ... @property def exchange_rate(self) -> Decimal: """환율""" - raise NotImplementedError + ... @runtime_checkable @@ -124,22 +124,22 @@ class KisDeposit(KisAccountProtocol, Protocol): @property def amount(self) -> Decimal: """예수금""" - raise NotImplementedError + ... @property def withdrawable_amount(self) -> Decimal: """출금가능금액""" - raise NotImplementedError + ... @property def withdrawable(self) -> Decimal: """출금가능금액""" - raise NotImplementedError + ... @property def exchange_rate(self) -> Decimal: """환율""" - raise NotImplementedError + ... @runtime_checkable @@ -149,63 +149,61 @@ class KisBalance(KisAccountProtocol, Protocol): @property def country(self) -> COUNTRY_TYPE | None: """국가코드 (스코프 지정시)""" - raise NotImplementedError + ... @property def stocks(self) -> list[KisBalanceStock]: """보유종목""" - raise NotImplementedError + ... @property def deposits(self) -> dict[CURRENCY_TYPE, KisDeposit]: """통화별 예수금""" - raise NotImplementedError + ... @property def amount(self) -> Decimal: """총자산금액 (원화, 보유종목 + 예수금)""" - raise NotImplementedError + ... @property def total(self) -> Decimal: """총평가금액 (원화, 보유종목 + 예수금)""" - raise NotImplementedError + ... @property def purchase_amount(self) -> Decimal: """총매입금액 (원화)""" - raise NotImplementedError + ... @property def current_amount(self) -> Decimal: """총평가금액 (원화)""" - raise NotImplementedError + ... @property def profit(self) -> Decimal: """총손익금액 (원화)""" - raise NotImplementedError + ... @property def profit_rate(self) -> Decimal: """총손익률 (-100 ~ 100)""" - raise NotImplementedError + ... @property def withdrawable_amount(self) -> Decimal: """총출금가능금액 (원화)""" - raise NotImplementedError + ... @property def withdrawable(self) -> Decimal: """총출금가능금액 (원화)""" - raise NotImplementedError + ... - def __iter__(self) -> Iterator[KisBalanceStock]: - raise NotImplementedError + def __iter__(self) -> Iterator[KisBalanceStock]: ... - def __len__(self) -> int: - raise NotImplementedError + def __len__(self) -> int: ... def __getitem__(self, key: int | str) -> KisBalanceStock: """ @@ -214,15 +212,15 @@ def __getitem__(self, key: int | str) -> KisBalanceStock: Args: key (int | str): 인덱스 또는 종목코드 """ - raise NotImplementedError + ... def stock(self, symbol: str) -> KisBalanceStock | None: """보유종목을 종목코드로 조회합니다.""" - raise NotImplementedError + ... def deposit(self, currency: CURRENCY_TYPE) -> KisDeposit | None: """통화별 예수금을 조회합니다.""" - raise NotImplementedError + ... @kis_repr( @@ -236,9 +234,7 @@ def deposit(self, currency: CURRENCY_TYPE) -> KisDeposit | None: "profit_rate", lines="single", ) -class KisBalanceStockBase( - KisAccountProductBase, KisOrderableAccountProductImpl, KisWebsocketQuotableProductImpl -): +class KisBalanceStockBase(KisAccountProductBase, KisOrderableAccountProductMixin, KisWebsocketQuotableProductMixin): """한국투자증권 보유종목""" kis: "PyKis" @@ -735,9 +731,7 @@ class KisForeignBalanceStock(KisDynamic, KisBalanceStockBase): """종목코드""" market: MARKET_TYPE = KisMarketType["ovrs_excg_cd"] """상품유형타입""" - account_number: KisAccountNumber = KisTransform( - lambda x: KisAccountNumber(f"{x['cano']}-{x['acnt_prdt_cd']}") - )() + account_number: KisAccountNumber = KisTransform(lambda x: KisAccountNumber(f"{x['cano']}-{x['acnt_prdt_cd']}"))() """계좌번호""" name: str = KisString["ovrs_item_name"] @@ -988,9 +982,7 @@ def _foreign_balance( KisAPIError: API 호출에 실패한 경우 ValueError: 계좌번호가 잘못된 경우 """ - markets = FOREIGN_COUNTRY_MARKET_MAP.get( - (not self.virtual, country), FOREIGN_COUNTRY_MARKET_MAP[(None, country)] - ) + markets = FOREIGN_COUNTRY_MARKET_MAP.get((not self.virtual, country), FOREIGN_COUNTRY_MARKET_MAP[(None, country)]) first = None @@ -1061,7 +1053,7 @@ def foreign_balance( # Issue #41 - [버그]: KisIntegrationBalance에서 해외주식 잔고수량이 0으로 표시됨 # https://apiportal.koreainvestment.com/apiservice/apiservice-oversea-stock-order#L_09baff2a-6e9d-4502-ba66-d7bb94094b67 # 위 Docs와 같이 "잔고 확인을 원하실 경우에는 해외주식 잔고[v1_해외주식-006] API 사용을 부탁드립니다.)" 라고 되어있음 - + result.stocks = _foreign_balance( self, account=account, diff --git a/pykis/api/account/order.py b/pykis/api/account/order.py index d27237f9..1f020902 100644 --- a/pykis/api/account/order.py +++ b/pykis/api/account/order.py @@ -15,11 +15,11 @@ from pykis.adapter.account_product.order_modify import ( KisOrderableOrder, - KisOrderableOrderImpl, + KisOrderableOrderMixin, ) from pykis.adapter.websocket.execution import ( KisRealtimeOrderableAccount, - KisRealtimeOrderableOrderImpl, + KisRealtimeOrderableOrderMixin, ) from pykis.api.base.account import KisAccountProtocol from pykis.api.base.account_product import ( @@ -345,18 +345,18 @@ class KisOrderNumber(KisAccountProductProtocol, KisEventFilter["KisWebsocketClie @property def branch(self) -> str: """지점코드""" - raise NotImplementedError + ... @property def number(self) -> str: """주문번호""" - raise NotImplementedError + ... def __eq__(self, value: "object | KisOrderNumber") -> bool: - raise NotImplementedError + ... def __hash__(self) -> int: - raise NotImplementedError + ... @runtime_checkable @@ -366,27 +366,27 @@ class KisOrder(KisOrderNumber, KisOrderableOrder, KisRealtimeOrderableAccount, P @property def time(self) -> datetime: """주문시간 (현지시간)""" - raise NotImplementedError + ... @property def time_kst(self) -> datetime: """주문시간 (한국시간)""" - raise NotImplementedError + ... @property def timezone(self) -> tzinfo: """시간대""" - raise NotImplementedError + ... @property def pending(self) -> bool: """미체결 여부""" - raise NotImplementedError + ... @property def pending_order(self) -> "KisPendingOrder | None": """미체결 주문""" - raise NotImplementedError + ... @staticmethod def from_number( @@ -545,7 +545,7 @@ def __repr__(self) -> str: )""" -class KisOrderBase(KisOrderNumberBase, KisOrderableOrderImpl, KisRealtimeOrderableOrderImpl): +class KisOrderBase(KisOrderNumberBase, KisOrderableOrderMixin, KisRealtimeOrderableOrderMixin): """한국투자증권 주문""" symbol: str diff --git a/pykis/api/account/pending_order.py b/pykis/api/account/pending_order.py index f50fa2f2..3e8fca37 100644 --- a/pykis/api/account/pending_order.py +++ b/pykis/api/account/pending_order.py @@ -7,9 +7,9 @@ from pykis.adapter.account_product.order_modify import ( KisOrderableOrder, - KisOrderableOrderImpl, + KisOrderableOrderMixin, ) -from pykis.adapter.websocket.execution import KisRealtimeOrderableOrderImpl +from pykis.adapter.websocket.execution import KisRealtimeOrderableOrderMixin from pykis.api.account.order import ( ORDER_CONDITION, ORDER_EXECUTION, @@ -61,92 +61,92 @@ class KisPendingOrder(KisOrder, Protocol): @property def order_number(self) -> KisOrder: """주문번호""" - raise NotImplementedError + ... @property def type(self) -> ORDER_TYPE: """주문유형""" - raise NotImplementedError + ... @property def price(self) -> Decimal: """체결단가""" - raise NotImplementedError + ... @property def unit_price(self) -> Decimal | None: """주문단가""" - raise NotImplementedError + ... @property def order_price(self) -> Decimal | None: """주문단가""" - raise NotImplementedError + ... @property def quantity(self) -> ORDER_QUANTITY: """주문수량""" - raise NotImplementedError + ... @property def qty(self) -> ORDER_QUANTITY: """주문수량""" - raise NotImplementedError + ... @property def executed_quantity(self) -> ORDER_QUANTITY: """체결수량""" - raise NotImplementedError + ... @property def orderable_quantity(self) -> ORDER_QUANTITY: """주문가능수량""" - raise NotImplementedError + ... @property def executed_qty(self) -> ORDER_QUANTITY: """체결수량""" - raise NotImplementedError + ... @property def executed_amount(self) -> Decimal: """체결금액""" - raise NotImplementedError + ... @property def orderable_qty(self) -> ORDER_QUANTITY: """주문가능수량""" - raise NotImplementedError + ... @property def pending_quantity(self) -> ORDER_QUANTITY: """미체결수량""" - raise NotImplementedError + ... @property def pending_qty(self) -> ORDER_QUANTITY: """미체결수량""" - raise NotImplementedError + ... @property def condition(self) -> ORDER_CONDITION | None: """주문조건""" - raise NotImplementedError + ... @property def execution(self) -> ORDER_EXECUTION | None: """체결조건""" - raise NotImplementedError + ... @property def rejected(self) -> bool: """거부여부""" - raise NotImplementedError + ... @property def rejected_reason(self) -> str | None: """거부사유""" - raise NotImplementedError + ... @runtime_checkable @@ -156,26 +156,26 @@ class KisPendingOrders(KisAccountProtocol, Protocol): @property def account_number(self) -> KisAccountNumber: """계좌번호""" - raise NotImplementedError + ... @property def orders(self) -> list[KisPendingOrder]: """미체결주문""" - raise NotImplementedError + ... def __getitem__(self, key: int | KisOrderNumber | str) -> KisPendingOrder: """인덱스 또는 주문번호로 주문을 조회합니다.""" - raise NotImplementedError + ... def order(self, key: KisOrderNumber | str) -> KisPendingOrder | None: """주문번호 또는 종목코드로 주문을 조회합니다.""" - raise NotImplementedError + ... def __len__(self) -> int: - raise NotImplementedError + ... def __iter__(self) -> Iterable[KisPendingOrder]: - raise NotImplementedError + ... @kis_repr( @@ -189,7 +189,7 @@ def __iter__(self) -> Iterable[KisPendingOrder]: lines="multiple", ) class KisPendingOrderBase( - KisAccountProductBase, KisOrderNumberEventFilter, KisRealtimeOrderableOrderImpl, KisOrderableOrderImpl + KisAccountProductBase, KisOrderNumberEventFilter, KisRealtimeOrderableOrderMixin, KisOrderableOrderMixin ): """한국투자증권 미체결 주식""" diff --git a/pykis/scope/account.py b/pykis/scope/account.py index b4644141..7b643d71 100644 --- a/pykis/scope/account.py +++ b/pykis/scope/account.py @@ -1,10 +1,10 @@ from typing import TYPE_CHECKING, Protocol, runtime_checkable -from pykis.adapter.account.balance import KisQuotableAccount, KisQuotableAccountImpl -from pykis.adapter.account.order import KisOrderableAccount, KisOrderableAccountImpl +from pykis.adapter.account.balance import KisQuotableAccount, KisQuotableAccountMixin +from pykis.adapter.account.order import KisOrderableAccount, KisOrderableAccountMixin from pykis.adapter.websocket.execution import ( KisRealtimeOrderableAccount, - KisRealtimeOrderableAccountImpl, + KisRealtimeOrderableAccountMixin, ) from pykis.api.base.account import KisAccountBase, KisAccountProtocol from pykis.client.account import KisAccountNumber @@ -38,9 +38,9 @@ class KisAccountScope( KisScopeBase, KisAccountBase, # Adapters - KisRealtimeOrderableAccountImpl, - KisOrderableAccountImpl, - KisQuotableAccountImpl, + KisRealtimeOrderableAccountMixin, + KisOrderableAccountMixin, + KisQuotableAccountMixin, ): """한국투자증권 계좌 Scope""" diff --git a/pykis/scope/stock.py b/pykis/scope/stock.py index 5e723a90..5716d473 100644 --- a/pykis/scope/stock.py +++ b/pykis/scope/stock.py @@ -2,12 +2,12 @@ from pykis.adapter.account_product.order import ( KisOrderableAccountProduct, - KisOrderableAccountProductImpl, + KisOrderableAccountProductMixin, ) -from pykis.adapter.product.quote import KisQuotableProduct, KisQuotableProductImpl +from pykis.adapter.product.quote import KisQuotableProduct, KisQuotableProductMixin from pykis.adapter.websocket.price import ( KisWebsocketQuotableProduct, - KisWebsocketQuotableProductImpl, + KisWebsocketQuotableProductMixin, ) from pykis.api.base.account_product import ( KisAccountProductBase, @@ -52,9 +52,9 @@ class KisStockScope( KisScopeBase, KisAccountProductBase, # Adapters - KisOrderableAccountProductImpl, - KisWebsocketQuotableProductImpl, - KisQuotableProductImpl, + KisOrderableAccountProductMixin, + KisWebsocketQuotableProductMixin, + KisQuotableProductMixin, # Filters KisProductEventFilter, ): From f559041a9bcfabdf079acb51624389df06eb057a Mon Sep 17 00:00:00 2001 From: Soju06 Date: Thu, 7 Nov 2024 15:41:25 +0900 Subject: [PATCH 2/3] =?UTF-8?q?=ED=94=84=EB=A1=9C=ED=86=A0=EC=BD=9C=20?= =?UTF-8?q?=EA=B0=9D=EC=B2=B4=20Ellipsis=20=EC=82=AC=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pykis/api/account/daily_order.py | 56 ++++++++-------- pykis/api/account/order_profit.py | 62 ++++++++--------- pykis/api/account/orderable_amount.py | 24 +++---- pykis/api/base/account.py | 4 +- pykis/api/base/market.py | 10 +-- pykis/api/base/product.py | 8 +-- pykis/api/stock/chart.py | 65 ++++++++---------- pykis/api/stock/info.py | 22 +++--- pykis/api/stock/order_book.py | 27 +++----- pykis/api/stock/quote.py | 60 ++++++++--------- pykis/api/stock/trading_hours.py | 14 ++-- pykis/api/websocket/order_execution.py | 38 +++++------ pykis/api/websocket/price.py | 92 +++++++++++++------------- pykis/client/form.py | 2 +- pykis/client/object.py | 2 +- pykis/event/filters/order.py | 12 ++-- pykis/event/filters/product.py | 4 +- pykis/responses/dynamic.py | 12 ++-- pykis/responses/response.py | 14 ++-- pykis/responses/websocket.py | 4 +- pykis/utils/repr.py | 3 +- 21 files changed, 251 insertions(+), 284 deletions(-) diff --git a/pykis/api/account/daily_order.py b/pykis/api/account/daily_order.py index dc14aed9..9d308742 100644 --- a/pykis/api/account/daily_order.py +++ b/pykis/api/account/daily_order.py @@ -50,107 +50,107 @@ class KisDailyOrder(KisAccountProductProtocol, Protocol): @property def time(self) -> datetime: """시간 (현지시간)""" - raise NotImplementedError + ... @property def time_kst(self) -> datetime: """시간 (한국시간)""" - raise NotImplementedError + ... @property def timezone(self) -> ZoneInfo: """시간대""" - raise NotImplementedError + ... @property def account_number(self) -> KisAccountNumber: """계좌번호""" - raise NotImplementedError + ... @property def order_number(self) -> KisOrder: """주문번호""" - raise NotImplementedError + ... @property def type(self) -> ORDER_TYPE: """주문유형""" - raise NotImplementedError + ... @property def price(self) -> Decimal | None: """체결단가""" - raise NotImplementedError + ... @property def unit_price(self) -> Decimal | None: """주문단가""" - raise NotImplementedError + ... @property def order_price(self) -> Decimal | None: """주문단가""" - raise NotImplementedError + ... @property def quantity(self) -> ORDER_QUANTITY: """주문수량""" - raise NotImplementedError + ... @property def qty(self) -> ORDER_QUANTITY: """주문수량""" - raise NotImplementedError + ... @property def executed_quantity(self) -> ORDER_QUANTITY: """체결수량""" - raise NotImplementedError + ... @property def pending_quantity(self) -> ORDER_QUANTITY: """미체결수량""" - raise NotImplementedError + ... @property def executed_qty(self) -> ORDER_QUANTITY: """체결수량""" - raise NotImplementedError + ... @property def executed_amount(self) -> Decimal: """체결금액""" - raise NotImplementedError + ... @property def pending_qty(self) -> ORDER_QUANTITY: """미체결수량""" - raise NotImplementedError + ... @property def condition(self) -> ORDER_CONDITION | None: """주문조건""" - raise NotImplementedError + ... @property def execution(self) -> ORDER_EXECUTION | None: """체결조건""" - raise NotImplementedError + ... @property def rejected(self) -> bool: """거부여부""" - raise NotImplementedError + ... @property def rejected_reason(self) -> str | None: """거부사유""" - raise NotImplementedError + ... @property def canceled(self) -> bool: """취소여부""" - raise NotImplementedError + ... @runtime_checkable @@ -160,26 +160,24 @@ class KisDailyOrders(KisAccountProtocol, Protocol): @property def account_number(self) -> KisAccountNumber: """계좌번호""" - raise NotImplementedError + ... @property def orders(self) -> list[KisDailyOrder]: """일별 체결내역""" - raise NotImplementedError + ... def __getitem__(self, key: int | KisOrder | str) -> KisDailyOrder: """인덱스 또는 주문번호로 주문을 조회합니다.""" - raise NotImplementedError + ... def order(self, key: KisOrder | str) -> KisDailyOrder | None: """주문번호 또는 종목코드로 주문을 조회합니다.""" - raise NotImplementedError + ... - def __len__(self) -> int: - raise NotImplementedError + def __len__(self) -> int: ... - def __iter__(self) -> Iterable[KisDailyOrder]: - raise NotImplementedError + def __iter__(self) -> Iterable[KisDailyOrder]: ... @kis_repr( diff --git a/pykis/api/account/order_profit.py b/pykis/api/account/order_profit.py index 368ab0ae..aa338b8d 100644 --- a/pykis/api/account/order_profit.py +++ b/pykis/api/account/order_profit.py @@ -43,82 +43,82 @@ class KisOrderProfit(KisAccountProductProtocol, Protocol): @property def time(self) -> datetime: """시간 (현지시간)""" - raise NotImplementedError + ... @property def time_kst(self) -> datetime: """시간 (한국시간)""" - raise NotImplementedError + ... @property def timezone(self) -> ZoneInfo: """시간대""" - raise NotImplementedError + ... @property def symbol(self) -> str: """종목코드""" - raise NotImplementedError + ... @property def market(self) -> MARKET_TYPE: """상품유형타입""" - raise NotImplementedError + ... @property def account_number(self) -> KisAccountNumber: """계좌번호""" - raise NotImplementedError + ... @property def name(self) -> str: """종목명""" - raise NotImplementedError + ... @property def buy_price(self) -> Decimal: """매수단가""" - raise NotImplementedError + ... @property def sell_price(self) -> Decimal: """매도단가""" - raise NotImplementedError + ... @property def buy_amount(self) -> Decimal: """매수금액""" - raise NotImplementedError + ... @property def sell_amount(self) -> Decimal: """매도금액""" - raise NotImplementedError + ... @property def quantity(self) -> ORDER_QUANTITY: """매도수량""" - raise NotImplementedError + ... @property def qty(self) -> ORDER_QUANTITY: """매도수량""" - raise NotImplementedError + ... @property def profit(self) -> Decimal: """손익금액""" - raise NotImplementedError + ... @property def profit_rate(self) -> Decimal: """손익률 (-100 ~ 100)""" - raise NotImplementedError + ... @property def exchange_rate(self) -> Decimal: """당일환율""" - raise NotImplementedError + ... @runtime_checkable @@ -128,46 +128,44 @@ class KisOrderProfits(KisAccountProtocol, Protocol): @property def account_number(self) -> KisAccountNumber: """계좌번호""" - raise NotImplementedError + ... @property def orders(self) -> list[KisOrderProfit]: """일별 체결내역""" - raise NotImplementedError + ... @property def fees(self) -> Decimal: """수수료""" - raise NotImplementedError + ... @property def buy_amount(self) -> Decimal: """매수금액""" - raise NotImplementedError + ... @property def sell_amount(self) -> Decimal: """매도금액""" - raise NotImplementedError + ... @property def profit(self) -> Decimal: """손익금액""" - raise NotImplementedError + ... def __getitem__(self, key: int | str) -> KisOrderProfit: """인덱스 또는 주문번호로 주문을 조회합니다.""" - raise NotImplementedError + ... def order(self, key: str) -> KisOrderProfit | None: """주문번호 또는 종목코드로 주문을 조회합니다.""" - raise NotImplementedError + ... - def __len__(self) -> int: - raise NotImplementedError + def __len__(self) -> int: ... - def __iter__(self) -> Iterable[KisOrderProfit]: - raise NotImplementedError + def __iter__(self) -> Iterable[KisOrderProfit]: ... @kis_repr( @@ -310,9 +308,7 @@ class KisDomesticOrderProfit(KisDynamic, KisOrderProfitBase): time: datetime """시간 (현지시간)""" - time_kst: datetime = KisTransform( - lambda x: datetime.strptime(x["trad_dt"], "%Y%m%d").replace(tzinfo=TIMEZONE) - )() + time_kst: datetime = KisTransform(lambda x: datetime.strptime(x["trad_dt"], "%Y%m%d").replace(tzinfo=TIMEZONE))() """시간 (한국시간)""" timezone: ZoneInfo = TIMEZONE """시간대""" @@ -391,9 +387,7 @@ class KisForeignOrderProfit(KisDynamic, KisOrderProfitBase): time: datetime """시간 (현지시간)""" - time_kst: datetime = KisTransform( - lambda x: datetime.strptime(x["trad_day"], "%Y%m%d").replace(tzinfo=TIMEZONE) - )() + time_kst: datetime = KisTransform(lambda x: datetime.strptime(x["trad_day"], "%Y%m%d").replace(tzinfo=TIMEZONE))() """시간 (한국시간)""" timezone: ZoneInfo = KisAny(get_market_code_timezone)["ovrs_excg_cd"] """시간대""" diff --git a/pykis/api/account/orderable_amount.py b/pykis/api/account/orderable_amount.py index 5d07cdf7..f2b1440c 100644 --- a/pykis/api/account/orderable_amount.py +++ b/pykis/api/account/orderable_amount.py @@ -44,37 +44,37 @@ class KisOrderableAmount(KisAccountProductProtocol, Protocol): @property def price(self) -> Decimal | None: """주문단가""" - raise NotImplementedError + ... @property def condition(self) -> ORDER_CONDITION | None: """주문조건""" - raise NotImplementedError + ... @property def execution(self) -> ORDER_EXECUTION | None: """체결조건""" - raise NotImplementedError + ... @property def unit_price(self) -> Decimal: """계산단가""" - raise NotImplementedError + ... @property def amount(self) -> Decimal: """주문가능금액 (통화)""" - raise NotImplementedError + ... @property def quantity(self) -> ORDER_QUANTITY: """주문가능수량 (통화)""" - raise NotImplementedError + ... @property def qty(self) -> ORDER_QUANTITY: """주문가능수량""" - raise NotImplementedError + ... @property def foreign_amount(self) -> Decimal: @@ -84,7 +84,7 @@ def foreign_amount(self) -> Decimal: 국내주식의 경우, 원화주문가능금액 + 외화주문가능금액을 합산한 금액 해외주식의 경우, 주문가능금액 (통화) + 주문가능금액 (원화 등)을 합산한 금액 """ - raise NotImplementedError + ... @property def foreign_quantity(self) -> ORDER_QUANTITY: @@ -94,22 +94,22 @@ def foreign_quantity(self) -> ORDER_QUANTITY: 국내주식의 경우, 원화주문가능수량 + 외화주문가능수량을 합산한 금액으로 계산한 수량 해외주식의 경우, 주문가능수량 (통화) + 주문가능수량 (원화 등)을 합산한 금액으로 계산한 수량 """ - raise NotImplementedError + ... @property def foreign_qty(self) -> ORDER_QUANTITY: """주문가능수량 (통합)""" - raise NotImplementedError + ... @property def exchange_rate(self) -> Decimal: """당일환율""" - raise NotImplementedError + ... @property def condition_kor(self) -> str: """주문조건 (한글)""" - raise NotImplementedError + ... @runtime_checkable diff --git a/pykis/api/base/account.py b/pykis/api/base/account.py index 632a918d..1e26bf4c 100644 --- a/pykis/api/base/account.py +++ b/pykis/api/base/account.py @@ -21,12 +21,12 @@ class KisAccountProtocol(KisObjectProtocol, Protocol): @property def account_number(self) -> KisAccountNumber: """계좌번호""" - raise NotImplementedError + ... @property def account(self) -> "KisAccount": """계좌 Scope""" - raise NotImplementedError + ... @kis_repr( diff --git a/pykis/api/base/market.py b/pykis/api/base/market.py index 1b86e8ca..092c085a 100644 --- a/pykis/api/base/market.py +++ b/pykis/api/base/market.py @@ -20,27 +20,27 @@ class KisMarketProtocol(KisObjectProtocol, Protocol): @property def market(self) -> "MARKET_TYPE": """시장유형""" - raise NotImplementedError + ... @property def market_name(self) -> str: """실제 상품유형명""" - raise NotImplementedError + ... @property def foreign(self) -> bool: """해외종목 여부""" - raise NotImplementedError + ... @property def domestic(self) -> bool: """국내종목 여부""" - raise NotImplementedError + ... @property def currency(self) -> "CURRENCY_TYPE": """통화""" - raise NotImplementedError + ... @kis_repr( diff --git a/pykis/api/base/product.py b/pykis/api/base/product.py index f250ff7c..9775fd19 100644 --- a/pykis/api/base/product.py +++ b/pykis/api/base/product.py @@ -22,22 +22,22 @@ class KisProductProtocol(KisMarketProtocol, Protocol): @property def symbol(self) -> str: """종목코드""" - raise NotImplementedError + ... @property def name(self) -> str: """상품명""" - raise NotImplementedError + ... @property def info(self) -> "KisStockInfo": """상품기본정보 조회""" - raise NotImplementedError + ... @property def stock(self) -> "KisStock": """종목 Scope""" - raise NotImplementedError + ... @kis_repr( diff --git a/pykis/api/stock/chart.py b/pykis/api/stock/chart.py index b74cce96..fe72b3a9 100644 --- a/pykis/api/stock/chart.py +++ b/pykis/api/stock/chart.py @@ -23,72 +23,72 @@ class KisChartBar(Protocol): @property def time(self) -> datetime: """시간 (현지시간)""" - raise NotImplementedError + ... @property def time_kst(self) -> datetime: """시간 (한국시간)""" - raise NotImplementedError + ... @property def open(self) -> Decimal: """시가""" - raise NotImplementedError + ... @property def close(self) -> Decimal: """종가 (현재가)""" - raise NotImplementedError + ... @property def high(self) -> Decimal: """고가""" - raise NotImplementedError + ... @property def low(self) -> Decimal: """저가""" - raise NotImplementedError + ... @property def volume(self) -> int: """거래량""" - raise NotImplementedError + ... @property def amount(self) -> Decimal: """거래대금""" - raise NotImplementedError + ... @property def change(self) -> Decimal: """전일대비""" - raise NotImplementedError + ... @property def sign(self) -> STOCK_SIGN_TYPE: """전일대비 부호""" - raise NotImplementedError + ... @property def price(self) -> Decimal: """현재가 (종가)""" - raise NotImplementedError + ... @property def prev_price(self) -> Decimal: """전일가""" - raise NotImplementedError + ... @property def rate(self) -> Decimal: """등락률 (-100 ~ 100)""" - raise NotImplementedError + ... @property def sign_name(self) -> str: """대비부호명""" - raise NotImplementedError + ... @runtime_checkable @@ -98,12 +98,12 @@ class KisChart(KisProductProtocol, Protocol): @property def timezone(self) -> tzinfo: """시간대""" - raise NotImplementedError + ... @property def bars(self) -> list[KisChartBar]: """차트 (오름차순)""" - raise NotImplementedError + ... def index(self, time: datetime | date | time, /, kst: bool = False) -> int: """ @@ -113,7 +113,7 @@ def index(self, time: datetime | date | time, /, kst: bool = False) -> int: time: 시간대 kst: 한국시간대 여부 """ - raise NotImplementedError + ... def order_by( self, @@ -128,7 +128,7 @@ def order_by( key: 정렬 키 reverse: 내림차순 여부 """ - raise NotImplementedError + ... @overload def __getitem__(self, index: datetime | date | time | int) -> KisChartBar: ... @@ -136,17 +136,13 @@ def __getitem__(self, index: datetime | date | time | int) -> KisChartBar: ... @overload def __getitem__(self, index: slice) -> list[KisChartBar]: ... - def __getitem__(self, index: datetime | date | time | int | slice) -> KisChartBar | list[KisChartBar]: - raise NotImplementedError + def __getitem__(self, index: datetime | date | time | int | slice) -> KisChartBar | list[KisChartBar]: ... - def __iter__(self) -> Iterable[KisChartBar]: - raise NotImplementedError + def __iter__(self) -> Iterable[KisChartBar]: ... - def __len__(self) -> int: - raise NotImplementedError + def __len__(self) -> int: ... - def __reversed__(self): - raise NotImplementedError + def __reversed__(self): ... def df(self): """ @@ -154,7 +150,7 @@ def df(self): 해당 함수는 Pandas가 설치되어 있어야 합니다. """ - raise NotImplementedError + ... @runtime_checkable @@ -217,21 +213,13 @@ def index(self, time: datetime | date | time, /, kst: bool = False) -> int: ( (lambda bar: bar.time_kst) if isinstance(time, datetime) - else ( - (lambda bar: bar.time_kst.date()) - if isinstance(time, date) - else (lambda bar: bar.time_kst.time()) - ) + else ((lambda bar: bar.time_kst.date()) if isinstance(time, date) else (lambda bar: bar.time_kst.time())) ) if kst else ( (lambda bar: bar.time) if isinstance(time, datetime) - else ( - (lambda bar: bar.time.date()) - if isinstance(time, date) - else (lambda bar: bar.time.time()) - ) + else ((lambda bar: bar.time.date()) if isinstance(time, date) else (lambda bar: bar.time.time())) ) ), ) @@ -299,8 +287,7 @@ def df(self): import pandas as pd # type: ignore except ImportError as e: raise ImportError( - "Pandas가 설치되어 있지 않습니다.\n" - "Pandas를 설치하려면 `pip install pandas`를 실행해주세요." + "Pandas가 설치되어 있지 않습니다.\n" "Pandas를 설치하려면 `pip install pandas`를 실행해주세요." ) from e return pd.DataFrame( diff --git a/pykis/api/stock/info.py b/pykis/api/stock/info.py index fb062dbf..5eae5d86 100644 --- a/pykis/api/stock/info.py +++ b/pykis/api/stock/info.py @@ -119,57 +119,57 @@ class KisStockInfo(Protocol): @property def symbol(self) -> str: """종목코드""" - raise NotImplementedError + ... @property def std_code(self) -> str: """표준코드""" - raise NotImplementedError + ... @property def name_kor(self) -> str: """종목명""" - raise NotImplementedError + ... @property def full_name_kor(self) -> str: """종목전체명""" - raise NotImplementedError + ... @property def name_eng(self) -> str: """종목영문명""" - raise NotImplementedError + ... @property def full_name_eng(self) -> str: """종목영문전체명""" - raise NotImplementedError + ... @property def name(self) -> str: """종목명""" - raise NotImplementedError + ... @property def market(self) -> MARKET_TYPE: """상품유형타입""" - raise NotImplementedError + ... @property def market_name(self) -> str: """상품유형명""" - raise NotImplementedError + ... @property def foreign(self) -> bool: """해외종목 여부""" - raise NotImplementedError + ... @property def domestic(self) -> bool: """국내종목 여부""" - raise NotImplementedError + ... @runtime_checkable diff --git a/pykis/api/stock/order_book.py b/pykis/api/stock/order_book.py index ec145b7b..4576979d 100644 --- a/pykis/api/stock/order_book.py +++ b/pykis/api/stock/order_book.py @@ -36,12 +36,12 @@ class KisOrderbookItem(Protocol): @property def price(self) -> Decimal: """호가가격""" - raise NotImplementedError + ... @property def volume(self) -> int: """호가잔량""" - raise NotImplementedError + ... @runtime_checkable @@ -51,41 +51,40 @@ class KisOrderbook(KisProductProtocol, Protocol): @property def decimal_places(self) -> int: """소수점 자리수""" - raise NotImplementedError + ... @property def asks(self) -> list[KisOrderbookItem]: """매도호가""" - raise NotImplementedError + ... @property def bids(self) -> list[KisOrderbookItem]: """매수호가""" - raise NotImplementedError + ... @property - def count(self) -> int: - raise NotImplementedError + def count(self) -> int: ... @property def ask_price(self) -> KisOrderbookItem: """매도 1호가""" - raise NotImplementedError + ... @property def bid_price(self) -> KisOrderbookItem: """매수 1호가""" - raise NotImplementedError + ... @property def ask_volume(self) -> int: """매도 1호가 잔량""" - raise NotImplementedError + ... @property def bid_volume(self) -> int: """매수 1호가 잔량""" - raise NotImplementedError + ... @kis_repr( @@ -363,11 +362,7 @@ def foreign_orderbook( "/uapi/overseas-price/v1/quotations/inquire-asking-price", api="HHDFS76200100", params={ - "EXCD": ( - DAYTIME_MARKET_SHORT_TYPE_MAP[market] - if condition == "extended" - else MARKET_SHORT_TYPE_MAP[market] - ), + "EXCD": (DAYTIME_MARKET_SHORT_TYPE_MAP[market] if condition == "extended" else MARKET_SHORT_TYPE_MAP[market]), "SYMB": symbol, }, response_type=KisForeignOrderbook( diff --git a/pykis/api/stock/quote.py b/pykis/api/stock/quote.py index b0d98941..78bd712d 100644 --- a/pykis/api/stock/quote.py +++ b/pykis/api/stock/quote.py @@ -77,112 +77,112 @@ class KisQuote(KisProductProtocol, Protocol): @property def sector_name(self) -> str | None: """업종명""" - raise NotImplementedError + ... @property def price(self) -> Decimal: """현재가""" - raise NotImplementedError + ... @property def volume(self) -> int: """거래량""" - raise NotImplementedError + ... @property def amount(self) -> Decimal: """거래대금""" - raise NotImplementedError + ... @property def market_cap(self) -> Decimal: """시가총액""" - raise NotImplementedError + ... @property def sign(self) -> STOCK_SIGN_TYPE: """대비부호""" - raise NotImplementedError + ... @property def risk(self) -> STOCK_RISK_TYPE: """위험도""" - raise NotImplementedError + ... @property def halt(self) -> bool: """거래정지""" - raise NotImplementedError + ... @property def overbought(self) -> bool: """단기과열구분""" - raise NotImplementedError + ... @property def prev_price(self) -> Decimal: """전일종가""" - raise NotImplementedError + ... @property def prev_volume(self) -> Decimal: """전일거래량""" - raise NotImplementedError + ... @property def change(self) -> Decimal: """전일대비""" - raise NotImplementedError + ... @property def indicator(self) -> "KisIndicator": """종목 지표""" - raise NotImplementedError + ... @property def open(self) -> Decimal: """당일시가""" - raise NotImplementedError + ... @property def high(self) -> Decimal: """당일고가""" - raise NotImplementedError + ... @property def low(self) -> Decimal: """당일저가""" - raise NotImplementedError + ... @property def high_limit(self) -> Decimal: """상한가""" - raise NotImplementedError + ... @property def low_limit(self) -> Decimal: """하한가""" - raise NotImplementedError + ... @property def unit(self) -> Decimal: """거래단위""" - raise NotImplementedError + ... @property def tick(self) -> Decimal: """호가단위""" - raise NotImplementedError + ... @property def decimal_places(self) -> int: """소수점 자리수""" - raise NotImplementedError + ... @property def exchange_rate(self) -> Decimal: """당일환율""" - raise NotImplementedError + ... @property def close(self) -> Decimal: @@ -207,42 +207,42 @@ class KisIndicator(Protocol): @property def eps(self) -> Decimal: """EPS (주당순이익)""" - raise NotImplementedError + ... @property def bps(self) -> Decimal: """BPS (주당순자산)""" - raise NotImplementedError + ... @property def per(self) -> Decimal: """PER (주가수익비율)""" - raise NotImplementedError + ... @property def pbr(self) -> Decimal: """PBR (주가순자산비율)""" - raise NotImplementedError + ... @property def week52_high(self) -> Decimal: """52주 최고가""" - raise NotImplementedError + ... @property def week52_low(self) -> Decimal: """52주 최저가""" - raise NotImplementedError + ... @property def week52_high_date(self) -> date: """52주 최고가 날짜""" - raise NotImplementedError + ... @property def week52_low_date(self) -> date: """52주 최저가 날짜""" - raise NotImplementedError + ... @runtime_checkable diff --git a/pykis/api/stock/trading_hours.py b/pykis/api/stock/trading_hours.py index 6ce3a1bc..6136d6c8 100644 --- a/pykis/api/stock/trading_hours.py +++ b/pykis/api/stock/trading_hours.py @@ -25,37 +25,37 @@ class KisTradingHours(KisMarketProtocol, Protocol): @property def market(self) -> MARKET_TYPE: """시장 종류""" - raise NotImplementedError + ... @property def open(self) -> time: """장 시작 시간""" - raise NotImplementedError + ... @property def open_kst(self) -> time: """장 시작 시간 (한국시간)""" - raise NotImplementedError + ... @property def close(self) -> time: """장 종료 시간""" - raise NotImplementedError + ... @property def close_kst(self) -> time: """장 종료 시간 (한국시간)""" - raise NotImplementedError + ... @property def timezone(self) -> tzinfo: """시간대""" - raise NotImplementedError + ... @property def market_name(self) -> str: """시장 종류""" - raise NotImplementedError + ... @kis_repr( diff --git a/pykis/api/websocket/order_execution.py b/pykis/api/websocket/order_execution.py index addb720a..aa5a42d4 100644 --- a/pykis/api/websocket/order_execution.py +++ b/pykis/api/websocket/order_execution.py @@ -42,97 +42,97 @@ class KisRealtimeExecution(KisWebsocketResponseProtocol, Protocol): @property def time(self) -> datetime: """주문시각""" - raise NotImplementedError + ... @property def time_kst(self) -> datetime: """주문시각(KST)""" - raise NotImplementedError + ... @property def timezone(self) -> ZoneInfo: """시간대""" - raise NotImplementedError + ... @property def order_number(self) -> KisOrderNumber: """주문번호""" - raise NotImplementedError + ... @property def type(self) -> ORDER_TYPE: """주문유형""" - raise NotImplementedError + ... @property def price(self) -> Decimal: """체결단가""" - raise NotImplementedError + ... @property def unit_price(self) -> Decimal | None: """주문단가""" - raise NotImplementedError + ... @property def order_price(self) -> Decimal | None: """주문단가""" - raise NotImplementedError + ... @property def quantity(self) -> ORDER_QUANTITY: """주문수량""" - raise NotImplementedError + ... @property def qty(self) -> ORDER_QUANTITY: """주문수량""" - raise NotImplementedError + ... @property def executed_quantity(self) -> ORDER_QUANTITY: """체결수량""" - raise NotImplementedError + ... @property def executed_qty(self) -> ORDER_QUANTITY: """체결수량""" - raise NotImplementedError + ... @property def executed_amount(self) -> Decimal: """체결금액""" - raise NotImplementedError + ... @property def condition(self) -> ORDER_CONDITION | None: """주문조건""" - raise NotImplementedError + ... @property def execution(self) -> ORDER_EXECUTION | None: """체결조건""" - raise NotImplementedError + ... @property def receipt(self) -> bool: """접수여부""" - raise NotImplementedError + ... @property def canceled(self) -> bool: """취소여부 (IOC/FOK)""" - raise NotImplementedError + ... @property def rejected(self) -> bool: """거부여부""" - raise NotImplementedError + ... @property def rejected_reason(self) -> str | None: """거부사유""" - raise NotImplementedError + ... @kis_repr( diff --git a/pykis/api/websocket/price.py b/pykis/api/websocket/price.py index 0cb11c82..5874a7f3 100644 --- a/pykis/api/websocket/price.py +++ b/pykis/api/websocket/price.py @@ -41,222 +41,222 @@ class KisRealtimePrice(KisWebsocketResponseProtocol, KisProductProtocol, Protoco @property def time(self) -> datetime: """체결 시간""" - raise NotImplementedError + ... @property def time_kst(self) -> datetime: """체결 시간(KST)""" - raise NotImplementedError + ... @property def timezone(self) -> tzinfo: """시간대""" - raise NotImplementedError + ... @property def price(self) -> Decimal: """현재가""" - raise NotImplementedError + ... @property def last(self) -> Decimal: """현재가""" - raise NotImplementedError + ... @property def prev_price(self) -> Decimal: """전일가""" - raise NotImplementedError + ... @property def change(self) -> Decimal: """전일대비""" - raise NotImplementedError + ... @property def sign(self) -> STOCK_SIGN_TYPE: """대비부호""" - raise NotImplementedError + ... @property def sign_name(self) -> str: """대비부호명""" - raise NotImplementedError + ... @property def change_rate(self) -> Decimal: """전일대비율 (-100~100)""" - raise NotImplementedError + ... @property def bid(self) -> Decimal: """매수호가""" - raise NotImplementedError + ... @property def ask(self) -> Decimal: """매도호가""" - raise NotImplementedError + ... @property def bid_quantity(self) -> int: """매수호가잔량""" - raise NotImplementedError + ... @property def ask_quantity(self) -> int: """매도호가잔량""" - raise NotImplementedError + ... @property def spread(self) -> Decimal: """매수/매도호가대비""" - raise NotImplementedError + ... @property def spread_rate(self) -> Decimal: """매수/매도호가대비율 (-100~100)""" - raise NotImplementedError + ... @property def bid_qty(self) -> int: """매수호가잔량""" - raise NotImplementedError + ... @property def ask_qty(self) -> int: """매도호가잔량""" - raise NotImplementedError + ... @property def open(self) -> Decimal: """당일시가""" - raise NotImplementedError + ... @property def open_time(self) -> datetime | None: """시가시간""" - raise NotImplementedError + ... @property def open_time_kst(self) -> datetime | None: """시가시간(KST)""" - raise NotImplementedError + ... @property def open_change(self) -> Decimal: """시가대비""" - raise NotImplementedError + ... @property def open_change_rate(self) -> Decimal: """시가대비율""" - raise NotImplementedError + ... @property def high(self) -> Decimal: """당일고가""" - raise NotImplementedError + ... @property def high_time(self) -> datetime | None: """고가시간""" - raise NotImplementedError + ... @property def high_time_kst(self) -> datetime | None: """고가시간(KST)""" - raise NotImplementedError + ... @property def high_change(self) -> Decimal: """고가대비""" - raise NotImplementedError + ... @property def high_change_rate(self) -> Decimal: """고가대비율""" - raise NotImplementedError + ... @property def low(self) -> Decimal: """당일저가""" - raise NotImplementedError + ... @property def low_time(self) -> datetime | None: """저가시간""" - raise NotImplementedError + ... @property def low_time_kst(self) -> datetime | None: """저가시간(KST)""" - raise NotImplementedError + ... @property def low_change(self) -> Decimal: """저가대비""" - raise NotImplementedError + ... @property def low_change_rate(self) -> Decimal: """저가대비율""" - raise NotImplementedError + ... @property def volume(self) -> int: """누적거래량""" - raise NotImplementedError + ... @property def amount(self) -> Decimal: """누적거래대금""" - raise NotImplementedError + ... @property def prev_volume(self) -> int | None: """전일동일시간거래량""" - raise NotImplementedError + ... @property def buy_quantity(self) -> int: """매수체결량""" - raise NotImplementedError + ... @property def sell_quantity(self) -> int: """매도체결량""" - raise NotImplementedError + ... @property def intensity(self) -> float: """체결강도 (0 ~ 100+)""" - raise NotImplementedError + ... @property def buy_qty(self) -> int: """매수체결량""" - raise NotImplementedError + ... @property def sell_qty(self) -> int: """매도체결량""" - raise NotImplementedError + ... @property def volume_rate(self) -> Decimal | None: """전일동일시간거래량비율 (-100~100)""" - raise NotImplementedError + ... @property def condition(self) -> ORDER_CONDITION | None: """주문조건""" - raise NotImplementedError + ... @property def decimal_places(self) -> int: """소수점 자리수""" - raise NotImplementedError + ... @kis_repr( @@ -642,9 +642,7 @@ class KisForeignRealtimePrice(KisRealtimePriceBase): KisInt["sell_quantity"], # 22 BIVL 매도체결량 KisInt["buy_quantity"], # 23 ASVL 매수체결량 None, # 24 STRN 체결강도 - KisAny(FOREIGN_REALTIME_PRICE_ORDER_CONDITION_MAP.get)[ - "condition" - ], # 25 MTYP 시장구분 1:장중,2:장전,3:장후 + KisAny(FOREIGN_REALTIME_PRICE_ORDER_CONDITION_MAP.get)["condition"], # 25 MTYP 시장구분 1:장중,2:장전,3:장후 ] symbol: str # RSYM 실시간종목코드 diff --git a/pykis/client/form.py b/pykis/client/form.py index 219a1788..463357a3 100644 --- a/pykis/client/form.py +++ b/pykis/client/form.py @@ -10,4 +10,4 @@ class KisForm(metaclass=ABCMeta): @abstractmethod def build(self, dict: dict[str, Any] | None = None) -> dict[str, Any]: """요청 폼을 생성합니다.""" - raise NotImplementedError + ... diff --git a/pykis/client/object.py b/pykis/client/object.py index c0a02e28..dec2b000 100644 --- a/pykis/client/object.py +++ b/pykis/client/object.py @@ -21,7 +21,7 @@ def kis(self) -> "PyKis": 기본적으로 __init__ 호출 이후 라이브러리 단위에서 lazy initialization 되며, 라이브러리 내에서는 해당 속성을 사용할 때 초기화 단계에서 사용하지 않도록 해야합니다. """ - raise NotImplementedError + ... class KisObjectBase: diff --git a/pykis/event/filters/order.py b/pykis/event/filters/order.py index 29d307a8..0e98af62 100644 --- a/pykis/event/filters/order.py +++ b/pykis/event/filters/order.py @@ -22,7 +22,7 @@ class KisSimpleRealtimeExecution(Protocol): @property def order_number(self) -> "KisOrderNumber": """주문번호""" - raise NotImplementedError + ... @runtime_checkable @@ -32,27 +32,27 @@ class KisSimpleOrderNumberProtocol(Protocol): @property def symbol(self) -> str: """종목코드""" - raise NotImplementedError + ... @property def market(self) -> MARKET_TYPE: """시장유형""" - raise NotImplementedError + ... @property def branch(self) -> str: """지점코드""" - raise NotImplementedError + ... @property def number(self) -> str: """주문번호""" - raise NotImplementedError + ... @property def account_number(self) -> KisAccountNumber: """계좌번호""" - raise NotImplementedError + ... class KisSimpleOrderNumber: diff --git a/pykis/event/filters/product.py b/pykis/event/filters/product.py index f3d4fbb6..5051f56f 100644 --- a/pykis/event/filters/product.py +++ b/pykis/event/filters/product.py @@ -21,12 +21,12 @@ class KisSimpleProductProtocol(Protocol): @property def symbol(self) -> str: """종목코드""" - raise NotImplementedError + ... @property def market(self) -> MARKET_TYPE: """시장유형""" - raise NotImplementedError + ... class KisSimpleProduct: diff --git a/pykis/responses/dynamic.py b/pykis/responses/dynamic.py index 08e4a40a..54472d8e 100644 --- a/pykis/responses/dynamic.py +++ b/pykis/responses/dynamic.py @@ -146,11 +146,11 @@ class KisDynamicProtocol(Protocol): @property def __data__(self) -> dict[str, Any]: """원본 응답 데이터""" - raise NotImplementedError + ... def raw(self) -> dict[str, Any] | None: """원본 응답 데이터의 복사본을 반환합니다.""" - raise NotImplementedError + ... class KisDynamic: @@ -313,9 +313,7 @@ def transform_( if ignore_missing: continue - raise KeyError( - f"{object_type.__name__}.{key} 필드의 {field}값이 존재하지 않습니다. ({type_!r})" - ) + raise KeyError(f"{object_type.__name__}.{key} 필드의 {field}값이 존재하지 않습니다. ({type_!r})") if callable(type_.default): value = type_.default() @@ -349,9 +347,7 @@ def transform_( missing -= ignore_missing_fields if missing: - logging.logger.warning( - f"{object_type.__name__}에 정의되지 않은 필드가 있습니다: {', '.join(missing)}" - ) + logging.logger.warning(f"{object_type.__name__}에 정의되지 않은 필드가 있습니다: {', '.join(missing)}") setattr(object, "__data__", data) diff --git a/pykis/responses/response.py b/pykis/responses/response.py index dd3d304e..2000aac8 100644 --- a/pykis/responses/response.py +++ b/pykis/responses/response.py @@ -53,17 +53,17 @@ class KisResponseProtocol(KisDynamicProtocol, KisObjectProtocol, Protocol): @property def __response__(self) -> Response | None: """원본 응답 데이터""" - raise NotImplementedError + ... @property def __message__(self) -> str: """응답 메시지""" - raise NotImplementedError + ... @property def __code__(self) -> str: """응답 코드""" - raise NotImplementedError + ... class KisResponse(KisDynamic, KisObjectBase): @@ -109,22 +109,22 @@ class KisPaginationAPIResponseProtocol(KisResponseProtocol, Protocol): @property def page_status(self) -> KisPageStatus: """페이징 상태""" - raise NotImplementedError + ... @property def next_page(self) -> KisPage: """페이징 정보""" - raise NotImplementedError + ... @property def is_last(self) -> bool: """마지막 페이지인지 확인합니다.""" - raise NotImplementedError + ... @property def has_next(self) -> bool: """다음 페이지가 있는지 확인합니다.""" - raise NotImplementedError + ... class KisPaginationAPIResponse(KisAPIResponse): diff --git a/pykis/responses/websocket.py b/pykis/responses/websocket.py index 4c16fa7f..92671352 100644 --- a/pykis/responses/websocket.py +++ b/pykis/responses/websocket.py @@ -18,11 +18,11 @@ class KisWebsocketResponseProtocol(Protocol): @property def __data__(self) -> list[str]: """원본 데이터""" - raise NotImplementedError + ... def raw(self) -> list[str]: """원본 응답 데이터를 반환합니다.""" - raise NotImplementedError + ... class KisWebsocketResponse: diff --git a/pykis/utils/repr.py b/pykis/utils/repr.py index 52f9f755..8dd3af75 100644 --- a/pykis/utils/repr.py +++ b/pykis/utils/repr.py @@ -76,8 +76,7 @@ def _append_with_indent(sb: StringIO, value: str, indent: str): class ReprFunction(Protocol): - def __call__(self, obj: Any, max_depth: int = 7, depth: int = 0) -> str: - raise NotImplementedError + def __call__(self, obj: Any, max_depth: int = 7, depth: int = 0) -> str: ... custom_reprs: dict[type, ReprFunction] = {} From 254000f90917c494969c66c285c2909a2da59392 Mon Sep 17 00:00:00 2001 From: Soju06 Date: Thu, 7 Nov 2024 16:52:48 +0900 Subject: [PATCH 3/3] =?UTF-8?q?Ellipsis=20=ED=83=80=EC=9E=85=20=ED=99=9C?= =?UTF-8?q?=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pykis/adapter/account/order.py | 8 ++-- pykis/adapter/account_product/order_modify.py | 15 +++--- pykis/api/account/order_modify.py | 48 +++++++++---------- pykis/responses/dynamic.py | 25 +++++----- pykis/utils/params.py | 6 --- 5 files changed, 47 insertions(+), 55 deletions(-) delete mode 100644 pykis/utils/params.py diff --git a/pykis/adapter/account/order.py b/pykis/adapter/account/order.py index 2b24861d..e38c088a 100644 --- a/pykis/adapter/account/order.py +++ b/pykis/adapter/account/order.py @@ -1,3 +1,4 @@ +from types import EllipsisType from typing import TYPE_CHECKING, Protocol, runtime_checkable from pykis.api.account.order import ( @@ -13,7 +14,6 @@ from pykis.api.account.pending_order import KisPendingOrders from pykis.api.stock.info import COUNTRY_TYPE from pykis.api.stock.market import MARKET_TYPE -from pykis.utils.params import EMPTY, EMPTY_TYPE if TYPE_CHECKING: from pykis.api.base.account import KisAccountProtocol @@ -274,10 +274,10 @@ def order( def modify( self: "KisAccountProtocol", order: KisOrderNumber, - price: ORDER_PRICE | None | EMPTY_TYPE = EMPTY, + price: ORDER_PRICE | None | EllipsisType = ..., qty: IN_ORDER_QUANTITY | None = None, - condition: ORDER_CONDITION | None | EMPTY_TYPE = EMPTY, - execution: ORDER_EXECUTION | None | EMPTY_TYPE = EMPTY, + condition: ORDER_CONDITION | None | EllipsisType = ..., + execution: ORDER_EXECUTION | None | EllipsisType = ..., ) -> KisOrder: """ 한국투자증권 통합 주식 주문정정 (국내 모의투자 미지원, 해외 주간거래 모의투자 미지원) diff --git a/pykis/adapter/account_product/order_modify.py b/pykis/adapter/account_product/order_modify.py index b20a561f..a08c5014 100644 --- a/pykis/adapter/account_product/order_modify.py +++ b/pykis/adapter/account_product/order_modify.py @@ -1,7 +1,6 @@ +from types import EllipsisType from typing import TYPE_CHECKING, Protocol, runtime_checkable -from pykis.utils.params import EMPTY, EMPTY_TYPE - if TYPE_CHECKING: from pykis.api.account.order import ( IN_ORDER_QUANTITY, @@ -41,10 +40,10 @@ class KisModifyableOrder(Protocol): def modify( self, - price: "ORDER_PRICE | None | EMPTY_TYPE" = EMPTY, + price: "ORDER_PRICE | None | EllipsisType" = ..., qty: "IN_ORDER_QUANTITY | None" = None, - condition: "ORDER_CONDITION | None | EMPTY_TYPE" = EMPTY, - execution: "ORDER_EXECUTION | None | EMPTY_TYPE" = EMPTY, + condition: "ORDER_CONDITION | None | EllipsisType" = ..., + execution: "ORDER_EXECUTION | None | EllipsisType" = ..., ) -> "KisOrder": """ 한국투자증권 통합 주식 주문정정 (국내 모의투자 미지원, 해외 주간거래 모의투자 미지원) @@ -88,10 +87,10 @@ class KisModifyableOrderMixin: def modify( self: "KisOrderNumber", - price: "ORDER_PRICE | None | EMPTY_TYPE" = EMPTY, + price: "ORDER_PRICE | None | EllipsisType" = ..., qty: "IN_ORDER_QUANTITY | None" = None, - condition: "ORDER_CONDITION | None | EMPTY_TYPE" = EMPTY, - execution: "ORDER_EXECUTION | None | EMPTY_TYPE" = EMPTY, + condition: "ORDER_CONDITION | None | EllipsisType" = ..., + execution: "ORDER_EXECUTION | None | EllipsisType" = ..., ) -> "KisOrder": """ 한국투자증권 통합 주식 주문정정 (국내 모의투자 미지원, 해외 주간거래 모의투자 미지원) diff --git a/pykis/api/account/order_modify.py b/pykis/api/account/order_modify.py index ec0329e8..451bc926 100644 --- a/pykis/api/account/order_modify.py +++ b/pykis/api/account/order_modify.py @@ -1,4 +1,5 @@ from datetime import datetime +from types import EllipsisType from typing import TYPE_CHECKING, Any, Literal from pykis.api.account.order import ( @@ -18,7 +19,6 @@ from pykis.client.exceptions import KisAPIError from pykis.responses.response import KisAPIResponse from pykis.responses.types import KisString -from pykis.utils.params import EMPTY, EMPTY_TYPE from pykis.utils.timezone import TIMEZONE if TYPE_CHECKING: @@ -103,10 +103,10 @@ def __pre_init__(self, data: dict[str, Any]): def domestic_modify_order( self: "PyKis", order: KisOrderNumber, - price: ORDER_PRICE | None | EMPTY_TYPE = EMPTY, + price: ORDER_PRICE | None | EllipsisType = ..., qty: IN_ORDER_QUANTITY | None = None, - condition: ORDER_CONDITION | None | EMPTY_TYPE = EMPTY, - execution: ORDER_EXECUTION | None | EMPTY_TYPE = EMPTY, + condition: ORDER_CONDITION | None | EllipsisType = ..., + execution: ORDER_EXECUTION | None | EllipsisType = ..., ) -> KisDomesticModifyOrder: """ 한국투자증권 국내 주식 주문정정 (모의투자 미지원) @@ -139,16 +139,16 @@ def domestic_modify_order( if not order_info: raise ValueError("주문정보를 찾을 수 없습니다. 이미 체결되었거나 취소된 주문일 수 있습니다.") - if isinstance(price, EMPTY_TYPE): + if isinstance(price, EllipsisType): price = order_info.price - if isinstance(qty, EMPTY_TYPE): + if isinstance(qty, EllipsisType): qty = order_info.qty - if isinstance(condition, EMPTY_TYPE): + if isinstance(condition, EllipsisType): condition = order_info.condition - if isinstance(execution, EMPTY_TYPE): + if isinstance(execution, EllipsisType): execution = order_info.execution price = None if price is None else ensure_price(price, 0) @@ -259,10 +259,10 @@ def domestic_cancel_order( def foreign_modify_order( self: "PyKis", order: KisOrderNumber, - price: ORDER_PRICE | None | EMPTY_TYPE = EMPTY, + price: ORDER_PRICE | None | EllipsisType = ..., qty: IN_ORDER_QUANTITY | None = None, - condition: ORDER_CONDITION | None | EMPTY_TYPE = EMPTY, - execution: ORDER_EXECUTION | None | EMPTY_TYPE = EMPTY, + condition: ORDER_CONDITION | None | EllipsisType = ..., + execution: ORDER_EXECUTION | None | EllipsisType = ..., ) -> KisForeignModifyOrder: """ 한국투자증권 해외 주식 주문정정 @@ -291,16 +291,16 @@ def foreign_modify_order( if not order_info: raise ValueError("주문정보를 찾을 수 없습니다. 이미 체결되었거나 취소된 주문일 수 있습니다.") - if isinstance(price, EMPTY_TYPE): + if isinstance(price, EllipsisType): price = order_info.price - if isinstance(qty, EMPTY_TYPE): + if isinstance(qty, EllipsisType): qty = order_info.qty - if isinstance(condition, EMPTY_TYPE): + if isinstance(condition, EllipsisType): condition = order_info.condition - if isinstance(execution, EMPTY_TYPE): + if isinstance(execution, EllipsisType): execution = order_info.execution price = None if price is None else ensure_price(price) @@ -389,7 +389,7 @@ def foreign_cancel_order( def foreign_daytime_modify_order( self: "PyKis", order: KisOrderNumber, - price: ORDER_PRICE | None | EMPTY_TYPE = EMPTY, + price: ORDER_PRICE | None | EllipsisType = ..., qty: IN_ORDER_QUANTITY | None = None, ) -> KisForeignDaytimeModifyOrder: """ @@ -425,10 +425,10 @@ def foreign_daytime_modify_order( if not order_info: raise ValueError("주문정보를 찾을 수 없습니다. 이미 체결되었거나 취소된 주문일 수 있습니다.") - if isinstance(price, EMPTY_TYPE): + if isinstance(price, EllipsisType): price = order_info.price - if isinstance(qty, EMPTY_TYPE): + if isinstance(qty, EllipsisType): qty = order_info.qty price = None if price is None else ensure_price(price) @@ -521,10 +521,10 @@ def foreign_daytime_cancel_order( def modify_order( self: "PyKis", order: KisOrderNumber, - price: ORDER_PRICE | None | EMPTY_TYPE = EMPTY, + price: ORDER_PRICE | None | EllipsisType = ..., qty: IN_ORDER_QUANTITY | None = None, - condition: ORDER_CONDITION | None | EMPTY_TYPE = EMPTY, - execution: ORDER_EXECUTION | None | EMPTY_TYPE = EMPTY, + condition: ORDER_CONDITION | None | EllipsisType = ..., + execution: ORDER_EXECUTION | None | EllipsisType = ..., ) -> KisOrder: """ 한국투자증권 통합 주식 주문정정 (국내 모의투자 미지원, 해외 주간거래 모의투자 미지원) @@ -574,10 +574,10 @@ def modify_order( def account_modify_order( self: "KisAccountProtocol", order: KisOrderNumber, - price: ORDER_PRICE | None | EMPTY_TYPE = EMPTY, + price: ORDER_PRICE | None | EllipsisType = ..., qty: IN_ORDER_QUANTITY | None = None, - condition: ORDER_CONDITION | None | EMPTY_TYPE = EMPTY, - execution: ORDER_EXECUTION | None | EMPTY_TYPE = EMPTY, + condition: ORDER_CONDITION | None | EllipsisType = ..., + execution: ORDER_EXECUTION | None | EllipsisType = ..., ) -> KisOrder: """ 한국투자증권 통합 주식 주문정정 (국내 모의투자 미지원, 해외 주간거래 모의투자 미지원) diff --git a/pykis/responses/dynamic.py b/pykis/responses/dynamic.py index 54472d8e..3ea6ca5a 100644 --- a/pykis/responses/dynamic.py +++ b/pykis/responses/dynamic.py @@ -1,4 +1,4 @@ -from types import NoneType +from types import EllipsisType, NoneType from typing import ( Any, Callable, @@ -10,7 +10,6 @@ ) from pykis import logging -from pykis.utils.params import EMPTY, EMPTY_TYPE __all__ = [ "KisType", @@ -62,22 +61,22 @@ def __init__(self): def __call__( self, - field: str | None | EMPTY_TYPE = EMPTY, - default: T | Callable[[], T] | None | object | EMPTY_TYPE = EMPTY, - scope: str | None | EMPTY_TYPE = EMPTY, - absolute: bool | EMPTY_TYPE = EMPTY, + field: str | None | EllipsisType = ..., + default: T | Callable[[], T] | None | object | EllipsisType = ..., + scope: str | None | EllipsisType = ..., + absolute: bool | EllipsisType = ..., ) -> T: - if field is not EMPTY: - self.field = field # type: ignore + if not isinstance(field, EllipsisType): + self.field = field - if default is not EMPTY: + if not isinstance(default, EllipsisType): self.default = default - if scope is not EMPTY: - self.scope = scope # type: ignore + if not isinstance(scope, EllipsisType): + self.scope = scope - if absolute is not EMPTY: - self.absolute = absolute # type: ignore + if not isinstance(absolute, EllipsisType): + self.absolute = absolute return self # type: ignore diff --git a/pykis/utils/params.py b/pykis/utils/params.py deleted file mode 100644 index a6c21e0a..00000000 --- a/pykis/utils/params.py +++ /dev/null @@ -1,6 +0,0 @@ -class EMPTY_TYPE: - def __eq__(self, other): - return isinstance(other, EMPTY_TYPE) - - -EMPTY = EMPTY_TYPE()