mirror of
https://github.com/NoFxAiOS/nofx.git
synced 2026-07-12 15:26:55 +08:00
feat(gate): complete Gate.io exchange integration with trader refactoring
Gate.io Integration: - Add Gate trader with full Trader interface implementation - Add order_sync.go for background trade synchronization - Fix quantity display (convert contracts to actual tokens via quanto_multiplier) - Fix fill price return in OpenLong/OpenShort/CloseLong/CloseShort - Add Gate-specific CoinAnk K-line data source support - Add Gate to supported exchanges in frontend and backend - Add Gate/KuCoin logo SVG icons Trader Package Refactoring: - Move exchange-specific code into subdirectories (binance/, bybit/, okx/, bitget/, hyperliquid/, aster/, lighter/, gate/) - Create types/ package for shared types to avoid circular dependencies - Move TraderTestSuite to trader/testutil package to avoid import cycles - Update market.GetWithExchange to support exchange-specific data
This commit is contained in:
193
trader/aster/order_sync.go
Normal file
193
trader/aster/order_sync.go
Normal file
@@ -0,0 +1,193 @@
|
||||
package aster
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"nofx/logger"
|
||||
"nofx/market"
|
||||
"nofx/store"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SyncOrdersFromAster syncs Aster exchange order history to local database
|
||||
// Also creates/updates position records to ensure orders/fills/positions data consistency
|
||||
// exchangeID: Exchange account UUID (from exchanges.id)
|
||||
// exchangeType: Exchange type ("aster")
|
||||
func (t *AsterTrader) SyncOrdersFromAster(traderID string, exchangeID string, exchangeType string, st *store.Store) error {
|
||||
if st == nil {
|
||||
return fmt.Errorf("store is nil")
|
||||
}
|
||||
|
||||
// Get recent trades (last 24 hours)
|
||||
startTime := time.Now().Add(-24 * time.Hour)
|
||||
|
||||
logger.Infof("🔄 Syncing Aster trades from: %s", startTime.Format(time.RFC3339))
|
||||
|
||||
// Use GetTrades method to fetch trade records
|
||||
trades, err := t.GetTrades(startTime, 500)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get trades: %w", err)
|
||||
}
|
||||
|
||||
logger.Infof("📥 Received %d trades from Aster", len(trades))
|
||||
|
||||
// Sort trades by time ASC (oldest first) for proper position building
|
||||
sort.Slice(trades, func(i, j int) bool {
|
||||
return trades[i].Time.UnixMilli() < trades[j].Time.UnixMilli()
|
||||
})
|
||||
|
||||
// Process trades one by one (no transaction to avoid deadlock)
|
||||
orderStore := st.Order()
|
||||
positionStore := st.Position()
|
||||
posBuilder := store.NewPositionBuilder(positionStore)
|
||||
syncedCount := 0
|
||||
|
||||
for _, trade := range trades {
|
||||
// Check if trade already exists (use exchangeID which is UUID, not exchange type)
|
||||
existing, err := orderStore.GetOrderByExchangeID(exchangeID, trade.TradeID)
|
||||
if err == nil && existing != nil {
|
||||
continue // Order already exists, skip
|
||||
}
|
||||
|
||||
// Normalize symbol
|
||||
symbol := market.Normalize(trade.Symbol)
|
||||
|
||||
// Determine order action based on side, positionSide, and realizedPnL
|
||||
// Aster uses one-way position mode (BOTH), so we need to infer from PnL
|
||||
// - RealizedPnL != 0 means it's a close trade
|
||||
// - RealizedPnL == 0 means it's an open trade
|
||||
orderAction := deriveAsterOrderAction(trade.Side, trade.PositionSide, trade.RealizedPnL)
|
||||
|
||||
// Determine position side from order action
|
||||
positionSide := "LONG"
|
||||
if strings.Contains(orderAction, "short") {
|
||||
positionSide = "SHORT"
|
||||
}
|
||||
|
||||
// Normalize side for storage
|
||||
side := strings.ToUpper(trade.Side)
|
||||
|
||||
// Create order record - use Unix milliseconds UTC
|
||||
tradeTimeMs := trade.Time.UTC().UnixMilli()
|
||||
orderRecord := &store.TraderOrder{
|
||||
TraderID: traderID,
|
||||
ExchangeID: exchangeID, // UUID
|
||||
ExchangeType: exchangeType, // Exchange type
|
||||
ExchangeOrderID: trade.TradeID,
|
||||
Symbol: symbol,
|
||||
Side: side,
|
||||
PositionSide: "BOTH", // Aster uses one-way position mode
|
||||
Type: "LIMIT",
|
||||
OrderAction: orderAction,
|
||||
Quantity: trade.Quantity,
|
||||
Price: trade.Price,
|
||||
Status: "FILLED",
|
||||
FilledQuantity: trade.Quantity,
|
||||
AvgFillPrice: trade.Price,
|
||||
Commission: trade.Fee,
|
||||
FilledAt: tradeTimeMs,
|
||||
CreatedAt: tradeTimeMs,
|
||||
UpdatedAt: tradeTimeMs,
|
||||
}
|
||||
|
||||
// Insert order record
|
||||
if err := orderStore.CreateOrder(orderRecord); err != nil {
|
||||
logger.Infof(" ⚠️ Failed to sync trade %s: %v", trade.TradeID, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Create fill record - use Unix milliseconds UTC
|
||||
fillRecord := &store.TraderFill{
|
||||
TraderID: traderID,
|
||||
ExchangeID: exchangeID, // UUID
|
||||
ExchangeType: exchangeType, // Exchange type
|
||||
OrderID: orderRecord.ID,
|
||||
ExchangeOrderID: trade.TradeID,
|
||||
ExchangeTradeID: trade.TradeID,
|
||||
Symbol: symbol,
|
||||
Side: side,
|
||||
Price: trade.Price,
|
||||
Quantity: trade.Quantity,
|
||||
QuoteQuantity: trade.Price * trade.Quantity,
|
||||
Commission: trade.Fee,
|
||||
CommissionAsset: "USDT",
|
||||
RealizedPnL: trade.RealizedPnL,
|
||||
IsMaker: false,
|
||||
CreatedAt: tradeTimeMs,
|
||||
}
|
||||
|
||||
if err := orderStore.CreateFill(fillRecord); err != nil {
|
||||
logger.Infof(" ⚠️ Failed to sync fill for trade %s: %v", trade.TradeID, err)
|
||||
}
|
||||
|
||||
// Create/update position record using PositionBuilder
|
||||
if err := posBuilder.ProcessTrade(
|
||||
traderID, exchangeID, exchangeType,
|
||||
symbol, positionSide, orderAction,
|
||||
trade.Quantity, trade.Price, trade.Fee, trade.RealizedPnL,
|
||||
tradeTimeMs, trade.TradeID,
|
||||
); err != nil {
|
||||
logger.Infof(" ⚠️ Failed to sync position for trade %s: %v", trade.TradeID, err)
|
||||
} else {
|
||||
logger.Infof(" 📍 Position updated for trade: %s (action: %s, qty: %.6f)", trade.TradeID, orderAction, trade.Quantity)
|
||||
}
|
||||
|
||||
syncedCount++
|
||||
logger.Infof(" ✅ Synced trade: %s %s %s qty=%.6f price=%.6f pnl=%.2f fee=%.6f action=%s",
|
||||
trade.TradeID, symbol, side, trade.Quantity, trade.Price, trade.RealizedPnL, trade.Fee, orderAction)
|
||||
}
|
||||
|
||||
logger.Infof("✅ Aster order sync completed: %d new trades synced", syncedCount)
|
||||
return nil
|
||||
}
|
||||
|
||||
// deriveAsterOrderAction determines order action from trade details
|
||||
// Aster uses one-way position mode (BOTH), so we infer from:
|
||||
// - Side: BUY or SELL
|
||||
// - RealizedPnL: non-zero means closing trade
|
||||
func deriveAsterOrderAction(side, positionSide string, realizedPnL float64) string {
|
||||
side = strings.ToUpper(side)
|
||||
positionSide = strings.ToUpper(positionSide)
|
||||
|
||||
// Check if this is a closing trade (has realized PnL)
|
||||
isClose := realizedPnL != 0
|
||||
|
||||
if positionSide == "LONG" {
|
||||
if isClose {
|
||||
return "close_long"
|
||||
}
|
||||
return "open_long"
|
||||
} else if positionSide == "SHORT" {
|
||||
if isClose {
|
||||
return "close_short"
|
||||
}
|
||||
return "open_short"
|
||||
} else {
|
||||
// BOTH mode - infer from side and PnL
|
||||
if side == "BUY" {
|
||||
if isClose {
|
||||
return "close_short" // Buying to close short
|
||||
}
|
||||
return "open_long" // Buying to open long
|
||||
} else {
|
||||
if isClose {
|
||||
return "close_long" // Selling to close long
|
||||
}
|
||||
return "open_short" // Selling to open short
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// StartOrderSync starts background order sync task for Aster
|
||||
func (t *AsterTrader) StartOrderSync(traderID string, exchangeID string, exchangeType string, st *store.Store, interval time.Duration) {
|
||||
ticker := time.NewTicker(interval)
|
||||
go func() {
|
||||
for range ticker.C {
|
||||
if err := t.SyncOrdersFromAster(traderID, exchangeID, exchangeType, st); err != nil {
|
||||
logger.Infof("⚠️ Aster order sync failed: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
logger.Infof("🔄 Aster order sync started (interval: %v)", interval)
|
||||
}
|
||||
1608
trader/aster/trader.go
Normal file
1608
trader/aster/trader.go
Normal file
File diff suppressed because it is too large
Load Diff
301
trader/aster/trader_test.go
Normal file
301
trader/aster/trader_test.go
Normal file
@@ -0,0 +1,301 @@
|
||||
package aster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"nofx/trader/testutil"
|
||||
"nofx/trader/types"
|
||||
)
|
||||
|
||||
// ============================================================
|
||||
// 1. AsterTraderTestSuite - inherits base test suite
|
||||
// ============================================================
|
||||
|
||||
// AsterTraderTestSuite Aster trader test suite
|
||||
// Inherits TraderTestSuite and adds Aster specific mock logic
|
||||
type AsterTraderTestSuite struct {
|
||||
*testutil.TraderTestSuite // Embeds base test suite
|
||||
mockServer *httptest.Server
|
||||
}
|
||||
|
||||
// NewAsterTraderTestSuite creates Aster test suite
|
||||
func NewAsterTraderTestSuite(t *testing.T) *AsterTraderTestSuite {
|
||||
// Create mock HTTP server
|
||||
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Return different mock responses based on URL path
|
||||
path := r.URL.Path
|
||||
|
||||
var respBody interface{}
|
||||
|
||||
switch {
|
||||
// Mock GetBalance - /fapi/v3/balance (returns array)
|
||||
case path == "/fapi/v3/balance":
|
||||
respBody = []map[string]interface{}{
|
||||
{
|
||||
"asset": "USDT",
|
||||
"walletBalance": "10000.00",
|
||||
"unrealizedProfit": "100.50",
|
||||
"marginBalance": "10100.50",
|
||||
"maintMargin": "200.00",
|
||||
"initialMargin": "2000.00",
|
||||
"maxWithdrawAmount": "8000.00",
|
||||
"crossWalletBalance": "10000.00",
|
||||
"crossUnPnl": "100.50",
|
||||
"availableBalance": "8000.00",
|
||||
},
|
||||
}
|
||||
|
||||
// Mock GetPositions - /fapi/v3/positionRisk
|
||||
case path == "/fapi/v3/positionRisk":
|
||||
respBody = []map[string]interface{}{
|
||||
{
|
||||
"symbol": "BTCUSDT",
|
||||
"positionAmt": "0.5",
|
||||
"entryPrice": "50000.00",
|
||||
"markPrice": "50500.00",
|
||||
"unRealizedProfit": "250.00",
|
||||
"liquidationPrice": "45000.00",
|
||||
"leverage": "10",
|
||||
"positionSide": "LONG",
|
||||
},
|
||||
}
|
||||
|
||||
// Mock GetMarketPrice - /fapi/v3/ticker/price (returns single object)
|
||||
case path == "/fapi/v3/ticker/price":
|
||||
// Get symbol from query parameters
|
||||
symbol := r.URL.Query().Get("symbol")
|
||||
if symbol == "" {
|
||||
symbol = "BTCUSDT"
|
||||
}
|
||||
// Return different price based on symbol
|
||||
price := "50000.00"
|
||||
if symbol == "ETHUSDT" {
|
||||
price = "3000.00"
|
||||
} else if symbol == "INVALIDUSDT" {
|
||||
// Return error response
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": -1121,
|
||||
"msg": "Invalid symbol",
|
||||
})
|
||||
return
|
||||
}
|
||||
respBody = map[string]interface{}{
|
||||
"symbol": symbol,
|
||||
"price": price,
|
||||
}
|
||||
|
||||
// Mock ExchangeInfo - /fapi/v3/exchangeInfo
|
||||
case path == "/fapi/v3/exchangeInfo":
|
||||
respBody = map[string]interface{}{
|
||||
"symbols": []map[string]interface{}{
|
||||
{
|
||||
"symbol": "BTCUSDT",
|
||||
"pricePrecision": 1,
|
||||
"quantityPrecision": 3,
|
||||
"baseAssetPrecision": 8,
|
||||
"quotePrecision": 8,
|
||||
"filters": []map[string]interface{}{
|
||||
{
|
||||
"filterType": "PRICE_FILTER",
|
||||
"tickSize": "0.1",
|
||||
},
|
||||
{
|
||||
"filterType": "LOT_SIZE",
|
||||
"stepSize": "0.001",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"symbol": "ETHUSDT",
|
||||
"pricePrecision": 2,
|
||||
"quantityPrecision": 3,
|
||||
"baseAssetPrecision": 8,
|
||||
"quotePrecision": 8,
|
||||
"filters": []map[string]interface{}{
|
||||
{
|
||||
"filterType": "PRICE_FILTER",
|
||||
"tickSize": "0.01",
|
||||
},
|
||||
{
|
||||
"filterType": "LOT_SIZE",
|
||||
"stepSize": "0.001",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Mock CreateOrder - /fapi/v1/order and /fapi/v3/order
|
||||
case (path == "/fapi/v1/order" || path == "/fapi/v3/order") && r.Method == "POST":
|
||||
// Parse parameters from request to determine symbol
|
||||
bodyBytes, _ := io.ReadAll(r.Body)
|
||||
var orderParams map[string]interface{}
|
||||
json.Unmarshal(bodyBytes, &orderParams)
|
||||
|
||||
symbol := "BTCUSDT"
|
||||
if s, ok := orderParams["symbol"].(string); ok {
|
||||
symbol = s
|
||||
}
|
||||
|
||||
respBody = map[string]interface{}{
|
||||
"orderId": 123456,
|
||||
"symbol": symbol,
|
||||
"status": "FILLED",
|
||||
"side": orderParams["side"],
|
||||
"type": orderParams["type"],
|
||||
}
|
||||
|
||||
// Mock CancelOrder - /fapi/v1/order (DELETE)
|
||||
case path == "/fapi/v1/order" && r.Method == "DELETE":
|
||||
respBody = map[string]interface{}{
|
||||
"orderId": 123456,
|
||||
"symbol": "BTCUSDT",
|
||||
"status": "CANCELED",
|
||||
}
|
||||
|
||||
// Mock ListOpenOrders - /fapi/v1/openOrders and /fapi/v3/openOrders
|
||||
case path == "/fapi/v1/openOrders" || path == "/fapi/v3/openOrders":
|
||||
respBody = []map[string]interface{}{}
|
||||
|
||||
// Mock SetLeverage - /fapi/v1/leverage
|
||||
case path == "/fapi/v1/leverage":
|
||||
respBody = map[string]interface{}{
|
||||
"leverage": 10,
|
||||
"symbol": "BTCUSDT",
|
||||
}
|
||||
|
||||
// Mock SetMarginMode - /fapi/v1/marginType
|
||||
case path == "/fapi/v1/marginType":
|
||||
respBody = map[string]interface{}{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
}
|
||||
|
||||
// Default: empty response
|
||||
default:
|
||||
respBody = map[string]interface{}{}
|
||||
}
|
||||
|
||||
// Serialize response
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(respBody)
|
||||
}))
|
||||
|
||||
// Generate a private key for testing
|
||||
privateKey, _ := crypto.GenerateKey()
|
||||
|
||||
// Create mock trader using mock server's URL
|
||||
traderInstance := &AsterTrader{
|
||||
ctx: context.Background(),
|
||||
user: "0x1234567890123456789012345678901234567890",
|
||||
signer: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
|
||||
privateKey: privateKey,
|
||||
client: mockServer.Client(),
|
||||
baseURL: mockServer.URL, // Use mock server's URL
|
||||
symbolPrecision: make(map[string]SymbolPrecision),
|
||||
}
|
||||
|
||||
// Create base suite
|
||||
baseSuite := testutil.NewTraderTestSuite(t, traderInstance)
|
||||
|
||||
return &AsterTraderTestSuite{
|
||||
TraderTestSuite: baseSuite,
|
||||
mockServer: mockServer,
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup cleans up resources
|
||||
func (s *AsterTraderTestSuite) Cleanup() {
|
||||
if s.mockServer != nil {
|
||||
s.mockServer.Close()
|
||||
}
|
||||
s.TraderTestSuite.Cleanup()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 2. Run common tests using AsterTraderTestSuite
|
||||
// ============================================================
|
||||
|
||||
// TestAsterTrader_InterfaceCompliance tests interface compliance
|
||||
func TestAsterTrader_InterfaceCompliance(t *testing.T) {
|
||||
var _ types.Trader = (*AsterTrader)(nil)
|
||||
}
|
||||
|
||||
// TestAsterTrader_CommonInterface runs all common interface tests using test suite
|
||||
func TestAsterTrader_CommonInterface(t *testing.T) {
|
||||
// Create test suite
|
||||
suite := NewAsterTraderTestSuite(t)
|
||||
defer suite.Cleanup()
|
||||
|
||||
// Run all common interface tests
|
||||
suite.RunAllTests()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 3. Aster specific unit tests
|
||||
// ============================================================
|
||||
|
||||
// TestNewAsterTrader tests creating Aster trader
|
||||
func TestNewAsterTrader(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
user string
|
||||
signer string
|
||||
privateKeyHex string
|
||||
wantError bool
|
||||
errorContains string
|
||||
}{
|
||||
{
|
||||
name: "successful creation",
|
||||
user: "0x1234567890123456789012345678901234567890",
|
||||
signer: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
|
||||
privateKeyHex: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
wantError: false,
|
||||
},
|
||||
{
|
||||
name: "invalid private key format",
|
||||
user: "0x1234567890123456789012345678901234567890",
|
||||
signer: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
|
||||
privateKeyHex: "invalid_key",
|
||||
wantError: true,
|
||||
errorContains: "failed to parse private key",
|
||||
},
|
||||
{
|
||||
name: "private key with 0x prefix",
|
||||
user: "0x1234567890123456789012345678901234567890",
|
||||
signer: "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
|
||||
privateKeyHex: "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
wantError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
at, err := NewAsterTrader(tt.user, tt.signer, tt.privateKeyHex)
|
||||
|
||||
if tt.wantError {
|
||||
assert.Error(t, err)
|
||||
if tt.errorContains != "" {
|
||||
assert.Contains(t, err.Error(), tt.errorContains)
|
||||
}
|
||||
assert.Nil(t, at)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, at)
|
||||
if at != nil {
|
||||
assert.Equal(t, tt.user, at.user)
|
||||
assert.Equal(t, tt.signer, at.signer)
|
||||
assert.NotNil(t, at.privateKey)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user