Commit Graph
35 Commits
Author SHA1 Message Date
jackyu66git 6baae85eaa feat: actual exchange fees for entry orders
- BitgetTrade: added GetTradeFee() queries /mix/order/fills
- HyperLiquidTrade: added GetTradeFee() parses MarketOpen response
- trader.placeOrder() now returns (errMsg, actualFeeUSD)
- executeEntry uses actual fee from exchange, falls back to estimate
2026-05-04 18:35:33 +08:00
jackyu66git 0aa9923067 fix: full arb table + net profit columns in price view
- ArbTable: removed slice(0,10) cap, shows all 42 opps (21x2)
- PriceTable: added net_bg_to_hl and net_hl_to_bg columns
- Backend SSE: sends net profit for both directions per coin
2026-05-04 18:26:49 +08:00
jackyu66git 49da6fd35b fix: HL balance now reads spot USDC via SpotUserState
HL testnet USDC lives in the spot account, not the perp clearinghouse.
GetBalance() was calling UserState() (perp clearinghouseState), which
returned /usr/bin/bash. Switched to SpotUserState() and parse USDC.total - USDC.hold.

Also cleaned up .gitignore to exclude .env, binary, logs, data/.
2026-05-04 17:48:14 +08:00
jackyu66git c5c4c7394f fix: HL testnet - add API wallet address to signed orders, 3-param constructor 2026-05-04 15:39:31 +08:00
jackyu66git 30436bbe75 fix: BG paper trading API - tradeSide param, correct host, marginMode 2026-05-04 15:28:08 +08:00
jackyu66git e5ea78ffd2 feat: real trading mode, auto-stop after 5 trades, HL testnet support
- config.json: test_mode=false, ready for sim/testnet trading
- trader.go: auto-stop after 5 real trades, exchange response logging,
  Stop()/Start() API, shuttingDown flag for graceful stop
- dashboard.go: POST /api/stop + POST /api/start endpoints,
  trading status in SSE stats
- exchange/hyperliquid.go: switch HL WS to testnet endpoint
- exchange/hyperliquid_trade.go: switch REST to testnet endpoint,
  support base64 + 32-byte EVM private keys
- main.go: listen on trader.StopCh (graceful, no process exit)
- scanner.go: trim TrackedCoins to only 6 core coins (DOGE/LINK/ONDO/OP/WIF/ARB)
- .gitignore: ignore main binary
2026-05-04 14:31:52 +08:00
jackyu66git f29e78a435 fix: db migration tab char corrupted, restore historical trades 2026-05-04 13:50:49 +08:00
jackyu66git ccfa27b1a6 fix: scanner netProfit 漏算exit fees + 孤儿仓位标记failed
- scanner.go: netProfit 扣费改为 2*(buyFee+sellFee) 匹配 calcArbPnL
- trader.go: 第二腿失败时设 pos.Status=failed,避免语义混淆
2026-05-04 06:39:24 +08:00
jackyu66git ddaa5badd2 fix: 重启后总PnL回到0的问题 + 前端PnL图表公式统一
- trader.go: NewTrader 启动时从DB GetAllClosedTrades() 加载所有已平仓交易到 closedTrades
- trader.go: 新增 safeFloat/safeStr 辅助函数处理DB空指针
- db/trade_repo.go: 新增 GetAllClosedTrades() 方法
- frontend: PnL图表标题和曲线改用 2*AmountUSD*NetPnl/100 公式,与后端Stats一致
2026-05-04 06:23:35 +08:00
jackyu66git 5aedcb6566 修复 scale-in 后 leg.EntryPrice 不更新 + 重启恢复时加载 scale prices
- trader.go: scale-in 后用 weightedAvgPrice 更新 LongLeg/ShortLeg.EntryPrice
- trader.go: restoreOpenPositions 从 orders 表加载 scale prices 重建完整价格切片
- db/trade_repo.go: 新增 GetScalePrices(tradeID) 方法
- README: v1.2.1 版本记录
2026-05-04 06:06:37 +08:00
jackyu66git a9a21de5a2 refactor: 逐批次实时写入DB,删除persistTrade 2026-05-04 05:29:04 +08:00
jackyu66git ec725ed11a fix: PnL计算改为美元归一化,加仓不再虚增手续费 (calcArbPnL) 2026-05-04 05:03:16 +08:00
jackyu66git 0288dc8284 feat: 手续费改为逐笔USD累算 + Vite React前端 + system_orders表 + README 2026-05-04 04:34:27 +08:00
jackyu66git d1e6c965cb fix: blacklistCoin 计算退出PnL字段, 避免DB写入零值
blacklistCoin 之前只设 Status=close_failed 就跑了, 没给
ExitDiffPct/ExitNetPnl/ExitLongPnl/ExitTotalFees 等字段赋值。
retryClose 写 TradeRecord 时全为零, 导致DB出现 PnL=0 的假记录。

