/
pnl.go
231 lines (197 loc) · 6.57 KB
/
pnl.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
package main
import (
"context"
"fmt"
"github.com/dgraph-io/ristretto"
"github.com/ljg-cqu/biance/biance"
"github.com/ljg-cqu/biance/biance/asset"
"github.com/ljg-cqu/biance/biance/pnl"
"github.com/ljg-cqu/biance/email"
"github.com/ljg-cqu/biance/logger"
"math/big"
"net/http"
"sync"
"time"
)
const (
FilterLevel0 FilterLevel = iota
FilterLevel1
FilterLevel2
FilterLevel3
FilterLevel4
FilterLevel5
FilterLevel6
)
var FilterMap = Filter{
FilterLevel0: {FilterLevel0, "0.03", "0.03", time.Second * 7, time.Second * 105},
FilterLevel1: {FilterLevel1, "0.05", "0.05", time.Second * 6, time.Second * 90},
FilterLevel2: {FilterLevel2, "0.10", "0.10", time.Second * 5, time.Second * 75},
FilterLevel3: {FilterLevel3, "0.15", "0.15", time.Second * 4, time.Second * 60},
FilterLevel4: {FilterLevel4, "0.20", "0.20", time.Second * 3, time.Second * 45},
FilterLevel5: {FilterLevel5, "0.25", "0.25", time.Second * 2, time.Second * 30},
FilterLevel6: {FilterLevel6, "0.30", "0.30", time.Second * 1, time.Second * 15},
}
type Filter map[FilterLevel]FilterGainValAndLoss
type FilterGainValAndLoss struct {
FilterLevel FilterLevel
GainPercent string
LossPercent string
CheckPNLInterval time.Duration
ReportPNLInterval time.Duration
}
type FilterLevel int
type PNLMonitor struct {
Logger logger.Logger
ApiKey string
SecretKey string
WP *sync.WaitGroup
Cache *ristretto.Cache
Filter FilterGainValAndLoss
client biance.Client
userAssetURL string
symbolPriceURL string
ReportGain bool
ReportLoss bool
emailGainReportCH chan string
emailLossReportCH chan string
gailEmailAddress string
lossEmailAddress string
lossReportTimeAmplifier time.Duration
}
func (m *PNLMonitor) Init() {
m.client = &http.Client{}
m.userAssetURL = biance.URLs[biance.URLUserAsset]
m.symbolPriceURL = biance.URLs[biance.URLSymbolPrice]
m.emailGainReportCH = make(chan string, 1024)
m.emailLossReportCH = make(chan string, 1024)
m.gailEmailAddress = "ljg_cqu@163.com"
m.lossEmailAddress = "1025003548@qq.com"
m.lossReportTimeAmplifier = 5
}
func (m *PNLMonitor) Run(ctx context.Context) {
tCheck := time.NewTicker(m.Filter.CheckPNLInterval)
defer tCheck.Stop()
defer m.WP.Done()
go m.sendPNLReportWIthEmail(ctx)
for {
select {
case <-ctx.Done():
return
case <-tCheck.C:
freePNLs, err := pnl.CheckFreePNLWithUSDTOrBUSD(m.client, m.userAssetURL, m.symbolPriceURL, "", m.ApiKey, m.SecretKey)
if err != nil {
m.Logger.ErrorOnError(err, "Failed to check PNL")
continue
}
var freePNLsFilter pnl.FreePNLs
var tokenFilerMap = map[asset.Token]string{
"NBS": "",
"USDT": "",
"BUSD": "",
"VIDT": "",
"OG": "",
}
for _, freePNL := range freePNLs {
_, ok1 := tokenFilerMap[freePNL.Token]
key := string(freePNL.Token) + m.Filter.ReportPNLInterval.String()
_, ok2 := m.Cache.Get(key)
if ok1 || ok2 {
continue
}
freePNLsFilter = append(freePNLsFilter, freePNL)
}
gain, loss := buildReport(freePNLsFilter, m.Filter.FilterLevel, m.Filter.GainPercent, m.Filter.LossPercent)
if gain != "" || loss != "" {
fmt.Println(gain + loss)
}
if gain != "" && m.ReportGain {
m.emailGainReportCH <- gain
for _, freePNLFilter := range freePNLsFilter {
key := string(freePNLFilter.Token) + m.Filter.ReportPNLInterval.String()
m.Cache.SetWithTTL(key, "", 1, m.Filter.ReportPNLInterval)
m.Cache.Wait()
}
}
if loss != "" && m.ReportLoss {
m.emailLossReportCH <- loss
for _, freePNLFilter := range freePNLsFilter {
key := string(freePNLFilter.Token) + m.Filter.ReportPNLInterval.String()
m.Cache.SetWithTTL(key, "", 1, m.Filter.ReportPNLInterval*m.lossReportTimeAmplifier)
m.Cache.Wait()
}
}
}
}
}
func (m *PNLMonitor) sendPNLReportWIthEmail(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case content := <-m.emailGainReportCH:
subject := "Biance Investment Gain Report"
m.doSendPNLReportWIthEmail(ctx, subject, content, m.gailEmailAddress)
case content := <-m.emailLossReportCH:
subject := "Biance Investment Loss Report"
m.doSendPNLReportWIthEmail(ctx, subject, content, m.lossEmailAddress)
}
}
}
func (m *PNLMonitor) doSendPNLReportWIthEmail(ctx context.Context, subject, content, to string) {
err := email.Send163Mail(m.Logger, ctx, subject, content, to)
m.Logger.DebugOnError(err, "Failed to send email with 163 mailbox")
if err != nil {
err = email.Send126Mail(m.Logger, ctx, subject, content, to)
m.Logger.DebugOnError(err, "Failed to send email with 126 mailbox")
}
if err != nil {
err := email.SendQQMail(m.Logger, ctx, subject, content, to)
m.Logger.DebugOnError(err, "Failed to send email with QQ mailbox.")
}
}
func buildReport(freePNLs pnl.FreePNLs, filterLevel FilterLevel, filterGainPercent, filterLossPercent string) (string, string) {
var filterGainPNLs []pnl.FreePNL
var filterLossPNLs []pnl.FreePNL
zeroGain, _ := new(big.Float).SetString("0")
zeroLoss, _ := new(big.Float).SetString("0")
filterGainPercentBig, _ := new(big.Float).SetString(filterGainPercent)
filterLossPercentBig, _ := new(big.Float).SetString(filterLossPercent)
var totalGain = zeroGain
var totalLoss = zeroLoss
oneHundred, _ := new(big.Float).SetString("100")
zero, _ := new(big.Float).SetString("0")
for _, freePNL := range freePNLs {
switch freePNL.PNLPercent.Cmp(zero) {
case 1:
if freePNL.PNLPercent.Cmp(filterGainPercentBig) == 1 {
filterGainPNLs = append(filterGainPNLs, freePNL)
totalGain = new(big.Float).Add(totalGain, freePNL.PNLValue)
}
case 0:
case -1:
if new(big.Float).Abs(freePNL.PNLPercent).Cmp(filterLossPercentBig) == 1 {
filterLossPNLs = append(filterLossPNLs, freePNL)
totalLoss = new(big.Float).Add(totalLoss, freePNL.PNLValue)
}
}
}
var gainInfoStr string
var lossInfoStr string
if len(filterGainPNLs) > 0 {
gainInfoStr = fmt.Sprintf("\n+++LEVEL:%v\n+++TOKEN:%v PROFIT:%v\n+++TIME:%v\n",
filterLevel, len(filterGainPNLs), totalGain, time.Now())
for i, gainPNL := range filterGainPNLs {
gainInfoStr += fmt.Sprintf("(%v) %v %v => %v @%v%%\n", i, gainPNL.Symbol, gainPNL.PNLAmountConvertable,
gainPNL.PNLValue, new(big.Float).Mul(oneHundred, gainPNL.PNLPercent))
}
}
if len(filterLossPNLs) > 0 {
lossInfoStr = fmt.Sprintf("\n---LEVEL:%v\n---TOKEN:%v LOSS:%v\n---%v\n",
filterLevel, len(filterLossPNLs), totalLoss, time.Now())
for i, lossPNL := range filterLossPNLs {
lossInfoStr += fmt.Sprintf("(%v) %v %v @%v%%\n", i, lossPNL.Symbol,
lossPNL.PNLValue, new(big.Float).Mul(oneHundred, lossPNL.PNLPercent))
}
}
return gainInfoStr, lossInfoStr
}