Use trading account and USDC/USDT market price for sim convert.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-08-14 18:52:38 +08:00
parent 9d1495658c
commit ad992ee262
7 changed files with 181 additions and 45 deletions
+26 -7
View File
@@ -240,18 +240,33 @@ class SimWallets:
from_ccy: str,
to_ccy: str,
amount: float,
account: str = "funding",
account: str = "trading",
to_amount: float | None = None,
rate: float | None = None,
fee: float | None = None,
note: str | None = None,
) -> dict[str, Any]:
"""USDT↔USDC 兑换. 默认交易账户; to_amount 未给时按 rate(USDT/USDC) 换算, 再否则 1:1."""
amt = float(amount)
if amt <= 0:
return {"ok": False, "detail": "数量须大于 0"}
fa = (from_ccy or "").strip().lower()
ta = (to_ccy or "").strip().lower()
acct = (account or "funding").strip().lower()
acct = normalize_sim_account(account) or "trading"
if acct not in ("funding", "trading"):
return {"ok": False, "detail": "account 须为 funding / trading"}
if {fa, ta} != {"usdt", "usdc"}:
return {"ok": False, "detail": "仅支持 USDT↔USDC 1:1"}
return {"ok": False, "detail": "仅支持 USDT↔USDC"}
if to_amount is not None:
got = float(to_amount)
elif rate is not None and float(rate) > 0:
r = float(rate)
# rate = USDT per 1 USDC
got = (amt / r) if fa == "usdt" else (amt * r)
else:
got = amt
if got <= 0:
return {"ok": False, "detail": "兑换所得须大于 0"}
src_key = _ACCT_MAP[(acct, fa)]
dst_key = _ACCT_MAP[(acct, ta)]
conn = self.get_db()
@@ -262,8 +277,9 @@ class SimWallets:
if amt > src + 1e-9:
return {"ok": False, "detail": f"{acct} {fa.upper()} 不足(可用 {src:.4f})"}
snap[src_key] = src - amt
snap[dst_key] = float(snap[dst_key]) + amt
snap[dst_key] = float(snap[dst_key]) + got
self._write(snap, conn=conn)
note_s = note or f"to {ta} @{rate if rate is not None else '1:1'}"
self._ledger(
conn,
kind="convert",
@@ -271,25 +287,28 @@ class SimWallets:
ccy=fa,
account=acct,
balance_after=snap[src_key],
note=f"to {ta}",
note=note_s,
)
self._ledger(
conn,
kind="convert",
amount=amt,
amount=got,
ccy=ta,
account=acct,
balance_after=snap[dst_key],
note=f"from {fa}",
)
conn.commit()
eff_rate = (amt / got) if fa == "usdt" and got > 0 else ((got / amt) if amt > 0 else None)
return {
"ok": True,
"detail": "converted",
"from_ccy": fa.upper(),
"to_ccy": ta.upper(),
"amount": amt,
"rate": 1.0,
"to_amount": got,
"rate": float(rate) if rate is not None else eff_rate,
"fee": float(fee or 0),
"account": acct,
"wallets": {k: float(snap[k]) for k in WALLET_KEYS},
"total_usdt_equiv": self.total_usdt_equiv(snap),