order

package
v0.0.0-...-301d963 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 19 Imported by: 222

README

GoCryptoTrader package Order

Build Status Software License GoDoc Coverage Status Go Report Card

This order 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 our GoCryptoTrader Kanban board.

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

Current Features for order

  • This package services the exchanges package with order handling.

    • Creation of order
    • Deletion of order
    • Order tracking
  • For futures orders, this package also contains a futures position controller. It is responsible for tracking all futures orders that GoCryptoTrader processes. It keeps a running history of realised and unrealised PNL to allow a trader to track their profits. Positions are closed once the exposure reaches zero, then upon a new futures order being processed, a new position is created. To view futures positions, see the GRPC command getfuturesposition

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 (
	ErrSubmissionIsNil            = errors.New("order submission is nil")
	ErrCancelOrderIsNil           = errors.New("cancel order is nil")
	ErrOrderDetailIsNil           = errors.New("order detail 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")
	ErrCollateralInvalid          = errors.New("collateral type 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")
	ErrSubmitLeverageNotSupported = errors.New("leverage is not supported via order submission")
	ErrClientOrderIDNotSupported  = errors.New("client order id not supported")
	ErrUnsupportedOrderType       = errors.New("unsupported order type")
	ErrUnsupportedStatusType      = errors.New("unsupported status type")
	// ErrNoRates is returned when no margin rates are returned when they are expected
	ErrNoRates         = errors.New("no rates")
	ErrCannotLiquidate = errors.New("cannot liquidate position")

	ErrUnknownTrackingMode = errors.New("unknown tracking mode")
	ErrGetFailed           = errors.New("get order failed")
	ErrPlaceFailed         = errors.New("place order failed")
	ErrCancelFailed        = errors.New("cancel order failed")
)

var error definitions

View Source
var (
	ErrUnableToPlaceOrder          = errors.New("order not placed")
	ErrOrderNotFound               = errors.New("order not found")
	ErrUnknownPriceType            = errors.New("unknown price type")
	ErrAmountMustBeSet             = errors.New("amount must be set")
	ErrClientOrderIDMustBeSet      = errors.New("client order ID must be set")
	ErrUnknownSubmissionAmountType = errors.New("unknown submission amount type")
	ErrUnrecognisedOrderType       = errors.New("unrecognised order type")
	ErrPositionSideUnsupported     = errors.New("position side unsupported")
)

Public error vars for order package

View Source
var (
	ErrInvalidTimeInForce     = errors.New("invalid time in force value provided")
	ErrUnsupportedTimeInForce = errors.New("unsupported time in force value")
)

var error definitions

AllOrderTypes collects all order types for easy and consistent comparisons

Functions

func FilterOrdersByPairs

func FilterOrdersByPairs(orders *[]Detail, pairs []currency.Pair)

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

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) error

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 IsValidOrderSubmissionSide

func IsValidOrderSubmissionSide(s Side) bool

IsValidOrderSubmissionSide validates that the order side is a valid submission direction

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 {
	Exchange      string
	OrderID       string
	ClientOrderID string
	AccountID     string
	ClientID      string
	Type          Type
	Side          Side
	AssetType     asset.Item
	Pair          currency.Pair
	MarginType    margin.Type
	TimeInForce   TimeInForce
}

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
}

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

func (*CancelAllResponse) Add

func (c *CancelAllResponse) Add(orderID, status string)

Add adds a new orderID and status to the CancelAllResponse

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 {
	HiddenOrder          bool
	TimeInForce          TimeInForce
	ReduceOnly           bool
	Leverage             float64
	Price                float64
	Amount               float64
	ContractAmount       float64
	LimitPriceUpper      float64
	LimitPriceLower      float64
	TriggerPrice         float64
	AverageExecutedPrice float64
	QuoteAmount          float64
	ExecutedAmount       float64
	RemainingAmount      float64
	Cost                 float64
	CostAsset            currency.Code
	Fee                  float64
	FeeAsset             currency.Code
	Exchange             string
	InternalOrderID      uuid.UUID
	OrderID              string
	ClientOrderID        string
	AccountID            string
	ClientID             string
	Type                 Type
	Side                 Side
	Status               Status
	AssetType            asset.Item
	Date                 time.Time
	CloseTime            time.Time
	LastUpdated          time.Time
	Pair                 currency.Pair
	MarginType           margin.Type
	Trades               []TradeHistory
	SettlementCurrency   currency.Code
}

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

