exchange

package
v0.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package trading 包含交易中的日历和时段相关的功能函数

Index

Constants

View Source
const (
	HistoricalTransactionDataFirstTime        = "09:25" // 第一个时间
	HistoricalTransactionDataStartTime        = "09:30" // 开盘时间
	HistoricalTransactionDataFinalBiddingTime = "14:57" // 尾盘集合竞价时间
	HistoricalTransactionDataLastTime         = "15:00" // 最后一个时间
)

历史成交数据 historical transaction data

View Source
const (
	CN = "cn" // A股
	HK = "hk" // 港股
	US = "us" // 美股
)
View Source
const (
	MarketShangHai string = "sh" // 上海
	MarketShenZhen string = "sz" // 深圳
	MarketBeiJing  string = "bj" // 北京
	MarketHongKong string = "hk" // 香港
	MarketUSA      string = "us" // 美国
)
View Source
const (
	MARKET_CN_FIRST_DATE     = "19901219"   // 上证指数的第一个交易日
	MARKET_CH_FIRST_LISTTIME = "1990-12-19" // 个股上市日期
)
View Source
const (
	STOCK = iota // 股票
	INDEX        // 指数
	BLOCK        // 板块
	ETF          // ETF
)
View Source
const (
	CN_TransactionTimeFormat   = "15:04"        // 分笔成交时间格式
	CN_SERVERTIME_FORMAT       = "15:04:05.000" // 服务器时间格式
	CN_SERVERTIME_SHORT_FORMAT = "15:04:05"     // 服务器时间格式
	TimeStampSecond            = "2006-01-02 15:04:05"
	TimeStampMilli             = "2006-01-02 15:04:05.000"
	TimeStampMicro             = "2006-01-02 15:04:05.000000"
	TimeStampNano              = "2006-01-02 15:04:05.000000000"
)
View Source
const (
	CN_MarketInitTime          = "09:00:00.000" // A股数据初始化时间
	CN_TradingStartTime        = "09:15:00.000" // A股数据开始时间
	CN_TradingSuspendBeginTime = "11:30:00.000" // A股午间休市开始时间
	CN_TradingSuspendEndTime   = "12:59:59.999" // A股午间休市结束时间
	CN_TradingStopTime         = "15:00:59.999" // A股数据结束时间
	CN_CallAuctionAmBegin      = "09:15:00.000" // 集合竞价-早盘-开始时间
	CN_CallAuctionAmEnd        = "09:27:59.999" // 集合竞价-早盘-结束时间
	CN_CallAuctionAmFinished   = "09:27:00.000" // 集合竞价-早盘-数据结束时间
	CN_CallAuctionTailBegin    = "14:30:00.000" // 尾盘时段-开始
	CN_CallAuctionTailEnd      = "15:01:59.999" // 尾盘时段-结束
	CN_CallAuctionPmBegin      = "14:57:00.000" // 集合竞价-尾盘-开始时间
	CN_CallAuctionPmEnd        = "15:01:59.999" // 集合竞价-尾盘-结束时间
	CN_CallAuctionPmFinished   = "15:01:30.000" // 集合竞价-尾盘-数据结束时间
)

交易日时间相关常量

View Source
const (
	BEGIN_A_AUCTION   = "09:15:00" // A股上午集合竞价开始时间
	END_A_AUCTION     = "09:25:00" // A股上午集合竞价结束时间
	END_A_AUCTION_SPE = "09:26:00" // A股上午集合竞价结束时间过一分钟
	BEGIN_P_AUCTION   = "14:57:00" // A股下午集合竞价开始时间
	END_P_AUCTION     = "15:01:00" // A股下午集合竞价结束时间
	END_P_AUCTION_SPE = "15:02:00" // A股下午集合竞价结束时间过一分钟
)

集合竞价时间相关常量

