bfldb

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 18, 2023 License: MIT Imports: 13 Imported by: 0

README

bfldb GoDoc

BFLDB is a wrapper around Binance's Futures Leaderboard API, in Golang.

This library provides a convenient way to access Binance's futures leaderboard API, which allows you to subscribe to positions opened by leading futures traders (that are sharing their positions publicly via Binance) and query other leaderboard data. Keep in mind that this is not a publicly documented API.

Installation

go get -u github.com/rtunazzz/bfldb

Example usage

Subscribe to a trader's positions
package main

import (
	"context"
	"fmt"

	"github.com/rtunazzz/bfldb"
)

func main() {
	// You can find this UID (encryptedUid) in the end of a leaderboard profile URL. 
	// For example: https://www.binance.com/en/futures-activity/leaderboard/user?encryptedUid=47E6D002EBB1173967A6561F72B9395C
	u := bfldb.NewUser("47E6D002EBB1173967A6561F72B9395C")
	cp, ce := u.SubscribePositions(context.Background())

	for {
		select {
		case position := <-cp:
			// Handle the new position as you need... Send a notification, copytrade...
			fmt.Printf("new position: %+v\n", position)
		case err := <-ce:
			fmt.Println("error has occured:", err)
			break
		}
	}
}

For more examples, check out the examples/ directory.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoPreviousPosition = errors.New("no previous position amount")
)

Functions

func NicknamesToUIDs

func NicknamesToUIDs(pCtx context.Context, nicks []string) (map[string][]string, error)

NicknamesToUIDs gets a list of UIDs for the nicknames provided. Returns a map with nicknames mapped to the UIDs and also any errors that might've occured.

It fires up one goroutine for each nickname and fetches the UIDs.

Types

type BadStatusError added in v1.1.5

type BadStatusError struct {
	Status     string
	StatusCode int
	Body       []byte
}

func (BadStatusError) Error added in v1.1.5

func (e BadStatusError) Error() string

type LdbAPIRes

type LdbAPIRes[T UserPositionData | UserBaseInfo | []NicknameDetails] struct {
	Success       bool        `json:"success"`       // Whether or not the request was successful
	Code          string      `json:"code"`          // Error code, "000000" means success
	Message       string      `json:"message"`       // Error message
	Data          T           `json:"data"`          // Data
	MessageDetail interface{} `json:"messageDetail"` // ???
}

LdbAPIRes represents a response from Binance's Futures LDB API.

func GetOtherLeaderboardBaseInfo added in v1.1.1

func GetOtherLeaderboardBaseInfo(ctx context.Context, UUID string) (LdbAPIRes[UserBaseInfo], error)

GetOtherLeaderboardBaseInfo gets information for the uuid passed in.

func GetOtherPosition added in v1.1.1

func GetOtherPosition(ctx context.Context, UUID string) (LdbAPIRes[UserPositionData], error)

GetOtherPosition gets all currently open positions for an user.

func SearchNickname

func SearchNickname(ctx context.Context, nickname string) (LdbAPIRes[[]NicknameDetails], error)

SearchNickname searches for a nickname.

type NicknameDetails

type NicknameDetails struct {
	EncryptedUID  string `json:"encryptedUid"`
	Nickname      string `json:"nickname"`
	FollowerCount int    `json:"followerCount"`
	UserPhotoURL  string `json:"userPhotoUrl"`
}

type Order added in v1.0.6

type Order struct {
	Direction  TradeDirection // Direction (e.g. LONG / SHORT)
	Ticker     string         // Ticker of the position (e.g. BTCUSDT)
	Amount     float64        // Amount
	ReduceOnly bool           // Whether or not the order is reduce only
	Leverage   int            // Leverage
}

Position represents an order to be used for placing a trade.

type Position

type Position struct {
	Type       PositionType   // Type of the position
	Direction  TradeDirection // Direction (e.g. LONG / SHORT)
	Ticker     string         // Ticker of the position (e.g. BTCUSDT)
	EntryPrice float64        // Entry price
	MarkPrice  float64        // Entry price
	Amount     float64        // Amount
	PrevAmount float64        // previous amount, used for determining position type
	Leverage   int            // Position leverage
	Pnl        float64        // PNL
	Roe        float64        // ROE
}

Position represents a position user is in.

func (Position) ToOrder added in v1.0.6

func (p Position) ToOrder() Order

ToOrder converts a position into an Order.

type PositionType

type PositionType int

PositionType is a type of a position

const (
	Opened          PositionType = iota + 1 // A completely new position
	Closed                                  // A completely closed position
	AddedTo                                 // A new position where there previously already was a position for the same direction and ticker + the amount increased
	PartiallyClosed                         // A new position where there previously already was a position for the same direction and ticker + the amount decreased
)

