From 264dc8b865b0b1c8886cbebb325bb2723343d99f Mon Sep 17 00:00:00 2001 From: nguyenhuy1812 Date: Fri, 24 May 2024 12:36:50 +0700 Subject: [PATCH] fix: add wd and dep tx binance --- pkg/response/binance.go | 39 +++++++++++ pkg/scheduler/update-binance-spot-history.go | 74 +++++++++++++++++++- pkg/service/binance/adapter/adapter.go | 72 ++++++++++++++++++- pkg/service/binance/binance.go | 18 ++++- pkg/service/binance/service.go | 4 +- 5 files changed, 201 insertions(+), 6 deletions(-) diff --git a/pkg/response/binance.go b/pkg/response/binance.go index bf32257e..13581ba9 100644 --- a/pkg/response/binance.go +++ b/pkg/response/binance.go @@ -244,3 +244,42 @@ type BinanceSpotTransactionResponse struct { CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } + +type BinanceDepositHistory struct { + Id string `json:"id"` + Amount string `json:"amount"` + Coin string `json:"coin"` + Network string `json:"network"` + Status int `json:"status"` + Address string `json:"address"` + AddressTag string `json:"addressTag"` + TxId string `json:"txId"` + InsertTime int64 `json:"insertTime"` + TransferType int `json:"transferType"` + ConfirmTimes string `json:"confirmTimes"` + UnlockConfirm int `json:"unlockConfirm"` + WalletType int `json:"walletType"` + WithdrawOrderId string `json:"withdrawOrderId"` + CompleteTime string `json:"completeTime"` +} + +type BinanceWithdrawHistory struct { + Id string `json:"id"` + Amount string `json:"amount"` + Coin string `json:"coin"` + Network string `json:"network"` + Status int `json:"status"` + Address string `json:"address"` + AddressTag string `json:"addressTag"` + TxId string `json:"txId"` + InsertTime int64 `json:"insertTime"` + TransferType int `json:"transferType"` + ConfirmTimes string `json:"confirmTimes"` + UnlockConfirm int `json:"unlockConfirm"` + WalletType int `json:"walletType"` + WithdrawOrderId string `json:"withdrawOrderId"` + CompleteTime string `json:"completeTime"` + Info string `json:"info"` + ConfirmNo int `json:"confirmNo"` + TxKey string `json:"txKey"` +} diff --git a/pkg/scheduler/update-binance-spot-history.go b/pkg/scheduler/update-binance-spot-history.go index 70b3d1c0..2e34ffb6 100644 --- a/pkg/scheduler/update-binance-spot-history.go +++ b/pkg/scheduler/update-binance-spot-history.go @@ -66,6 +66,8 @@ func (s *updateBinanceSpotHistory) schedulerUpdate() error { s.log.Fields(logger.Fields{"profileId": acc.ProfileId}).Error(err, "[updateBinanceSpotHistory] - BinanceTracking.FirstOrCreate() fail to first or create binance tracking ") continue } + startTime := strconv.Itoa(int(binanceTracking.SpotLastTime.UnixMilli())) + endTime := strconv.Itoa(int(binanceTracking.SpotLastTime.Add(1 * time.Hour).UnixMilli())) // update status of NEW order in case it filled or cancel newTxs, _ := s.entity.GetRepo().BinanceSpotTransaction.List(binancespottransaction.ListQuery{ ProfileId: acc.ProfileId, @@ -87,6 +89,74 @@ func (s *updateBinanceSpotHistory) schedulerUpdate() error { continue } } + // withdrawTx + wdTxs, err := s.svc.Binance.GetWithdrawHistory(acc.ApiKey, acc.ApiSecret, startTime, endTime) + if err != nil { + s.log.Fields(logger.Fields{"profileId": acc.ProfileId}).Error(err, "[updateBinanceSpotHistory] - svc.Binance.GetWithdrawHistory() fail to get spot txs") + break + } + for _, wdTx := range wdTxs { + status := "" + switch wdTx.Status { + case 6: + status = "FILLED" + case 1: + status = "CANCELED" + } + timeParsed, _ := time.Parse(time.DateTime, wdTx.CompleteTime) + priceInUsd := "" + usdtpair := fmt.Sprintf("%sUSDT", wdTx.Coin) + ticks, _ := s.svc.Binance.Kline(usdtpair, binance.Interval1m, timeParsed.UnixMilli(), 0) + if len(ticks) > 0 && len(ticks[0]) > 0 { + priceInUsd = ticks[0][4].(string) + } + + err = s.entity.GetRepo().BinanceSpotTransaction.Create(&model.BinanceSpotTransaction{ + ProfileId: acc.ProfileId, + Symbol: wdTx.Coin, + OrigQty: wdTx.Amount, + ExecutedQty: wdTx.Amount, + Status: status, + Time: timeParsed.UnixMilli(), + CreatedAt: timeParsed, + Side: "WITHDRAW", + PriceInUsd: priceInUsd, + }) + } + // deposit + depositTxs, err := s.svc.Binance.GetDepositHistory(acc.ApiKey, acc.ApiSecret, startTime, endTime) + if err != nil { + s.log.Fields(logger.Fields{"profileId": acc.ProfileId}).Error(err, "[updateBinanceSpotHistory] - svc.Binance.GetDepositHistory() fail to get spot txs") + break + } + for _, depositTx := range depositTxs { + status := "" + switch depositTx.Status { + case 1: + status = "FILLED" + case 0: + status = "PENDING" + case 7: + status = "CANCELED" + } + priceInUsd := "" + usdtpair := fmt.Sprintf("%sUSDT", depositTx.Coin) + ticks, _ := s.svc.Binance.Kline(usdtpair, binance.Interval1m, depositTx.InsertTime, 0) + if len(ticks) > 0 && len(ticks[0]) > 0 { + priceInUsd = ticks[0][4].(string) + } + err = s.entity.GetRepo().BinanceSpotTransaction.Create(&model.BinanceSpotTransaction{ + ProfileId: acc.ProfileId, + Symbol: depositTx.Coin, + OrigQty: depositTx.Amount, + ExecutedQty: depositTx.Amount, + Status: status, + Time: depositTx.InsertTime, + CreatedAt: time.UnixMilli(depositTx.InsertTime), + Side: "DEPOSIT", + PriceInUsd: priceInUsd, + }) + } symbols := []string{} assetBal, _, _, _ := s.entity.GetBinanceAssets(request.GetBinanceAssetsRequest{ @@ -112,8 +182,6 @@ func (s *updateBinanceSpotHistory) schedulerUpdate() error { for _, symbol := range symbols { pairs := symbolPairs[symbol] for _, p := range pairs { - startTime := strconv.Itoa(int(binanceTracking.SpotLastTime.UnixMilli())) - endTime := strconv.Itoa(int(binanceTracking.SpotLastTime.Add(1 * time.Hour).UnixMilli())) txs, err := s.svc.Binance.GetSpotTransactions(acc.ApiKey, acc.ApiSecret, p, startTime, endTime) if err != nil { s.log.Fields(logger.Fields{"profileId": acc.ProfileId}).Error(err, "[updateBinanceSpotHistory] - svc.Binance.GetSpotTransactions() fail to get spot txs") @@ -137,7 +205,7 @@ func (s *updateBinanceSpotHistory) schedulerUpdate() error { break } if len(ticks) > 0 && len(ticks[0]) > 0 { - priceInUsd = ticks[0][0] + priceInUsd = ticks[0][4].(string) } } err = s.entity.GetRepo().BinanceSpotTransaction.Create(&model.BinanceSpotTransaction{ diff --git a/pkg/service/binance/adapter/adapter.go b/pkg/service/binance/adapter/adapter.go index 84a9b001..1a7566f6 100644 --- a/pkg/service/binance/adapter/adapter.go +++ b/pkg/service/binance/adapter/adapter.go @@ -380,7 +380,7 @@ func GetSpotTransaction(apiKey, apiSecret, symbol, startTime, endTime string) (t return txs, nil } -func Kline(symbol, interval string, startTime, endTime int64) (tickers [][]string, err error) { +func Kline(symbol, interval string, startTime, endTime int64) (tickers [][]interface{}, err error) { // http request req, err := http.NewRequest("GET", url+"/api/v3/klines", nil) if err != nil { @@ -465,3 +465,73 @@ func GetSpotTransactionByOrderId(apiKey, apiSecret, symbol string, orderId int64 } return } + +func GetDepositHistory(apiKey, apiSecret, startTime, endTime string) (txs []response.BinanceDepositHistory, err error) { + q := map[string]string{ + "timestamp": strconv.Itoa(int(time.Now().UnixMilli())), + "startTime": startTime, + "endTime": endTime, + "recvWindow": "59000", + } + queryString := butils.QueryString(q, apiSecret) + + // http request + req, err := http.NewRequest("GET", url+"/sapi/v1/capital/deposit/hisrec?"+queryString, nil) + if err != nil { + return nil, err + } + + resp, err := do(req, apiKey, 0) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + resBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + // decode response json + err = json.Unmarshal(resBody, &txs) + if err != nil { + return nil, err + } + + return txs, nil +} + +func GetWithdrawHistory(apiKey, apiSecret, startTime, endTime string) (txs []response.BinanceWithdrawHistory, err error) { + q := map[string]string{ + "timestamp": strconv.Itoa(int(time.Now().UnixMilli())), + "startTime": startTime, + "endTime": endTime, + "recvWindow": "59000", + } + queryString := butils.QueryString(q, apiSecret) + + // http request + req, err := http.NewRequest("GET", url+"/sapi/v1/capital/withdraw/history?"+queryString, nil) + if err != nil { + return nil, err + } + + resp, err := do(req, apiKey, 0) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + resBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + // decode response json + err = json.Unmarshal(resBody, &txs) + if err != nil { + return nil, err + } + + return txs, nil +} diff --git a/pkg/service/binance/binance.go b/pkg/service/binance/binance.go index b2e4e107..73aab43b 100644 --- a/pkg/service/binance/binance.go +++ b/pkg/service/binance/binance.go @@ -536,7 +536,7 @@ const ( Interval1M Interval = "1M" ) -func (b *Binance) Kline(symbol string, interval Interval, startTime int64, endTime int64) ([][]string, error) { +func (b *Binance) Kline(symbol string, interval Interval, startTime int64, endTime int64) ([][]interface{}, error) { return badapter.Kline(symbol, string(interval), startTime, endTime) } @@ -547,3 +547,19 @@ func (b *Binance) GetSpotTransactionByOrderId(apiKey, apiSecret, symbol string, // get spot transaction return badapter.GetSpotTransactionByOrderId(apiKey, apiSecret, symbol, orderId) } + +func (b *Binance) GetWithdrawHistory(apiKey, apiSecret, startTime, endTime string) ([]response.BinanceWithdrawHistory, error) { + b.logger.Debug("start binance.GetSpotTransactionByOrderId()") + defer b.logger.Debug("end binance.GetSpotTransactionByOrderId()") + + // get spot transaction + return badapter.GetWithdrawHistory(apiKey, apiSecret, startTime, endTime) +} + +func (b *Binance) GetDepositHistory(apiKey, apiSecret, startTime, endTime string) ([]response.BinanceDepositHistory, error) { + b.logger.Debug("start binance.GetSpotTransactionByOrderId()") + defer b.logger.Debug("end binance.GetSpotTransactionByOrderId()") + + // get spot transaction + return badapter.GetDepositHistory(apiKey, apiSecret, startTime, endTime) +} diff --git a/pkg/service/binance/service.go b/pkg/service/binance/service.go index da307dd9..1aeede58 100644 --- a/pkg/service/binance/service.go +++ b/pkg/service/binance/service.go @@ -21,5 +21,7 @@ type Service interface { GetPrice(symbol string) (*response.BinanceApiTickerPriceResponse, error) GetSpotTransactions(apiKey, apiSecret, symbol, startTime, endTime string) ([]response.BinanceSpotTransactionResponse, error) GetSpotTransactionByOrderId(apiKey, apiSecret, symbol string, orderId int64) (*response.BinanceSpotTransactionResponse, error) - Kline(symbol string, interval Interval, startTime int64, endTime int64) ([][]string, error) + Kline(symbol string, interval Interval, startTime int64, endTime int64) ([][]interface{}, error) + GetWithdrawHistory(apiKey, apiSecret, startTime, endTime string) ([]response.BinanceWithdrawHistory, error) + GetDepositHistory(apiKey, apiSecret, startTime, endTime string) ([]response.BinanceDepositHistory, error) }