View Source
const (
	CN_DEFAULT_TOTALFZNUM = 240 // A股默认全天交易240分钟
	BEGIN_A_AM_HOUR       = 9   // A股开市-时
	BEGIN_A_AM_MINUTE     = 30  // A股开市-分
	END_A_AM_HOUR         = 11  // A股休市-时
	END_A_AM_MINUTE       = 30  // A股休市-分
	BEGIN_A_PM_HOUR       = 13  // A股开市-时
	BEGIN_A_PM_MINUTE     = 0   // A股开市-分
	END_A_PM_HOUR         = 15  // A股休市-时
	END_A_PM_MINUTE       = 0   // A股休市-分
)

分时数据相关常量

View Source
const (
	TimeOnly = time.TimeOnly // 时分秒的格式
)
View Source
const (
	TradingDayDateFormat = "2006-01-02" // 交易日历日期格式

)
View Source
const (
	TransactionStartTime = "09:30:00" // 交易开始时间
)

Variables

View Source
var (
	ErrNoUpdateRequired = errors.New("no update required")
)
View Source
var (
	ErrNumberFormat = exception.New(errnoConfig+1, "数值范围格式错误")
)
View Source
var (
	ErrRangeFormat = exception.New(errnoConfig+0, "数值范围格式错误")
)

错误信息

View Source
var (
	ErrTimeFormat = exception.New(errnoConfig+2, "时间范围格式错误")
)

Functions

func AssertBlockBySecurityCode

func AssertBlockBySecurityCode(securityCode *string) (isBlock bool)

AssertBlockBySecurityCode 断言证券代码是否板块

func AssertETFByMarketAndCode

func AssertETFByMarketAndCode(marketId MarketType, symbol string) (isETF bool)

AssertETFByMarketAndCode 通过市场id和代码判断是否ETF

func AssertIndexByMarketAndCode

func AssertIndexByMarketAndCode(marketId MarketType, symbol string) (isIndex bool)

AssertIndexByMarketAndCode 通过市场id和短码判断是否指数

func AssertIndexBySecurityCode

func AssertIndexBySecurityCode(securityCode string) (isIndex bool)

AssertIndexBySecurityCode 通过证券代码判断是否指数

func AssertStockByMarketAndCode

func AssertStockByMarketAndCode(marketId MarketType, symbol string) (isStock bool)

AssertStockByMarketAndCode 通过市场id和代码判断是否个股

func AssertStockBySecurityCode

func AssertStockBySecurityCode(securityCode string) (isStock bool)

AssertStockBySecurityCode 通过证券代码判断是否个股

func CanInitialize

func CanInitialize(lastModified ...time.Time) (toInit bool)

CanInitialize 数据是否初始化(One-time update)

func CanUpdate

func CanUpdate(lastModified ...time.Time) (updated bool)

CanUpdate 数据是否可以更新

func CanUpdateInRealtime

func CanUpdateInRealtime(lastModified ...time.Time) (updateInRealTime bool, status int)

CanUpdateInRealtime 能否实时更新

func CheckCallAuctionClose

func CheckCallAuctionClose(timestamp time.Time) (canUpdate bool)

CheckCallAuctionClose 检查当前时间是否集合竞价阶段

func CheckCallAuctionCloseFinished

func CheckCallAuctionCloseFinished(timestamp time.Time) (finished bool)

CheckCallAuctionCloseFinished 检查当前时间是否集合竞价阶段-结束

func CheckCallAuctionOpen

func CheckCallAuctionOpen(timestamp time.Time) (canUpdate bool)

CheckCallAuctionOpen 检查当前时间是否集合竞价阶段-进行中

func CheckCallAuctionOpenFinished

func CheckCallAuctionOpenFinished(timestamp time.Time) (finished bool)

CheckCallAuctionOpenFinished 检查当前时间是否集合竞价阶段-结束

func CheckCallAuctionTail

func CheckCallAuctionTail(timestamp time.Time) (finished bool)

CheckCallAuctionTail 检查当前时间是否集合竞价阶段-结束

func CheckCallAuctionTime

func CheckCallAuctionTime(timestamp time.Time) (canUpdate bool)

CheckCallAuctionTime 检查当前时间是否集合竞价阶段

