order

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: May 15, 2024 License: MIT Imports: 19 Imported by: 0

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 this Trello board: https://trello.com/b/ZAhMhpOy/gocryptotrader.

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 unreaslied 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

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")
	// ErrCannotValidateAsset is thrown when the asset is not loaded
	ErrCannotValidateAsset = errors.New("cannot check limit, asset not loaded")
	// ErrCannotValidateBaseCurrency is thrown when the base currency is not loaded
	ErrCannotValidateBaseCurrency = errors.New("cannot check limit, base currency not loaded")
	// ErrCannotValidateQuoteCurrency is thrown when the quote currency is not loaded
	ErrCannotValidateQuoteCurrency = errors.New("cannot check limit, quote currency not loaded")
)
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")
	// ErrNoRates is returned when no margin rates are returned when they are expected
	ErrNoRates         = errors.New("no rates")
	ErrCannotLiquidate = errors.New("cannot liquidate position")
)

var error definitions

View Source
var (
	// ErrUnableToPlaceOrder defines an error when an order submission has
	// failed.
	ErrUnableToPlaceOrder = errors.New("order not placed")
	// ErrOrderNotFound is returned when no order is found
	ErrOrderNotFound = errors.New("order not found")

	// ErrUnknownPriceType returned when price type is unknown
	ErrUnknownPriceType = errors.New("unknown price type")
)

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
	WalletAddress string
	Type          Type
	Side          Side
	AssetType     asset.Item
	Pair          currency.Pair
	MarginType    margin.Type
}

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
	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
	WalletAddress        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 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) (MinMaxLevel, 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 uuid.UUID
	OrderID         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 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 MinMaxLevel

type MinMaxLevel struct {
	Pair                    currency.Pair
	Asset                   asset.Item
	MinPrice                float64
	MaxPrice                float64
	PriceStepIncrementSize  float64
	MultiplierUp            float64
	MultiplierDown          float64
	MultiplierDecimal       float64
	AveragePriceMinutes     int64
	MinimumBaseAmount       float64
	MaximumBaseAmount       float64
	MinimumQuoteAmount      float64
	MaximumQuoteAmount      float64
	AmountStepIncrementSize float64
	QuoteStepIncrementSize  float64
	MinNotional             float64
	MaxIcebergParts         int64
	MarketMinQty            float64
	MarketMaxQty            float64
	MarketStepIncrementSize float64
	MaxTotalOrders          int64
	MaxAlgoOrders           int64
}

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

func (*MinMaxLevel) ConformToAmount

func (m *MinMaxLevel) ConformToAmount(amount float64) float64

ConformToAmount (POC) conforms amount to its amount interval

func (*MinMaxLevel) ConformToDecimalAmount

func (m *MinMaxLevel) ConformToDecimalAmount(amount decimal.Decimal) decimal.Decimal

ConformToDecimalAmount (POC) conforms amount to its amount interval

func (*MinMaxLevel) Conforms

func (m *MinMaxLevel) Conforms(price, amount float64, orderType Type) error

Conforms checks outbound parameters

type Modify

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

	// Change fields
	ImmediateOrCancel bool
	PostOnly          bool
	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
}

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
	ImmediateOrCancel bool
	PostOnly          bool
	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
	StartTime time.Time
	EndTime   time.Time
	// FromOrderID for some APIs require order history searching
	// from a specific orderID rather than via timestamps
	FromOrderID string
}

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-los 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
}

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

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

	// Time in force values ------ TODO: Time In Force uint8
	ImmediateOrCancel bool
	FillOrKill        bool

	PostOnly bool
	// 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

	// 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
	// TradeMode specifies the trading mode for margin and non-margin orders: see okcoin_wrapper.go
	TradeMode string
}

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 customized in caller scope if needed.

func (*Submit) Validate

func (s *Submit) Validate(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

	ImmediateOrCancel    bool
	FillOrKill           bool
	PostOnly             bool
	ReduceOnly           bool
	Leverage             float64
	Price                float64
	AverageExecutedPrice float64
	Amount               float64
	QuoteAmount          float64
	TriggerPrice         float64
	ClientID             string
	ClientOrderID        string

	LastUpdated time.Time
	Date        time.Time
	Status      Status
	OrderID     string
	Trades      []TradeHistory
	Fee         float64
	FeeAsset    currency.Code
	Cost        float64

	BorrowSize  float64
	LoanApplyID string
	MarginType  margin.Type
}

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 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 uint32

Type enforces a standard for order types across the code base

const (
	UnknownType Type = 0
	Limit       Type = 1 << iota
	Market
	PostOnly
	ImmediateOrCancel
	Stop
	StopLimit
	StopMarket
	TakeProfit
	TakeProfitMarket
	TrailingStop
	FillOrKill
	IOS
	AnyType
	Liquidation
	Trigger
	OptimalLimitIOC
	OCO             // One-cancels-the-other order
	ConditionalStop // One-way stop order
)

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