func CopyPointerOrderSlice

func CopyPointerOrderSlice(old []*Detail) []*Detail

CopyPointerOrderSlice returns a copy of all order detail and returns a slice of pointers.

func (*Detail) Copy

func (d *Detail) Copy() Detail

Copy makes a full copy of underlying details NOTE: This is Addressable.

func (*Detail) CopyToPointer

func (d *Detail) CopyToPointer() *Detail

CopyToPointer will return the address of a new copy of the order Detail WARNING: DO NOT DEREFERENCE USE METHOD Copy().

func (*Detail) DeriveCancel

func (d *Detail) DeriveCancel() (*Cancel, error)

DeriveCancel populates a cancel struct by the managed order details

func (*Detail) DeriveModify

func (d *Detail) DeriveModify() (*Modify, error)

DeriveModify populates a modify struct by the managed order details. Note: Price, Amount, Trigger price and order execution bools need to be changed in scope. This only derives identifiers for ease.

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) error

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

func (*Detail) UpdateOrderFromModifyResponse

func (d *Detail) UpdateOrderFromModifyResponse(m *ModifyResponse)

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

func (*Detail) WasOrderPlaced

func (d *Detail) WasOrderPlaced() bool

WasOrderPlaced returns true if an order has a status that indicates that it was accepted by an exchange.

type Filter

type Filter struct {
	Exchange        string
	InternalOrderID uuid.UUID
	OrderID         string
	ClientOrderID   string
	AccountID       string
	ClientID        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 FilteredOrders

type FilteredOrders []Detail

FilteredOrders defines orders that have been filtered at the wrapper level forcing required filter operations when calling method Filter() on MultiOrderRequest.

type Modify

type Modify struct {
	// Order Identifiers
	Exchange         string
	OrderID          string
	ClientOrderID    string
	NewClientOrderID string
	Type             Type
	Side             Side
	AssetType        asset.Item
	Pair             currency.Pair

	// Change fields
	TimeInForce  TimeInForce
	Price        float64
	Amount       float64
	TriggerPrice float64

	// added to represent a unified trigger price type information such as LastPrice, MarkPrice, and IndexPrice
	// https://bybit-exchange.github.io/docs/v5/order/create-order
	TriggerPriceType PriceType

	RiskManagementModes RiskManagementModes

	// SlippageTolerance used to control the maximum slippage ratio, the value range is greater than 0 and less than 1
	// https://api-docs.poloniex.com/spot/api/private/order
	SlippageTolerance float64
}

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) DeriveModifyResponse

func (m *Modify) DeriveModifyResponse() (*ModifyResponse, error)

DeriveModifyResponse populates a modify response with its identifiers for cross exchange standard. NOTE: New OrderID and/or ClientOrderID plus any changes *might* need to be populated in scope.

func (*Modify) Validate

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

Validate checks internal struct requirements

type ModifyResponse

type ModifyResponse struct {
	// Order Identifiers
	Exchange      string
	OrderID       string
	ClientOrderID string
	Pair          currency.Pair
	Type          Type
	Side          Side
	Status        Status
	AssetType     asset.Item

	// Fields that will be copied over from Modify
	TimeInForce  TimeInForce
	Price        float64
	Amount       float64
	TriggerPrice float64

	// Fields that need to be handled in scope after DeriveModifyResponse()
	// if applicable
	RemainingAmount float64
	Date            time.Time
	LastUpdated     time.Time
}

ModifyResponse is an order modifying return type

type MultiOrderRequest

type MultiOrderRequest struct {
	// Currencies Empty array = all currencies. Some endpoints only support
	// singular currency enquiries
	Pairs       currency.Pairs
	AssetType   asset.Item
	Type        Type
	Side        Side
	TimeInForce TimeInForce
	StartTime   time.Time
	EndTime     time.Time
	// FromOrderID for some APIs require order history searching
	// from a specific orderID rather than via timestamps
	FromOrderID string

	MarginType margin.Type
}