func CorrectSecurityCode

func CorrectSecurityCode(securityCode string) string

CorrectSecurityCode 修正证券代码

func CurrentlyTrading

func CurrentlyTrading(date ...string) bool

CurrentlyTrading 今天的交易是否已经开始

func DateIsTradingDay

func DateIsTradingDay(date ...string) bool

DateIsTradingDay date是否交易日?默认是今天

func DateRange

func DateRange(start, end string) []string

DateRange 在start和end闭区间的所有交易日

start 开始日期
end 结束日期

func EvaluateYields

func EvaluateYields(prices, markets []float64, riskFreeRate float64) (beta, alpha float64)

EvaluateYields 评估收益率

func FixTradeDate

func FixTradeDate(datetime string, format ...string) string

FixTradeDate 强制修正交易日字符串

默认格式 YYYY-MM-DD, 支持其它格式

func GetCurrentDate

func GetCurrentDate(date ...string) (currentDate string)

GetCurrentDate 获取数据有效的最后一个交易日, 以9点整划分

func GetCurrentlyDay

func GetCurrentlyDay() (currentlyDay string)

GetCurrentlyDay 获取数据有效的最后一个交易日, 以9点15分划分

func GetFrontTradeDay

func GetFrontTradeDay() string

GetFrontTradeDay 获取上一个交易日

func GetLastDayForUpdate

func GetLastDayForUpdate() string

GetLastDayForUpdate 获取可以更新数据的最后一个交易日

func GetMarket

func GetMarket(symbol string) string

GetMarket 判断股票ID对应的证券市场匹配规则

