bbgo_origin/pkg/exchange/ftx/stream.go

76 lines
1.5 KiB
Go
Raw Normal View History

package ftx
import (
"context"
"sync/atomic"
2021-03-27 10:07:35 +00:00
"time"
"github.com/c9s/bbgo/pkg/types"
)
type Stream struct {
2021-03-02 14:18:41 +00:00
*types.StandardStream
wsService *WebsocketService
// publicOnly must be accessed atomically
publicOnly int32
}
func NewStream(key, secret string) *Stream {
wss := NewWebsocketService(key, secret)
s := &Stream{
2021-03-02 14:18:41 +00:00
StandardStream: &types.StandardStream{},
wsService: wss,
}
2021-02-27 10:41:46 +00:00
2021-03-04 00:55:52 +00:00
wss.OnMessage((&messageHandler{StandardStream: s.StandardStream}).handleMessage)
return s
}
func (s *Stream) Connect(ctx context.Context) error {
2021-03-27 08:58:51 +00:00
// If it's not public only, let's do the authentication.
if atomic.LoadInt32(&s.publicOnly) == 0 {
2021-03-27 10:07:35 +00:00
logger.Infof("subscribe private events")
2021-03-27 11:02:19 +00:00
s.subscribePrivateEvents()
2021-03-27 10:07:35 +00:00
}
if err := s.wsService.Connect(ctx); err != nil {
return err
2021-03-27 08:58:51 +00:00
}
return nil
}
2021-03-27 11:02:19 +00:00
func (s *Stream) subscribePrivateEvents() {
s.wsService.Subscribe(
newLoginRequest(s.wsService.key, s.wsService.secret, time.Now()),
)
s.wsService.Subscribe(websocketRequest{
Operation: subscribe,
Channel: privateOrdersChannel,
})
}
func (s *Stream) SetPublicOnly() {
atomic.StoreInt32(&s.publicOnly, 1)
}
2021-02-27 10:41:46 +00:00
func (s *Stream) Subscribe(channel types.Channel, symbol string, _ types.SubscribeOptions) {
2021-03-27 10:07:35 +00:00
if channel != types.BookChannel {
// TODO: return err
2021-02-27 10:41:46 +00:00
}
2021-03-27 10:07:35 +00:00
s.wsService.Subscribe(websocketRequest{
Operation: subscribe,
Channel: orderBookChannel,
2021-03-27 10:07:35 +00:00
Market: TrimUpperString(symbol),
})
}
2021-03-27 10:07:35 +00:00
2021-02-27 11:27:44 +00:00
func (s *Stream) Close() error {
2021-03-27 01:54:12 +00:00
if s.wsService != nil {
return s.wsService.Close()
}
return nil
}