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 ExecutionLimits
- type Filter
- type FilteredOrders
- type MinMaxLevel
- type Modify
- type ModifyResponse
- type MultiOrderRequest
- type PriceType
- type RiskManagement
- type RiskManagementModes
- type Side
- type Status
- type Submit
- type SubmitResponse
- type TradeHistory
- type Type
Constants ¶
This section is empty.
Variables ¶
var ( ErrLoadLimitsFailed = errors.New("failed to load exchange limits") ErrExchangeLimitNotLoaded = errors.New("exchange limits not loaded") ErrPriceBelowMin = errors.New("price below minimum limit") ErrPriceExceedsMax = errors.New("price exceeds maximum limit") ErrPriceExceedsStep = errors.New("price exceeds step limit") // price is not divisible by its step ErrAmountBelowMin = errors.New("amount below minimum limit") ErrAmountExceedsMax = errors.New("amount exceeds maximum limit") ErrAmountExceedsStep = errors.New("amount exceeds step limit") // amount is not divisible by its step ErrNotionalValue = errors.New("total notional value is under minimum limit") ErrMarketAmountBelowMin = errors.New("market order amount below minimum limit") ErrMarketAmountExceedsMax = errors.New("market order amount exceeds maximum limit") ErrMarketAmountExceedsStep = errors.New("market order amount exceeds step limit") // amount is not divisible by its step for a market order ErrCannotValidateAsset = errors.New("cannot check limit, asset not loaded") ErrCannotValidateBaseCurrency = errors.New("cannot check limit, base currency not loaded") ErrCannotValidateQuoteCurrency = errors.New("cannot check limit, quote currency not loaded") )
Public errors for order limits
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
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") )
Public error vars for order package
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 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 ¶
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
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 { 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 ¶
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 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
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.
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 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) 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 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 // Iceberg specifies whether or not only visible portions of orders are shown in iceberg orders Iceberg bool }
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) 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 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 ¶
StringToOrderType for converting case insensitive order type and returning a real Type