['50', '51', '60', '90', '110'] 为 sh
['00', '12','13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz
['5', '6', '9'] 开头的为 sh, 其余为 sz

func GetMarketFlag

func GetMarketFlag(marketId MarketType) string

func GetMarketId

func GetMarketId(symbol string) uint8

GetMarketId 获得市场ID

func GetSecurityCode

func GetSecurityCode(market MarketType, symbol string) (securityCode string)

func GetTodayTimeByString

func GetTodayTimeByString(timeStr string) (time.Time, error)

GetTodayTimeByString 返回当天指定时刻的时间

func IndexList

func IndexList() []string

IndexList 指数列表

func IndexToday

func IndexToday() string

IndexToday 当天

func IsHoliday

func IsHoliday(date string) bool

IsHoliday 是否节假日

func IsTimeInRange

func IsTimeInRange(timeStr, startStr, endStr string) (bool, error)

func IsTrading

func IsTrading(date ...string) bool

func LastNDate

func LastNDate(date string, n ...int) []string

LastNDate 获得指定日期前的N个交易日期数组

func LastTradeDate

func LastTradeDate() string

LastTradeDate 获得最后一个交易日

func LimitUp

func LimitUp(securityCode string, price float64) float64

LimitUp 返回涨停板价格

func MarketLimit

func MarketLimit(securityCode string) float64

MarketLimit 涨跌停板限制

func Minutes

func Minutes(date ...string) int

Minutes 分钟数

func NextTradeDate

func NextTradeDate(date string) string

NextTradeDate 获取指定日期的下一个交易日

func ToUint32Date

func ToUint32Date(datetime string) uint32

ToUint32Date 通达信协议日期为YYYYMMDD格式的十进制整型

func Today

func Today() string

Today 当日, 区别于IndexToday, IndexToday可能存在调整

func TradeRange deprecated

func TradeRange(start, end string, threadSafe ...bool) []string

TradeRange 输出交易日范围

默认是线程安全

Deprecated: 推荐使用 TradingDateRange

func TradeSessionHasEnd

func TradeSessionHasEnd(date string) bool

TradeSessionHasEnd 是否收盘

func TradeSessionIsPreMarket

func TradeSessionIsPreMarket(date string) bool

TradeSessionIsPreMarket 是否盘前交易

func TradingDateRange

func TradingDateRange(start, end string, threadSafe ...bool) []string

TradingDateRange 输出交易日范围

默认是线程安全, 日期区间为左闭右开

Types

type CalendarDecoder

type CalendarDecoder struct {
	// contains filtered or unexported fields
}

func NewCalendarDecoder

func NewCalendarDecoder(data string) *CalendarDecoder

func (*CalendarDecoder) Decode

func (d *CalendarDecoder) Decode() any

func (*CalendarDecoder) N

func (d *CalendarDecoder) N() int

func (*CalendarDecoder) S

func (d *CalendarDecoder) S() []map[string]string

func (*CalendarDecoder) T

func (d *CalendarDecoder) T() []map[string]string

type DateTimeRange

type DateTimeRange struct {
	Begin time.Time
	End   time.Time
}

func (*DateTimeRange) Minutes

func (tr *DateTimeRange) Minutes() int

type FinancialHoliday

type FinancialHoliday struct {
	Date     string `name:"日期" array:"0"`
	Holiday  string `name:"节日" array:"1"`
	Country  string `name:"地区" array:"2"`
	Exchange string `name:"交易所" array:"3"`
}

FinancialHoliday 金融假日

type KLine

type KLine struct {
	Date   string  `json:"date" array:"0" name:"日期" dataframe:"date,string"`
	Open   float64 `json:"open" array:"1" name:"开盘价" dataframe:"open,float64"`
	Close  float64 `json:"close" array:"2" name:"收盘价" dataframe:"close,float64"`
	High   float64 `json:"high" array:"3" name:"最高价" dataframe:"high,float64"`
	Low    float64 `json:"low" array:"4" name:"最低价" dataframe:"low,float64"`
	Volume int64   `json:"volume" array:"5" name:"成交量" dataframe:"volume,int64"`
	Amount float64 `json:"amount" array:"6" name:"成交金额" dataframe:"amount,float64"`
}

func A

func A(code string) ([]KLine, error)

A 下载A股数据

type MarketHours

type MarketHours struct {
	// contains filtered or unexported fields
}

MarketHours 交易时段

func ExchangeMarketHours

func ExchangeMarketHours(sessions ...TradingTimeRange) MarketHours

func GetExchangeMarketHours

func GetExchangeMarketHours(name string) MarketHours

func (*MarketHours) CanStopLoss

func (this *MarketHours) CanStopLoss(milliseconds ...int64) bool

CanStopLoss 当前时段是否可以进行止损操作

如果是3个时段, 止损操作在第2时段, 如果是4个时段, 止损在第3个
如果是2个时段, 则是第2个时段, 也就是最后一个时段

func (*MarketHours) CanTakeProfit

func (this *MarketHours) CanTakeProfit(milliseconds ...int64) bool

CanTakeProfit 当前时段是否可以止盈

func (*MarketHours) GetTimeKind

func (this *MarketHours) GetTimeKind(milliseconds int64) (TimeKind, int, error)

func (*MarketHours) Index

func (this *MarketHours) Index(milliseconds ...int64) int

Index 判断timestamp是第几个交易时段

func (*MarketHours) IsTodayLastSession

func (this *MarketHours) IsTodayLastSession(milliseconds ...int64) bool

IsTodayLastSession 当前时段是否今天最后一个交易时段

备选函数名 IsTodayFinalSession

func (*MarketHours) IsTrading

func (this *MarketHours) IsTrading(milliseconds ...int64) bool

IsTrading 是否交易时段

func (MarketHours) MarshalText

func (this MarketHours) MarshalText() (text []byte, err error)

func (MarketHours) Minutes

func (this MarketHours) Minutes() int

func (*MarketHours) Parse

func (this *MarketHours) Parse(text string) error

func (*MarketHours) Size

func (this *MarketHours) Size() int

Size 获取时段总数

func (MarketHours) String

func (this MarketHours) String() string

func (*MarketHours) UnmarshalText

func (this *MarketHours) UnmarshalText(text []byte) error

UnmarshalText 设置默认值调用

func (*MarketHours) UnmarshalYAML

func (this *MarketHours) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML YAML自定义解析

type MarketHoursOperator

type MarketHoursOperator struct {
}

func (MarketHoursOperator) Kind

func (o MarketHoursOperator) Kind(ms ...int64) (kind TimeKind, index int)

Kind 实现了Operator接口的Kind方法

type MarketType

type MarketType = uint8
const (
	MarketIdShenZhen MarketType = iota // 深圳
	MarketIdShangHai MarketType = 1    // 上海
	MarketIdBeiJing  MarketType = 2    // 北京
	MarketIdHongKong MarketType = 21   // 香港
	MarketIdUSA      MarketType = 22   // 美国

	StockDelisting = "DELISTING" // 退市
)

func DetectMarket

func DetectMarket(symbol string) (marketId MarketType, market string, code string)

DetectMarket 检测市场代码

type NumberRange

type NumberRange struct {
	// contains filtered or unexported fields
}

NumberRange 数值范围

支持:
1) "1~2",   最小值1, 最大值2
2) "",      最小值默认, 最大值默认
3) "3.82",  最小值, 最大值默认
4) "3.82~", 最小值, 最大值默认
5) "~3.82", 最小值默认, 最大值

