-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive.go
More file actions
303 lines (278 loc) · 8.74 KB
/
interactive.go
File metadata and controls
303 lines (278 loc) · 8.74 KB
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
package main
import (
"context"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/chzyer/readline"
exchanges "github.com/QuantProcessing/exchanges"
"go.uber.org/zap"
)
// interactiveState holds mutable state for the interactive session.
type interactiveState struct {
exchName string
market string
marketType exchanges.MarketType
useWS bool
jsonOut bool
adp exchanges.Exchange
ctx context.Context
cancel context.CancelFunc
logger *zap.SugaredLogger
}
func (s *interactiveState) prompt() string {
mode := "rest"
if s.useWS {
mode = "ws"
}
return fmt.Sprintf("%s/%s(%s)> ", colorBold(s.exchName), s.market, mode)
}
func (s *interactiveState) reconnect() error {
// Close existing adapter if any
if s.adp != nil {
s.adp.Close()
}
var err error
if s.useWS {
s.adp, err = createAdapter(s.ctx, s.exchName, s.marketType, s.logger)
} else {
s.adp, err = createRESTAdapter(s.ctx, s.exchName, s.marketType, s.logger)
}
return err
}
// historyPath returns the path to the command history file.
func historyPath() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".tctl_history")
}
func runInteractive(exchangeFlag, market string, jsonOut, useWS bool, logger *zap.SugaredLogger) {
exchName := resolveExchange(exchangeFlag)
if exchName == "" {
// Show available exchanges and prompt
configured := configuredExchanges()
if len(configured) == 0 {
fatal(jsonOut, "no exchanges configured. Set credentials in .env file.")
}
fmt.Printf("Available exchanges: %s\n", colorCyan(strings.Join(configured, ", ")))
fmt.Print("Select exchange: ")
// Use a simple readline for exchange selection
rl, err := readline.New("> ")
if err != nil {
return
}
line, err := rl.Readline()
rl.Close()
if err != nil {
return
}
exchName = strings.ToUpper(strings.TrimSpace(line))
if exchName == "" {
return
}
}
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
marketType := exchanges.MarketTypePerp
if market == "spot" {
marketType = exchanges.MarketTypeSpot
}
state := &interactiveState{
exchName: exchName,
market: market,
marketType: marketType,
useWS: useWS,
jsonOut: jsonOut,
ctx: ctx,
cancel: cancel,
logger: logger,
}
if err := state.reconnect(); err != nil {
fatal(jsonOut, "failed to create %s adapter: %v", exchName, err)
}
// Create readline instance with history
rl, err := readline.NewEx(&readline.Config{
Prompt: state.prompt(),
HistoryFile: historyPath(),
InterruptPrompt: "^C",
EOFPrompt: "exit",
})
if err != nil {
// Fallback: if readline fails, we can't do interactive mode
fatal(jsonOut, "failed to initialize readline: %v", err)
}
defer rl.Close()
fmt.Printf("Connected to %s (%s). Type %s for commands, %s to quit.\n",
colorBold(exchName), market, colorCyan("help"), colorCyan("exit"))
for {
rl.SetPrompt(state.prompt())
line, err := rl.Readline()
if err != nil {
if err == readline.ErrInterrupt {
continue // Ctrl-C: clear line, don't exit
}
if err == io.EOF {
fmt.Println("Bye!")
return
}
break
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.Fields(line)
cmd := strings.ToLower(parts[0])
switch cmd {
case "exit", "quit", "q":
fmt.Println("Bye!")
return
case "help", "h", "?":
printInteractiveHelp()
continue
case "status":
printStatus(state)
continue
case "use", "switch":
if len(parts) < 2 {
outputError("Usage: use <exchange>")
continue
}
newExch := strings.ToUpper(parts[1])
state.exchName = newExch
if err := state.reconnect(); err != nil {
outputError("Failed to connect to %s: %v", newExch, err)
continue
}
outputSuccess("Switched to %s", newExch)
continue
case "market":
if len(parts) < 2 {
outputError("Usage: market perp|spot")
continue
}
newMarket := strings.ToLower(parts[1])
switch newMarket {
case "perp":
state.market = "perp"
state.marketType = exchanges.MarketTypePerp
case "spot":
state.market = "spot"
state.marketType = exchanges.MarketTypeSpot
default:
outputError("Invalid market type. Use: perp | spot")
continue
}
if err := state.reconnect(); err != nil {
outputError("Failed to switch to %s: %v", newMarket, err)
continue
}
outputSuccess("Switched to %s market", newMarket)
continue
case "mode":
if len(parts) < 2 {
outputError("Usage: mode rest|ws")
continue
}
switch strings.ToLower(parts[1]) {
case "rest":
state.useWS = false
case "ws":
state.useWS = true
default:
outputError("Invalid mode. Use: rest | ws")
continue
}
if err := state.reconnect(); err != nil {
outputError("Failed to switch mode: %v", err)
continue
}
outputSuccess("Switched to %s mode", parts[1])
continue
case "json":
state.jsonOut = !state.jsonOut
if state.jsonOut {
outputSuccess("JSON output enabled")
} else {
outputSuccess("JSON output disabled")
}
continue
}
// fund-arb is special: creates its own spot+perp adapters
if cmd == "fund-arb" || cmd == "fa" {
if err := cmdFundArb(state.ctx, state.exchName, parts[1:], state.jsonOut, state.logger); err != nil {
outputError("%v", err)
}
continue
}
if err := dispatch(state.ctx, state.adp, state.exchName, cmd, parts[1:], state.jsonOut); err != nil {
outputError("%v", err)
}
}
}
func printStatus(s *interactiveState) {
mode := "REST"
if s.useWS {
mode = "WebSocket"
}
fmt.Printf(" Exchange: %s\n", colorBold(s.exchName))
fmt.Printf(" Market: %s\n", s.market)
fmt.Printf(" Mode: %s\n", mode)
fmt.Printf(" JSON: %v\n", s.jsonOut)
configured := configuredExchanges()
fmt.Printf(" Available: %s\n", colorDim(strings.Join(configured, ", ")))
}
func printInteractiveHelp() {
fmt.Println(colorBold("Market Data:"))
fmt.Println(" ticker <symbol> (t) get ticker")
fmt.Println(" orderbook <symbol> [depth] (ob) get order book")
fmt.Println(" trades <symbol> [limit] recent trades")
fmt.Println(" klines <symbol> <interval> (kl) candlestick data")
fmt.Println(" details <symbol> symbol details")
fmt.Println(" fee <symbol> fee rate")
fmt.Println(" funding <symbol> funding rate (perp)")
fmt.Println()
fmt.Println(colorBold("Trading:"))
fmt.Println(" buy <symbol> <qty> [--price P] [flags] place buy order")
fmt.Println(" sell <symbol> <qty> [--price P] [flags] place sell order")
fmt.Println(" modify <orderID> <symbol> [flags] modify order (perp)")
fmt.Println(" cancel <orderID> <symbol> cancel order")
fmt.Println(" cancel-all <symbol> cancel all orders")
fmt.Println(" order <orderID> <symbol> fetch order details")
fmt.Println(" Flags: --tif GTC|IOC|FOK|PO --post-only --reduce-only --client-id ID")
fmt.Println()
fmt.Println(colorBold("Arbitrage:"))
fmt.Println(" fund-arb <symbol> <qty> [flags] (fa) funding rate arb (spot+perp)")
fmt.Println(" Flags: --leverage N --close --spot-price P --perp-price P")
fmt.Println(" --spot-exchange EX --perp-exchange EX")
fmt.Println()
fmt.Println(colorBold("Account:"))
fmt.Println(" positions (p) list positions (perp)")
fmt.Println(" orders [symbol] (o) list open orders")
fmt.Println(" balance (b) show balance")
fmt.Println(" account (acc) full account info")
fmt.Println(" leverage <symbol> <value> (lev) set leverage (perp)")
fmt.Println(" spot-balances (sb) spot balances (spot)")
fmt.Println(" transfer <asset> <amount> [flags] asset transfer (spot)")
fmt.Println()
fmt.Println(colorBold("Streaming (WSS):"))
fmt.Println(" watch-ticker <symbol> (wt) live ticker")
fmt.Println(" watch-ob <symbol> [depth] (wob) live order book")
fmt.Println(" watch-orders (wo) live order updates")
fmt.Println(" watch-trades <symbol> (wtr) live trade stream")
fmt.Println()
fmt.Println(colorBold("Session:"))
fmt.Println(" use <exchange> switch exchange")
fmt.Println(" market perp|spot switch market type")
fmt.Println(" mode rest|ws switch session mode")
fmt.Println(" status show session info")
fmt.Println(" json toggle JSON output")
fmt.Println(" help (h,?) show this help")
fmt.Println(" exit (q) quit")
}