Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions hyperliquid/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"math"
"math/big"
"strconv"
"strings"
Expand Down Expand Up @@ -56,8 +57,8 @@ func OrderRequestToWire(req OrderRequest, meta map[string]AssetInfo, isSpot bool
return OrderWire{
Asset: assetId,
IsBuy: req.IsBuy,
LimitPx: FloatToWire(req.LimitPx, maxDecimals, info.SzDecimals),
SizePx: FloatToWire(req.Sz, maxDecimals, info.SzDecimals),
LimitPx: RoundOrderPrice(req.LimitPx, info.SzDecimals, maxDecimals),
SizePx: RoundOrderSize(req.Sz, info.SzDecimals),
ReduceOnly: req.ReduceOnly,
OrderType: OrderTypeToWire(req.OrderType),
Cloid: req.Cloid,
Expand All @@ -80,8 +81,8 @@ func ModifyOrderRequestToWire(req ModifyOrderRequest, meta map[string]AssetInfo,
Order: OrderWire{
Asset: assetId,
IsBuy: req.IsBuy,
LimitPx: FloatToWire(req.LimitPx, maxDecimals, info.SzDecimals),
SizePx: FloatToWire(req.Sz, maxDecimals, info.SzDecimals),
LimitPx: RoundOrderPrice(req.LimitPx, info.SzDecimals, maxDecimals),
SizePx: RoundOrderSize(req.Sz, info.SzDecimals),
ReduceOnly: req.ReduceOnly,
OrderType: OrderTypeToWire(req.OrderType),
},
Expand Down Expand Up @@ -143,3 +144,38 @@ func StructToMap(strct any) (res map[string]interface{}, err error) {
json.Unmarshal(a, &res)
return res, nil
}

// Round the order size to the nearest tick size
func RoundOrderSize(x float64, szDecimals int) string {
newX := math.Round(x*math.Pow10(szDecimals)) / math.Pow10(szDecimals)
// TODO: add rounding
return big.NewFloat(newX).Text('f', szDecimals)
}

// Round the order price to the nearest tick size
func RoundOrderPrice(x float64, szDecimals int, maxDecimals int) string {
maxSignFigures := 5
allowedDecimals := maxDecimals - szDecimals
numberOfDigitsInIntegerPart := len(strconv.Itoa(int(x)))
if numberOfDigitsInIntegerPart >= maxSignFigures {
return RoundOrderSize(x, 0)
}
allowedSignFigures := maxSignFigures - numberOfDigitsInIntegerPart
if x < 1 {
text := RoundOrderSize(x, allowedDecimals)
startSignFigures := false
for i := 2; i < len(text); i++ {
if text[i] == '0' && !startSignFigures {
continue
}
startSignFigures = true
allowedSignFigures--
if allowedSignFigures == 0 {
return text[:i+1]
}
}
return text
} else {
return RoundOrderSize(x, min(allowedSignFigures, allowedDecimals))
}
}