func (NumberRange) MarshalText

func (this NumberRange) MarshalText() (text []byte, err error)

func (*NumberRange) Max

func (this *NumberRange) Max() float64

func (*NumberRange) Min

func (this *NumberRange) Min() float64

func (*NumberRange) Parse

func (this *NumberRange) Parse(text string) error

func (NumberRange) String

func (this NumberRange) String() string

func (*NumberRange) UnmarshalText

func (this *NumberRange) UnmarshalText(bytes []byte) error

UnmarshalText 设置默认值调用

func (*NumberRange) UnmarshalYAML

func (this *NumberRange) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML YAML自定义解析

func (*NumberRange) Validate

func (this *NumberRange) Validate(v float64) bool

Validate 验证

type Operator

type Operator interface {
	// Kind 取得ms所在时段的操作类别和序号
	//	ms是nil的话, 即默认值, 取当前时间戳的毫秒数
	Kind(ms ...int64) (kind TimeKind, index int)
}

Operator 操作员接口

func GetOperator

func GetOperator() Operator

GetOperator 获取一个Operator实例

type TargetKind

type TargetKind int

TargetKind 标的类型

func AssertCode

func AssertCode(securityCode string) TargetKind

AssertCode 判断一个代码类型

type TimeInterval

type TimeInterval struct {
	// contains filtered or unexported fields
}

TimeInterval 时间范围

左闭右开[begin, end)

func ExchangeTime

func ExchangeTime(kind TimeKind, begin, end string) TimeInterval

func (*TimeInterval) IsTrading

func (this *TimeInterval) IsTrading(milliseconds int64) bool

func (TimeInterval) Minutes

func (this TimeInterval) Minutes() int

func (*TimeInterval) Parse

func (this *TimeInterval) Parse(text string) error

Parse 解析文本, 覆盖属性

func (TimeInterval) String

func (this TimeInterval) String() string

func (*TimeInterval) UnmarshalText

func (this *TimeInterval) UnmarshalText(text []byte) error

UnmarshalText 设置默认值调用

由于begin和end字段不可访问, 默认值调用实际无效

func (*TimeInterval) UnmarshalYAML

func (this *TimeInterval) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML YAML自定义解析

type TimeKind

type TimeKind uint64

TimeKind 时段类型

const (
	CallAuction TimeKind = 1 << iota // 集合竞价
	CanCancel                        // 可撤单
	Trading                          // 交易时段
)
const (
	CallAuctionAndCancel  TimeKind = CallAuction | CanCancel // 集合竞价可撤单
	TradingAndCancel      TimeKind = Trading | CanCancel     // 交易可撤单
	CallAuctionAndTrading TimeKind = CallAuction | Trading   // 集合竞价可撤单

)

func StringToTimeKind

func StringToTimeKind(timeKindString string) TimeKind

type TimeStatus