MultiOrderRequest used for GetOrderHistory and GetOpenOrders wrapper functions

func (*MultiOrderRequest) Filter

func (g *MultiOrderRequest) Filter(exch string, orders []Detail) FilteredOrders

Filter reduces slice by optional fields

func (*MultiOrderRequest) Validate

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

Validate checks internal struct requirements and returns filter requirement options for wrapper standardization procedures.

type PriceType

type PriceType uint8

PriceType enforces a standard for price types used for take-profit and stop-loss trigger types

const (
	LastPrice  PriceType = 0
	IndexPrice PriceType = 1 << iota
	MarkPrice
	UnknownPriceType
)

price types

func (PriceType) String

func (t PriceType) String() string

String implements the stringer interface

func (PriceType) StringToPriceType

func (t PriceType) StringToPriceType(priceType string) (PriceType, error)

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

type RiskManagement

type RiskManagement struct {
	Enabled          bool
	TriggerPriceType PriceType
	Price            float64

	// LimitPrice limit order price when stop-loss or take-profit risk management method is triggered
	LimitPrice float64
	// OrderType order type when stop-loss or take-profit risk management method is triggered.
	OrderType Type
}

RiskManagement represents a risk management detail information.

type RiskManagementModes

type RiskManagementModes struct {
	// Mode take-profit/stop-loss mode
	Mode       string
	TakeProfit RiskManagement
	StopLoss   RiskManagement

	// StopEntry stop: 'entry': Triggers when the last trade price changes to a value at or above the stopPrice.
	// see: https://www.kucoin.com/docs/rest/spot-trading/stop-order/introduction
	StopEntry RiskManagement
}

RiskManagementModes represents take-profit and stop-loss risk management methods.

type Side

type Side uint32

Side enforces a standard for order sides across the code base

const (
	UnknownSide Side = 0
	Buy         Side = 1 << iota
	Sell
	Bid
	Ask
	AnySide
	Long
	Short
	ClosePosition
	// Backtester signal types
	DoNothing
	TransferredFunds
	CouldNotBuy
	CouldNotSell
	CouldNotShort
	CouldNotLong
	CouldNotCloseShort
	CouldNotCloseLong
	MissingData
)

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) IsLong

func (s Side) IsLong() bool

IsLong returns if the side is long

func (Side) IsShort

func (s Side) IsShort() bool

IsShort returns if the side is short

func (Side) Lower

func (s Side) Lower() string

Lower returns the side lower case string

func (Side) MarshalJSON

func (s Side) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON-encoded order side

func (Side) Position

func (s Side) Position() (Side, error)

Position converts a spot side to a futures position; eg BUY => LONG Returns UnknownSide with an ErrPositionSideUnsupported error unless s.IsLong or s.IsShort

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"

func (*Side) UnmarshalJSON

func (s *Side) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON parses the JSON-encoded order side and stores the result It expects a quoted string input, and uses StringToOrderSide to parse it

type Status

type Status uint32

Status defines order status types

const (
	UnknownStatus Status = 0
	AnyStatus     Status = 1 << iota
	New
	Active
	PartiallyCancelled
	PartiallyFilled
	PartiallyFilledCancelled
	Filled
	Cancelled
	PendingCancel
	InsufficientBalance
	MarketUnavailable
	Rejected
	Expired
	Hidden
	Open
	AutoDeleverage
	Closed
	Pending
	Cancelling
	Liquidated
	STP
)

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) IsInactive

func (s Status) IsInactive() bool

IsInactive returns true if the status indicates it is currently not available on the exchange

func (Status) String

func (s Status) String() string

String implements the stringer interface

type StopDirection

type StopDirection bool

StopDirection is the direction from which the stop order will trigger; Up will have the order trigger when the last trade price goes above the TriggerPrice; Down will have the order trigger when the last trade price goes below the TriggerPrice

const (
	StopUp   StopDirection = true
	StopDown StopDirection = false
)

StopDirection types

type Submit