func DeterminePositionType added in v1.1.6

func DeterminePositionType(amt float64, prevAmt float64) PositionType

DeterminePositionType determines the type of a position, based on the current and previous position size.

func (PositionType) String added in v1.0.9

func (pt PositionType) String() string

type TradeDirection added in v1.0.6

type TradeDirection int

TradeDirection can be either LONG / SHORT

const (
	Short TradeDirection = iota + 1
	Long
)

func (TradeDirection) String added in v1.0.6

func (pd TradeDirection) String() string

type User

type User struct {
	UID string // Encrypted User ID
	// contains filtered or unexported fields
}

User represents one Binance leaderboard User

func NewUser

func NewUser(UID string, opts ...UserOption) *User

NewUser creates a new User with his encrypted UserID.

func (*User) APIBase added in v1.2.1

func (u *User) APIBase() string

APIBase returns the API base used for requests.

func (*User) Delay added in v1.2.0

func (u *User) Delay() time.Duration

Delay returns the delay between requests updating user's current positions

func (*User) GetOtherLeaderboardBaseInfo

func (u *User) GetOtherLeaderboardBaseInfo(ctx context.Context) (LdbAPIRes[UserBaseInfo], error)

GetOtherLeaderboardBaseInfo gets information about an user.

func (*User) GetOtherPosition

func (u *User) GetOtherPosition(ctx context.Context) (LdbAPIRes[UserPositionData], error)

GetOtherPosition gets all currently open positions for an user.

func (*User) Headers added in v1.2.0

func (u *User) Headers() map[string]string

Headers returns headers the client uses for every request.

func (*User) SetAPIBase added in v1.3.0

func (u *User) SetAPIBase(s string)

SetAPIBase sets the API base used for requests.

func (*User) SetDelay added in v1.2.0

func (u *User) SetDelay(d time.Duration)

SetDelay sets the delay between requests updating user's current positions.

func (*User) SetHeaders added in v1.2.0

func (u *User) SetHeaders(h map[string]string)

SetHeaders sets headers the client uses for every request.

func (*User) SubscribePositions

func (u *User) SubscribePositions(ctx context.Context) (<-chan Position, <-chan error)

SubscribePositions subscribes to user's potition details in a new goroutine.

Returns two read-only channels, one with user's positions, other with any errors occured during the subsription.

type UserBaseInfo

type UserBaseInfo struct {
	NickName               string      `json:"nickName"`               // Nickname
	UserPhotoURL           string      `json:"userPhotoUrl"`           // Photo URL
	PositionShared         bool        `json:"positionShared"`         // true if user is sharing their USD positions, false otherwise
	DeliveryPositionShared bool        `json:"deliveryPositionShared"` // true if user is sharing their COIN positions, false otherwise
	FollowingCount         int         `json:"followingCount"`         // How many people user follows
	FollowerCount          int         `json:"followerCount"`          // How many people follow user
	TwitterURL             string      `json:"twitterUrl"`             // Twitter URL
	Introduction           string      `json:"introduction"`           // Introduction (profile description)
	TwShared               bool        `json:"twShared"`               // Sharing their TraderWagon
	IsTwTrader             bool        `json:"isTwTrader"`             // Connected with TraderWagon
	OpenID                 interface{} `json:"openId"`                 // ???
}

UserBaseInfo represents user's data.

type UserOption

type UserOption func(*User)

func WithCustomLogger

func WithCustomLogger(l *log.Logger) UserOption

WithCustomLogger writes all user logs using the logger provided.

func WithCustomRefresh

func WithCustomRefresh(d time.Duration) UserOption

WithCustomRefresh sets the duration between requests updating user's current positions.

func WithHTTPClient

func WithHTTPClient(c *http.Client) UserOption

WithHTTPClient sets user's HTTP Client.

func WithHeaders added in v1.1.5

func WithHeaders(h map[string]string) UserOption

WithHeaders sets headers the client uses for every request.

func WithLogging

func WithLogging() UserOption

WithLogging writes all user logs to STDOUT.

func WithTestnet added in v1.2.1

func WithTestnet() UserOption

WithTestnet uses the testnet API

type UserPositionData

type UserPositionData struct {
	OtherPositionRetList []rawPosition `json:"otherPositionRetList"` // List of positions
	UpdateTimeStamp      int64         `json:"updateTimeStamp"`      // Timestamp
	UpdateTime           []int         `json:"updateTime"`           // Time array in the format of [YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, ... ]
}

UserPositionData represents data about user's positions.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL