order

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2022 License: MIT Imports: 12 Imported by: 0

README

GoCryptoTrader package Orders

Build Status Software License GoDoc Coverage Status Go Report Card

This orders package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progress on this Trello board: https://trello.com/b/ZAhMhpOy/gocryptotrader.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

Current Features for orders

  • This package services the exchanges package with order handling.
    • Creation of order
    • Deletion of order
    • Order tracking
Please click GoDocs chevron above to view current GoDoc information for this package

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

bc1qk0jareu4jytc0cfrhr5wgshsq8282awpavfahc

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrExchangeLimitNotLoaded defines if an exchange does not have minmax
	// values
	ErrExchangeLimitNotLoaded = errors.New("exchange limits not loaded")
	// ErrPriceBelowMin is when the price is lower than the minimum price
	// limit accepted by the exchange
	ErrPriceBelowMin = errors.New("price below minimum limit")
	// ErrPriceExceedsMax is when the price is higher than the maximum price
	// limit accepted by the exchange
	ErrPriceExceedsMax = errors.New("price exceeds maximum limit")
	// ErrPriceExceedsStep is when the price is not divisible by its step
	ErrPriceExceedsStep = errors.New("price exceeds step limit")
	// ErrAmountBelowMin is when the amount is lower than the minimum amount
	// limit accepted by the exchange
	ErrAmountBelowMin = errors.New("amount below minimum limit")
	// ErrAmountExceedsMax is when the amount is higher than the maximum amount
	// limit accepted by the exchange
	ErrAmountExceedsMax = errors.New("amount exceeds maximum limit")
	// ErrAmountExceedsStep is when the amount is not divisible by its step
	ErrAmountExceedsStep = errors.New("amount exceeds step limit")
	// ErrNotionalValue is when the notional value does not exceed currency pair
	// requirements
	ErrNotionalValue = errors.New("total notional value is under minimum limit")
	// ErrMarketAmountBelowMin is when the amount is lower than the minimum
	// amount limit accepted by the exchange for a market order
	ErrMarketAmountBelowMin = errors.New("market order amount below minimum limit")
	// ErrMarketAmountExceedsMax is when the amount is higher than the maximum
	// amount limit accepted by the exchange for a market order
	ErrMarketAmountExceedsMax = errors.New("market order amount exceeds maximum limit")
	// ErrMarketAmountExceedsStep is when the amount is not divisible by its
	// step for a market order
	ErrMarketAmountExceedsStep = errors.New("market order amount exceeds step limit")
)
View Source
var (
	ErrSubmissionIsNil            = errors.New("order submission is nil")
	ErrCancelOrderIsNil           = errors.New("cancel order is nil")
	ErrGetOrdersRequestIsNil      = errors.New("get order request is nil")
	ErrModifyOrderIsNil           = errors.New("modify order request is nil")
	ErrPairIsEmpty                = errors.New("order pair is empty")
	ErrAssetNotSet                = errors.New("order asset type is not set")
	ErrSideIsInvalid              = errors.New("order side is invalid")
	ErrTypeIsInvalid              = errors.New("order type is invalid")
	ErrAmountIsInvalid            = errors.New("order amount is equal or less than zero")
	ErrPriceMustBeSetIfLimitOrder = errors.New("order price must be set if limit order type is desired")
	ErrOrderIDNotSet              = errors.New("order id or client order id is not set")
)

var error definitions

Functions

func FilterOrdersByCurrencies

func FilterOrdersByCurrencies(orders *[]Detail, currencies []currency.Pair)

FilterOrdersByCurrencies removes any order details that do not match the provided currency list. It is forgiving in that the provided currencies can match quote or base currencies

func FilterOrdersBySide

func FilterOrdersBySide(orders *[]Detail, side Side)

FilterOrdersBySide removes any order details that don't match the order status provided

func FilterOrdersByTimeRange

func FilterOrdersByTimeRange(orders *[]Detail, startTime, endTime time.Time)

FilterOrdersByTimeRange removes any OrderDetails outside of the time range

func FilterOrdersByType

func FilterOrdersByType(orders *[]Detail, orderType Type)

FilterOrdersByType removes any order details that don't match the order type provided

func SortOrdersByCurrency

func SortOrdersByCurrency(orders *[]Detail, reverse bool)

SortOrdersByCurrency the caller function to sort orders

func SortOrdersByDate

func SortOrdersByDate(orders *[]Detail, reverse bool)

SortOrdersByDate the caller function to sort orders

func SortOrdersByPrice

func SortOrdersByPrice(orders *[]Detail, reverse bool)

SortOrdersByPrice the caller function to sort orders

func SortOrdersBySide

func SortOrdersBySide(orders *[]Detail, reverse bool)

SortOrdersBySide the caller function to sort orders

func SortOrdersByType

func SortOrdersByType(orders *[]Detail, reverse bool)

SortOrdersByType the caller function to sort orders

Types

type ByCurrency

type ByCurrency []Detail

ByCurrency used for sorting orders by order currency

func (ByCurrency) Len

func (b ByCurrency) Len() int

func (ByCurrency) Less

func (b ByCurrency) Less(i, j int) bool

func (ByCurrency) Swap

func (b ByCurrency) Swap(i, j int)

type ByDate

type ByDate []Detail

ByDate used for sorting orders by order date

func (ByDate) Len

func (b ByDate) Len() int

func (ByDate) Less

func (b ByDate) Less(i, j int) bool

func (ByDate) Swap

func (b ByDate) Swap(i, j int)

type ByOrderSide

type ByOrderSide []Detail

ByOrderSide used for sorting orders by order side (buy sell)

func (ByOrderSide) Len

func (b ByOrderSide) Len() int

func (ByOrderSide) Less

func (b ByOrderSide) Less(i, j int) bool

func (ByOrderSide) Swap

func (b ByOrderSide) Swap(i, j int)

type ByOrderType

type ByOrderType []Detail

ByOrderType used for sorting orders by order type

func (ByOrderType) Len

func (b ByOrderType) Len() int

func (ByOrderType) Less

func (b ByOrderType) Less(i, j int) bool

func (ByOrderType) Swap

func (b ByOrderType) Swap(i, j int)

type ByPrice

type ByPrice []Detail

ByPrice used for sorting orders by price

func (ByPrice) Len

func (b ByPrice) Len() int

func (ByPrice) Less

func (b ByPrice) Less(i, j int) bool

func (ByPrice) Swap

func (b ByPrice) Swap(i, j int)

type Cancel

type Cancel struct {
	Price         float64
	Amount        float64
	Exchange      string
	ID            string
	ClientOrderID string
	AccountID     string
	ClientID      string
	WalletAddress string
	Type          Type
	Side          Side
	Status        Status
	AssetType     asset.Item
	Date          time.Time
	Pair          currency.Pair
	Symbol        string
	Trades        []TradeHistory
}

Cancel contains all properties that may be required to cancel an order on an exchange Each exchange has their own requirements, so not all fields are required to be populated

func (*Cancel) PairAssetRequired

func (c *Cancel) PairAssetRequired() validate.Checker

PairAssetRequired is a validation check for when a cancel request requires an asset type and currency pair to be present

func (*Cancel) StandardCancel

func (c *Cancel) StandardCancel() validate.Checker

StandardCancel defines an option in the validator to make sure an ID is set for a standard cancel

func (*Cancel) Validate

func (c *Cancel) Validate(opt ...validate.Checker) error

Validate checks internal struct requirements

type CancelAllResponse

type CancelAllResponse struct {
	Status map[string]string
	Count  int64
}

CancelAllResponse returns the status from attempting to cancel all orders on an exchange

type CancelBatchResponse

type CancelBatchResponse struct {
	Status map[string]string
}

CancelBatchResponse returns the status of orders that have been requested for cancellation

type ClassificationError

type ClassificationError struct {
	Exchange string
	OrderID  string
	Err      error
}

ClassificationError returned when an order status side or type cannot be recognised

func (*ClassificationError) Error

func (o *ClassificationError) Error() string

type Detail

