109 lines
1.9 KiB
Go
109 lines
1.9 KiB
Go
package trade
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"math/rand"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func GetSide(in string) string {
|
|
in = strings.TrimSpace(in)
|
|
|
|
if in == "buy" || in == "sell" {
|
|
return in
|
|
}
|
|
|
|
switch strings.ToUpper(in) {
|
|
case "LONG":
|
|
return "buy"
|
|
case "SHORT":
|
|
return "sell"
|
|
}
|
|
|
|
return ""
|
|
}
|
|
|
|
|
|
|
|
// 根据持仓状态执行相应的方法
|
|
func GetPositionStats(LongExists, ShortExists bool) PositionStatus {
|
|
switch {
|
|
case !LongExists && !ShortExists:
|
|
return NoPositions
|
|
case LongExists && !ShortExists:
|
|
return LongOnly
|
|
case !LongExists && ShortExists:
|
|
return ShortOnly
|
|
case LongExists && ShortExists:
|
|
return BothPositions
|
|
}
|
|
|
|
return -1
|
|
}
|
|
|
|
func FmtNumber(in float64, place int) string {
|
|
if place == 0 {
|
|
return fmt.Sprintf("%.0f", in)
|
|
}
|
|
if place == 1 {
|
|
return fmt.Sprintf("%.1f", in)
|
|
}
|
|
if place == 2 {
|
|
return fmt.Sprintf("%.2f", in)
|
|
}
|
|
if place == 3 {
|
|
return fmt.Sprintf("%.3f", in)
|
|
}
|
|
if place == 4 {
|
|
return fmt.Sprintf("%.4f", in)
|
|
}
|
|
if place == 5 {
|
|
return fmt.Sprintf("%.5f", in)
|
|
}
|
|
|
|
return fmt.Sprintf("%.6f", in)
|
|
}
|
|
|
|
func FloatRound(in float64, place int) float64 {
|
|
// 限制 place 范围在合理区间
|
|
if place < 0 {
|
|
place = 0
|
|
}
|
|
|
|
// 使用 strconv.FormatFloat 直接格式化,避免多次条件判断
|
|
str := strconv.FormatFloat(in, 'f', place, 64)
|
|
num, _ := strconv.ParseFloat(str, 64)
|
|
return num
|
|
}
|
|
|
|
func RateToFloat64(s string) float64 {
|
|
// 去掉百分号
|
|
s = strings.TrimSuffix(s, "%")
|
|
// 转换为 float64
|
|
f, err := strconv.ParseFloat(s, 64)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return f
|
|
}
|
|
func Output(v any) {
|
|
jsonBy, _ := json.Marshal(v)
|
|
var out bytes.Buffer
|
|
json.Indent(&out, jsonBy, "", "\t")
|
|
out.WriteTo(os.Stdout)
|
|
fmt.Printf("\n")
|
|
}
|
|
|
|
func GenClientId() string {
|
|
cTime := time.Now().Format("20060102150405")
|
|
|
|
rand.Seed(time.Now().UnixNano())
|
|
random := fmt.Sprintf("%04d", rand.Intn(10000))
|
|
return cTime + random
|
|
}
|