type Submit struct {
	Exchange  string
	Type      Type
	Side      Side
	Pair      currency.Pair
	AssetType asset.Item

	// TimeInForce holds time in force values
	TimeInForce TimeInForce

	// ReduceOnly reduces a position instead of opening an opposing
	// position; this also equates to closing the position in huobi_wrapper.go
	// swaps.
	ReduceOnly bool
	// Leverage is the amount of leverage that will be used: see huobi_wrapper.go
	Leverage float64
	Price    float64
	// Amount in base terms
	Amount float64
	// QuoteAmount is the max amount in quote currency when purchasing base.
	// This is only used in Market orders.
	QuoteAmount float64
	// TriggerPrice is mandatory if order type `Stop, Stop Limit or Take Profit`
	// See btcmarkets_wrapper.go.
	TriggerPrice float64

	// added to represent a unified trigger price type information such as LastPrice, MarkPrice, and IndexPrice
	// https://bybit-exchange.github.io/docs/v5/order/create-order
	TriggerPriceType PriceType
	ClientID         string // TODO: Shift to credentials
	ClientOrderID    string

	// The system will first borrow you funds at the optimal interest rate and then place an order for you.
	// see kucoin_wrapper.go
	AutoBorrow bool
	// AutoRepay when enabled the system will automatically repay the borrowed funds after the order is filled.
	// Used in conjunction with margin trading to close/reduce short positions.
	AutoRepay bool

	// MarginType such as isolated or cross margin for when an exchange
	// supports margin type definition when submitting an order eg okx
	MarginType margin.Type
	// RetrieveFees use if an API submit order response does not return fees
	// enabling this will perform additional request(s) to retrieve them
	// and set it in the SubmitResponse
	RetrieveFees bool
	// RetrieveFeeDelay some exchanges take time to properly save order data
	// and cannot retrieve fees data immediately
	RetrieveFeeDelay    time.Duration
	RiskManagementModes RiskManagementModes

	// Hidden when enabled orders not displaying in order book.
	Hidden bool

	// Iceberg specifies whether or not only visible portions of orders are shown in iceberg orders
	Iceberg bool

	// EndTime is the moment which a good til date order is valid until
	EndTime time.Time

	// StopDirection is the direction from which the stop order will trigger
	StopDirection StopDirection
	// TrackingMode specifies the way trailing stop and chase orders follow the market price or ask/bid prices.
	// See: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-place-algo-order
	TrackingMode  TrackingMode
	TrackingValue float64

	// LimitTrackingMode specifies the limit price offset used to place a limit order relative to the market price.
	LimitTrackingMode  TrackingMode
	LimitTrackingValue float64

	// RFQDisabled, when set, attempts to route the order to the exchange CLOB. Currently only supported by Coinbase
	RFQDisabled bool

	// SlippageTolerance used to control the maximum slippage ratio, the value range is greater than 0 and less than 1
	// https://api-docs.poloniex.com/spot/api/private/order
	SlippageTolerance float64
}

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 need to be populated

func (*Submit) DeriveSubmitResponse

func (s *Submit) DeriveSubmitResponse(orderID string) (*SubmitResponse, error)

DeriveSubmitResponse will construct an order SubmitResponse when a successful submission has occurred. NOTE: order status is populated as order.Filled for a market order else order.New if an order is accepted as default, date and lastupdated fields have been populated as time.Now(). All fields can be customised in caller scope if needed.

func (*Submit) GetTradeAmount

func (s *Submit) GetTradeAmount(tr protocol.TradingRequirements) float64

GetTradeAmount returns the trade amount based on the exchange's trading requirements. Some exchanges depending on direction and order type use quotation (funds in balance) or base amounts. If the exchange does not have any specific requirements it will return the base amount.

func (*Submit) Validate

func (s *Submit) Validate(requirements protocol.TradingRequirements, opt ...validate.Checker) error

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

type SubmitResponse