type TimeStatus = int
const (
	ExchangePreMarket   TimeStatus = -1 // 盘前
	ExchangeSuspend     TimeStatus = 0  // 休市中, 交易暂停
	ExchangeTrading     TimeStatus = 1  // 交易中
	ExchangeCallAuction TimeStatus = 2  // 交易中, 集合竞价
	ExchangeClosing     TimeStatus = 3  // 当日收盘, 交易停止
)

type TradingDay

type TradingDay string

交易日, 固定格式YYYY-MM-DD

func NewTradingDay

func NewTradingDay(date string) TradingDay

func (TradingDay) String

func (t TradingDay) String() string

type TradingSession

type TradingSession struct {
	// contains filtered or unexported fields
}

TradingSession 交易时段

func ExchangeSessions

func ExchangeSessions(sessions ...TimeInterval) TradingSession

func GetExchange

func GetExchange(name string) TradingSession

func (*TradingSession) CanStopLoss

func (this *TradingSession) CanStopLoss(milliseconds ...int64) bool

CanStopLoss 当前时段是否可以进行止损操作

如果是3个时段, 止损操作在第2时段, 如果是4个时段, 止损在第3个
如果是2个时段, 则是第2个时段, 也就是最后一个时段

func (*TradingSession) CanTakeProfit

func (this *TradingSession) CanTakeProfit(milliseconds ...int64) bool

CanTakeProfit 当前时段是否可以止盈

func (*TradingSession) Index

func (this *TradingSession) Index(milliseconds ...int64) int

Index 判断timestamp是第几个交易时段

func (*TradingSession) IsTodayLastSession

func (this *TradingSession) IsTodayLastSession(milliseconds ...int64) bool

IsTodayLastSession 当前时段是否今天最后一个交易时段

备选函数名 IsTodayFinalSession

func (*TradingSession) IsTrading

func (this *TradingSession) IsTrading(milliseconds ...int64) bool

IsTrading 是否交易时段

func (TradingSession) MarshalText

func (this TradingSession) MarshalText() (text []byte, err error)

func (TradingSession) Minutes

func (this TradingSession) Minutes() int

func (*TradingSession) Parse

func (this *TradingSession) Parse(text string) error

func (*TradingSession) Size

func (this *TradingSession) Size() int

Size 获取时段总数

func (TradingSession) String

func (this TradingSession) String() string

func (*TradingSession) UnmarshalText

func (this *TradingSession) UnmarshalText(text []byte) error

UnmarshalText 设置默认值调用

func (*TradingSession) UnmarshalYAML

func (this *TradingSession) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML YAML自定义解析

type TradingTimeRange

type TradingTimeRange struct {
	// contains filtered or unexported fields
}

TradingTimeRange 时间范围

左闭右开[begin, end)

func ExchangeTradingTimeRange

func ExchangeTradingTimeRange(kind TimeKind, begin, end string) TradingTimeRange

func (*TradingTimeRange) IsTrading

func (this *TradingTimeRange) IsTrading(milliseconds int64) bool

func (TradingTimeRange) Minutes

func (this TradingTimeRange) Minutes() int

func (*TradingTimeRange) Parse

func (this *TradingTimeRange) Parse(text string) error

Parse 解析文本, 覆盖属性

func (TradingTimeRange) String

func (this TradingTimeRange) String() string

func (*TradingTimeRange) UnmarshalText

func (this *TradingTimeRange) UnmarshalText(text []byte) error

UnmarshalText 设置默认值调用

由于begin和end字段不可访问, 默认值调用实际无效

func (*TradingTimeRange) UnmarshalYAML

func (this *TradingTimeRange) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML YAML自定义解析

type ValueRange

type ValueRange[T ValueType] struct {
	// contains filtered or unexported fields
}

ValueRange 数值范围

func ParseRange

func ParseRange[T ValueType](text string) ValueRange[T]

func (ValueRange[T]) In

func (r ValueRange[T]) In(v T) bool

In 检查是否包含在范围内

type ValueType

type ValueType interface {
	~int | ~float64 | ~string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL