Files
gocryptotrader/exchanges/alphapoint/alphapoint.go
Samuael A. 3f534a15f1 cmd/exchange_template, exchanges: Update templates and propogate to exchanges (#1777)
* Added TimeInForce type and updated related files

* Linter issue fix and minor coinbasepro type update

* Bitrex consts update

* added unit test and minor changes in bittrex

* Unit tests update

* Fix minor linter issues

* Update TestStringToTimeInForce unit test

* Exchange test template change

* A different approach

* fix conflict with gateio timeInForce

* minor exchange template update

* Minor fix to test_files template

* Update order tests

* Complete updating the order unit tests

* Updating exchange wrapper and test template files

* update kucoin and deribit wrapper to match the time in force change

* minor comment update

* fix time-in-force related test errors

* linter issue fix

* ADD_NEW_EXCHANGE documentation update

* time in force constants, functions and unit tests update

* shift tif policies to TimeInForce

* Update time-in-force, related functions, and unit tests

* fix linter issue and time-in-force processing

* added a good till crossing tif value

* order type fix and fix related tim-in-force entries

* update time-in-force unmarshaling and unit test

* consistency guideline added

* fix time-in-force error in gateio

* linter issue fix

* update based on review comments

* add unit test and fix missing issues

* minor fix and added benchmark unit test

* change GTT to GTC for limit

* fix linter issue

* added time-in-force value to place order param

* fix minor issues based on review comment and move tif code to separate files

* update on exchanges linked to time-in-force

* resolve missing review comments

* minor linter issues fix

* added time-in-force handler and update timeInForce parametered endpoint

* minor fixes based on review

* nits fix

* update based on review

* linter fix

* rm getTimeInForce func and minor change to time-in-force

* minor change

* update based on review comments

* wrappers and time-in-force calling approach

* minor change

* update gateio string to timeInForce conversion and unit test

* update exchange template

* update wrapper template file

* policy comments, and template files update

* rename all exchange types name to Exchange

* update on template files and template generation

* templates and generation code and other updates

* linter issue fix

* added subscriptions and websocket templates

* update ADD_NEW_EXCHANGE.md with recent binance functions and implementations

* rename template files and update unit tests

* minor template and unit test fix

* rename templates and fix on unit tests

* update on template files and documentation

* removed unnecessary tag fix and update templates

* fix Add_NEW_EXCHANGE.md doc file

* formatting, comments, and error checks update on template files

* rename exchange receivers to e and ex for consistency

* rename unit test exchange receiver and minor updates

* linter issues fix

* fix deribit issue and minor style update

* fix test issues caused by receiver change

* raname local variables exchange declaration variables

* update templates comments

* update templates and related comments

* renamed ex to e

* update template comments

* toggle WS to false to improve coverage

* template comments update

* added test coverage to Ws enabled and minor changes

---------

Co-authored-by: Samuel Reid <43227667+cranktakular@users.noreply.github.com>
2025-07-17 10:46:36 +10:00

599 lines
16 KiB
Go

package alphapoint
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
gws "github.com/gorilla/websocket"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/encoding/json"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/nonce"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
)
const (
alphapointDefaultAPIURL = "https://sim3.alphapoint.com:8400"
alphapointAPIVersion = "1"
alphapointTicker = "GetTicker"
alphapointTrades = "GetTrades"
alphapointTradesByDate = "GetTradesByDate"
alphapointOrderbook = "GetOrderBook"
alphapointProductPairs = "GetProductPairs"
alphapointProducts = "GetProducts"
alphapointCreateAccount = "CreateAccount"
alphapointUserInfo = "GetUserInfo"
alphapointAccountInfo = "GetAccountInfo"
alphapointAccountTrades = "GetAccountTrades"
alphapointDepositAddresses = "GetDepositAddresses"
alphapointWithdraw = "Withdraw"
alphapointCreateOrder = "CreateOrder"
alphapointModifyOrder = "ModifyOrder"
alphapointCancelOrder = "CancelOrder"
alphapointCancelAllOrders = "CancelAllOrders"
alphapointOpenOrders = "GetAccountOpenOrders"
alphapointOrderFee = "GetOrderFee"
)
// Exchange implements exchange.IBotExchange and contains additional specific api methods for interacting with Alphapoint
type Exchange struct {
exchange.Base
WebsocketConn *gws.Conn
}
// GetTicker returns current ticker information from Alphapoint for a selected
// currency pair ie "BTCUSD"
func (e *Exchange) GetTicker(ctx context.Context, currencyPair string) (Ticker, error) {
req := make(map[string]any)
req["productPair"] = currencyPair
response := Ticker{}
err := e.SendHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointTicker,
req,
&response)
if err != nil {
return response, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
}
// GetTrades fetches past trades for the given currency pair
// currencyPair: ie "BTCUSD"
// StartIndex: specifies the index to begin from, -1 being the first trade on
// AlphaPoint Exchange. To begin from the most recent trade, set startIndex to
// 0 (default: 0)
// Count: specifies the number of trades to return (default: 10)
func (e *Exchange) GetTrades(ctx context.Context, currencyPair string, startIndex, count int) (Trades, error) {
req := make(map[string]any)
req["ins"] = currencyPair
req["startIndex"] = startIndex
req["Count"] = count
response := Trades{}
err := e.SendHTTPRequest(ctx,
exchange.RestSpot, http.MethodPost, alphapointTrades, req, &response)
if err != nil {
return response, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
}
// GetOrderbook fetches the current orderbook for a given currency pair
// CurrencyPair - trade pair (ex: “BTCUSD”)
func (e *Exchange) GetOrderbook(ctx context.Context, currencyPair string) (Orderbook, error) {
req := make(map[string]any)
req["productPair"] = currencyPair
response := Orderbook{}
err := e.SendHTTPRequest(ctx,
exchange.RestSpot, http.MethodPost, alphapointOrderbook, req, &response)
if err != nil {
return response, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
}
// GetProductPairs gets the currency pairs currently traded on alphapoint
func (e *Exchange) GetProductPairs(ctx context.Context) (ProductPairs, error) {
response := ProductPairs{}
err := e.SendHTTPRequest(ctx,
exchange.RestSpot, http.MethodPost, alphapointProductPairs, nil, &response)
if err != nil {
return response, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
}
// GetProducts gets the currency products currently supported on alphapoint
func (e *Exchange) GetProducts(ctx context.Context) (Products, error) {
response := Products{}
err := e.SendHTTPRequest(ctx,
exchange.RestSpot, http.MethodPost, alphapointProducts, nil, &response)
if err != nil {
return response, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
}
// CreateAccount creates a new account on alphapoint
// FirstName - First name
// LastName - Last name
// Email - Email address
// Phone - Phone number (ex: “+12223334444”)
// Password - Minimum 8 characters
func (e *Exchange) CreateAccount(ctx context.Context, firstName, lastName, email, phone, password string) error {
if len(password) < 8 {
return errors.New(
"alphapoint Error - Create account - Password must be 8 characters or more",
)
}
req := make(map[string]any)
req["firstname"] = firstName
req["lastname"] = lastName
req["email"] = email
req["phone"] = phone
req["password"] = password
response := Response{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot, http.MethodPost, alphapointCreateAccount, req, &response)
if err != nil {
return fmt.Errorf("unable to create account. Reason: %s", err)
}
if !response.IsAccepted {
return errors.New(response.RejectReason)
}
return nil
}
// GetUserInfo returns current account user information
func (e *Exchange) GetUserInfo(ctx context.Context) (UserInfo, error) {
response := UserInfo{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointUserInfo,
map[string]any{},
&response)
if err != nil {
return UserInfo{}, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
}
// SetUserInfo changes user name and/or 2FA settings
// userInfoKVP - An array of key value pairs
// FirstName - First name
// LastName - Last name
// UseAuthy2FA - “true” or “false” toggle Authy app
// Cell2FACountryCode - Cell country code (ex: 1), required for Authentication
// Cell2FAValue - Cell phone number, required for Authentication
// Use2FAForWithdraw - “true” or “false” set to true for using 2FA for
// withdrawals
func (e *Exchange) SetUserInfo(ctx context.Context, firstName, lastName, cell2FACountryCode, cell2FAValue string, useAuthy2FA, use2FAForWithdraw bool) (UserInfoSet, error) {
response := UserInfoSet{}
userInfoKVPs := []UserInfoKVP{
{
Key: "FirstName",
Value: firstName,
},
{
Key: "LastName",
Value: lastName,
},
{
Key: "Cell2FACountryCode",
Value: cell2FACountryCode,
},
{
Key: "Cell2FAValue",
Value: cell2FAValue,
},
{
Key: "UseAuthy2FA",
Value: strconv.FormatBool(useAuthy2FA),
},
{
Key: "Use2FAForWithdraw",
Value: strconv.FormatBool(use2FAForWithdraw),
},
}
req := make(map[string]any)
req["userInfoKVP"] = userInfoKVPs
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointUserInfo,
req,
&response,
)
if err != nil {
return response, err
}
if response.IsAccepted != "true" {
return response, errors.New(response.RejectReason)
}
return response, nil
}
// GetAccountInformation returns account info
func (e *Exchange) GetAccountInformation(ctx context.Context) (AccountInfo, error) {
response := AccountInfo{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointAccountInfo,
map[string]any{},
&response,
)
if err != nil {
return response, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
}
// GetAccountTrades returns the trades executed on the account.
// CurrencyPair - Instrument code (ex: “BTCUSD”)
// StartIndex - Starting index, if less than 0 then start from the beginning
// Count - Returns last trade, (Default: 30)
func (e *Exchange) GetAccountTrades(ctx context.Context, currencyPair string, startIndex, count int) (Trades, error) {
req := make(map[string]any)
req["ins"] = currencyPair
req["startIndex"] = startIndex
req["count"] = count
response := Trades{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointAccountTrades,
req,
&response,
)
if err != nil {
return response, err
}
if !response.IsAccepted {
return response, errors.New(response.RejectReason)
}
return response, nil
}
// GetDepositAddresses generates a deposit address
func (e *Exchange) GetDepositAddresses(ctx context.Context) ([]DepositAddresses, error) {
response := Response{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointDepositAddresses,
map[string]any{},
&response,
)
if err != nil {
return nil, err
}
if !response.IsAccepted {
return nil, errors.New(response.RejectReason)
}
return response.Addresses, nil
}
// WithdrawCoins withdraws a coin to a specific address
// symbol - Instrument name (ex: “BTCUSD”)
// product - Currency name (ex: “BTC”)
// amount - Amount (ex: “.011”)
// address - Withdraw address
func (e *Exchange) WithdrawCoins(ctx context.Context, symbol, product, address string, amount float64) error {
req := make(map[string]any)
req["ins"] = symbol
req["product"] = product
req["amount"] = strconv.FormatFloat(amount, 'f', -1, 64)
req["sendToAddress"] = address
response := Response{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointWithdraw,
req,
&response,
)
if err != nil {
return err
}
if !response.IsAccepted {
return errors.New(response.RejectReason)
}
return nil
}
func (e *Exchange) convertOrderTypeToOrderTypeNumber(orderType string) (orderTypeNumber int64) {
if orderType == order.Market.String() {
orderTypeNumber = 1
}
return orderTypeNumber
}
// CreateOrder creates a market or limit order
// symbol - Instrument code (ex: “BTCUSD”)
// side - “buy” or “sell”
// orderType - “1” for market orders, “0” for limit orders
// quantity - Quantity
// price - Price in USD
func (e *Exchange) CreateOrder(ctx context.Context, symbol, side, orderType string, quantity, price float64) (int64, error) {
orderTypeNumber := e.convertOrderTypeToOrderTypeNumber(orderType)
req := make(map[string]any)
req["ins"] = symbol
req["side"] = side
req["orderType"] = orderTypeNumber
req["qty"] = strconv.FormatFloat(quantity, 'f', -1, 64)
req["px"] = strconv.FormatFloat(price, 'f', -1, 64)
response := Response{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointCreateOrder,
req,
&response,
)
if err != nil {
return 0, err
}
if !response.IsAccepted {
return 0, errors.New(response.RejectReason)
}
return response.ServerOrderID, nil
}
// ModifyExistingOrder modifies and existing Order
// OrderID - tracked order id number
// symbol - Instrument code (ex: “BTCUSD”)
// modifyAction - “0” or “1”
// “0” means "Move to top", which will modify the order price to the top of the
// book. A buy order will be modified to the highest bid and a sell order will
// be modified to the lowest ask price. “1” means "Execute now", which will
// convert a limit order into a market order.
func (e *Exchange) ModifyExistingOrder(ctx context.Context, symbol string, orderID, action int64) (int64, error) {
req := make(map[string]any)
req["ins"] = symbol
req["serverOrderId"] = orderID
req["modifyAction"] = action
response := Response{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointModifyOrder,
req,
&response,
)
if err != nil {
return 0, err
}
if !response.IsAccepted {
return 0, errors.New(response.RejectReason)
}
return response.ModifyOrderID, nil
}
// CancelExistingOrder cancels an order that has not been executed.
// symbol - Instrument code (ex: “BTCUSD”)
// OrderID - Order id (ex: 1000)
func (e *Exchange) CancelExistingOrder(ctx context.Context, orderID int64, omsid string) (int64, error) {
req := make(map[string]any)
req["OrderId"] = orderID
req["OMSId"] = omsid
response := Response{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointCancelOrder,
req,
&response,
)
if err != nil {
return 0, err
}
if !response.IsAccepted {
return 0, errors.New(response.RejectReason)
}
return response.CancelOrderID, nil
}
// CancelAllExistingOrders cancels all open orders by symbol.
// symbol - Instrument code (ex: “BTCUSD”)
func (e *Exchange) CancelAllExistingOrders(ctx context.Context, omsid string) error {
req := make(map[string]any)
req["OMSId"] = omsid
response := Response{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointCancelAllOrders,
req,
&response,
)
if err != nil {
return err
}
if !response.IsAccepted {
return errors.New(response.RejectReason)
}
return nil
}
// GetOrders returns all current open orders
func (e *Exchange) GetOrders(ctx context.Context) ([]OpenOrders, error) {
response := OrderInfo{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointOpenOrders,
map[string]any{},
&response,
)
if err != nil {
return nil, err
}
if !response.IsAccepted {
return nil, errors.New(response.RejectReason)
}
return response.OpenOrders, nil
}
// GetOrderFee returns a fee associated with an order
// symbol - Instrument code (ex: “BTCUSD”)
// side - “buy” or “sell”
// quantity - Quantity
// price - Price in USD
func (e *Exchange) GetOrderFee(ctx context.Context, symbol, side string, quantity, price float64) (float64, error) {
req := make(map[string]any)
req["ins"] = symbol
req["side"] = side
req["qty"] = strconv.FormatFloat(quantity, 'f', -1, 64)
req["px"] = strconv.FormatFloat(price, 'f', -1, 64)
response := Response{}
err := e.SendAuthenticatedHTTPRequest(ctx,
exchange.RestSpot,
http.MethodPost,
alphapointOrderFee,
req,
&response,
)
if err != nil {
return 0, err
}
if !response.IsAccepted {
return 0, errors.New(response.RejectReason)
}
return response.Fee, nil
}
// SendHTTPRequest sends an unauthenticated HTTP request
func (e *Exchange) SendHTTPRequest(ctx context.Context, ep exchange.URL, method, path string, data map[string]any, result any) error {
endpoint, err := e.API.Endpoints.GetURL(ep)
if err != nil {
return err
}
headers := make(map[string]string)
headers["Content-Type"] = "application/json"
path = fmt.Sprintf("%s/ajax/v%s/%s", endpoint, alphapointAPIVersion, path)
PayloadJSON, err := json.Marshal(data)
if err != nil {
return errors.New("unable to JSON request")
}
item := &request.Item{
Method: method,
Path: path,
Headers: headers,
Result: result,
Verbose: e.Verbose,
HTTPDebugging: e.HTTPDebugging,
HTTPRecording: e.HTTPRecording,
}
return e.SendPayload(ctx, request.Unset, func() (*request.Item, error) {
item.Body = bytes.NewBuffer(PayloadJSON)
return item, nil
}, request.UnauthenticatedRequest)
}
// SendAuthenticatedHTTPRequest sends an authenticated request
func (e *Exchange) SendAuthenticatedHTTPRequest(ctx context.Context, ep exchange.URL, method, path string, data map[string]any, result any) error {
creds, err := e.GetCredentials(ctx)
if err != nil {
return err
}
endpoint, err := e.API.Endpoints.GetURL(ep)
if err != nil {
return err
}
n := e.Requester.GetNonce(nonce.UnixNano)
headers := make(map[string]string)
headers["Content-Type"] = "application/json"
data["apiKey"] = creds.Key
data["apiNonce"] = n
hmac, err := crypto.GetHMAC(crypto.HashSHA256,
[]byte(n.String()+creds.ClientID+creds.Key),
[]byte(creds.Secret))
if err != nil {
return err
}
data["apiSig"] = strings.ToUpper(hex.EncodeToString(hmac))
path = fmt.Sprintf("%s/ajax/v%s/%s", endpoint, alphapointAPIVersion, path)
PayloadJSON, err := json.Marshal(data)
if err != nil {
return errors.New("unable to JSON request")
}
item := &request.Item{
Method: method,
Path: path,
Headers: headers,
Result: result,
NonceEnabled: true,
Verbose: e.Verbose,
HTTPDebugging: e.HTTPDebugging,
HTTPRecording: e.HTTPRecording,
}
return e.SendPayload(ctx, request.Unset, func() (*request.Item, error) {
item.Body = bytes.NewBuffer(PayloadJSON)
return item, nil
}, request.AuthenticatedRequest)
}