feat: paginate KIS balance inquiries
This commit is contained in:
@@ -209,6 +209,8 @@ def test_get_balance_rejects_failure_instead_of_false_empty(monkeypatch):
|
||||
monkeypatch.setattr(b, "_headers", lambda _tr: {})
|
||||
|
||||
class Response:
|
||||
headers = {"tr_cont": "E"}
|
||||
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
@@ -225,6 +227,8 @@ def test_get_balance_accepts_validated_empty_balance(monkeypatch):
|
||||
monkeypatch.setattr(b, "_headers", lambda _tr: {})
|
||||
|
||||
class Response:
|
||||
headers = {"tr_cont": "E"}
|
||||
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
@@ -235,6 +239,141 @@ def test_get_balance_accepts_validated_empty_balance(monkeypatch):
|
||||
assert b.get_balance() == []
|
||||
|
||||
|
||||
class _BalanceResponse:
|
||||
def __init__(self, payload, tr_cont="E"):
|
||||
self.payload = payload
|
||||
self.headers = {} if tr_cont is None else {"tr_cont": tr_cont}
|
||||
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
def json(self):
|
||||
return self.payload
|
||||
|
||||
|
||||
def _balance_broker(monkeypatch, responses):
|
||||
broker = KISBroker("12345678-01", app_key="app-key", app_secret="app-secret", base_url=_MOCK_URL)
|
||||
monkeypatch.setattr(broker, "_headers", lambda _tr: {"authorization": "Bearer token"})
|
||||
calls = []
|
||||
|
||||
def fake_get(*args, **kwargs):
|
||||
calls.append({**kwargs, "headers": dict(kwargs["headers"]), "params": dict(kwargs["params"])})
|
||||
response = responses.pop(0)
|
||||
if isinstance(response, BaseException):
|
||||
raise response
|
||||
return response
|
||||
|
||||
monkeypatch.setattr("trex_core.adapters.broker.kis.httpx.get", fake_get)
|
||||
return broker, calls
|
||||
|
||||
|
||||
def _balance_payload(rows, *, fk="", nk="", rt_cd="0"):
|
||||
return {"rt_cd": rt_cd, "output1": rows, "ctx_area_fk100": fk, "ctx_area_nk100": nk}
|
||||
|
||||
|
||||
def test_get_balance_reads_all_pages_and_aggregates_by_symbol(monkeypatch):
|
||||
broker, calls = _balance_broker(monkeypatch, [
|
||||
_BalanceResponse(_balance_payload([{"pdno": "005930", "hldg_qty": "2"}], fk="A", nk="1"), "F"),
|
||||
_BalanceResponse(_balance_payload([{"pdno": "000660", "hldg_qty": "4"}], fk="B", nk="2"), "M"),
|
||||
_BalanceResponse(_balance_payload([
|
||||
{"pdno": "005930", "hldg_qty": "3"},
|
||||
{"pdno": "035420", "hldg_qty": "1"},
|
||||
]), "E"),
|
||||
])
|
||||
|
||||
assert [(item.symbol, item.hldg_qty) for item in broker.get_balance()] == [
|
||||
("005930", 5), ("000660", 4), ("035420", 1),
|
||||
]
|
||||
assert len(calls) == 3
|
||||
assert "tr_cont" not in calls[0]["headers"]
|
||||
assert calls[0]["params"]["CTX_AREA_FK100"] == ""
|
||||
assert calls[0]["params"]["CTX_AREA_NK100"] == ""
|
||||
assert calls[1]["headers"]["tr_cont"] == "N"
|
||||
assert calls[1]["params"]["CTX_AREA_FK100"] == "A"
|
||||
assert calls[1]["params"]["CTX_AREA_NK100"] == "1"
|
||||
assert calls[2]["headers"]["tr_cont"] == "N"
|
||||
assert calls[2]["params"]["CTX_AREA_FK100"] == "B"
|
||||
assert calls[2]["params"]["CTX_AREA_NK100"] == "2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminal", ["D", "E"])
|
||||
def test_get_balance_stops_at_terminal_header_without_page_size_assumptions(monkeypatch, terminal):
|
||||
broker, calls = _balance_broker(monkeypatch, [
|
||||
_BalanceResponse(_balance_payload([
|
||||
{"pdno": "005930", "hldg_qty": "1"},
|
||||
{"pdno": "000660", "hldg_qty": "0"},
|
||||
{"pdno": "035420", "hldg_qty": "-1"},
|
||||
]), terminal),
|
||||
])
|
||||
|
||||
assert [(item.symbol, item.hldg_qty) for item in broker.get_balance()] == [("005930", 1)]
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("responses", "expected_code", "calls_expected"),
|
||||
[
|
||||
([_BalanceResponse(_balance_payload([]), None)], "malformed_response", 1),
|
||||
([_BalanceResponse(_balance_payload([]), "X")], "malformed_response", 1),
|
||||
([_BalanceResponse(_balance_payload([], fk="", nk=""), "F")], "malformed_response", 1),
|
||||
([_BalanceResponse(_balance_payload([], fk="A", nk="1"), "F"),
|
||||
_BalanceResponse(_balance_payload([], fk="A", nk="1"), "M")], "malformed_response", 2),
|
||||
([_BalanceResponse(_balance_payload([], fk="A", nk="1"), "F"),
|
||||
_BalanceResponse(_balance_payload([], fk="B", nk="2"), "M"),
|
||||
_BalanceResponse(_balance_payload([], fk="A", nk="1"), "F")], "malformed_response", 3),
|
||||
([_BalanceResponse(_balance_payload(["not-an-object"]))], "malformed_response", 1),
|
||||
([_BalanceResponse(_balance_payload([{"pdno": "005930"}]))], "malformed_response", 1),
|
||||
([_BalanceResponse(_balance_payload([{"pdno": "005930", "hldg_qty": "bad"}]))], "malformed_response", 1),
|
||||
([_BalanceResponse(_balance_payload([{"pdno": "", "hldg_qty": "1"}]))], "malformed_response", 1),
|
||||
([_BalanceResponse(_balance_payload({}, rt_cd="0"))], "malformed_response", 1),
|
||||
([_BalanceResponse([], "E")], "malformed_response", 1),
|
||||
([_BalanceResponse(_balance_payload([], rt_cd="1"))], "broker_rejected", 1),
|
||||
],
|
||||
)
|
||||
def test_get_balance_fails_closed_for_malformed_or_nonprogressing_pages(
|
||||
monkeypatch, responses, expected_code, calls_expected
|
||||
):
|
||||
broker, calls = _balance_broker(monkeypatch, responses)
|
||||
|
||||
with pytest.raises(BrokerBalanceError) as raised:
|
||||
broker.get_balance()
|
||||
assert raised.value.code == expected_code
|
||||
assert len(calls) == calls_expected
|
||||
assert "app-secret" not in str(raised.value)
|
||||
assert "token" not in str(raised.value)
|
||||
|
||||
|
||||
def test_get_balance_fails_closed_on_later_transport_and_http_errors(monkeypatch):
|
||||
request = httpx.Request("GET", "https://example.test/balance")
|
||||
response = httpx.Response(503, request=request)
|
||||
for failure, expected_code in [
|
||||
(httpx.ConnectTimeout("unavailable"), "transport_failed"),
|
||||
(httpx.HTTPStatusError("bad gateway", request=request, response=response), "transport_failed"),
|
||||
]:
|
||||
broker, calls = _balance_broker(monkeypatch, [
|
||||
_BalanceResponse(_balance_payload([{"pdno": "005930", "hldg_qty": "2"}], fk="A", nk="1"), "F"),
|
||||
failure,
|
||||
])
|
||||
with pytest.raises(BrokerBalanceError) as raised:
|
||||
broker.get_balance()
|
||||
assert raised.value.code == expected_code
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_get_balance_fails_closed_on_json_decode_error(monkeypatch):
|
||||
class InvalidJsonResponse(_BalanceResponse):
|
||||
def json(self):
|
||||
raise ValueError("invalid JSON with app-secret")
|
||||
|
||||
broker, calls = _balance_broker(monkeypatch, [InvalidJsonResponse(None)])
|
||||
|
||||
with pytest.raises(BrokerBalanceError) as raised:
|
||||
broker.get_balance()
|
||||
assert raised.value.code == "malformed_response"
|
||||
assert len(calls) == 1
|
||||
assert "app-secret" not in str(raised.value)
|
||||
|
||||
|
||||
def test_get_balance_sanitizes_token_issuance_failure(monkeypatch):
|
||||
b = KISBroker("12345678-01", app_key="k", app_secret="s", base_url=_MOCK_URL)
|
||||
monkeypatch.setattr(
|
||||
|
||||
@@ -92,6 +92,22 @@ def test_strategy_quantity_above_raw_broker_total_fails_closed(tmp_path):
|
||||
assert exc.value.code == "ownership_mismatch"
|
||||
|
||||
|
||||
def test_projection_includes_strategy_symbol_alongside_first_page_manual_holding(tmp_path):
|
||||
store = StrategyOwnershipStore(tmp_path / "ownership.json")
|
||||
store.apply_fill(
|
||||
execution_id="buy-1",
|
||||
symbol="000660",
|
||||
side="buy",
|
||||
quantity=4,
|
||||
)
|
||||
broker = OwnershipAwareBroker(
|
||||
FakeBroker([BalanceItem("005930", 19), BalanceItem("000660", 4)]),
|
||||
store,
|
||||
)
|
||||
|
||||
assert broker.get_balance() == [BalanceItem("000660", 4)]
|
||||
|
||||
|
||||
def test_sell_cannot_reduce_below_strategy_owned_zero(tmp_path):
|
||||
store = StrategyOwnershipStore(tmp_path / "ownership.json")
|
||||
with pytest.raises(BrokerBalanceError):
|
||||
|
||||
Reference in New Issue
Block a user