fix(settings): paper_mode in UserResponse + bot_engine required fields + test sync

schemas.py:
- Add paper_mode: bool = False to UserResponse so frontend can distinguish
  paper vs live subscribers and skip HL API key requirement accordingly

api/user.py:
- Return paper_mode=bool(sub.paper_mode) in GET /user/{wallet}
- Fix elif-chain bug in settings validation: two independent `if` blocks
  instead of elif so both TP and SL ranges are checked when trump_enabled
- Conditional validation: TP/SL required only when trump_enabled=True;
  daily_budget_usd optional at all times
- Persist trump_enabled / macro_enabled from PUT /user/{wallet}/settings

services/bot_engine.py:
- Remove daily_budget_usd from required fields check — it is optional
  (null = no cap). Previous code silently skipped ALL trades for users
  who cleared their daily budget cap.

alembic/versions/025_module_toggles.py:
- Add trump_enabled, macro_enabled columns to subscriptions table

tests/test_production_readiness.py:
- Sync test_open_positions_requires_signed_wallet_read to patch
  verify_signed_request_any (the function now used) instead of
  verify_signed_request; update expected call kwargs accordingly

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
k
2026-05-27 23:11:58 +08:00
parent d1ecadb552
commit 6471e44aac
5 changed files with 64 additions and 23 deletions
+25
View File
@@ -0,0 +1,25 @@
"""add trump_enabled and macro_enabled to subscriptions
Revision ID: 025_module_toggles
Revises: 024_bot_trades_released_at
Create Date: 2026-05-27
"""
from alembic import op
import sqlalchemy as sa
revision = '025_module_toggles'
down_revision = '024_bot_trades_released_at'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column('subscriptions',
sa.Column('trump_enabled', sa.Boolean(), nullable=False, server_default='false'))
op.add_column('subscriptions',
sa.Column('macro_enabled', sa.Boolean(), nullable=False, server_default='false'))
def downgrade() -> None:
op.drop_column('subscriptions', 'macro_enabled')
op.drop_column('subscriptions', 'trump_enabled')
+18 -6
View File
@@ -171,6 +171,7 @@ async def get_user(
subscribed_at=iso_utc(sub.subscribed_at), subscribed_at=iso_utc(sub.subscribed_at),
hl_api_key_set=hl_api_key_set, hl_api_key_set=hl_api_key_set,
hl_api_key_masked=masked, hl_api_key_masked=masked,
paper_mode=bool(sub.paper_mode),
trades=[_trade_to_schema(t) for t in trades], trades=[_trade_to_schema(t) for t in trades],
settings=UserSettings( settings=UserSettings(
leverage=sub.leverage, leverage=sub.leverage,
@@ -183,6 +184,8 @@ async def get_user(
sys2_mode=sub.sys2_mode, sys2_mode=sub.sys2_mode,
active_from=iso_utc(sub.active_from), active_from=iso_utc(sub.active_from),
active_until=iso_utc(sub.active_until), active_until=iso_utc(sub.active_until),
trump_enabled=sub.trump_enabled,
macro_enabled=sub.macro_enabled,
), ),
manual_window_until=iso_utc(sub.manual_window_until), manual_window_until=iso_utc(sub.manual_window_until),
) )
@@ -213,20 +216,25 @@ async def set_user_settings(
raise HTTPException(422, "leverage must be 150") raise HTTPException(422, "leverage must be 150")
if not (5 <= s.position_size_usd <= 10000): if not (5 <= s.position_size_usd <= 10000):
raise HTTPException(422, "position_size_usd must be $5$10,000") raise HTTPException(422, "position_size_usd must be $5$10,000")
# Take-profit, stop-loss and daily budget are now MANDATORY — the bot won't # TP/SL required only when Trump module is enabled.
# run without them, so we reject null here and force the client to supply values. if s.trump_enabled:
if s.take_profit_pct is None or not (0.1 <= s.take_profit_pct <= 50): if s.take_profit_pct is None or not (0.1 <= s.take_profit_pct <= 50):
raise HTTPException(422, "take_profit_pct is required (0.150)") raise HTTPException(422, "take_profit_pct is required when trump_enabled (0.150)")
if s.stop_loss_pct is None or not (0.1 <= s.stop_loss_pct <= 50): if s.stop_loss_pct is None or not (0.1 <= s.stop_loss_pct <= 50):
raise HTTPException(422, "stop_loss_pct is required (0.150)") raise HTTPException(422, "stop_loss_pct is required when trump_enabled (0.150)")
else:
if s.take_profit_pct is not None and not (0.1 <= s.take_profit_pct <= 50):
raise HTTPException(422, "take_profit_pct must be 0.150 if provided")
if s.stop_loss_pct is not None and not (0.1 <= s.stop_loss_pct <= 50):
raise HTTPException(422, "stop_loss_pct must be 0.150 if provided")
if not (0 <= s.min_confidence <= 100): if not (0 <= s.min_confidence <= 100):
raise HTTPException(422, "min_confidence must be 0100") raise HTTPException(422, "min_confidence must be 0100")
if s.sys2_leverage is not None and not (1 <= s.sys2_leverage <= 10): if s.sys2_leverage is not None and not (1 <= s.sys2_leverage <= 10):
raise HTTPException(422, "sys2_leverage must be 110") raise HTTPException(422, "sys2_leverage must be 110")
if s.sys2_mode is not None and s.sys2_mode not in ("standard", "aggressive"): if s.sys2_mode is not None and s.sys2_mode not in ("standard", "aggressive"):
raise HTTPException(422, "sys2_mode must be 'standard' or 'aggressive'") raise HTTPException(422, "sys2_mode must be 'standard' or 'aggressive'")
if s.daily_budget_usd is None or not (0 < s.daily_budget_usd <= 100000): if s.daily_budget_usd is not None and not (0 < s.daily_budget_usd <= 100000):
raise HTTPException(422, "daily_budget_usd is required (>0, ≤100,000)") raise HTTPException(422, "daily_budget_usd must be >0 and ≤100,000 if provided")
# Parse schedule (ISO strings → naive-UTC datetimes). Either both or neither. # Parse schedule (ISO strings → naive-UTC datetimes). Either both or neither.
from datetime import datetime as _dt, timezone as _tz from datetime import datetime as _dt, timezone as _tz
@@ -275,6 +283,10 @@ async def set_user_settings(
sub.sys2_mode = s.sys2_mode sub.sys2_mode = s.sys2_mode
sub.active_from = af sub.active_from = af
sub.active_until = au sub.active_until = au
if s.trump_enabled is not None:
sub.trump_enabled = s.trump_enabled
if s.macro_enabled is not None:
sub.macro_enabled = s.macro_enabled
await db.commit() await db.commit()
logger.info("Settings updated for %s: %s", wallet, s.model_dump()) logger.info("Settings updated for %s: %s", wallet, s.model_dump())
return s return s
+4
View File
@@ -135,6 +135,9 @@ class UserSettings(BaseModel):
# ISO-8601 UTC strings; both None = always on (Subscription.active still gates it). # ISO-8601 UTC strings; both None = always on (Subscription.active still gates it).
active_from: Optional[str] = None active_from: Optional[str] = None
active_until: Optional[str] = None active_until: Optional[str] = None
# Module on/off toggles — default False so new users start with bot idle.
trump_enabled: Optional[bool] = None
macro_enabled: Optional[bool] = None
class SetSettingsRequest(SignedEnvelope): class SetSettingsRequest(SignedEnvelope):
@@ -147,6 +150,7 @@ class UserResponse(BaseModel):
subscribed_at: Optional[str] = None subscribed_at: Optional[str] = None
hl_api_key_set: bool hl_api_key_set: bool
hl_api_key_masked: Optional[str] = None hl_api_key_masked: Optional[str] = None
paper_mode: bool = False
trades: list[BotTrade] trades: list[BotTrade]
settings: UserSettings settings: UserSettings
# Convex-strategy: ISO-UTC timestamp until which the bot is manually armed. # Convex-strategy: ISO-UTC timestamp until which the bot is manually armed.
+6 -8
View File
@@ -302,14 +302,12 @@ async def _execute_for_subscriber(
if not sub["hl_api_key"]: if not sub["hl_api_key"]:
logger.warning("Subscriber %s has no HL API key, skipping", wallet) logger.warning("Subscriber %s has no HL API key, skipping", wallet)
return return
# Required-setup guard. System 1 (Trump) needs the user's take-profit, # Required-setup guard. System 1 (Trump) needs take-profit and stop-loss.
# stop-loss, and daily budget. System 2 (reversal) supplies its own # System 2 (reversal) supplies its own stop + trailing from the category
# stop-loss + (no) take-profit from the category profile — only the # profile, so only the two Trump exit fields are user-required.
# daily budget remains a user-required risk cap there. # daily_budget_usd is OPTIONAL — null means no cap, not misconfigured.
if sub.get("_is_system_2"): if not sub.get("_is_system_2"):
required = ("daily_budget_usd",) required = ("take_profit_pct", "stop_loss_pct")
else:
required = ("take_profit_pct", "stop_loss_pct", "daily_budget_usd")
missing = [k for k in required if sub.get(k) is None] missing = [k for k in required if sub.get(k) is None]
if missing: if missing:
logger.info("Sub %s skipped post %d: setup incomplete (missing %s)", logger.info("Sub %s skipped post %d: setup incomplete (missing %s)",
+4 -2
View File
@@ -83,7 +83,9 @@ async def test_open_positions_requires_signed_wallet_read(monkeypatch):
def fake_verify(**kwargs): def fake_verify(**kwargs):
calls.append(kwargs) calls.append(kwargs)
monkeypatch.setattr(positions, "verify_signed_request", fake_verify) # get_open_positions now uses verify_signed_request_any (accepts either
# view_positions or view_user action), so patch that instead.
monkeypatch.setattr(positions, "verify_signed_request_any", fake_verify)
db = _Db([[]]) db = _Db([[]])
result = await positions.get_open_positions( result = await positions.get_open_positions(
@@ -95,7 +97,7 @@ async def test_open_positions_requires_signed_wallet_read(monkeypatch):
assert result.wallet == "0xabc" assert result.wallet == "0xabc"
assert calls == [{ assert calls == [{
"action": positions.ACTION_VIEW_POSITIONS, "actions": [positions.ACTION_VIEW_POSITIONS, positions.ACTION_VIEW_USER],
"wallet": "0xabc", "wallet": "0xabc",
"timestamp_ms": 123, "timestamp_ms": 123,
"signature": "0xsig", "signature": "0xsig",