bbgo_origin/pkg/strategy/xbalance/strategy.go

371 lines
10 KiB
Go
Raw Normal View History

2021-05-11 17:21:40 +00:00
package xbalance
import (
"context"
2021-05-26 15:24:05 +00:00
"encoding/json"
2021-05-11 17:21:40 +00:00
"fmt"
2021-05-15 16:32:27 +00:00
"sync"
2021-05-11 17:21:40 +00:00
"time"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/slack-go/slack"
2021-05-11 17:21:40 +00:00
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
2022-08-22 18:12:26 +00:00
"github.com/c9s/bbgo/pkg/util/templateutil"
"github.com/c9s/bbgo/pkg/util/timejitter"
2021-05-11 17:21:40 +00:00
)
const ID = "xbalance"
2021-05-15 16:32:27 +00:00
const stateKey = "state-v1"
var priceFixer = fixedpoint.NewFromFloat(0.99)
2021-05-11 17:21:40 +00:00
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
type State struct {
2021-05-15 16:32:27 +00:00
Asset string `json:"asset"`
DailyNumberOfTransfers int `json:"dailyNumberOfTransfers,omitempty"`
2021-05-11 17:21:40 +00:00
DailyAmountOfTransfers fixedpoint.Value `json:"dailyAmountOfTransfers,omitempty"`
Since int64 `json:"since"`
}
2021-05-15 16:32:27 +00:00
func (s *State) IsOver24Hours() bool {
2022-06-17 11:19:51 +00:00
return time.Since(time.Unix(s.Since, 0)) >= 24*time.Hour
2021-05-15 16:32:27 +00:00
}
2021-05-15 16:59:57 +00:00
func (s *State) PlainText() string {
2022-08-22 18:12:26 +00:00
return templateutil.Render(`{{ .Asset }} transfer stats:
2021-05-15 16:59:57 +00:00
daily number of transfers: {{ .DailyNumberOfTransfers }}
daily amount of transfers {{ .DailyAmountOfTransfers.Float64 }}`, s)
}
2021-05-15 16:32:27 +00:00
func (s *State) SlackAttachment() slack.Attachment {
return slack.Attachment{
// Pretext: "",
// Text: text,
2021-05-15 16:51:51 +00:00
Title: s.Asset + " Transfer States",
2021-05-15 16:32:27 +00:00
Fields: []slack.AttachmentField{
{Title: "Total Number of Transfers", Value: fmt.Sprintf("%d", s.DailyNumberOfTransfers), Short: true},
2022-12-26 08:05:21 +00:00
{Title: "Total Amount of Transfers", Value: s.DailyAmountOfTransfers.String(), Short: true},
2021-05-15 16:32:27 +00:00
},
2022-08-22 18:12:26 +00:00
Footer: templateutil.Render("Since {{ . }}", time.Unix(s.Since, 0).Format(time.RFC822)),
2021-05-15 16:32:27 +00:00
}
}
func (s *State) Reset() {
2022-08-22 18:12:26 +00:00
var beginningOfTheDay = types.BeginningOfTheDay(time.Now().Local())
2021-05-15 16:32:27 +00:00
*s = State{
DailyNumberOfTransfers: 0,
DailyAmountOfTransfers: fixedpoint.Zero,
2021-05-15 16:32:27 +00:00
Since: beginningOfTheDay.Unix(),
}
}
type WithdrawalRequest struct {
FromSession string `json:"fromSession"`
ToSession string `json:"toSession"`
Asset string `json:"asset"`
Amount fixedpoint.Value `json:"amount"`
}
func (r *WithdrawalRequest) String() string {
return fmt.Sprintf("WITHDRAWAL REQUEST: sending %s %s from %s -> %s",
r.Amount.FormatString(4),
r.Asset,
r.FromSession,
r.ToSession,
)
}
func (r *WithdrawalRequest) PlainText() string {
return fmt.Sprintf("Withdraw request: sending %s %s from %s -> %s",
r.Amount.FormatString(4),
2021-05-15 16:45:08 +00:00
r.Asset,
r.FromSession,
r.ToSession,
)
}
func (r *WithdrawalRequest) SlackAttachment() slack.Attachment {
var color = "#DC143C"
2022-08-22 18:12:26 +00:00
title := templateutil.Render(`Withdraw Request {{ .Asset }}`, r)
return slack.Attachment{
// Pretext: "",
// Text: text,
Title: title,
Color: color,
Fields: []slack.AttachmentField{
{Title: "Asset", Value: r.Asset, Short: true},
{Title: "Amount", Value: r.Amount.FormatString(4), Short: true},
{Title: "From", Value: r.FromSession},
{Title: "To", Value: r.ToSession},
},
2022-08-22 18:12:26 +00:00
Footer: templateutil.Render("Time {{ . }}", time.Now().Format(time.RFC822)),
// FooterIcon: "",
}
}
2021-05-26 15:24:05 +00:00
type Address struct {
Address string `json:"address"`
AddressTag string `json:"addressTag"`
Network string `json:"network"`
ForeignFee fixedpoint.Value `json:"foreignFee"`
2021-05-26 15:24:05 +00:00
}
func (a *Address) UnmarshalJSON(body []byte) error {
var arg interface{}
err := json.Unmarshal(body, &arg)
if err != nil {
return err
}
switch argT := arg.(type) {
case string:
a.Address = argT
return nil
}
2021-05-26 15:37:08 +00:00
type addressTemplate Address
return json.Unmarshal(body, (*addressTemplate)(a))
2021-05-26 15:24:05 +00:00
}
2021-05-11 17:21:40 +00:00
type Strategy struct {
Interval types.Duration `json:"interval"`
2021-05-26 15:24:05 +00:00
Addresses map[string]Address `json:"addresses"`
2021-05-11 17:21:40 +00:00
2021-05-15 16:50:15 +00:00
MaxDailyNumberOfTransfer int `json:"maxDailyNumberOfTransfer"`
MaxDailyAmountOfTransfer fixedpoint.Value `json:"maxDailyAmountOfTransfer"`
2021-05-11 17:21:40 +00:00
2021-05-18 00:32:00 +00:00
CheckOnStart bool `json:"checkOnStart"`
2021-05-11 17:21:40 +00:00
Asset string `json:"asset"`
// Low is the low balance level for triggering transfer
Low fixedpoint.Value `json:"low"`
// Middle is the middle balance level used for re-fill asset
Middle fixedpoint.Value `json:"middle"`
2021-09-03 06:25:26 +00:00
Verbose bool `json:"verbose"`
State *State `persistence:"state"`
2021-05-11 17:21:40 +00:00
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) CrossSubscribe(sessions map[string]*bbgo.ExchangeSession) {}
2021-05-11 17:21:40 +00:00
func (s *Strategy) checkBalance(ctx context.Context, sessions map[string]*bbgo.ExchangeSession) {
2021-09-03 06:25:26 +00:00
if s.Verbose {
bbgo.Notify("📝 Checking %s low balance level exchange session...", s.Asset)
2021-09-03 06:25:26 +00:00
}
var total fixedpoint.Value
for _, session := range sessions {
if b, ok := session.GetAccount().Balance(s.Asset); ok {
total = total.Add(b.Total())
2021-09-03 06:25:26 +00:00
}
}
2021-05-11 17:21:40 +00:00
lowLevelSession, lowLevelBalance, err := s.findLowBalanceLevelSession(sessions)
if err != nil {
bbgo.Notify("Can not find low balance level session: %s", err.Error())
2021-09-03 06:25:26 +00:00
log.WithError(err).Errorf("Can not find low balance level session")
2021-05-11 17:21:40 +00:00
return
}
if lowLevelSession == nil {
2021-09-03 06:25:26 +00:00
if s.Verbose {
bbgo.Notify("✅ All %s balances are looking good, total value: %v", s.Asset, total)
2021-09-03 06:25:26 +00:00
}
2021-05-11 17:21:40 +00:00
return
}
bbgo.Notify("⚠️ Found low level %s balance from session %s: %v", s.Asset, lowLevelSession.Name, lowLevelBalance)
2021-05-11 17:21:40 +00:00
middle := s.Middle
if middle.IsZero() {
middle = total.Div(fixedpoint.NewFromInt(int64(len(sessions)))).Mul(priceFixer)
bbgo.Notify("Total value %v %s, setting middle to %v", total, s.Asset, middle)
}
requiredAmount := middle.Sub(lowLevelBalance.Available)
2021-05-11 17:21:40 +00:00
bbgo.Notify("Need %v %s to satisfy the middle balance level %v", requiredAmount, s.Asset, middle)
2021-05-11 17:21:40 +00:00
fromSession, _, err := s.findHighestBalanceLevelSession(sessions, requiredAmount)
if err != nil || fromSession == nil {
bbgo.Notify("Can not find session with enough balance")
2021-05-11 17:21:40 +00:00
log.WithError(err).Errorf("can not find session with enough balance")
return
}
withdrawalService, ok := fromSession.Exchange.(types.ExchangeWithdrawalService)
if !ok {
log.Errorf("exchange %s does not implement withdrawal service, we can not withdrawal", fromSession.ExchangeName)
return
}
if !fromSession.Withdrawal {
bbgo.Notify("The withdrawal function exchange session %s is not enabled", fromSession.Name)
log.Errorf("The withdrawal function of exchange session %s is not enabled", fromSession.Name)
return
}
2021-05-11 17:21:40 +00:00
toAddress, ok := s.Addresses[lowLevelSession.Name]
if !ok {
log.Errorf("%s address of session %s not found", s.Asset, lowLevelSession.Name)
bbgo.Notify("%s address of session %s not found", s.Asset, lowLevelSession.Name)
2021-05-11 17:21:40 +00:00
return
}
if toAddress.ForeignFee.Sign() > 0 {
requiredAmount = requiredAmount.Add(toAddress.ForeignFee)
}
if s.State != nil {
2021-05-15 16:50:15 +00:00
if s.MaxDailyNumberOfTransfer > 0 {
if s.State.DailyNumberOfTransfers >= s.MaxDailyNumberOfTransfer {
bbgo.Notify("⚠️ Exceeded %s max daily number of transfers %d (current %d), skipping transfer...",
2021-05-15 16:50:15 +00:00
s.Asset,
s.MaxDailyNumberOfTransfer,
s.State.DailyNumberOfTransfers)
2021-05-15 16:50:15 +00:00
return
}
}
if s.MaxDailyAmountOfTransfer.Sign() > 0 {
if s.State.DailyAmountOfTransfers.Compare(s.MaxDailyAmountOfTransfer) >= 0 {
bbgo.Notify("⚠️ Exceeded %s max daily amount of transfers %v (current %v), skipping transfer...",
2021-05-15 16:50:15 +00:00
s.Asset,
s.MaxDailyAmountOfTransfer,
s.State.DailyAmountOfTransfers)
2021-05-15 16:50:15 +00:00
return
}
}
}
bbgo.Notify(&WithdrawalRequest{
FromSession: fromSession.Name,
ToSession: lowLevelSession.Name,
Asset: s.Asset,
Amount: requiredAmount,
})
if err := withdrawalService.Withdraw(ctx, s.Asset, requiredAmount, toAddress.Address, &types.WithdrawalOptions{
2021-05-26 15:24:05 +00:00
Network: toAddress.Network,
AddressTag: toAddress.AddressTag,
}); err != nil {
2021-05-11 17:21:40 +00:00
log.WithError(err).Errorf("withdrawal failed")
bbgo.Notify("withdrawal request failed, error: %v", err)
return
2021-05-11 17:21:40 +00:00
}
bbgo.Notify("%s withdrawal request sent", s.Asset)
2021-05-15 16:32:27 +00:00
if s.State != nil {
if s.State.IsOver24Hours() {
s.State.Reset()
2021-05-15 16:32:27 +00:00
}
s.State.DailyNumberOfTransfers += 1
s.State.DailyAmountOfTransfers = s.State.DailyAmountOfTransfers.Add(requiredAmount)
2022-10-03 10:45:24 +00:00
bbgo.Sync(ctx, s)
2021-05-15 16:32:27 +00:00
}
2021-05-11 17:21:40 +00:00
}
func (s *Strategy) findHighestBalanceLevelSession(
sessions map[string]*bbgo.ExchangeSession, requiredAmount fixedpoint.Value,
) (*bbgo.ExchangeSession, types.Balance, error) {
2021-05-11 17:21:40 +00:00
var balance types.Balance
var maxBalanceLevel = fixedpoint.Zero
2021-05-11 17:21:40 +00:00
var maxBalanceSession *bbgo.ExchangeSession = nil
for sessionID := range s.Addresses {
session, ok := sessions[sessionID]
if !ok {
return nil, balance, fmt.Errorf("session %s does not exist", sessionID)
}
if b, ok := session.GetAccount().Balance(s.Asset); ok {
if b.Available.Sub(requiredAmount).Compare(s.Low) > 0 && b.Available.Compare(maxBalanceLevel) > 0 {
2021-05-11 17:21:40 +00:00
maxBalanceLevel = b.Available
maxBalanceSession = session
balance = b
}
}
}
return maxBalanceSession, balance, nil
}
func (s *Strategy) findLowBalanceLevelSession(sessions map[string]*bbgo.ExchangeSession) (*bbgo.ExchangeSession, types.Balance, error) {
var balance types.Balance
for sessionID := range s.Addresses {
session, ok := sessions[sessionID]
if !ok {
return nil, balance, fmt.Errorf("session %s does not exist", sessionID)
}
balance, ok = session.GetAccount().Balance(s.Asset)
2021-05-11 17:21:40 +00:00
if ok {
if balance.Available.Compare(s.Low) <= 0 {
2021-05-11 17:21:40 +00:00
return session, balance, nil
}
}
}
return nil, balance, nil
}
2021-05-15 16:32:27 +00:00
func (s *Strategy) newDefaultState() *State {
return &State{
Asset: s.Asset,
DailyNumberOfTransfers: 0,
DailyAmountOfTransfers: fixedpoint.Zero,
2021-05-15 16:32:27 +00:00
}
}
2021-05-11 17:21:40 +00:00
func (s *Strategy) CrossRun(ctx context.Context, _ bbgo.OrderExecutionRouter, sessions map[string]*bbgo.ExchangeSession) error {
if s.Interval == 0 {
return errors.New("interval can not be zero")
}
if s.State == nil {
s.State = s.newDefaultState()
2021-05-15 16:32:27 +00:00
}
2022-10-03 08:01:08 +00:00
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
2021-05-15 16:32:27 +00:00
defer wg.Done()
})
2021-05-18 00:32:00 +00:00
if s.CheckOnStart {
s.checkBalance(ctx, sessions)
}
2021-05-11 17:21:40 +00:00
go func() {
ticker := time.NewTicker(timejitter.Milliseconds(s.Interval.Duration(), 1000))
2021-05-11 17:21:40 +00:00
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.checkBalance(ctx, sessions)
}
}
}()
return nil
}