type Detail struct {
	ImmediateOrCancel    bool
	HiddenOrder          bool
	FillOrKill           bool
	PostOnly             bool
	Leverage             float64
	Price                float64
	Amount               float64
	LimitPriceUpper      float64
	LimitPriceLower      float64
	TriggerPrice         float64
	AverageExecutedPrice float64
	TargetAmount         float64
	ExecutedAmount       float64
	RemainingAmount      float64
	Cost                 float64
	CostAsset            currency.Code
	Fee                  float64
	FeeAsset             currency.Code
	Exchange             string
	InternalOrderID      string
	ID                   string
	ClientOrderID        string
	AccountID            string
	ClientID             string
	WalletAddress        string
	Type                 Type
	Side                 Side
	Status               Status
	AssetType            asset.Item
	Date                 time.Time
	CloseTime            time.Time
	LastUpdated          time.Time
	Pair                 currency.Pair
	Trades               []TradeHistory
	StopPrice            float64
	TimeInForce          string
}

Detail contains all properties of an order Each exchange has their own requirements, so not all fields are required to be populated

func (*Detail) Copy

func (d *Detail) Copy() Detail

Copy will return a copy of Detail

func (*Detail) GenerateInternalOrderID

func (d *Detail) GenerateInternalOrderID()

GenerateInternalOrderID sets a new V4 order ID or a V5 order ID if the V4 function returns an error

func (*Detail) InferCostsAndTimes

func (d *Detail) InferCostsAndTimes()

InferCostsAndTimes infer order costs using execution information and times when available

func (*Detail) IsActive

func (d *Detail) IsActive() bool

IsActive returns true if an order has a status that indicates it is currently available on the exchange

func (*Detail) IsInactive

func (d *Detail) IsInactive() bool

IsInactive returns true if an order has a status that indicates it is currently not available on the exchange

func (*Detail) MatchFilter

func (d *Detail) MatchFilter(f *Filter) bool

MatchFilter will return true if a detail matches the filter criteria empty elements are ignored

func (*Detail) UpdateOrderFromDetail

func (d *Detail) UpdateOrderFromDetail(m *Detail)

UpdateOrderFromDetail Will update an order detail (used in order management) by comparing passed in and existing values

func (*Detail) UpdateOrderFromModify

func (d *Detail) UpdateOrderFromModify(m *Modify)

UpdateOrderFromModify Will update an order detail (used in order management) by comparing passed in and existing values

type ExecutionLimits

type ExecutionLimits struct {
	// contains filtered or unexported fields
}

ExecutionLimits defines minimum and maximum values in relation to order size, order pricing, total notional values, total maximum orders etc for execution on an exchange.

func (*ExecutionLimits) CheckOrderExecutionLimits

func (e *ExecutionLimits) CheckOrderExecutionLimits(a asset.Item, cp currency.Pair, price, amount float64, orderType Type) error

CheckOrderExecutionLimits checks to see if the price and amount conforms with exchange level order execution limits

func (*ExecutionLimits) GetOrderExecutionLimits

func (e *ExecutionLimits) GetOrderExecutionLimits(a asset.Item, cp currency.Pair) (*Limits, error)

GetOrderExecutionLimits returns the exchange limit parameters for a currency

func (*ExecutionLimits) LoadLimits

func (e *ExecutionLimits) LoadLimits(levels []MinMaxLevel) error

LoadLimits loads all limits levels into memory

type Filter

type Filter struct {
	Exchange        string
	InternalOrderID string
	ID              string
	ClientOrderID   string
	AccountID       string
	ClientID        string
	WalletAddress   string
	Type            Type
	Side            Side
	Status          Status
	AssetType       asset.Item
	Pair            currency.Pair
}

Filter contains all properties an order can be filtered for empty strings indicate to ignore the property otherwise all need to match

type GetOrdersRequest

type GetOrdersRequest struct {
	Type      Type
	Side      Side
	StartTime time.Time
	EndTime   time.Time
	OrderID   string
	// Currencies Empty array = all currencies. Some endpoints only support
	// singular currency enquiries
	Pairs     currency.Pairs
	AssetType asset.Item
}

