market endpoints

This commit is contained in:
wuhewuhe 2023-11-05 22:35:56 +01:00
parent 8695a773c9
commit 19e79e0676
12 changed files with 800 additions and 202 deletions

View File

@ -67,6 +67,13 @@ func (c *Client) debug(format string, v ...interface{}) {
} }
} }
func GetCurrentTime() int64 {
now := time.Now()
unixNano := now.UnixNano()
timeStamp := unixNano / int64(time.Millisecond)
return timeStamp
}
// NewBybitHttpClient NewClient Create client function for initialising new Bybit client // NewBybitHttpClient NewClient Create client function for initialising new Bybit client
func NewBybitHttpClient(apiKey string, APISecret string, options ...ClientOption) *Client { func NewBybitHttpClient(apiKey string, APISecret string, options ...ClientOption) *Client {
c := &Client{ c := &Client{
@ -109,9 +116,7 @@ func (c *Client) parseRequest(r *request, opts ...RequestOption) (err error) {
header.Set("User-Agent", fmt.Sprintf("%s/%s", Name, Version)) header.Set("User-Agent", fmt.Sprintf("%s/%s", Name, Version))
if r.secType == secTypeSigned { if r.secType == secTypeSigned {
now := time.Now() timeStamp := GetCurrentTime()
unixNano := now.UnixNano()
timeStamp := unixNano / 1000000
header.Set(signTypeKey, "2") header.Set(signTypeKey, "2")
header.Set(apiRequestKey, c.APIKey) header.Set(apiRequestKey, c.APIKey)
header.Set(timestampKey, strconv.FormatInt(timeStamp, 10)) header.Set(timestampKey, strconv.FormatInt(timeStamp, 10))
@ -188,11 +193,6 @@ func (c *Client) callAPI(ctx context.Context, r *request, opts ...RequestOption)
return data, nil return data, nil
} }
// NewServerTimeService Market Endpoints
func (c *Client) NewServerTimeService() *ServerTime {
return &ServerTime{c: c}
}
// NewMarketKlineService Market Endpoints // NewMarketKlineService Market Endpoints
func (c *Client) NewMarketKlineService(klineType, category, symbol, interval string) *Klines { func (c *Client) NewMarketKlineService(klineType, category, symbol, interval string) *Klines {
return &Klines{ return &Klines{
@ -204,6 +204,27 @@ func (c *Client) NewMarketKlineService(klineType, category, symbol, interval str
} }
} }
func (c *Client) NewMarketKLinesService(klineType string, params map[string]interface{}) *MarketClient {
return &MarketClient{
c: c,
klineType: klineType,
params: params,
}
}
func (c *Client) NewMarketInfoServiceNoParams() *MarketClient {
return &MarketClient{
c: c,
}
}
func (c *Client) NewMarketInfoService(params map[string]interface{}) *MarketClient {
return &MarketClient{
c: c,
params: params,
}
}
// NewPlaceOrderService Trade Endpoints // NewPlaceOrderService Trade Endpoints
func (c *Client) NewPlaceOrderService(category, symbol, side, orderType, qty string) *Order { func (c *Client) NewPlaceOrderService(category, symbol, side, orderType, qty string) *Order {
return &Order{ return &Order{
@ -215,3 +236,10 @@ func (c *Client) NewPlaceOrderService(category, symbol, side, orderType, qty str
qty: qty, qty: qty,
} }
} }
func (c *Client) NewPlaceTradeService(params map[string]interface{}) *Trade {
return &Trade{
c: c,
params: params,
}
}

View File

@ -0,0 +1,22 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
PlaceTrade()
}
func PlaceTrade() {
client := bybit.NewBybitHttpClient("8wYkmpLsMg10eNQyPm", "Ouxc34myDnXvei54XsBZgoQzfGxO4bkr2Zsj", bybit.WithBaseURL(bybit.TESTNET))
params := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "side": "Buy", "positionIdx": 0, "orderType": "Limit", "qty": "0.001", "price": "10000", "timeInForce": "GTC"}
orderResult, err := client.NewPlaceTradeService(params).Do(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(orderResult))
}

View File

@ -0,0 +1,25 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
InstrumentInfo()
}
func InstrumentInfo() {
client := bybit.NewBybitHttpClient("", "")
// NewServerTimeService
params := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "status": "Trading"}
marketKline, err := client.NewMarketInfoService(params).GetInstrumentInfo(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(marketKline))
}

View File

@ -0,0 +1,25 @@
package main
import (
"context"
"fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
)
func main() {
IndexKline()
}
func IndexKline() {
client := bybit.NewBybitHttpClient("", "")
// NewServerTimeService
params := map[string]interface{}{"category": "linear", "symbol": "BTCUSDT", "interval": "1", "Limit": 2}
marketKline, err := client.NewMarketKLinesService("index-price-kline", params).GetMarketKline(context.Background())
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bybit.PrettyPrint(marketKline))
}

View File

@ -15,7 +15,7 @@ func ServerTime() {
client := bybit.NewBybitHttpClient("", "") client := bybit.NewBybitHttpClient("", "")
// NewServerTimeService // NewServerTimeService
serverTime, err := client.NewServerTimeService().Do(context.Background()) serverTime, err := client.NewMarketInfoServiceNoParams().GetServerTime(context.Background())
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
return return

View File

@ -1,8 +1,8 @@
package main package main
import ( import (
bybit "bybit.go.api"
"fmt" "fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
) )
func main() { func main() {

View File

@ -1,8 +1,8 @@
package main package main
import ( import (
bybit "bybit.go.api"
"fmt" "fmt"
bybit "github.com/wuhewuhe/bybit.go.api"
) )
func main() { func main() {

View File

@ -0,0 +1,23 @@
package handlers
import (
"fmt"
)
func ValidateParams(params map[string]interface{}) error {
seenKeys := make(map[string]bool)
for key, value := range params {
if key == "" {
return fmt.Errorf("empty key found in parameters")
}
if seenKeys[key] {
return fmt.Errorf("duplicate key found in parameters: %s", key)
}
if value == nil {
return fmt.Errorf("parameter for key '%s' is nil", key)
}
seenKeys[key] = true
}
return nil
}

323
market.go
View File

@ -3,21 +3,17 @@ package bybit_connector
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http" "net/http"
) )
type ServerTimeResult struct { type MarketClient struct {
TimeSecond string `json:"timeSecond"` c *Client
TimeNano string `json:"timeNano"` klineType string
params map[string]interface{}
} }
// ServerTime Binance Check Server Time endpoint (GET /v5/market/time) func (s *MarketClient) GetServerTime(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
type ServerTime struct {
c *Client
}
// Do Send the request
func (s *ServerTime) Do(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
r := &request{ r := &request{
method: http.MethodGet, method: http.MethodGet,
endpoint: "/v5/market/time", endpoint: "/v5/market/time",
@ -35,71 +31,258 @@ func (s *ServerTime) Do(ctx context.Context, opts ...RequestOption) (res *Server
return res, nil return res, nil
} }
type MarketKlineCandle struct { func (s *MarketClient) GetMarketKline(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
StartTime string `json:"startTime"` if err = handlers.ValidateParams(s.params); err != nil {
OpenPrice string `json:"openPrice"` return nil, err
HighPrice string `json:"highPrice"` }
LowPrice string `json:"lowPrice"`
ClosePrice string `json:"closePrice"`
Volume string `json:"volume"`
Turnover string `json:"turnover"`
}
type MarketKlineResponse struct {
Category string `json:"category"`
Symbol string `json:"symbol"`
List []MarketKlineCandle `json:"list"`
}
// Klines Market Kline (GET /v5/market/kline)
type Klines struct {
c *Client
klineType string
category string
symbol string
interval string
limit *int
start *uint64
end *uint64
}
// Limit set limit
func (s *Klines) Limit(limit int) *Klines {
s.limit = &limit
return s
}
// Start set startTime
func (s *Klines) Start(startTime uint64) *Klines {
s.start = &startTime
return s
}
// End set endTime
func (s *Klines) End(endTime uint64) *Klines {
s.end = &endTime
return s
}
// Do Send the request
func (s *Klines) Do(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
r := &request{ r := &request{
method: http.MethodGet, method: http.MethodGet,
endpoint: "/v5/market/" + s.klineType, endpoint: "/v5/market/" + s.klineType,
secType: secTypeNone, secType: secTypeNone,
} }
r.setParam("category", s.category) r.setParams(s.params)
r.setParam("symbol", s.symbol) data, err := s.c.callAPI(ctx, r, opts...)
r.setParam("interval", s.interval) if err != nil {
if s.limit != nil { return nil, err
r.setParam("limit", *s.limit) }
} res = new(ServerResponse)
if s.start != nil { err = json.Unmarshal(data, res)
r.setParam("start", *s.start) if err != nil {
} return nil, err
if s.end != nil { }
r.setParam("end", *s.end) return res, nil
} }
func (s *MarketClient) GetInstrumentInfo(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/instruments-info",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetOrderBookInfo(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/orderbook",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetMarketTickers(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/tickers",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetFundingRates(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/tickers",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetPublicRecentTrades(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/recent-trade",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetOpenInterests(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/open-interest",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetHistoricalVolatility(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/historical-volatility",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetInsuranceInfo(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/insurance",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetRiskLimit(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/risk-limit",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetDeliveryPrice(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/delivery-price",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *MarketClient) GetMarketLSRatio(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/account-ratio",
secType: secTypeNone,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...) data, err := s.c.callAPI(ctx, r, opts...)
if err != nil { if err != nil {
return nil, err return nil, err

67
market_klines.go Normal file
View File

@ -0,0 +1,67 @@
package bybit_connector
import (
"context"
"encoding/json"
"net/http"
)
// Klines Market Kline (GET /v5/market/kline)
type Klines struct {
c *Client
klineType string
category string
symbol string
interval string
limit *int
start *uint64
end *uint64
}
// Limit set limit
func (s *Klines) Limit(limit int) *Klines {
s.limit = &limit
return s
}
// Start set startTime
func (s *Klines) Start(startTime uint64) *Klines {
s.start = &startTime
return s
}
// End set endTime
func (s *Klines) End(endTime uint64) *Klines {
s.end = &endTime
return s
}
func (s *Klines) Do(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
r := &request{
method: http.MethodGet,
endpoint: "/v5/market/" + s.klineType,
secType: secTypeNone,
}
r.setParam("category", s.category)
r.setParam("symbol", s.symbol)
r.setParam("interval", s.interval)
if s.limit != nil {
r.setParam("limit", *s.limit)
}
if s.start != nil {
r.setParam("start", *s.start)
}
if s.end != nil {
r.setParam("end", *s.end)
}
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}

197
models/marketResponse.go Normal file
View File

@ -0,0 +1,197 @@
package models
type ServerTimeResult struct {
TimeSecond string `json:"timeSecond"`
TimeNano string `json:"timeNano"`
}
type MarketKlineCandle struct {
StartTime string `json:"startTime"`
OpenPrice string `json:"openPrice"`
HighPrice string `json:"highPrice"`
LowPrice string `json:"lowPrice"`
ClosePrice string `json:"closePrice"`
Volume string `json:"volume"`
Turnover string `json:"turnover"`
}
type MarketKlineResponse struct {
Category string `json:"category"`
Symbol string `json:"symbol"`
List []MarketKlineCandle `json:"list"`
}
type InstrumentInfo struct {
Category string `json:"category"`
NextPageCursor string `json:"nextPageCursor"`
List []Instrument `json:"list"`
}
type Instrument struct {
Symbol string `json:"symbol"`
ContractType string `json:"contractType"`
Status string `json:"status"`
BaseCoin string `json:"baseCoin"`
QuoteCoin string `json:"quoteCoin"`
LaunchTime string `json:"launchTime"`
DeliveryTime string `json:"deliveryTime"`
DeliveryFeeRate string `json:"deliveryFeeRate"`
PriceScale string `json:"priceScale"`
LeverageFilter LeverageFilter `json:"leverageFilter"`
PriceFilter PriceFilter `json:"priceFilter"`
LotSizeFilter LotSizeFilter `json:"lotSizeFilter"`
UnifiedMarginTrade bool `json:"unifiedMarginTrade"`
FundingInterval int `json:"fundingInterval"`
SettleCoin string `json:"settleCoin"`
CopyTrading string `json:"copyTrading"`
}
type LeverageFilter struct {
MinLeverage string `json:"minLeverage"`
MaxLeverage string `json:"maxLeverage"`
LeverageStep string `json:"leverageStep"`
}
type PriceFilter struct {
MinPrice string `json:"minPrice"`
MaxPrice string `json:"maxPrice"`
TickSize string `json:"tickSize"`
}
type LotSizeFilter struct {
MaxOrderQty string `json:"maxOrderQty"`
MinOrderQty string `json:"minOrderQty"`
QtyStep string `json:"qtyStep"`
PostOnlyMaxOrderQty string `json:"postOnlyMaxOrderQty"`
}
type OrderBookEntry struct {
Price string `json:"0"`
Size string `json:"1"`
}
type OrderBookInfo struct {
Symbol string `json:"s"`
Bids []OrderBookEntry `json:"b"`
Asks []OrderBookEntry `json:"a"`
Timestamp int64 `json:"ts"`
UpdateID int64 `json:"u"`
}
type TickerInfo struct {
Symbol string `json:"symbol"`
LastPrice string `json:"lastPrice"`
IndexPrice string `json:"indexPrice"`
MarkPrice string `json:"markPrice"`
PrevPrice24h string `json:"prevPrice24h"`
Price24hPcnt string `json:"price24hPcnt"`
HighPrice24h string `json:"highPrice24h"`
LowPrice24h string `json:"lowPrice24h"`
PrevPrice1h string `json:"prevPrice1h"`
OpenInterest string `json:"openInterest"`
OpenInterestValue string `json:"openInterestValue"`
Turnover24h string `json:"turnover24h"`
Volume24h string `json:"volume24h"`
FundingRate string `json:"fundingRate"`
NextFundingTime string `json:"nextFundingTime"`
PredictedDeliveryPrice string `json:"predictedDeliveryPrice"`
BasisRate string `json:"basisRate"`
Basis string `json:"basis"`
DeliveryFeeRate string `json:"deliveryFeeRate"`
DeliveryTime string `json:"deliveryTime"`
Ask1Size string `json:"ask1Size"`
Bid1Price string `json:"bid1Price"`
Ask1Price string `json:"ask1Price"`
Bid1Size string `json:"bid1Size"`
}
type MarketTickers struct {
Category string `json:"category"`
List []TickerInfo `json:"list"`
}
type FundingRateInfo struct {
Symbol string `json:"symbol"`
FundingRate string `json:"fundingRate"`
FundingRateTimestamp string `json:"fundingRateTimestamp"`
}
type FundingRate struct {
Category string `json:"category"`
List []FundingRateInfo `json:"list"`
}
type TradeInfo struct {
ExecId string `json:"execId"`
Symbol string `json:"symbol"`
Price string `json:"price"`
Size string `json:"size"`
Side string `json:"side"`
Time string `json:"time"`
IsBlockTrade bool `json:"isBlockTrade"`
}
type PublicRecentTradeHistory struct {
Category string `json:"category"`
List []TradeInfo `json:"list"`
}
type VolatilityData struct {
Period int `json:"period"`
Value string `json:"value"`
Time string `json:"time"`
}
type HistoricalVolatilityInfo struct {
Category string `json:"category"`
List []VolatilityData `json:"list"`
}
type InsuranceData struct {
Coin string `json:"coin"`
Balance string `json:"balance"`
Value string `json:"value"`
}
type MarketInsuranceInfo struct {
UpdatedTime string `json:"updatedTime"`
List []InsuranceData `json:"list"`
}
type RiskLimitData struct {
Id int `json:"id"`
Symbol string `json:"symbol"`
RiskLimitValue string `json:"riskLimitValue"`
MaintenanceMargin float64 `json:"maintenanceMargin"`
InitialMargin float64 `json:"initialMargin"`
IsLowestRisk int `json:"isLowestRisk"`
MaxLeverage string `json:"maxLeverage"`
}
type MarketRiskLimitInfo struct {
Category string `json:"category"`
List []RiskLimitData `json:"list"`
}
type DeliveryPriceData struct {
Symbol string `json:"symbol"`
DeliveryPrice string `json:"deliveryPrice"`
DeliveryTime string `json:"deliveryTime"`
}
type DeliveryPriceInfo struct {
Category string `json:"category"`
List []DeliveryPriceData `json:"list"`
NextPageCursor string `json:"nextPageCursor"`
}
type LongShortRatioData struct {
Symbol string `json:"symbol"`
BuyRatio string `json:"buyRatio"`
SellRatio string `json:"sellRatio"`
Timestamp string `json:"timestamp"`
}
type MarketLongShortRatioInfo struct {
List []LongShortRatioData `json:"list"`
}

270
trade.go
View File

@ -3,6 +3,7 @@ package bybit_connector
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"github.com/wuhewuhe/bybit.go.api/handlers"
"net/http" "net/http"
) )
@ -11,6 +12,11 @@ type OrderResult struct {
OrderLinkId string `json:"orderLinkId"` OrderLinkId string `json:"orderLinkId"`
} }
type Trade struct {
c *Client
params map[string]interface{}
}
type Order struct { type Order struct {
c *Client c *Client
category string category string
@ -43,206 +49,228 @@ type Order struct {
slOrderType *string slOrderType *string
} }
func (o *Order) TimeInForce(tif string) *Order { func (order *Order) TimeInForce(tif string) *Order {
o.timeInForce = &tif order.timeInForce = &tif
return o return order
} }
func (s *Order) IsLeverage(isLeverage int) *Order { func (order *Order) IsLeverage(isLeverage int) *Order {
s.isLeverage = &isLeverage order.isLeverage = &isLeverage
return s return order
} }
func (s *Order) TriggerPrice(triggerPrice string) *Order { func (order *Order) TriggerPrice(triggerPrice string) *Order {
s.triggerPrice = &triggerPrice order.triggerPrice = &triggerPrice
return s return order
} }
func (s *Order) OrderLinkId(orderLinkId string) *Order { func (order *Order) OrderLinkId(orderLinkId string) *Order {
s.orderLinkId = &orderLinkId order.orderLinkId = &orderLinkId
return s return order
} }
func (o *Order) Price(price string) *Order { func (order *Order) Price(price string) *Order {
o.price = &price order.price = &price
return o return order
} }
func (o *Order) TriggerDirection(direction int) *Order { func (order *Order) TriggerDirection(direction int) *Order {
o.triggerDirection = &direction order.triggerDirection = &direction
return o return order
} }
func (o *Order) OrderFilter(filter string) *Order { func (order *Order) OrderFilter(filter string) *Order {
o.orderFilter = &filter order.orderFilter = &filter
return o return order
} }
func (o *Order) TriggerBy(triggerBy string) *Order { func (order *Order) TriggerBy(triggerBy string) *Order {
o.triggerBy = &triggerBy order.triggerBy = &triggerBy
return o return order
} }
func (o *Order) OrderIv(iv string) *Order { func (order *Order) OrderIv(iv string) *Order {
o.orderIv = &iv order.orderIv = &iv
return o return order
} }
func (o *Order) PositionIdx(idx int) *Order { func (order *Order) PositionIdx(idx int) *Order {
o.positionIdx = &idx order.positionIdx = &idx
return o return order
} }
func (o *Order) TakeProfit(profit string) *Order { func (order *Order) TakeProfit(profit string) *Order {
o.takeProfit = &profit order.takeProfit = &profit
return o return order
} }
func (o *Order) StopLoss(loss string) *Order { func (order *Order) StopLoss(loss string) *Order {
o.stopLoss = &loss order.stopLoss = &loss
return o return order
} }
func (o *Order) TpTriggerBy(triggerBy string) *Order { func (order *Order) TpTriggerBy(triggerBy string) *Order {
o.tpTriggerBy = &triggerBy order.tpTriggerBy = &triggerBy
return o return order
} }
func (o *Order) SlTriggerBy(triggerBy string) *Order { func (order *Order) SlTriggerBy(triggerBy string) *Order {
o.slTriggerBy = &triggerBy order.slTriggerBy = &triggerBy
return o return order
} }
func (o *Order) ReduceOnly(reduce bool) *Order { func (order *Order) ReduceOnly(reduce bool) *Order {
o.reduceOnly = &reduce order.reduceOnly = &reduce
return o return order
} }
func (o *Order) CloseOnTrigger(close bool) *Order { func (order *Order) CloseOnTrigger(close bool) *Order {
o.closeOnTrigger = &close order.closeOnTrigger = &close
return o return order
} }
func (o *Order) SmpType(smp string) *Order { func (order *Order) SmpType(smp string) *Order {
o.smpType = &smp order.smpType = &smp
return o return order
} }
func (o *Order) Mmp(mmp bool) *Order { func (order *Order) Mmp(mmp bool) *Order {
o.mmp = &mmp order.mmp = &mmp
return o return order
} }
func (o *Order) TpslMode(mode string) *Order { func (order *Order) TpslMode(mode string) *Order {
o.tpslMode = &mode order.tpslMode = &mode
return o return order
} }
func (o *Order) TpLimitPrice(price string) *Order { func (order *Order) TpLimitPrice(price string) *Order {
o.tpLimitPrice = &price order.tpLimitPrice = &price
return o return order
} }
func (o *Order) SlLimitPrice(price string) *Order { func (order *Order) SlLimitPrice(price string) *Order {
o.slLimitPrice = &price order.slLimitPrice = &price
return o return order
} }
func (o *Order) TpOrderType(orderType string) *Order { func (order *Order) TpOrderType(orderType string) *Order {
o.tpOrderType = &orderType order.tpOrderType = &orderType
return o return order
} }
func (o *Order) SlOrderType(orderType string) *Order { func (order *Order) SlOrderType(orderType string) *Order {
o.slOrderType = &orderType order.slOrderType = &orderType
return o return order
} }
func (s *Order) Do(ctx context.Context, opts ...RequestOption) (*ServerResponse, error) { func (order *Order) Do(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
r := &request{ r := &request{
method: http.MethodPost, method: http.MethodPost,
endpoint: "/v5/order/create", endpoint: "/v5/order/create",
secType: secTypeSigned, secType: secTypeSigned,
} }
m := params{ m := params{
"category": s.category, "category": order.category,
"symbol": s.symbol, "symbol": order.symbol,
"side": s.side, "side": order.side,
"orderType": s.orderType, "orderType": order.orderType,
"qty": s.qty, "qty": order.qty,
} }
if s.price != nil { if order.price != nil {
m["price"] = *s.price m["price"] = *order.price
} }
if s.triggerDirection != nil { if order.triggerDirection != nil {
m["triggerDirection"] = *s.triggerDirection m["triggerDirection"] = *order.triggerDirection
} }
if s.orderFilter != nil { if order.orderFilter != nil {
m["orderFilter"] = *s.orderFilter m["orderFilter"] = *order.orderFilter
} }
if s.triggerPrice != nil { if order.triggerPrice != nil {
m["triggerPrice"] = *s.triggerPrice m["triggerPrice"] = *order.triggerPrice
} }
if s.triggerBy != nil { if order.triggerBy != nil {
m["triggerBy"] = *s.triggerBy m["triggerBy"] = *order.triggerBy
} }
if s.orderIv != nil { if order.orderIv != nil {
m["orderIv"] = *s.orderIv m["orderIv"] = *order.orderIv
} }
if s.timeInForce != nil { if order.timeInForce != nil {
m["timeInForce"] = *s.timeInForce m["timeInForce"] = *order.timeInForce
} }
if s.positionIdx != nil { if order.positionIdx != nil {
m["positionIdx"] = *s.positionIdx m["positionIdx"] = *order.positionIdx
} }
if s.orderLinkId != nil { if order.orderLinkId != nil {
m["orderLinkId"] = *s.orderLinkId m["orderLinkId"] = *order.orderLinkId
} }
if s.takeProfit != nil { if order.takeProfit != nil {
m["takeProfit"] = *s.takeProfit m["takeProfit"] = *order.takeProfit
} }
if s.stopLoss != nil { if order.stopLoss != nil {
m["stopLoss"] = *s.stopLoss m["stopLoss"] = *order.stopLoss
} }
if s.tpTriggerBy != nil { if order.tpTriggerBy != nil {
m["tpTriggerBy"] = *s.tpTriggerBy m["tpTriggerBy"] = *order.tpTriggerBy
} }
if s.slTriggerBy != nil { if order.slTriggerBy != nil {
m["slTriggerBy"] = *s.slTriggerBy m["slTriggerBy"] = *order.slTriggerBy
} }
if s.reduceOnly != nil { if order.reduceOnly != nil {
m["reduceOnly"] = *s.reduceOnly m["reduceOnly"] = *order.reduceOnly
} }
if s.closeOnTrigger != nil { if order.closeOnTrigger != nil {
m["closeOnTrigger"] = *s.closeOnTrigger m["closeOnTrigger"] = *order.closeOnTrigger
} }
if s.smpType != nil { if order.smpType != nil {
m["smpType"] = *s.smpType m["smpType"] = *order.smpType
} }
if s.mmp != nil { if order.mmp != nil {
m["mmp"] = *s.mmp m["mmp"] = *order.mmp
} }
if s.tpslMode != nil { if order.tpslMode != nil {
m["tpslMode"] = *s.tpslMode m["tpslMode"] = *order.tpslMode
} }
if s.tpLimitPrice != nil { if order.tpLimitPrice != nil {
m["tpLimitPrice"] = *s.tpLimitPrice m["tpLimitPrice"] = *order.tpLimitPrice
} }
if s.slLimitPrice != nil { if order.slLimitPrice != nil {
m["slLimitPrice"] = *s.slLimitPrice m["slLimitPrice"] = *order.slLimitPrice
} }
if s.tpOrderType != nil { if order.tpOrderType != nil {
m["tpOrderType"] = *s.tpOrderType m["tpOrderType"] = *order.tpOrderType
} }
if s.slOrderType != nil { if order.slOrderType != nil {
m["slOrderType"] = *s.slOrderType m["slOrderType"] = *order.slOrderType
} }
r.setParams(m) r.setParams(m)
data, err := s.c.callAPI(ctx, r, opts...) data, err := order.c.callAPI(ctx, r, opts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res := new(ServerResponse) res = new(ServerResponse)
err = json.Unmarshal(data, res)
if err != nil {
return nil, err
}
return res, nil
}
func (s *Trade) Do(ctx context.Context, opts ...RequestOption) (res *ServerResponse, err error) {
if err = handlers.ValidateParams(s.params); err != nil {
return nil, err
}
r := &request{
method: http.MethodPost,
endpoint: "/v5/order/create",
secType: secTypeSigned,
}
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return nil, err
}
res = new(ServerResponse)
err = json.Unmarshal(data, res) err = json.Unmarshal(data, res)
if err != nil { if err != nil {
return nil, err return nil, err