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
34 changes: 26 additions & 8 deletions api/grid_ladders/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@
from databases.tables.grid_ladder_table import GridLadderTable
from databases.tables.symbol_table import SymbolTable
from databases.utils import get_session
from pybinbot import ExchangeId, GridLadderStatus, KucoinFutures, MarketType
from pybinbot import (
ExchangeId,
GridLadderStatus,
KucoinFutures,
MarketType,
)
from pybinbot.models.grid_ladder import (
GridLadderCloseRequest,
GridLadderListResponse,
Expand All @@ -23,6 +28,7 @@
from grid_ladders.models import GridLadderCreate
from grid_ladders.sizing import KucoinGridMarginRules
from tools.config import Config
from tools.handle_error import kucoin_rate_limit_detail
from user.models.user import UserTokenData
from user.services.auth import get_current_user

Expand Down Expand Up @@ -186,7 +192,13 @@ def post_grid_ladder(

active_ladders = grid_ladder_crud.get_active()

balance = ConsolidatedAccounts(session=session).get_balance()
try:
balance = ConsolidatedAccounts(session=session).get_balance()
except Exception as error:
detail = kucoin_rate_limit_detail(error)
if detail is not None:
raise HTTPException(status_code=429, detail=detail) from error
raise
available_fiat_balance = balance.fiat_available
try:
GridCapitalSettings(session).evaluate_grid_capital(
Expand All @@ -197,12 +209,18 @@ def post_grid_ladder(
except ValueError as error:
raise HTTPException(status_code=400, detail=str(error)) from error

sizer = _build_margin_sizer(
session,
payload.symbol,
payload.exchange,
payload.market_type,
)
try:
sizer = _build_margin_sizer(
session,
payload.symbol,
payload.exchange,
payload.market_type,
)
except Exception as error:
detail = kucoin_rate_limit_detail(error)
if detail is not None:
raise HTTPException(status_code=429, detail=detail) from error
raise
try:
calculated = calculate_grid_levels(
range_low=payload.range_low,
Expand Down
2 changes: 1 addition & 1 deletion api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ dependencies = [
"sqlalchemy>=2.0.30",
"alembic>=1.18.4",
"alembic-postgresql-enum",
"pybinbot>=1.9.34",
"pybinbot>=1.9.36",
]

[project.urls]
Expand Down
22 changes: 22 additions & 0 deletions api/tests/test_grid_ladders.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
DealType,
ExchangeId,
GridLadderStatus,
KucoinErrors,
MarketType,
OrderBase,
OrderStatus,
Expand Down Expand Up @@ -85,6 +86,17 @@ def get_balance(self):
monkeypatch.setattr("grid_ladders.routes.ConsolidatedAccounts", Accounts)


def _patch_balance_error(monkeypatch, error: Exception) -> None:
class Accounts:
def __init__(self, *args, **kwargs):
pass

def get_balance(self):
raise error

monkeypatch.setattr("grid_ladders.routes.ConsolidatedAccounts", Accounts)


@pytest.fixture(autouse=True)
def clean_grid_ladders(create_test_tables):
with Session(create_test_tables) as session:
Expand Down Expand Up @@ -381,6 +393,16 @@ def test_post_grid_ladder_persists_ladder_and_levels(client, monkeypatch):
]


def test_post_grid_ladder_returns_kucoin_rate_limit_error(client, monkeypatch):
_patch_balance_error(monkeypatch, KucoinErrors("Too many requests", "429000"))
_patch_contract_meta(monkeypatch)

response = client.post("/grid-ladders", json=_payload())

assert response.status_code == 429
assert response.json()["detail"] == "Kucoin 429000 Too many requests"


def test_post_grid_ladder_rejects_second_active_ladder_for_same_symbol(
client, monkeypatch, create_test_tables
):
Expand Down
16 changes: 16 additions & 0 deletions api/tools/handle_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,22 @@ def json_response_error(message):
return json_response(body, status=422)


def kucoin_rate_limit_detail(error: Exception) -> str | None:
code = getattr(error, "code", None)
message = getattr(error, "message", None)
if str(code) == "429000":
return f"Kucoin {code} {message or 'Too many requests'}"

error_text = str(error)
if "429000" in error_text:
message_text = (
"Too many requests" if "Too many requests" in error_text else error_text
)
return f"Kucoin 429000 {message_text}"

return None


def encode_json(raw):
return jsonable_encoder(raw)

Expand Down
Loading
Loading