Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add wd and dep tx binance #1394

Merged
merged 1 commit into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions pkg/response/binance.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
74 changes: 71 additions & 3 deletions pkg/scheduler/update-binance-spot-history.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@
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,
Expand All @@ -87,6 +89,74 @@
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)

Check failure on line 106 in pkg/scheduler/update-binance-spot-history.go

View workflow job for this annotation

GitHub Actions / CI testing

undefined: time.DateTime
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{
Expand All @@ -112,8 +182,6 @@
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")
Expand All @@ -137,7 +205,7 @@
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{
Expand Down
72 changes: 71 additions & 1 deletion pkg/service/binance/adapter/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
18 changes: 17 additions & 1 deletion pkg/service/binance/binance.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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)
}
4 changes: 3 additions & 1 deletion pkg/service/binance/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Loading