/
trading.go
264 lines (231 loc) · 6.88 KB
/
trading.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package main
import (
"context"
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/shopspring/decimal"
"github.com/transerver/commons/configs"
"github.com/transerver/commons/dbs"
"github.com/transerver/commons/logger"
"github.com/xo/dburl"
"net/url"
"strconv"
"strings"
"time"
)
const (
tradingPath = "/api/fake/"
)
var (
minProfitRate = decimal.NewFromFloat(0.002)
two = decimal.NewFromInt(2)
db *dbs.Database
)
type Trading struct {
user User
market Market
logger *logger.Logger
robot Robot
}
func initDatabase() {
u, err := dburl.Parse(Settings.Database[0].URL)
if err != nil {
logger.Fatal(err)
}
db = dbs.NewDatabase(dbs.WithConfig(&configs.DBConfig{
Driver: "mysql",
DSN: u.DSN,
URL: u.RawPath,
DBName: u.Path[1:],
DesensitiseDSN: u.Redacted(),
Options: Settings.Database[0].Options,
}))
err = db.Connect()
if err != nil {
logger.Fatal("获取不到数据库连接", err)
}
// db.SetDatabaseLoggerHook()
}
func StartTradingRobot(user User, market Market) *Trading {
t := &Trading{
user: user,
market: market,
logger: logger.NewLogger(logger.WithPrefix("TRADING:%d:%s", user.ID, user.Username)),
}
t.Start()
return t
}
func (t *Trading) Start() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
row := db.QueryRowxContext(ctx, "SELECT id, strategyId, userId, status, userName, initialAsset, coinAmount, faitAmount, income, extractedIncome, totalIncome, isBuy, createTime, startTime, params FROM robot WHERE userId = ? AND status <= 1 AND marketName = 'btc_qc' LIMIT 1", t.user.ID)
if row.Err() != nil {
t.logger.Errorf("查询机器人失败: %v", row.Err())
return
}
var robot Robot
err := row.StructScan(&robot)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
err := t.CreateRobot()
if err != nil {
t.logger.Errorf("重来!!!, %v", err)
time.Sleep(time.Second * 10)
t.Start()
return
}
t.logger.Debugf("没有记录")
} else {
t.logger.Errorf("反序列化机器人失败: %v", err)
}
}
t.robot = robot
}
func (t *Trading) CreateRobot() (err error) {
count := Random(int64(101))
_, upper := t.getPrice(count)
if upper.IsZero() {
t.logger.Warnf("生成网格价格异常 -> Upper: %s", upper)
return nil
}
diff := minProfitRate.Add(minProfitRate.Mul(two)).Mul(upper).Sub(minProfitRate)
lower := upper.Sub(diff.Mul(decimal.NewFromInt(count)))
strategyId := RandomRange(15, 18)
var currency string
var isBuy bool
if strategyId == 16 {
currency = t.market.Currency
isBuy = true
} else if strategyId == 17 {
currency = t.market.Symbol
isBuy = false
} else {
currency = t.randomCurrency()
isBuy = currency == t.market.Currency
}
_ = isBuy
amount := t.getTotalAmount(upper, lower, count, isBuy)
err = Recharge(t.user.ID, currency, amount)
if err != nil {
return err
}
params := url.Values{
"userId": []string{strconv.Itoa(t.user.ID)},
"username": []string{t.user.Username},
"market": []string{t.market.Name},
"currency": []string{currency},
"strategyId": []string{strconv.Itoa(strategyId)},
"gridAmount": []string{strconv.FormatInt(count, 10)},
"type": []string{"1"},
"totalAmount": []string{amount.String()},
"lowerPrice": []string{lower.String()},
"upperPrice": []string{upper.String()},
"triggerPrice": []string{},
"exchangeWithStopLoss": []string{t.randomExchange()},
"exchangeWithStopProfit": []string{t.randomExchange()},
}
t.logger.Debugf("创建机器人参数: %s", params.Encode())
var resp Response[Robot]
err = timeout.GET(getTradingRequestURL("saveStrategy")).SetQuery(params.Encode()).BindJSON(&resp).Do()
if err != nil || !resp.Success() {
return fmt.Errorf("创建机器人失败 -> %s%v", resp.ResMsg.Message, err)
}
t.robot = resp.Payload
return nil
}
func (t *Trading) getTotalAmount(upper, lower decimal.Decimal, count int64, isBuy bool) decimal.Decimal {
// diff := minProfitRate.Add(minProfitRate.Mul(decimal.NewFromInt(2))).Mul(upper)
// diff := upper.Sub(lower).Div(decimal.NewFromInt(count))
// amount := upper.Sub(lower).Div(diff)
c := decimal.NewFromInt(int64(t.market.CurrencyBix))
minexchange := t.market.MinExchange.Add(c)
if isBuy {
return minexchange.Mul(decimal.NewFromInt(count))
}
minAmount := minexchange.Div(lower)
return decimal.Max(minAmount, t.market.MinAmount.Add(decimal.NewFromInt(int64(t.market.SymbolBix)))).Mul(c)
}
func (t *Trading) getPrice(count int64) (min, max decimal.Decimal) {
depth := Depth()
if depth.NotValid() {
return
}
downLen := len(depth.ListDown)
upLen := len(depth.ListUp)
if count <= 30 {
return t.prices(depth, downLen, upLen, 5)
} else if count <= 60 {
return t.prices(depth, downLen, upLen, 10)
} else if count <= 80 {
return t.prices(depth, downLen, upLen, 15)
} else {
return t.prices(depth, downLen, upLen, 20)
}
// if count <= 30 {
// return t.prices(depth, downLen, upLen, 5)
// } else if count <= 70 {
// return t.prices(depth, downLen, upLen, 10)
// } else if count <= 110 {
// return t.prices(depth, downLen, upLen, 15)
// } else {
// return t.prices(depth, downLen, upLen, 20)
// }
}
func (t *Trading) prices(depth QuickDepth, downLen, upLen, index int) (min, max decimal.Decimal) {
if downLen > index {
min = depth.ListDown[downLen-index][0]
} else {
min = depth.ListDown[downLen-1][0]
}
if upLen > index {
max = depth.ListUp[index][0]
} else {
max = depth.ListUp[upLen-1][0]
}
return
}
func (t *Trading) randomCurrency() string {
if Random(2) == 1 {
return t.market.Currency
}
return t.market.Symbol
}
func (t *Trading) randomExchange() string {
if Random(2) == 1 {
return "true"
}
return "false"
}
func ExtractIncome(robotId int) ([]byte, error) {
params := url.Values{"id": []string{strconv.Itoa(robotId)}}
var resp []byte
err := timeout.GET(getTradingRequestURL("extractIncome")).SetQuery(params.Encode()).BindBody(&resp).Do()
if err != nil {
logger.Errorf("提取收益[%d]失败 -> %v", robotId, err)
return resp, err
}
return resp, nil
}
func Shutdown(userId, robotId int, exchange bool) ([]byte, error) {
params := url.Values{
"userId": []string{strconv.Itoa(userId)},
"id": []string{strconv.Itoa(robotId)},
"exchangeWithStop": []string{strconv.FormatBool(exchange)},
}
var resp []byte
err := timeout.GET(getTradingRequestURL("shutdown")).SetQuery(params.Encode()).BindBody(&resp).Do()
if err != nil {
logger.Errorf("停止机器人[%d:%d]失败 -> %v", userId, robotId, err)
return resp, err
}
return resp, nil
}
func getTradingRequestURL(method string) string {
requestURL := Settings.Basic.TradingUrl
if strings.HasSuffix(requestURL, "/") {
requestURL = requestURL[:len(requestURL)-1]
}
return requestURL + tradingPath + method
}