修复: blacklistCoin 现在接收当前价格, 用 checkExit 相同方式
计算 PnL/价差收敛标签并存入 pos 字段。
2026-05-04 02:00:04 +08:00
jackyu66git dd15c6fe43 fix: 移除多余的netPnl和反转检查, 收敛即退出(0.02%) 2026-05-04 01:57:56 +08:00
jackyu66git 1c0618583c fix: 收敛退出放宽到0.02%+净利为正, 恢复到0.02%即退不亏钱 2026-05-04 01:55:22 +08:00
jackyu66git 21a3f9a962 feat: 所有参数移至config.json, 重构退出逻辑, 清理遗留接口
- 将所有硬编码参数迁移到 config.json (手续费率、止盈/止损阈值、
  超时、腿间隔、加仓步进等)
- 退出条件: 净利 >= take_profit_pct 止盈, 价差 <= 0 平仓
- 删除 Binance/dYdX 遗留代码
- 更新 README 文档
- Dashboard: 双交易所价格表、黑名单UI、按币名排序持仓
- Bitget WS: 文本ping保活
- 数据库: 重置, 无历史仓位
2026-05-04 01:46:17 +08:00
jackyu66git 5d6d9352f3 fix: use taker fees (BG 0.06%, HL 0.045%) + threshold 0.25%
All IOC market orders incur taker fees, not maker fees. Previous
makerFees (BG 0.02%, HL 0.015%) caused 0.10% threshold trades to
actually lose 0.11% per round trip.

Changes:
- scanner.go: makerFees → takerFees (BG 0.060, HL 0.045)
- dashboard.go: makerFees → takerFees
- types.go: makerFees → takerFees
- trader.go: makerFees → takerFees
- config.json: trade_threshold 0.1 → 0.25
2026-05-03 23:34:01 +08:00
jackyu66git 68c0a342a6 fix: retryClose saves trade record and persists to DB on success 2026-05-03 23:19:15 +08:00
jackyu66git cf6548c37f fix: 4 bugfixes for production readiness
1. GetHLSize: add minimum size checks (prevent size=0 when price > amount)
2. executeEntry: orphan position warning when leg1 close also fails after leg2
3. checkExit: keep position as close_failed on failure, retryClose on each Tick
4. persistTrade: sync instead of goroutine (prevent data loss on exit)
2026-05-03 23:13:44 +08:00
jackyu66git 721abc02a9 fix: async entry race condition — 'entering' status prevents premature exit
During async executeEntry goroutine, the 300ms sleep between legs
left the position vulnerable to checkExit() from the main loop.
Added intermediate Status='entering' that checkExit/checkScaleIn
skip ('entering' != 'open'), switched to 'open' only after both
legs are placed.
2026-05-03 22:40:48 +08:00
jackyu66git 29f2072e90 feat: async TryEntry with goroutine, non-blocking main loop
- TryEntry now spawns a goroutine for order placement
- Main loop continues at 50-250ms even during entry
- 'entering' map prevents duplicate entries on same coin
- Async cleanup of entering state on completion
2026-05-03 22:32:09 +08:00
jackyu66git 32f06b57d6 move DetailedStats calc out of trader.go into dashboard.go
- Remove DetailedStats struct and GetDetailedStats() method from trader.go
- Add calcDetailedStats() standalone pure function in dashboard.go
- Dashboard calls d.trader.GetClosedTrades() + calcDetailedStats()
- Trading logic now has zero display-oriented calculations
2026-05-03 21:13:11 +08:00
jackyu66git 1e4a3f3b37 Add detailed PnL and duration stats to dashboard 2026-05-03 21:03:40 +08:00
jackyu66git 89d92b6672 Fix entry latency: synchronous execution with scan-time prices
- Remove goroutine in TryEntry (executeEntry now synchronous)
- Use opp.BuyPrice/SellPrice directly instead of re-reading from store
- Keep lightweight direction sanity check (0.1% tolerance)
- executeEntry returns bool for call chain consistency
2026-05-03 20:17:35 +08:00
jackyu66git e319b73331 fix: reversal = take profit, not stop loss
HL→BG position: long HL, short BG.
When bgP and hlP cross over (spread reverses):
- Long HL: price went up → profit
- Short BG: price went down → profit
Both legs profit simultaneously. Reversal is MAX profit moment.
2026-05-03 19:24:51 +08:00
jackyu66git db52152ef9 fix: stop-loss on spread reversal + current spread sign (#3)
- Add explicit stop-loss when diffPct < -0.02 (价差反转,止损平仓)
  instead of relying on the convergence threshold to catch reversals
- Dashboard currentSpread now direction-aware for HL→BG positions
- Trade detail modal with clickable rows (previous commit partial)

Before: reversals would exit via  with wrong reason
  '价差收敛'. After: dedicated < -0.02 check with correct reason.
2026-05-03 19:22:35 +08:00
jackyu66git 505137bcb0 feat(web): trade detail modal with prices, fees, timestamps
- Click any trade row in history table to open detail modal
- Modal shows 6 sections: 概览, 时间, 价差, 手续费, 多仓, 空仓
- Entries and exits displayed with 6 decimal precision
- Fee entry/exit and total fee displayed
- Open/close timestamps with full date-time format
- Duration, scale count, total amount, exit reason
- Orders sub-table if available
- Escape key and overlay click to close
2026-05-03 18:59:28 +08:00
jackyu66git 02b74f1ec0 decouple display from trading: snapMu + RefreshSnapshot/ReadSnapshot
- Add snapMu RWMutex + positionsSnapshot to Trader
- RefreshSnapshot() called from main loop after Tick() — acquires
  t.mu briefly, stores deep copy under snapMu
- ReadSnapshot() returns snapshot copy under snapMu.RLock — never
  touches t.mu, zero contention with trading path
- Dashboard + handleStatus + hourly summary + status log all
  use ReadSnapshot() instead of GetPositionsCopy()
- Trading path (Tick/TryEntry/executeEntry/checkExit/checkScaleIn)
  never blocked by display reads
- Snapshot is at most 1 tick behind live state — acceptable delay
2026-05-03 18:35:47 +08:00
jackyu66git b08d8490fc fix: data race, scale-in PnL, nonce mutex, dead code, hourly check
- 🔴 Data race: Add GetPositionsCopy() returning deep copies (no shared
  ArbPosition pointers). Use it in dashboard broadcastLoop + handleStatus.
- 🟡 Scale-in PnL: Track LongEntryPrices/ShortEntryPrices on ArbPosition,
  compute weighted average (harmonic mean) at exit for accurate PnL.
- 🟢 CalcNetProfit: Delete dead code from exchange/helpers.go.
- 🟢 HL nonce: Add sync.Mutex around lastNonce++ (thread safety).
- 🟢 Hourly check: Change from 5-second window to minute window.
- 🟢 ExitPrice: Test mode closeLeg already handled by checkExit.
2026-05-03 18:31:14 +08:00
jackyu66git ab48e207a5 Fix 3 arbitrage logic issues from code review
Issue #1 (critical): reProfit false positive on price reversal
  executeEntry used CalcNetProfit which auto-swaps prices when
  hlP < bgP. If prices flipped between scan and execution, reProfit
  reported positive even when direction was now wrong.
  Fix: use netProfit() with explicit direction + verify spread
  direction hasn't flipped (hlP <= bgP prevents BG->HL when
  HL is no longer more expensive).