GetOrdersRequest used for GetOrderHistory and GetOpenOrders wrapper functions

func (*GetOrdersRequest) Validate

func (g *GetOrdersRequest) Validate(opt ...validate.Checker) error

Validate checks internal struct requirements

type Limits

type Limits struct {
	// contains filtered or unexported fields
}

Limits defines total limit values for an associated currency to be checked before execution on an exchange

func (*Limits) ConformToAmount

func (l *Limits) ConformToAmount(amount float64) float64

ConformToAmount (POC) conforms amount to its amount interval

func (*Limits) ConformToDecimalAmount

func (l *Limits) ConformToDecimalAmount(amount decimal.Decimal) decimal.Decimal

ConformToDecimalAmount (POC) conforms amount to its amount interval

func (*Limits) Conforms

func (l *Limits) Conforms(price, amount float64, orderType Type) error

Conforms checks outbound parameters

type MinMaxLevel

type MinMaxLevel struct {
	Pair                currency.Pair
	Asset               asset.Item
	MinPrice            float64
	MaxPrice            float64
	StepPrice           float64
	MultiplierUp        float64
	MultiplierDown      float64
	MultiplierDecimal   float64
	AveragePriceMinutes int64
	MinAmount           float64
	MaxAmount           float64
	StepAmount          float64
	MinNotional         float64
	MaxIcebergParts     int64
	MarketMinQty        float64
	MarketMaxQty        float64
	MarketStepSize      float64
	MaxTotalOrders      int64
	MaxAlgoOrders       int64
}

MinMaxLevel defines the minimum and maximum parameters for a currency pair for outbound exchange execution

type Modify

type Modify struct {
	ImmediateOrCancel bool
	HiddenOrder       bool
	FillOrKill        bool
	PostOnly          bool
	Leverage          float64
	Price             float64
	Amount            float64
	LimitPriceUpper   float64
	LimitPriceLower   float64
	TriggerPrice      float64
	TargetAmount      float64
	ExecutedAmount    float64
	RemainingAmount   float64
	Fee               float64
	Exchange          string
	InternalOrderID   string
	ID                string
	ClientOrderID     string
	AccountID         string
	ClientID          string
	WalletAddress     string
	Type              Type
	Side              Side
	Status            Status
	AssetType         asset.Item
	Date              time.Time
	LastUpdated       time.Time
	Pair              currency.Pair
	Trades            []TradeHistory
}

Modify contains all properties of an order that may be updated after it has been created Each exchange has their own requirements, so not all fields are required to be populated

func (*Modify) Validate

func (m *Modify) Validate(opt ...validate.Checker) error

Validate checks internal struct requirements

type ModifyResponse

type ModifyResponse struct {
	OrderID string
}

ModifyResponse is an order modifying return type

type Side

type Side string

Side enforces a standard for order sides across the code base

const (
	AnySide     Side = "ANY"
	Buy         Side = "BUY"
	Sell        Side = "SELL"
	Bid         Side = "BID"
	Ask         Side = "ASK"
	UnknownSide Side = "UNKNOWN"
)

Order side types

func StringToOrderSide

func StringToOrderSide(side string) (Side, error)

StringToOrderSide for converting case insensitive order side and returning a real Side

func (Side) Lower

func (s Side) Lower() string

Lower returns the side lower case string

func (Side) String

func (s Side) String() string

String implements the stringer interface

func (Side) Title

func (s Side) Title() string

Title returns the side titleized, eg "Buy"

type Status

type Status string

Status defines order status types

const (
	AnyStatus           Status = "ANY"
	New                 Status = "NEW"
	Active              Status = "ACTIVE"
	PartiallyCancelled  Status = "PARTIALLY_CANCELLED"
	PartiallyFilled     Status = "PARTIALLY_FILLED"
	Filled              Status = "FILLED"
	Cancelled           Status = "CANCELLED"
	PendingCancel       Status = "PENDING_CANCEL"
	InsufficientBalance Status = "INSUFFICIENT_BALANCE"
	MarketUnavailable   Status = "MARKET_UNAVAILABLE"
	Rejected            Status = "REJECTED"
	Expired             Status = "EXPIRED"
	Hidden              Status = "HIDDEN"
	UnknownStatus       Status = "UNKNOWN"
	Open                Status = "OPEN"
	AutoDeleverage      Status = "ADL"
	Closed              Status = "CLOSED"
	Pending             Status = "PENDING"
)

