-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
2729 lines (2364 loc) · 69.7 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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*MIT License
Copyright (c) 2021 Joerg Hillebrand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. */
package main
import (
"bufio"
"bytes"
"database/sql"
"encoding/json"
"fmt"
"image/png"
"math"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
_ "github.com/lib/pq"
"github.com/pquerna/otp/totp"
"github.com/sajari/regression"
"github.com/spf13/viper"
)
var pipeFile = "/tmp/yourpipe"
var do_trace bool = true
var btcref bool = false
var sleepbeforerun int
var sell_days int64
var exchange_name string
var curr_quote string = "EUR"
var pairs []string
var tradepairs []string
var nobuypairs []string
var gctcmd string
var wwwpath string
var pguser string
var pgpassword string
var pgdb string
var tbtoken string
var limit_depth int
var invest_amount int
var minwin int
var useticker bool = false
var usezerostrategy bool = false
var bullstrategy bool = false
var bullwin int
var bulltrend float64 = 1
var amountcomma map[string]string
var pricecomma map[string]string
var key_issuer string
var key_account string
var key_secret string
type Parm struct {
key string
intp int64
floatp float64
stringp string
datep time.Time
timep time.Time
timestampp time.Time
}
type Order struct {
exchange string
id string
base_currency string
quote_currency string
asset string
order_side string
order_type string
creation_time float64
update_time float64
status string
price float64
amount float64
open_volume float64
cost float64
}
func main() {
fmt.Printf("%v\n", time.Now().String())
// Set location of config
dirname, err := os.UserHomeDir()
if err != nil {
fmt.Println(err)
}
// viper.SetConfigName("yourCryptoBot") // name of config file (without extension)
viper.AddConfigPath(dirname + "/.yourCryptoBot/") // path to look for the config file in
// Get commandline args
if len(os.Args) > 2 {
exc := os.Args[1]
viper.SetConfigName(exc) // name of config file (name of exchange)
// Read config
read_config()
if exc != exchange_name {
panic("Wrong exchange")
}
a1 := os.Args[2]
if a1 == "cron" {
time.Sleep(time.Duration(sleepbeforerun) * time.Second)
getCandles()
deleteCandles()
deleteStats()
insertStats()
updateStats()
processMinMax()
calculateLimit()
calculateTrends()
if btcref {
btcReference()
}
deleteAccounts()
deleteOldOrders()
readAccount()
readOrders()
processOrders()
deleteOrders()
writeCharts()
buyOrders()
sellOrders()
deactivatePositions()
activatePositions()
decreasePositionRates()
os.Exit(0)
}
if a1 == "sell" {
sellOrders()
os.Exit(0)
}
if a1 == "jhtest" {
jhtest()
os.Exit(0)
}
if a1 == "report" {
deleteOldSum()
calculateSum()
writeReport()
writeSumAll()
writeDiff()
os.Exit(0)
}
if a1 == "gettransactionsall" {
getTransactionsAll()
writeReport()
os.Exit(0)
}
if a1 == "butsell" {
time.Sleep(15 * time.Second)
getCandles()
deleteCandles()
deleteStats()
insertStats()
updateStats()
processMinMax()
calculateLimit()
calculateTrends()
writeCharts()
os.Exit(0)
}
if a1 == "candles" {
getCandles()
deleteCandles()
os.Exit(0)
}
if a1 == "updatestats" {
deleteStats()
insertStats()
updateStats()
calculateLimit()
calculateTrends()
os.Exit(0)
}
if a1 == "limits" {
calculateLimit()
os.Exit(0)
}
if a1 == "doorder" {
buyOrders()
sellOrders()
os.Exit(0)
}
if a1 == "forceorder" {
forceOrder(os.Args[3], os.Args[4], os.Args[5])
os.Exit(0)
}
if a1 == "ticker" {
runTicker(os.Args[3], os.Args[4], os.Args[5], os.Args[6], os.Args[7])
os.Exit(0)
}
if a1 == "telegram" {
sendTelegram()
os.Exit(0)
}
if a1 == "totp" {
genTotp()
os.Exit(0)
}
if a1 == "testtotp" {
testTotp(os.Args[3])
os.Exit(0)
}
if a1 == "allowtrade" {
allowTrade(os.Args[3])
os.Exit(0)
}
if a1 == "account" {
deleteAccounts()
readAccount()
os.Exit(0)
}
if a1 == "orders" {
readOrders()
processOrders()
deleteOrders()
os.Exit(0)
}
if a1 == "trend" {
calculateTrends()
os.Exit(0)
}
if a1 == "chart" {
writeCharts()
os.Exit(0)
}
if a1 == "sum" {
calculateSum()
os.Exit(0)
}
if a1 == "positions" {
deactivatePositions()
activatePositions()
os.Exit(0)
}
fmt.Println("parameter invalid")
os.Exit(-1)
}
if len(os.Args) == 1 {
myUsage()
}
}
func getCandles() {
var start string
var end string
var exchange string
var interval string
var base string
var quote string
var open float64
var close float64
var low float64
var high float64
var volume float64
var stime string
var layout string = "2006-01-02 15:04:05 MST"
var cand map[string]interface{}
var pair map[string]interface{}
var cndls []interface{}
ti1 := time.Now()
ti2 := time.Now()
ti1 = ti1.Add(time.Minute * -15)
fmt.Println(ti2.String())
limit1 := ti1.String()[0:16]
limit2 := ti2.String()[0:16]
for i, v := range pairs {
fmt.Printf("Index: %d, Value: %v\n", i, v)
out := getPair(v, limit1+":00", limit2+":00")
if out == nil {
fmt.Println("Result empty")
continue
}
err := json.Unmarshal(out, &cand)
if err != nil { // Handle JSON errors
fmt.Printf("JSON error: %v\n", err)
fmt.Printf("JSON input: %v\n", string(out))
continue
}
if cand["start"] != nil {
start = cand["start"].(string)
}
if cand["end"] != nil {
end = cand["end"].(string)
}
if cand["exchange"] == nil {
continue
}
exchange = cand["exchange"].(string)
interval = cand["interval"].(string)
pair = cand["pair"].(map[string]interface{})
base = pair["base"].(string)
quote = pair["quote"].(string)
cndls = cand["candle"].([]interface{})
fmt.Printf("S: %s, E: %s, Ex: %s, I: %s, C:%s-%s\n", start, end, exchange, interval, base, quote)
for _, cndl := range cndls {
cn := cndl.(map[string]interface{})
if cn != nil {
open = cn["open"].(float64)
close = cn["close"].(float64)
if cn["volume"] != nil {
volume = cn["volume"].(float64)
} else {
volume = 0
}
low = cn["low"].(float64)
high = cn["high"].(float64)
stime = cn["time"].(string)
t, err := time.Parse(layout, stime)
if err != nil {
fmt.Printf("Time conversion error: %v", err)
}
fmt.Printf("O: %f, C: %f, H: %f, L: %f, V: %f, T: %s\n", open, close, high, low, volume, t)
insertCandles(exchange, base+"-"+quote, interval, t, open, high, low, close, volume, "SPOT")
}
}
}
}
func readAccount() {
var cur string
output := getAccount()
str := string(output)
lines := strings.Split(str, "\n")
for _, value := range lines {
value = strings.TrimSpace(value)
words := strings.Split(value, " ")
if strings.Contains(words[0], "currency") {
cur = strings.Trim(words[1], "\",")
}
if strings.Contains(words[0], "total") {
tot := strings.Trim(words[1], "\",")
if total, err := strconv.ParseFloat(tot, 64); err == nil {
fmt.Printf("Curr: %s, Total: %f\n", cur, total)
storeAccount(exchange_name, cur, total)
}
}
}
}
func insertCandles(exchange string, pair string, interval string, timest time.Time, open float64, high float64, low float64,
close float64, volume float64, asset string) {
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
UPDATE yourcandle
set open = $1, high = $2, low = $3, close = $4, volume = $5
where exchange = $6 and pair = $7 and asset = $8 and interval = $9 and timestamp = $10`
info, _ := db.Exec(sqlStatement, open, high, low, close, volume, exchange, pair, asset, interval, timest)
count, err := info.RowsAffected()
if err != nil {
panic(err)
}
if count == 0 {
sqlStatement := `
INSERT INTO yourcandle (
exchange, pair, interval, timestamp, open, high, low, close, volume, asset)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`
_, err = db.Exec(sqlStatement, exchange, pair, interval, timest, open, high, low, close, volume, asset)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
}
func insertPositions(exchange string, pair string, trtype string, timest time.Time, rate float64, amount float64) {
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
INSERT INTO yourposition (exchange, pair, trtype, timestamp, rate, amount)
VALUES ($1, $2, $3, $4, $5, $6)`
_, err = db.Exec(sqlStatement, exchange, pair, trtype, timest, rate, amount)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func deletePositions(exchange string, pair string) {
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
DELETE FROM yourposition
WHERE exchange = $1 and pair = $2 and active = true;`
_, err = db.Exec(sqlStatement, exchange, pair)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func storeAccount(exchange string, currency string, amount float64) {
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
UPDATE youraccount
set amount = $1
where exchange = $2 and currency = $3`
info, _ := db.Exec(sqlStatement, amount, exchange, currency)
count, err := info.RowsAffected()
if err != nil {
panic(err)
}
if count == 0 {
sqlStatement := `
INSERT INTO youraccount (exchange, currency, amount)
VALUES ($1, $2, $3)`
_, err = db.Exec(sqlStatement, exchange, currency, amount)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
}
func storeOrder(exchange string, id string, pair string, asset string, side string, otype string,
timest float64, status string, price float64, amount float64) {
var tst time.Time = time.Unix(int64(timest), 0)
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
UPDATE yourorder
set pair = $3, asset = $4, price = $5, amount = $6, side = $7, timestamp = $8, order_type = $9, status = $10
where exchange = $1 and id = $2`
info, err := db.Exec(sqlStatement, exchange, id, pair, asset, price, amount, side, tst, otype, status)
if err != nil {
panic(err)
}
count, err := info.RowsAffected()
if err != nil {
panic(err)
}
if count == 0 {
sqlStatement := `
INSERT INTO yourorder (exchange, id, pair, asset, price ,amount, side, timestamp, order_type, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8 ,$9, $10)`
_, err = db.Exec(sqlStatement, exchange, id, pair, asset, price, amount, side, tst, otype, status)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
}
func insertStats() {
var advicePeriod int64 = 7 * 24
var intv string = "'168 hours'"
parm, err := getParms("AdvicePeriod")
if err == nil {
advicePeriod = parm.intp
intv = fmt.Sprintf("'%d hours'", advicePeriod)
}
fmt.Printf("Insert statistics %s\n", intv)
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
insert into yourlimits (exchange,pair, min,avg,max,count,potwin)
(select exchange,pair, min(close) as min, avg(close) as avg, max(close) as max, count(close) as count,
(max(close) - min(close)) * $1 / min(close) as potwin
from yourcandle
where "timestamp" > current_timestamp - interval ` + intv + `
AND LOWER(exchange) = $2
group by exchange,pair
order by pair);`
_, err = db.Exec(sqlStatement, limit_depth, exchange_name)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func calculateMinMax(pair string) {
var advicePeriod int64 = 7 * 24
var intv string = "'168 hours'"
var min float64
var max float64
var last float64
parm, err := getParms("AdvicePeriod")
if err == nil {
advicePeriod = parm.intp
intv = fmt.Sprintf("'%d hours'", advicePeriod)
}
fmt.Printf("Calculate MinMax for pair %s\n", pair)
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
select close
from yourcandle
where "timestamp" > current_timestamp - interval ` + intv + `
AND LOWER(exchange) = $1
AND pair = $2
order by close;`
rows, err := db.Query(sqlStatement, exchange_name, pair)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
defer rows.Close()
var i int = 0
for rows.Next() {
var cls float64
if err := rows.Scan(&cls); err != nil {
fmt.Println(err)
} else {
if i == 1 {
min = cls
}
if i > 0 {
max = last
}
last = cls
}
i++
}
if err := rows.Err(); err != nil {
fmt.Println(err)
}
fmt.Printf("Min: %f, Max: %f\n", min, max)
sqlStatement = `
UPDATE yourlimits
SET min = $1, max = $2
where pair = $3
AND LOWER(exchange) = $4;`
_, err = db.Exec(sqlStatement, min, max, pair, exchange_name)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func updateStats() {
fmt.Println("Update statistics")
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
for _, v := range pairs {
sqlStatement := `
WITH subquery AS (
select close, pair, ((close - open) * 100 / open) as lastcandle from yourcandle y
where timestamp =
(select max(timestamp) from yourcandle where LOWER(exchange) = $1 and pair = $2)
AND LOWER(exchange) = $1 and pair = $2
)
UPDATE yourlimits l
SET current = subquery.close,
lastcandle = subquery.lastcandle
FROM subquery
WHERE l.pair = subquery.pair
AND LOWER(l.exchange) = $1;`
_, err = db.Exec(sqlStatement, exchange_name, v)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
}
func calculateLimit() {
var depth int = (100 - limit_depth) / 2
fmt.Println("Calculate limit")
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
with subquery as (
select
pair,
(min + (max - min)*$1/100) as limitbuy,
(max - (max - min)*$1/100) as limitsell
from yourlimits where LOWER(exchange) = $2
)
UPDATE yourlimits l
SET "limitbuy" = subquery.limitbuy,
"limitsell" = subquery.limitsell
FROM subquery
WHERE l.pair = subquery.pair
AND LOWER(l.exchange) = $2;`
_, err = db.Exec(sqlStatement, depth, exchange_name)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func deleteStats() {
fmt.Println("Delete statistics")
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
delete from yourlimits
WHERE LOWER(exchange) = $1;`
_, err = db.Exec(sqlStatement, exchange_name)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func deleteAccounts() {
fmt.Println("Delete accounts")
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
delete from youraccount
WHERE exchange = $1;`
_, err = db.Exec(sqlStatement, exchange_name)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func deleteOrders() {
fmt.Println("Delete orders")
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
delete from yourorder
where status in ('CANCELLED','CANCELED','REJECTED')
AND LOWER(exchange) = $1;`
_, err = db.Exec(sqlStatement, exchange_name)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func deleteOldOrders() {
fmt.Println("Delete old orders")
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
delete from yourorder
where "timestamp" < current_timestamp - interval '30 days'
AND LOWER(exchange) = $1;`
_, err = db.Exec(sqlStatement, exchange_name)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func deleteOldSum() {
fmt.Println("Delete old sums")
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
delete from yoursum
where valdate < current_date - interval '35 days';`
_, err = db.Exec(sqlStatement)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func deleteCandles() {
fmt.Println("Delete candles")
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
delete from yourcandle
where "timestamp" < current_timestamp - interval '35 days'`
_, err = db.Exec(sqlStatement)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func getPair(p string, s string, e string) []byte {
out, err := exec.Command(gctcmd, "gethistoriccandlesextended",
"-e", exchange_name, "-a", "SPOT", "-p", p, "-i", "900",
"--start", s, "--end", e).Output()
if err != nil {
fmt.Printf("Command finished with error: %v", err)
}
return out
}
func getAccount() []byte {
out, err := exec.Command(gctcmd, "getaccountinfo",
"--exchange", exchange_name, "--asset", "SPOT").Output()
if err != nil {
fmt.Printf("Command finished with error: %v", err)
}
return out
}
func getOrder(pair string, id string) []byte {
cmd := exec.Command(gctcmd, "getorder",
"--exchange", exchange_name, "--asset", "SPOT", "--pair", pair, "--order_id", id)
out, err := cmd.Output()
if err != nil {
fmt.Printf("Command finished with error: %v", err)
fmt.Println(cmd.String())
}
return out
}
func getOrders(pair string) []byte {
out, err := exec.Command(gctcmd, "getorders",
"--exchange", exchange_name, "--asset", "SPOT", "--pair", pair).Output()
if err != nil {
fmt.Printf("Command finished with error: %v", err)
}
return out
}
func submitOrder(pair string, side string, otype string, amount float64, price float64, clientid string) []byte {
var resp map[string]interface{}
var stramount string
var strprice string
var aformat string = "%." + amountcomma[strings.ToLower(pair)] + "f"
var pformat string = "%." + pricecomma[strings.ToLower(pair)] + "f"
apot, _ := strconv.ParseInt(amountcomma[strings.ToLower(pair)], 10, 32)
fac := math.Pow(float64(10), float64(apot))
amount = float64(math.Floor(amount*fac) / fac)
stramount = fmt.Sprintf(aformat, amount)
strprice = fmt.Sprintf(pformat, price)
fmt.Printf("A: %s, P: %s\n", stramount, strprice)
cmd := exec.Command(gctcmd, "submitorder",
"--exchange", exchange_name, "--asset", "SPOT", "--pair", pair, "--side", side, "--type", otype,
"--amount", stramount, "--price", strprice, "--client_id", clientid)
out, err := cmd.Output()
if err != nil {
fmt.Printf("Command finished with error: %v", err)
fmt.Println(cmd.String())
} else {
err := json.Unmarshal(out, &resp)
if err != nil { // Handle JSON errors
fmt.Printf("JSON error: %v\n", err)
fmt.Printf("JSON input: %v\n", string(out))
} else {
// status = strings.ToLower(resp["exchange"].(string))
if resp["order_id"] != nil {
id := resp["order_id"].(string)
storeOrder(exchange_name, id, pair, "SPOT", side, otype, float64(time.Now().Unix()), "NEW", price, amount)
} else if resp["id"] != nil {
id := resp["id"].(string)
storeOrder(exchange_name, id, pair, "SPOT", side, otype, float64(time.Now().Unix()), "NEW", price, amount)
} else {
fmt.Printf("Submit error: P: %s, S: %s, T: %s, A: %s, Pr: %s\n", pair, side, otype, stramount, strprice)
}
}
}
return out
}
func cancelOrder(pair string, oid string) []byte {
out, err := exec.Command(gctcmd, "cancelorder",
"--exchange", exchange_name, "--asset", "SPOT", "--pair", pair, "--order_id", oid).Output()
if err != nil {
fmt.Printf("Command finished with error: %v", err)
}
return out
}
func insertParms(key string, intp int64, floatp float64, stringp string, datep time.Time, timep time.Time, timestampp time.Time) {
fmt.Printf("Insert parm %v\n", key)
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
insert into yourparameter (key, "int", "float", "string", "date", "time", "timestamp")
values ($1,$2,$3,$4,$5,$6,$7);`
_, err = db.Exec(sqlStatement, key, intp, floatp, stringp, datep, timep, timestampp)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
}
func getParms(key string) (parms Parm, err error) {
fmt.Printf("Get parm %v\n", key)
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
parms.key = ""
sqlStatement := `
select "key", "int", "float", "string", "date", "time", "timestamp" from yourparameter
where key = $1;`
err = db.QueryRow(sqlStatement, key).Scan(&parms.key, &parms.intp, &parms.floatp, &parms.stringp, &parms.datep, &parms.timep, &parms.timestampp)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
return
}
func getBuyPriceNew(pair string) (price float64, amount float64, err error) {
var current float64
var limit float64
var min float64
var potwin float64
var trend1 float64
var trend2 float64
var trend3 float64
var lastcandle float64
price = 0
amount = 0
if arrayContains(nobuypairs, pair) {
fmt.Println("Nobuyflag set for this pair")
return
}
fmt.Printf("Get buy price %v\n", pair)
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", "localhost", 5432, pguser, pgpassword, pgdb)
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
defer db.Close()
sqlStatement := `
select l.limitbuy, l.current, l.min, l.potwin, l.trend1, l.trend2, l.trend3, l.lastcandle from yourlimits l
where l.pair = $1
AND LOWER(l.exchange) = $2
and l.pair not in
(select distinct p.pair from yourposition p, yourlimits x
where p.pair = $1
AND LOWER(p.exchange) = $2
and LOWER(x.exchange) = LOWER(p.exchange)
and x.pair = p.pair
and p.notrade = false
AND
(p.active = true
or
p.rate > (x.current * 0.98) and
p.rate < (x.current * 1.02)
)
);`
err = db.QueryRow(sqlStatement, pair, exchange_name).Scan(&limit, ¤t, &min, &potwin, &trend1, &trend2, &trend3, &lastcandle)
if err != nil {
fmt.Printf("SQL error: %v\n", err)
}
fmt.Printf("C: %f, L: %f, M: %f, P: %f, T1: %f, T2: %f, T3: %f, LC: %f\n", current, limit, min, potwin, trend1, trend2, trend3, lastcandle)
if (current < limit) && (potwin > float64(minwin)+1) && isEnoughMoney() {
var dobuy bool = false
if (current >= min) && (trend2 < -1) && (trend1 > 0.1) {
dobuy = true
fmt.Println("Rule 1")
} else if (current >= min) && (trend3 < -0.3) && (trend2 < -0.1) && (trend2 > -0.5) && (trend1 > 0.1) {
dobuy = true
fmt.Println("Rule 2")
} else if (current >= min) && (trend2 < 0.7) && (trend2 > -0.7) && (trend1 > 0.1) {
dobuy = true
fmt.Println("Rule 3")
} else if (usezerostrategy) && (math.Abs(trend1) < 0.03) {
dobuy = true
fmt.Println("Rule 4")
} else {
fmt.Println("wait due to trend")
if useticker {
_ = exec.Command(os.Args[0], exchange_name, "ticker", pair,
"BUY", fmt.Sprintf("%f", limit), fmt.Sprintf("%f", current), "0").Start()
fmt.Printf("BUY ticker started -- P: %s, L: %f, C: %f\n", pair, limit, current)
}
}
if dobuy {
price = limit
amount = float64(invest_amount) / price
fmt.Printf("Price: %f\n", limit)
}
}
if (current > limit) && (limit > 0) && (bullstrategy) && (trend1 > bulltrend) && (trend2 > bulltrend) && (lastcandle > 0) && isEnoughMoney() {
fmt.Println("use bull strategy")
price = current * 1.005
amount = float64(invest_amount) / price
}
fmt.Printf("A: %f, P: %f\n", amount, price)
return
}
func getSellPrice(pair string) (price float64, amount float64, err error) {
var rate float64