-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
522 lines (472 loc) · 11.5 KB
/
main.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package main
import (
"errors"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/t0mk/pri/symbols"
)
const (
Binance Exchange = "binance"
Bitfinex Exchange = "bitfinex"
// Bitstamp Exchange = "bitstamp"
Bybit Exchange = "bybit"
Coinbase Exchange = "coinbase"
Coinmate Exchange = "coinmate"
Gateio Exchange = "gateio"
Huobi Exchange = "huobi"
Kraken Exchange = "kraken"
Kucoin Exchange = "kucoin"
Okx Exchange = "okx"
)
var exchangeGetters = map[Exchange]TickerGetter{
Binance: BinanceGetter,
Bitfinex: BitfinexGetter,
// Bitstamp: BitstampGetter,
Bybit: BybitGetter,
Coinbase: CoinbaseGetter,
Coinmate: CoinmateGetter,
Gateio: GateIOGetter,
Huobi: HuobiGetter,
Kraken: KrakenGetter,
Kucoin: KUCoinGetter,
Okx: OkxGetter,
}
var exchangeSymbols = map[Exchange][]string{
Binance: symbols.Binance,
Bitfinex: symbols.Bitfinex,
// Bitstamp: symbols.Bitstamp,
Bybit: symbols.Bybit,
Coinbase: symbols.Coinbase,
Coinmate: symbols.Coinmate,
Gateio: symbols.Gateio,
Huobi: symbols.Huobi,
Kraken: symbols.Kraken,
Kucoin: symbols.Kucoin,
Okx: symbols.Okx,
}
var debug = false
type Exchange string
type ExTick struct {
Exchange Exchange
Ticker string
}
type ExTickSet struct {
Name string
ExTicks []ExTick
}
type TickPrice struct {
MinAsk float64
MaxBid float64
}
type ExTickPri struct {
ExTick
Price TickPrice
Compare *ComparePrice
}
func formatRatioPercent(f1, f2 float64) string {
return fmt.Sprintf("%.1f%%", f1/f2*100)
}
func (etp ExTickPri) String() string {
et := etp.ExTick
r := fmt.Sprintf("[%15s]\t[%15s - %15s]", et, formatFloat(etp.Price.MinAsk), formatFloat(etp.Price.MaxBid))
if etp.Compare != nil {
// print how much is the bid or ask in comparison
if etp.Compare.Type == Bid {
r += fmt.Sprintf("\tcmp bid: %s", formatRatioPercent(etp.Price.MaxBid, etp.Compare.Price))
} else {
r += fmt.Sprintf("\tcmp ask: %s", formatRatioPercent(etp.Price.MinAsk, etp.Compare.Price))
}
}
return r
}
type ExTickPris []ExTickPri
type BidAsk string
const (
Bid BidAsk = "b"
Ask BidAsk = "a"
)
type ComparePrice struct {
Type BidAsk
Price float64
}
func ComparePriceFromString(s string) *ComparePrice {
if s == "" {
return nil
}
t := s[:1]
if t != "a" && t != "b" {
panic(fmt.Sprintf("invalid compare price type: %s", t))
}
f := parseFloat(s[1:])
ba := BidAsk(t)
return &ComparePrice{ba, f}
}
func (etps ExTickPris) MinAsk() ExTickPri {
min := etps[0]
for _, v := range etps {
if v.Price.MinAsk < min.Price.MinAsk {
min = v
}
}
return min
}
func (etps ExTickPris) MaxBid() ExTickPri {
max := etps[0]
for _, v := range etps {
if v.Price.MaxBid > max.Price.MaxBid {
max = v
}
}
return max
}
func (etps ExTickPris) String() string {
str := ""
for _, v := range etps {
str += fmt.Sprintf("%s\n", v)
}
return str
}
func ExTickPrisToArbResult(n string, etps ExTickPris) ArbResult {
return ArbResult{
Name: n,
TickPris: etps,
MinAsk: etps.MinAsk(),
MaxBid: etps.MaxBid(),
SpreadPercent: SpreadType(etps.SpreadPercent()),
}
}
type SpreadType float64
func (st SpreadType) String() string {
return fmt.Sprintf("%.3f%%", st)
}
type ArbResult struct {
Name string
TickPris ExTickPris
MinAsk ExTickPri
MaxBid ExTickPri
SpreadPercent SpreadType
}
func (ar ArbResult) String() string {
return fmt.Sprintf("name: %s\nmin: %s\nmax: %s\nspread: %s", ar.Name, ar.MinAsk, ar.MaxBid, ar.SpreadPercent)
}
type ArbResults []ArbResult
func (ars ArbResults) HighestSpread() ArbResult {
max := ars[0]
for _, v := range ars {
if v.SpreadPercent > max.SpreadPercent {
max = v
}
}
return max
}
func (ars ArbResults) LowestSpread() ArbResult {
min := ars[0]
for _, v := range ars {
if v.SpreadPercent < min.SpreadPercent {
min = v
}
}
return min
}
func (ars ArbResults) Report() {
for _, v := range ars {
fmt.Println(v.Name, v.SpreadPercent)
}
fmt.Println("Highest spread:")
fmt.Println(ars.HighestSpread())
fmt.Println("Lowest spread:")
fmt.Println(ars.LowestSpread())
}
func (etps ExTickPris) SpreadPercent() float64 {
min := etps.MinAsk().Price.MinAsk
max := etps.MaxBid().Price.MaxBid
return (max - min) / min * 100
}
func getExchangeTickerPrice(et ExTick) (*ExTickPri, error) {
start := time.Now()
getter := exchangeGetters[et.Exchange]
ab, err := getter(et.Ticker)
if err != nil {
return nil, errors.New(fmt.Sprintf("[%s]: error getting price: %v", et, err))
}
elapsed := time.Since(start)
if debug {
log.Printf("[%15s]\t[%5s]\t%s\n", et, elapsed, ab)
}
return &ExTickPri{et, TickPrice{ab.Ask, ab.Bid}, nil}, nil
}
func getExchangeTickerPriceAsync(et ExTick, channel chan *ExTickPri) {
etp, err := getExchangeTickerPrice(et)
if err != nil {
log.Printf("error getting price for %s: %v", et, err)
channel <- nil
return
}
channel <- etp
}
func findExTick(symbol string) (*ExTick, error) {
if hasExchangePrefix(symbol) {
sli := strings.SplitN(symbol, "-", 2)
if len(sli) != 2 {
return nil, fmt.Errorf("invalid symbol: %s", symbol)
}
exchange := Exchange(sli[0])
ticker := sli[1]
if _, ok := exchangeGetters[exchange]; !ok {
return nil, fmt.Errorf("ticker %s not found in exchange %s", ticker, exchange)
}
return &ExTick{exchange, ticker}, nil
}
foundSymbols := []string{}
foundExchanges := []Exchange{}
for k, v := range exchangeSymbols {
for _, t := range v {
if t == symbol {
foundSymbols = append(foundSymbols, t)
foundExchanges = append(foundExchanges, k)
}
}
}
if len(foundSymbols) == 0 {
return nil, fmt.Errorf("symbol not found: %s", symbol)
}
if len(foundSymbols) > 1 {
lst := []string{}
for i, v := range foundSymbols {
lst = append(lst, fmt.Sprintf("%s-%s", foundExchanges[i], v))
}
lines := strings.Join(lst, "\n")
return nil, fmt.Errorf("symbol %s found in multiple exchanges:\n%s", symbol, lines)
}
return &ExTick{foundExchanges[0], foundSymbols[0]}, nil
}
func preSetup() {
if (os.Getenv("DEBUG") != "") && (os.Getenv("DEBUG") != "0") {
debug = true
}
}
func stringIsInSlice(s string, sl []string) bool {
for _, v := range sl {
if v == s {
return true
}
}
return false
}
func searchForExchangeTicker(symbol string) []ExTick {
replacer := strings.NewReplacer("-", "", "/", "", "_", "")
found := []ExTick{}
for k, v := range exchangeSymbols {
for _, t := range v {
lowerT := strings.ToLower(t)
lowerTNoDashNoSlash := replacer.Replace(lowerT)
lowerSymbol := strings.ToLower(symbol)
lowerSymbolNoDashNoSlash := replacer.Replace(lowerSymbol)
if strings.Contains(lowerTNoDashNoSlash, lowerSymbolNoDashNoSlash) {
found = append(found, ExTick{k, t})
}
}
}
return found
}
func hasExchangePrefix(symbol string) bool {
for e, _ := range exchangeSymbols {
if strings.HasPrefix(symbol, string(e)) {
return true
}
}
return false
}
func main() {
preSetup()
la := len(os.Args)
if la == 1 {
panic("usage: pri [find] <symbol>")
}
cmd := os.Args[1]
if stringIsInSlice(cmd, arbitrageCommands) {
if la == 2 {
fmt.Println("arbitrage groups:")
for k, v := range arbs {
fmt.Printf("%s: %s\n", k, v)
}
return
}
if cmd == "aa" {
exTickSets := []ExTickSet{}
for name, a := range arbs {
arbTicks, err := ExTicksFromSlice(a)
if err != nil {
panic(err)
}
if len(arbTicks) < 2 {
fmt.Printf("Arbitrage group %s has less than 2 tickers, skipping\n", a)
continue
}
exTickSets = append(exTickSets, ExTickSet{name, arbTicks})
}
arbResultChannel := getArbResultAsync(exTickSets)
ars := CollectArbResultsFromChannel(arbResultChannel, len(exTickSets))
ars.Report()
return
}
}
if stringIsInSlice(cmd, findCommands) {
if la < 3 {
fmt.Println("usage: pri find <symbol>")
return
}
symbol := os.Args[2]
if hasExchangePrefix(symbol) {
sli := strings.SplitN(symbol, "-", 2)
fmt.Printf("Symbol should not have exchange prefix, use only %s instead of %s\n", sli[1], symbol)
return
}
<<<<<<< Updated upstream
fmt.Println(etp)
}
if len(os.Args) == 3 {
cmd := os.Args[1]
if stringIsInSlice(cmd, findCommands) {
symbol := os.Args[2]
if hasExchangePrefix(symbol) {
sli := strings.SplitN(symbol, "-", 2)
fmt.Printf("Symbol should not have exchange prefix, use only %s instead of %s\n", sli[1], symbol)
return
}
if len(symbol) < 3 {
fmt.Println("Symbol should be at least 3 characters long")
}
found := searchForExchangeTicker(symbol)
if len(found) == 0 {
fmt.Printf("Symbol \"%s\" not found\n", symbol)
return
}
fmt.Println("Found symbols:")
for _, v := range found {
fmt.Println(v)
}
if strings.Contains(cmd, "!") {
tickerChannel := getExTickPriChan(found)
CollectExTickPrisFromChannel(tickerChannel, len(found))
}
} else if stringIsInSlice(cmd, arbitrageCommands) {
arbName := os.Args[2]
arb, ok := arbs[arbName]
if !ok {
fmt.Printf("Arbitrage group %s not found\n", arbName)
return
=======
if len(symbol) < 3 {
fmt.Println("Symbol should be at least 3 characters long")
}
found := searchForExchangeTicker(symbol)
if len(found) == 0 {
fmt.Printf("Symbol \"%s\" not found\n", symbol)
return
}
fmt.Println("Found symbols:")
for _, v := range found {
fmt.Println(v)
}
if strings.Contains(cmd, "!") {
fmt.Println("Getting prices...")
tickerChannel := getExTickPriAsync(found)
for _, v := range found {
go getExchangeTickerPriceAsync(v, tickerChannel)
>>>>>>> Stashed changes
}
for i := 0; i < len(found); i++ {
etp := <-tickerChannel
fmt.Println(etp)
}
}
return
}
if stringIsInSlice(cmd, arbitrageCommands) {
arbName := os.Args[2]
arb, ok := arbs[arbName]
if !ok {
fmt.Printf("Arbitrage group %s not found\n", arbName)
return
}
for _, v := range arb {
fmt.Println(v)
}
if strings.Contains(cmd, "!") {
fmt.Println("Getting prices...")
arbTicks, err := ExTicksFromSlice(arb)
if err != nil {
panic(err)
}
arbResult := ExTicksToArbResult(ExTickSet{arbName, arbTicks})
fmt.Println(arbResult)
}
return
}
xt, err := findExTick(cmd)
if err != nil {
panic(err)
}
etp, err := getExchangeTickerPrice(*xt)
if err != nil {
panic(err)
}
if len(os.Args) > 2 {
c := ComparePriceFromString(os.Args[2])
etp.Compare = c
}
fmt.Println(etp)
}
func parseFloat(s string) float64 {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0
}
return f
}
func getArbResultAsync(exTickSets []ExTickSet) chan ArbResult {
arbResultChannel := make(chan ArbResult)
for _, v := range exTickSets {
go func(ets ExTickSet) {
arbResultChannel <- ExTicksToArbResult(ets)
}(v)
}
return arbResultChannel
}
func CollectArbResultsFromChannel(channel chan ArbResult, n int) ArbResults {
result := ArbResults{}
for i := 0; i < n; i++ {
ar := <-channel
result = append(result, ar)
}
return result
}
func ExTicksToArbResult(ets ExTickSet) ArbResult {
tickerChannel := getExTickPriChan(ets.ExTicks)
result := CollectExTickPrisFromChannel(tickerChannel, len(ets.ExTicks))
arbResult := ExTickPrisToArbResult(ets.Name, result)
return arbResult
}
func getExTickPriChan(tickers []ExTick) chan *ExTickPri {
tickerChannel := make(chan *ExTickPri)
for _, v := range tickers {
go getExchangeTickerPriceAsync(v, tickerChannel)
}
return tickerChannel
}
func CollectExTickPrisFromChannel(channel chan *ExTickPri, n int) ExTickPris {
result := ExTickPris{}
for i := 0; i < n; i++ {
etp := <-channel
if etp != nil {
fmt.Println(etp)
result = append(result, *etp)
}
}
return result
}