Issue #2 (medium): Scale-in was paper-only, didn't place orders
  Now actually places additional orders on both legs via new
  placeOrderAt(). Test mode uses mock fills. Live mode sends
  real API orders. AmountUSD properly tracks total deployed
  capital. Partial fill handled gracefully (don't close main leg).

Issue #3 (minor): closeLeg missing ExitTime on mock mode
2026-05-03 18:19:25 +08:00
jackyu66git beb3611778 Phase 3: Real-time enhancements
P3-1: Scan optimization — only BG↔HL (50+ pair combos → 2)
P3-2: Real-time spread chart — spreadHistory ring buffer +
      /api/spread-history endpoint + Chart.js spread chart
P3-3: Live position PnL — positions SSE now includes
      estimated current profit/loss + current spread
P3-4: Real-time trade events — trader.OnTradeEvent callback
      fires SSE 'trade_open' / 'trade_close' immediately
P3-5: Connection status monitoring — tracks last update time
      per exchange, broadcast via stats.connections + /api/connections

Frontend: spread chart card, PnL column in positions,
          connection status dots in stats bar,
          green/red border flash on trade events
2026-05-03 18:05:19 +08:00
jackyu66git eb74495470 Fix 8 bugs from code review
B#1 — sigCh shared across goroutines, SIGINT unreliable
  → context.WithCancel: main loop cancels ctx on SIGINT,
    4 WS goroutines select on ctx.Done() instead of shared sigCh

B#3 — restoreOpenPositions missing LastScaleAt
  → Set LastScaleAt = tr.OpenedAt on restore so scale-in cooldown works

B#4 — dYdX heartbeat goroutine leaks on reconnect
  → Added stopHeartbeat chan + heartbeatMu mutex; close old channel
    before spawning new heartbeat goroutine

B#5 — GetBitgetSize fmt.Sprintf rounds up, may exceed amountUSD
  → Added math.Floor(sz*multiplier)/multiplier before format to round
    DOWN to nearest valid step size for every coin

B#6 — netProfit and CalcNetProfit duplicate formula
  → scanner.go netProfit now delegates to exchange.CalcNetProfit

B#7 — Aevo Run callback only 2 params, incompatible with startExchange
  → Changed to 4-arg callback func(coin, price, bid, ask) with bid=ask=0

B#8 — parseFloat uses fmt.Sscanf (slow, locale-sensitive)
  → Replaced with strconv.ParseFloat

B#9 — dYdX receives hlSymbols instead of its own symbol list
  → Added dydxSymbols var, built from c.HL like other exchanges
2026-05-03 17:48:06 +08:00
jackyu66git b09314f317 Phase 1: SQLite persistence layer
- Add modernc.org/sqlite (pure Go, no CGO)
- db/ package: trades, orders, config_log tables + CRUD
- Trade persistence: every closed trade saved to SQLite
- Restart recovery: open positions restored from DB
- Automatic migration on startup
2026-05-03 17:28:08 +08:00
jackyu66git 719f0a061d Initial commit 2026-05-03 16:54:36 +08:00