Documentation
¶
Index ¶
- Variables
- func FilterOrdersByPairs(orders *[]Detail, pairs []currency.Pair)
- func FilterOrdersBySide(orders *[]Detail, side Side)
- func FilterOrdersByTimeRange(orders *[]Detail, startTime, endTime time.Time) error
- func FilterOrdersByType(orders *[]Detail, orderType Type)
- func IsValidOrderSubmissionSide(s Side) bool
- func SortOrdersByCurrency(orders *[]Detail, reverse bool)
- func SortOrdersByDate(orders *[]Detail, reverse bool)
- func SortOrdersByPrice(orders *[]Detail, reverse bool)
- func SortOrdersBySide(orders *[]Detail, reverse bool)
- func SortOrdersByType(orders *[]Detail, reverse bool)
- type ByCurrency
- type ByDate
- type ByOrderSide
- type ByOrderType
- type ByPrice
- type Cancel
- type CancelAllResponse
- type CancelBatchResponse
- type ClassificationError
- type Detail
- func (d *Detail) Copy() Detail
- func (d *Detail) CopyToPointer() *Detail
- func (d *Detail) DeriveCancel() (*Cancel, error)
- func (d *Detail) DeriveModify() (*Modify, error)
- func (d *Detail) GenerateInternalOrderID()
- func (d *Detail) InferCostsAndTimes()
- func (d *Detail) IsActive() bool
- func (d *Detail) IsInactive() bool
- func (d *Detail) MatchFilter(f *Filter) bool
- func (d *Detail) UpdateOrderFromDetail(m *Detail) error
- func (d *Detail) UpdateOrderFromModifyResponse(m *ModifyResponse)
- func (d *Detail) WasOrderPlaced() bool
- type Filter
- type FilteredOrders
- type Modify
- type ModifyResponse
- type MultiOrderRequest
- type PriceType
- type RiskManagement
- type RiskManagementModes
- type Side
- type Status
- type StopDirection
- type Submit
- type SubmitResponse
- type TimeInForce
- type TrackingMode
- type TradeHistory
- type Type
Constants ¶
This section is empty.
Variables ¶
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
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
var ( ErrInvalidTimeInForce = errors.New("invalid time in force value provided") ErrUnsupportedTimeInForce = errors.New("unsupported time in force value") )
var error definitions
var AllOrderTypes = Limit | Market | Stop | TakeProfit | TrailingStop | IOS | AnyType | Liquidation | Trigger | LimitMaker | OCO | ConditionalStop | TWAP | Chase | OptimalLimit | MarketMakerProtection
AllOrderTypes collects all order types for easy and consistent comparisons
Functions ¶
func FilterOrdersByPairs ¶
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 ¶
FilterOrdersBySide removes any order details that don't match the order status provided
func FilterOrdersByTimeRange ¶
FilterOrdersByTimeRange removes any OrderDetails outside of the time range
func FilterOrdersByType ¶
FilterOrdersByType removes any order details that don't match the order type provided
func IsValidOrderSubmissionSide ¶
IsValidOrderSubmissionSide validates that the order side is a valid submission direction
func SortOrdersByCurrency ¶
SortOrdersByCurrency the caller function to sort orders
func SortOrdersByDate ¶
SortOrdersByDate the caller function to sort orders
func SortOrdersByPrice ¶
SortOrdersByPrice the caller function to sort orders
func SortOrdersBySide ¶
SortOrdersBySide the caller function to sort orders
func SortOrdersByType ¶
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 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 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 ¶
PairAssetRequired is a validation check for when a cancel request requires an asset type and currency pair to be present
func (*Cancel) StandardCancel ¶
StandardCancel defines an option in the validator to make sure an ID is set for a standard cancel
type CancelAllResponse ¶
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 ¶
CancelBatchResponse returns the status of orders that have been requested for cancellation
type ClassificationError ¶
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 ¶
CopyPointerOrderSlice returns a copy of all order detail and returns a slice of pointers.
func (*Detail) CopyToPointer ¶
CopyToPointer will return the address of a new copy of the order Detail WARNING: DO NOT DEREFERENCE USE METHOD Copy().
func (*Detail) DeriveCancel ¶
DeriveCancel populates a cancel struct by the managed order details
func (*Detail) DeriveModify ¶
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 ¶
IsActive returns true if an order has a status that indicates it is currently available on the exchange
func (*Detail) IsInactive ¶
IsInactive returns true if an order has a status that indicates it is currently not available on the exchange
func (*Detail) MatchFilter ¶
MatchFilter will return true if a detail matches the filter criteria empty elements are ignored
func (*Detail) UpdateOrderFromDetail ¶
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 ¶
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.
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
type PriceType ¶
type PriceType uint8
PriceType enforces a standard for price types used for take-profit and stop-loss trigger types
price types
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 ¶
StringToOrderSide for converting case insensitive order side and returning a real Side
func (Side) MarshalJSON ¶
MarshalJSON returns the JSON-encoded order side
func (Side) Position ¶
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) UnmarshalJSON ¶
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 Rejected Expired Hidden Open AutoDeleverage Closed Pending Cancelling Liquidated STP )
All order status types
func StringToOrderStatus ¶
StringToOrderStatus for converting case insensitive order status and returning a real Status
func (Status) IsInactive ¶
IsInactive returns true if the status indicates it is currently not available on the exchange
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.
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 ¶
StringToOrderType for converting case insensitive order type and returning a real Type