/
start_bot.go
83 lines (70 loc) · 2.28 KB
/
start_bot.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
package backend
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"strings"
"github.com/stellar/kelp/gui/model2"
"github.com/stellar/kelp/support/kelpos"
)
func (s *APIServer) startBot(w http.ResponseWriter, r *http.Request) {
botNameBytes, e := ioutil.ReadAll(r.Body)
if e != nil {
s.writeError(w, fmt.Sprintf("error when reading request input: %s\n", e))
return
}
botName := string(botNameBytes)
e = s.doStartBot(botName, "buysell", nil, nil)
if e != nil {
s.writeError(w, fmt.Sprintf("error starting bot: %s\n", e))
return
}
e = s.kos.AdvanceBotState(botName, kelpos.BotStateStopped)
if e != nil {
s.writeError(w, fmt.Sprintf("error advancing bot state: %s\n", e))
return
}
w.WriteHeader(http.StatusOK)
}
func (s *APIServer) doStartBot(botName string, strategy string, iterations *uint8, maybeFinishCallback func()) error {
filenamePair := model2.GetBotFilenames(botName, strategy)
logPrefix := model2.GetLogPrefix(botName, strategy)
command := fmt.Sprintf("trade -c %s/%s -s %s -f %s/%s -l %s/%s --ui", s.configsDir, filenamePair.Trader, strategy, s.configsDir, filenamePair.Strategy, s.logsDir, logPrefix)
if iterations != nil {
command = fmt.Sprintf("%s --iter %d", command, *iterations)
}
if s.noHeaders {
command = fmt.Sprintf("%s --no-headers", command)
}
if s.ccxtRestUrl != "" {
command = fmt.Sprintf("%s --ccxt-rest-url %s", command, s.ccxtRestUrl)
}
log.Printf("run command for bot '%s': %s\n", botName, command)
p, e := s.runKelpCommandBackground(botName, command)
if e != nil {
return fmt.Errorf("could not start bot %s: %s", botName, e)
}
go func(kelpCommand *exec.Cmd, name string) {
defer s.kos.SafeUnregister(name)
if kelpCommand == nil {
log.Printf("kelpCommand was nil for bot '%s' with strategy '%s'\n", name, strategy)
return
}
e := kelpCommand.Wait()
if e != nil {
if strings.Contains(e.Error(), "signal: terminated") {
log.Printf("terminated start bot command for bot '%s' with strategy '%s'\n", name, strategy)
return
}
log.Printf("error when starting bot '%s' with strategy '%s': %s\n", name, strategy, e)
return
}
log.Printf("finished start bot command for bot '%s' with strategy '%s'\n", name, strategy)
if maybeFinishCallback != nil {
maybeFinishCallback()
}
}(p.Cmd, botName)
return nil
}