All order status types

func StringToOrderStatus

func StringToOrderStatus(status string) (Status, error)

StringToOrderStatus for converting case insensitive order status and returning a real Status

func (Status) String

func (s Status) String() string

String implements the stringer interface

type Submit

type Submit struct {
	ImmediateOrCancel bool
	HiddenOrder       bool
	FillOrKill        bool
	PostOnly          bool
	ReduceOnly        bool
	Leverage          float64
	QuoteOrderQty     float64 // 币安需要,市价单时使用成交额
	PositionSide      string  // 币安合约使用, 持仓方向,单向持仓模式下非必填,默认且仅可填BOTH;在双向持仓模式下必填,且仅可选择 LONG 或 SHORT
	Price             float64
	Amount            float64
	StopPrice         float64
	LimitPriceUpper   float64
	LimitPriceLower   float64
	TriggerPrice      float64
	TargetAmount      float64
	ExecutedAmount    float64
	RemainingAmount   float64
	Fee               float64
	Exchange          string
	InternalOrderID   string
	ID                string
	AccountID         string
	ClientID          string
	ClientOrderID     string
	WalletAddress     string
	Offset            string
	Type              Type
	Side              Side
	Status            Status
	AssetType         asset.Item
	Date              time.Time
	LastUpdated       time.Time
	Pair              currency.Pair
	Trades            []TradeHistory
}

Submit contains all properties of an order that may be required for an order to be created on an exchange Each exchange has their own requirements, so not all fields are required to be populated

func (*Submit) Validate

func (s *Submit) Validate(opt ...validate.Checker) error

Validate checks the supplied data and returns whether or not it's valid

type SubmitResponse

type SubmitResponse struct {
	IsOrderPlaced bool
	FullyMatched  bool
	OrderID       string
	Rate          float64
	Fee           float64
	Cost          float64
	Trades        []TradeHistory
}

SubmitResponse is what is returned after submitting an order to an exchange

type TradeHistory

type TradeHistory struct {
	Price       float64
	Amount      float64
	Fee         float64
	Exchange    string
	TID         string
	Description string
	Type        Type
	Side        Side
	Timestamp   time.Time
	IsMaker     bool
	FeeAsset    string
	Total       float64
}

TradeHistory holds exchange history data

type Type

type Type string

Type enforces a standard for order types across the code base

const (
	AnyType           Type = "ANY"
	Limit             Type = "LIMIT"
	Market            Type = "MARKET"
	PostOnly          Type = "POST_ONLY"
	ImmediateOrCancel Type = "IMMEDIATE_OR_CANCEL"
	Stop              Type = "STOP"
	StopLimit         Type = "STOP LIMIT"
	StopLossLimit     Type = "STOP_LOSS_LIMIT"
	StopMarket        Type = "STOP MARKET"
	TakeProfit        Type = "TAKE PROFIT"
	TakeProfitLimit   Type = "TAKE_PROFIT_LIMIT"
	TakeProfitMarket  Type = "TAKE PROFIT MARKET"
	TrailingStop      Type = "TRAILING_STOP"
	FillOrKill        Type = "FOK"
	IOS               Type = "IOS"
	UnknownType       Type = "UNKNOWN"
	Liquidation       Type = "LIQUIDATION"
	Trigger           Type = "TRIGGER"
)

Defined package order types

func StringToOrderType

func StringToOrderType(oType string) (Type, error)

StringToOrderType for converting case insensitive order type and returning a real Type

func (Type) Lower

func (t Type) Lower() string

Lower returns the type lower case string

func (Type) String

func (t Type) String() string

String implements the stringer interface

func (Type) Title

func (t Type) Title() string

Title returns the type titleized, eg "Limit"

Jump to

Keyboard shortcuts

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