You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

79 lines
2.3 KiB

package exchange
import (
"context"
"fmt"
"sig-pub/pkg/types"
"sig-pub/pkg/utils/collect"
"sync"
)
// 交易所行情数据订阅
type ExchangeSubscriber interface {
// 交易所类型
ExhcangeType() types.Exchange
// 消费k线行情数据
ConsumerKline() <-chan *types.ChannelKline
// 订阅产品k线行情
SubscribeKline(instIds ...string) (err error)
// 取消订阅产品k线行情
UnsubscribeKline(instIds ...string) (err error)
}
// 交易所行情数据请求
type ExchangeFetcher interface {
// 交易所类型
ExhcangeType() types.Exchange
// 获取区间内历史k线数据
FetchHistoryKlines(ctx context.Context, instId string, interval types.Interval, after, before int64) (klines []*types.Kline, err error)
}
// 交易所交互接口
type Exchange struct {
ExType types.Exchange
Fetcher ExchangeFetcher
Subscriber ExchangeSubscriber
Insts *collect.SyncMap[string, *ExchangeTradeInstance] // map[string]*ExchangeTradeInstance // <ExchangeInstId, Inst>
// sync.RWMutex
}
// 交易所交易产品
type ExchangeTradeInstance struct {
Inst *types.TradeInstance
Status int32 // 交易产品状态, 0.初始化中 1.正常
LiveMarkTs int64 // websocket订阅k线标记时间戳
LiveKStartTs map[types.Interval]int64 // ws开始订阅k线标记时间戳
LiveKMarkTs map[types.Interval]int64 // ws实时订阅k线(confirmed)标记时间戳
HistoryMarkTs map[types.Interval]int64 // 拉取历史k线标记时间戳
Lock sync.RWMutex
}
func (exInst *ExchangeTradeInstance) GetLiveMarkTs(interval types.Interval) (ts int64) {
exInst.Lock.RLock()
ts = exInst.LiveKMarkTs[interval]
exInst.Lock.RUnlock()
return
}
func (exInst *ExchangeTradeInstance) SetLiveMarkTs(interval types.Interval, ts int64) {
exInst.Lock.Lock()
exInst.LiveKMarkTs[interval] = ts
exInst.Lock.Unlock()
}
func NewExchange(fetcher ExchangeFetcher, subscriber ExchangeSubscriber) *Exchange {
exType := fetcher.ExhcangeType()
if exType != subscriber.ExhcangeType() {
panic(fmt.Errorf("exchange type not match: %#v, %#v", exType, subscriber.ExhcangeType()))
}
return &Exchange{
ExType: exType,
Fetcher: fetcher,
Subscriber: subscriber,
Insts: collect.NewSyncMap[string, *ExchangeTradeInstance](),
}
}