type SubmitResponse struct {
	Exchange             string
	Type                 Type
	Side                 Side
	Pair                 currency.Pair
	AssetType            asset.Item
	TimeInForce          TimeInForce
	ReduceOnly           bool
	Leverage             float64
	Price                float64
	Amount               float64
	QuoteAmount          float64
	RemainingAmount      float64
	TriggerPrice         float64
	ClientID             string
	ClientOrderID        string
	AverageExecutedPrice float64
	LastUpdated          time.Time
	Date                 time.Time
	Status               Status
	OrderID              string
	Trades               []TradeHistory
	Fee                  float64
	FeeAsset             currency.Code
	Cost                 float64
	Purchased            float64 // Buy in base currency, Sell in quote
	BorrowSize           float64
	LoanApplyID          string
	MarginType           margin.Type
	SubmissionError      error
}

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

func (*SubmitResponse) AdjustBaseAmount

func (s *SubmitResponse) AdjustBaseAmount(a float64) error

AdjustBaseAmount will adjust the base amount of a submit response if the exchange has modified the amount. This is usually due to decimal place restrictions or rounding. This will return an error if the amount is zero or the submit response is nil.

func (*SubmitResponse) AdjustQuoteAmount

func (s *SubmitResponse) AdjustQuoteAmount(a float64) error

AdjustQuoteAmount will adjust the quote amount of a submit response if the exchange has modified the amount. This is usually due to decimal place restrictions or rounding. This will return an error if the amount is zero or the submit response is nil.

func (*SubmitResponse) DeriveDetail

func (s *SubmitResponse) DeriveDetail(internal uuid.UUID) (*Detail, error)

DeriveDetail will construct an order detail when a successful submission has occurred. Has an optional parameter field internal uuid for internal management.

type TimeInForce

type TimeInForce uint16

TimeInForce enforces a standard for time-in-force values across the code base.

const (
	UnknownTIF     TimeInForce = 0
	GoodTillCancel TimeInForce = 1 << iota
	GoodTillDay
	GoodTillTime
	GoodTillCrossing
	FillOrKill
	ImmediateOrCancel
	PostOnly
	StopOrReduce
)

TimeInForce types

func StringToTimeInForce

func StringToTimeInForce(timeInForce string) (TimeInForce, error)

StringToTimeInForce converts time in force string value to TimeInForce instance.

func (TimeInForce) Is

func (t TimeInForce) Is(in TimeInForce) bool

Is checks to see if the enum contains the flag

func (TimeInForce) IsValid

func (t TimeInForce) IsValid() bool

IsValid returns whether or not the supplied time in force value is valid or not

func (TimeInForce) Lower

func (t TimeInForce) Lower() string

Lower returns a lower case string representation of time-in-force

func (TimeInForce) MarshalJSON

func (t TimeInForce) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON-encoded order time-in-force value

func (TimeInForce) String

func (t TimeInForce) String() string

String implements the stringer interface.

func (*TimeInForce) UnmarshalJSON

func (t *TimeInForce) UnmarshalJSON(data []byte) error

UnmarshalJSON deserialises a string data into TimeInForce instance.

type TrackingMode

type TrackingMode uint8

TrackingMode defines how the stop price follows the market price.

const (
	UnknownTrackingMode TrackingMode = iota
	Distance                         // Distance fixed amount away from the market price
	Percentage                       // Percentage fixed percentage away from the market price
)

Defined package tracking modes

func StringToTrackingMode

func StringToTrackingMode(mode string) TrackingMode

StringToTrackingMode converts TrackingMode instance from string

func (TrackingMode) String

func (t TrackingMode) String() string

String implements the stringer interface

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 uint64

Type enforces a standard for order types across the code base

const (
	UnknownType Type = 0
	Limit       Type = 1 << iota
	Market
	Stop
	TakeProfit
	TrailingStop
	IOS
	AnyType
	Liquidation
	Trigger
	LimitMaker
	OCO             // One-cancels-the-other order
	ConditionalStop // One-way stop order
	TWAP            // time-weighted average price
	Chase           // chase limit order
	OptimalLimit
	MarketMakerProtection

	// Hybrid order types
	StopLimit         = Stop | Limit
	StopMarket        = Stop | Market
	TakeProfitMarket  = TakeProfit | Market
	TrailingStopLimit = TrailingStop | Limit
	Bracket           = Stop | TakeProfit
)

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) Is

func (t Type) Is(cmp Type) bool

Is checks to see if the Type contains the Type cmp

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