This repository was archived by the owner on Feb 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
129 lines (107 loc) · 2.09 KB
/
client.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
package xapi
import (
"context"
"errors"
"net/url"
"sync"
"time"
"github.com/gorilla/websocket"
)
const (
SYNC_PORT_REAL = 5112
SYNC_PORT_DEMO = 5124
SYNC_WEBSOCKET_ADDRESS_REAL = "wss://ws.xtb.com/real"
SYNC_WEBSOCKET_ADDRESS_DEMO = "wss://ws.xtb.com/demo"
API_ADDRESS_BASE = "https://xapi.xtb.com"
)
type ClientMode string
var (
ClientModeDemo ClientMode = "demo"
ClientModeReal ClientMode = "real"
)
type Client struct {
conn *websocket.Conn
userID int
password string
url *url.URL
cancelPing context.CancelFunc
m sync.Mutex
}
type optFunc func(*Client) error
func WithUserCredentials(userID int, password string) optFunc {
return func(c *Client) error {
c.userID = userID
c.password = password
return nil
}
}
func WithMode(mode ClientMode) optFunc {
return func(c *Client) error {
var rawURL string
if mode == ClientModeDemo {
rawURL = SYNC_WEBSOCKET_ADDRESS_DEMO
} else if mode == ClientModeReal {
rawURL = SYNC_WEBSOCKET_ADDRESS_REAL
}
u, err := url.Parse(rawURL)
if err != nil {
return err
}
c.url = u
return nil
}
}
func WithURL(rawURL string) optFunc {
return func(c *Client) error {
u, err := url.Parse(rawURL)
if err != nil {
return err
}
c.url = u
return nil
}
}
func NewClient(ctx context.Context, opts ...optFunc) (*Client, error) {
ctx, cancel := context.WithCancel(ctx)
c := &Client{
cancelPing: cancel,
}
for _, opt := range opts {
err := opt(c)
if err != nil {
return nil, err
}
}
if c.url == nil {
return nil, errors.New("url is required")
}
dialer := websocket.DefaultDialer
conn, _, err := dialer.Dial(c.url.String(), nil)
if err != nil {
return nil, err
}
c.conn = conn
ticker := time.NewTicker(5 * time.Minute)
go func() {
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
c.ping()
}
}
}()
return c, nil
}
func (c *Client) Login() error {
return login(c)
}
func (c *Client) Close() {
c.cancelPing()
c.conn.Close()
}
func (c *Client) ping() error {
_, err := getSync[any, any](c, "ping", nil)
return err
}