Skip to content

Commit

Permalink
Update wrapper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
samuael committed Sep 25, 2024
1 parent 4d6ec05 commit 2aea80f
Show file tree
Hide file tree
Showing 8 changed files with 88 additions and 50 deletions.
10 changes: 5 additions & 5 deletions exchanges/apexpro/apexpro.go
Original file line number Diff line number Diff line change
Expand Up @@ -806,21 +806,21 @@ func (ap *Apexpro) getWorstPrice(ctx context.Context, symbol, side, path string,
}

// CancelPerpOrder cancels a perpetual contract order cancellation.
func (ap *Apexpro) CancelPerpOrder(ctx context.Context, orderID int64) (types.Number, error) {
func (ap *Apexpro) CancelPerpOrder(ctx context.Context, orderID string) (types.Number, error) {
return ap.cancelOrderByID(ctx, orderID, "v3/delete-order")
}

// CancelPerpOrderByClientOrderID cancels a perpetual contract order by client order ID.
func (ap *Apexpro) CancelPerpOrderByClientOrderID(ctx context.Context, clientOrderID int64) (types.Number, error) {
func (ap *Apexpro) CancelPerpOrderByClientOrderID(ctx context.Context, clientOrderID string) (types.Number, error) {
return ap.cancelOrderByID(ctx, clientOrderID, "v3/delete-client-order-id")
}

func (ap *Apexpro) cancelOrderByID(ctx context.Context, id int64, path string) (types.Number, error) {
if id == 0 {
func (ap *Apexpro) cancelOrderByID(ctx context.Context, id, path string) (types.Number, error) {
if id == "" {
return 0, order.ErrOrderIDNotSet
}
var resp types.Number
return resp, ap.SendAuthenticatedHTTPRequest(ctx, exchange.RestFutures, http.MethodPost, path, request.UnAuth, nil, map[string]interface{}{"id": strconv.FormatInt(id, 10)}, &resp)
return resp, ap.SendAuthenticatedHTTPRequest(ctx, exchange.RestFutures, http.MethodPost, path, request.UnAuth, nil, map[string]interface{}{"id": id}, &resp)
}

// CancelAllOpenOrdersV3 cancels all open orders
Expand Down
8 changes: 0 additions & 8 deletions exchanges/apexpro/apexpro_constants.go

This file was deleted.

24 changes: 18 additions & 6 deletions exchanges/apexpro/apexpro_starkex_process.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ var (
errSettlementCurrencyInfoNotFound = errors.New("settlement currency information not found")
errInvalidAssetID = errors.New("invalid asset ID provided")
errInvalidPositionIDMissing = errors.New("invalid position or account ID")
errL2CredentialsMismatch = errors.New("l2 credentials mismatch")
errTokenDetailIsMissing = errors.New("token detail is missing")
)

Expand Down Expand Up @@ -447,6 +448,7 @@ func (ap *Apexpro) ProcessConditionalTransfer(ctx context.Context, arg *FastWith
return "", err
}
}

assetID, ok := big.NewInt(0).SetString(currencyInfo.StarkExAssetID, 0)
if !ok {
return "", fmt.Errorf("%w, assetId: %s", errInvalidAssetID, currencyInfo.StarkExAssetID)
Expand All @@ -461,6 +463,9 @@ func (ap *Apexpro) ProcessConditionalTransfer(ctx context.Context, arg *FastWith
return "", err
}
}
if ap.UserAccountDetail.StarkKey != creds.L2Key {
return "", errL2CredentialsMismatch
}
resolution, err := decimal.NewFromString(currencyInfo.StarkExResolution)
if err != nil {
return "", err
Expand Down Expand Up @@ -494,9 +499,18 @@ func (ap *Apexpro) ProcessConditionalTransfer(ctx context.Context, arg *FastWith
if token == nil {
return "", errTokenDetailIsMissing
}
fact, err := GetTransferErc20Fact(arg.ERC20Address, int(token.Decimals),
println(
"\n\n",
int(token.Decimals),
arg.ERC20Address,
strconv.FormatFloat(arg.Amount, 'f', -1, 64), token.TokenAddress,
nonceFromClientID(arg.ClientID).String())
"0x"+nonceFromClientID(arg.ClientID).Text(16),
"\n\n",
)
fact, err := GetTransferErc20Fact(int(token.Decimals),
arg.ERC20Address,
strconv.FormatFloat(arg.Amount, 'f', -1, 64), token.TokenAddress,
"0x"+nonceFromClientID(arg.ClientID).Text(16))
if err != nil {
return "", err
}
Expand All @@ -505,11 +519,10 @@ func (ap *Apexpro) ProcessConditionalTransfer(ctx context.Context, arg *FastWith
expEpoch = int64(math.Ceil(float64(time.Now().Add(time.Hour*24*28).UnixMilli()) / float64(3600*1000)))
arg.Expiration = expEpoch * 3600 * 1000
}
senderPublicKey, ok := big.NewInt(0).SetString(creds.L2Key, 0)
senderPublicKey, ok := big.NewInt(0).SetString(ap.UserAccountDetail.StarkKey, 0)
if !ok {
return "", errL2KeyMissing
}

r, s, err := ap.StarkConfig.Sign(&starkex.ConditionalTransferParams{
AssetID: assetID,
AssetIDFee: big.NewInt(0),
Expand Down Expand Up @@ -541,8 +554,7 @@ func FactToCondition(factRegistryAddress, fact string) *big.Int {

// GetTransferErc20Fact get erc20 fact
// tokenDecimals is COLLATERAL_TOKEN_DECIMALS
func GetTransferErc20Fact(recipient string, tokenDecimals int, humanAmount, tokenAddress, salt string) (string, error) {
fmt.Println("GetTransferErc20Fact", recipient, tokenDecimals, humanAmount, tokenAddress, salt)
func GetTransferErc20Fact(tokenDecimals int, recipient, humanAmount, tokenAddress, salt string) (string, error) {
amount, err := decimal.NewFromString(humanAmount)
if err != nil {
return "", err
Expand Down
20 changes: 14 additions & 6 deletions exchanges/apexpro/apexpro_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const (

ethereumAddress = ""

canManipulateRealOrders = false
canManipulateRealOrders = true
)

var ap = &Apexpro{}
Expand Down Expand Up @@ -595,7 +595,6 @@ func TestCreateOrder(t *testing.T) {
assert.NoError(t, err)
assert.NotNil(t, ap.UserAccountDetail)
}
ap.Verbose = true
result, err := ap.CreateOrderV3(context.Background(), &CreateOrderParams{
Symbol: futuresTradablePair,
Side: order.Buy.String(),
Expand All @@ -613,22 +612,22 @@ func TestCreateOrder(t *testing.T) {

func TestCancelPerpOrder(t *testing.T) {
t.Parallel()
_, err := ap.CancelPerpOrder(context.Background(), 0)
_, err := ap.CancelPerpOrder(context.Background(), "")
require.ErrorIs(t, err, order.ErrOrderIDNotSet)

sharedtestvalues.SkipTestIfCredentialsUnset(t, ap, canManipulateRealOrders)
result, err := ap.CancelPerpOrder(context.Background(), 123231)
result, err := ap.CancelPerpOrder(context.Background(), "123231")
require.NoError(t, err)
assert.NotNil(t, result)
}

func TestCancelPerpOrderByClientOrderID(t *testing.T) {
t.Parallel()
_, err := ap.CancelPerpOrderByClientOrderID(context.Background(), 0)
_, err := ap.CancelPerpOrderByClientOrderID(context.Background(), "")
require.ErrorIs(t, err, order.ErrOrderIDNotSet)

sharedtestvalues.SkipTestIfCredentialsUnset(t, ap, canManipulateRealOrders)
result, err := ap.CancelPerpOrderByClientOrderID(context.Background(), 2312312)
result, err := ap.CancelPerpOrderByClientOrderID(context.Background(), "2312312")
require.NoError(t, err)
assert.NotNil(t, result)
}
Expand Down Expand Up @@ -1329,3 +1328,12 @@ func TestWsConnect(t *testing.T) {
err := ap.WsConnect()
assert.NoError(t, err)
}

func TestGetTransferErc20Fact(t *testing.T) {
fact, err := GetTransferErc20Fact(
3, "0x1234567890123456789012345678901234567890",
"123.456", "0xaAaAaAaaAaAaAaaAaAAAAAAAAaaaAaAaAaaAaaAa",
"0x1234567890abcdef")
assert.NoError(t, err)
assert.Equal(t, "34052387b5efb6132a42b244cff52a85a507ab319c414564d7a89207d4473672", fact)
}
24 changes: 15 additions & 9 deletions exchanges/apexpro/apexpro_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@ package apexpro

import (
"encoding/json"
"math/big"
"time"

"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/types"
)

var one = big.NewInt(1)

// BitMask250 (2 ** 250) - 1
var BitMask250 = big.NewInt(0).Sub(big.NewInt(0).Exp(big.NewInt(2), big.NewInt(250), nil), one)

// AllSymbolsConfigs represents all symbols configurations.
type AllSymbolsConfigs struct {
SpotConfig struct {
Expand Down Expand Up @@ -590,11 +596,11 @@ type ChainInfo struct {

// TokenInfo represents a token info detail
type TokenInfo struct {
Decimals int64 `json:"decimals"`
IconURL string `json:"iconUrl"`
Token string `json:"token"`
TokenAddress string `json:"tokenAddress"`
PullOff bool `json:"pullOff"`
Decimals float64 `json:"decimals"`
IconURL string `json:"iconUrl"`
Token string `json:"token"`
TokenAddress string `json:"tokenAddress"`
PullOff bool `json:"pullOff"`
}

// PerpetualContractDetail represents a perpetual contract detail.
Expand Down Expand Up @@ -1324,11 +1330,11 @@ type CreateOrderParams struct {
TriggerPriceType string `json:"triggerPriceType"`

ClientID string `json:"clientId,omitempty"`
IsPositionTpsl string `json:"isPositionTpsl,omitempty"`
IsOpenTpslOrder string `json:"isOpenTpslOrder,omitempty"`
IsPositionTPSL string `json:"isPositionTpsl,omitempty"`
IsOpenTPSLOrder string `json:"isOpenTpslOrder,omitempty"`

IsSetOpenSl string `json:"isSetOpenSl,omitempty"`
IsSetOpenTp string `json:"isSetOpenTp,omitempty"`
IsSetOpenSL string `json:"isSetOpenSl,omitempty"`
IsSetOpenTP string `json:"isSetOpenTp,omitempty"`

SlClientOrderID string `json:"slClientOrderId,omitempty"`
SlPrice string `json:"slPrice,omitempty"`
Expand Down
4 changes: 3 additions & 1 deletion exchanges/apexpro/apexpro_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,12 +493,13 @@ func (ap *Apexpro) processCandlestickData(respRaw []byte) error {
if err != nil {
return err
}
klineData := make([]stream.KlineData, len(resp.Data))
for a := range resp.Data {
pair, err := currency.NewPairFromString(resp.Data[a].Symbol)
if err != nil {
return err
}
ap.Websocket.DataHandler <- stream.KlineData{
klineData[a] = stream.KlineData{
Timestamp: resp.Timestamp.Time(),
Pair: pair,
AssetType: asset.Futures,
Expand All @@ -512,6 +513,7 @@ func (ap *Apexpro) processCandlestickData(respRaw []byte) error {
Volume: resp.Data[a].Volume.Float64(),
}
}
ap.Websocket.DataHandler <- klineData
return nil
}

Expand Down
45 changes: 30 additions & 15 deletions exchanges/apexpro/apexpro_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,20 +395,27 @@ func (ap *Apexpro) GetServerTime(ctx context.Context, _ asset.Item) (time.Time,
}

// SubmitOrder submits a new order
func (ap *Apexpro) SubmitOrder(_ context.Context, s *order.Submit) (*order.SubmitResponse, error) {
func (ap *Apexpro) SubmitOrder(ctx context.Context, s *order.Submit) (*order.SubmitResponse, error) {
if err := s.Validate(ap.GetTradingRequirements()); err != nil {
return nil, err
}
// When an order has been submitted you can use this helpful constructor to
// return. Please add any additional order details to the
// order.SubmitResponse if you think they are applicable.
// resp, err := s.DeriveSubmitResponse( /*newOrderID*/)
// if err != nil {
// return nil, nil
// }
// resp.Date = exampleTime // e.g. If this is supplied by the exchanges API.
// return resp, nil
return nil, common.ErrNotYetImplemented
orderResp, err := ap.CreateOrderV2(ctx, &CreateOrderParams{
Symbol: s.Pair,
Side: s.Side.String(),
OrderType: s.Type.Lower(),
Size: s.Amount,
Price: s.Price,
TriggerPrice: s.TriggerPrice,
ClientOrderID: s.ClientOrderID,
ReduceOnly: s.ReduceOnly,
TriggerPriceType: s.TriggerPriceType.String(),
ClientID: s.ClientID,
TrailingPercent: s.TrailingPercent,
})
if err != nil {
return nil, err
}
return s.DeriveSubmitResponse(orderResp.ID)
}

// ModifyOrder will allow of changing orderbook placement and limit to
Expand All @@ -418,11 +425,19 @@ func (ap *Apexpro) ModifyOrder(_ context.Context, _ *order.Modify) (*order.Modif
}

// CancelOrder cancels an order by its corresponding ID number
func (ap *Apexpro) CancelOrder(_ context.Context, ord *order.Cancel) error {
func (ap *Apexpro) CancelOrder(ctx context.Context, ord *order.Cancel) error {
if err := ord.Validate(ord.StandardCancel()); err != nil {
return err
}
return common.ErrNotYetImplemented
if ord.OrderID == "" && ord.ClientOrderID == "" {
return order.ErrOrderIDNotSet
}
if ord.OrderID != "" {
_, err := ap.CancelPerpOrder(ctx, ord.OrderID)
return err
}
_, err := ap.CancelPerpOrderByClientOrderID(ctx, ord.ClientOrderID)
return err
}

// CancelBatchOrders cancels orders by their corresponding ID numbers
Expand Down Expand Up @@ -525,13 +540,13 @@ func (ap *Apexpro) WithdrawCryptocurrencyFunds(ctx context.Context, withdrawRequ
// WithdrawFiatFunds returns a withdrawal ID when a withdrawal is
// submitted
func (ap *Apexpro) WithdrawFiatFunds(_ context.Context, _ *withdraw.Request) (*withdraw.ExchangeResponse, error) {
return nil, common.ErrNotYetImplemented
return nil, common.ErrFunctionNotSupported
}

// WithdrawFiatFundsToInternationalBank returns a withdrawal ID when a withdrawal is
// submitted
func (ap *Apexpro) WithdrawFiatFundsToInternationalBank(_ context.Context, _ *withdraw.Request) (*withdraw.ExchangeResponse, error) {
return nil, common.ErrNotYetImplemented
return nil, common.ErrFunctionNotSupported
}

// GetActiveOrders retrieves any orders that are active/open
Expand Down
3 changes: 3 additions & 0 deletions exchanges/order/order_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ type Submit struct {

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

// Specifies used with trailing stop order types.
TrailingPercent float64
}

// SubmitResponse is what is returned after submitting an order to an exchange
Expand Down

0 comments on commit 2aea80f

Please sign in to comment.