Compare commits

...

27 Commits

Author SHA1 Message Date
injoyai
5c8091ac26 修复深圳指数历史分时成交价格小10倍的问题 2025-10-20 09:49:01 +08:00
钱纯净
d7b6963bd6 修复workday没有要更新时会报错的问题 "no element on slice when insert" 2025-10-19 22:46:06 +08:00
injoyai
456a0af9a5 增加Manage对mysql的支持 2025-10-16 14:00:31 +08:00
injoyai
84404bcb2c 增加Manage对mysql的支持 2025-10-16 11:00:58 +08:00
injoyai
716e35122f 增加Manage对mysql的支持 2025-10-16 10:54:44 +08:00
injoyai
c4866a2f2e 增加Manage对mysql的支持 2025-10-16 10:47:24 +08:00
injoyai
fa98199dae 增加Codes和Workday对mysql的支持 2025-10-16 10:33:04 +08:00
injoyai
29882ea5c0 修复IsSZStock的判断 2025-10-14 13:07:59 +08:00
injoyai
37eb34beaa 优化 2025-10-14 09:23:45 +08:00
钱纯净
7bf4839310 修改GetHistoryTradeAll为GetHistoryTradeDay,增加GetHistoryTradeFull,获取上市至今的分时成交 2025-10-13 20:04:47 +08:00
钱纯净
cbf56d936d 优化Klines的Kline和Merge 2025-10-13 19:53:19 +08:00
injoyai
80ecdec737 增加extend.ListenCodesHTTP,因为北交所代码是网页爬虫,爬被封ip,感觉好像用处也不大 2025-10-13 15:05:21 +08:00
injoyai
ecf0365879 优化protocol.Trades,能直接生成完整的分时k线,和实际误差很小 2025-10-13 15:01:44 +08:00
injoyai
f1da1182ce 优化protocol.Trades,能直接生成完整的分时k线,和实际误差很小 2025-10-13 15:01:27 +08:00
injoyai
8fb069b855 简单测试北交所数据 2025-09-30 11:44:12 +08:00
injoyai
110eaddc4d 兼容北交所代码到GetCodeAll,方便原先的逻辑不用改动 2025-09-30 11:43:37 +08:00
injoyai
aec2cf1518 优化NewWorkday 2025-09-30 11:42:33 +08:00
injoyai
a596139d3e 移动GetBjCodes至tdx包 2025-09-30 11:42:10 +08:00
injoyai
578617e458 修复北交所(历史)分时成交小10倍的问题 2025-09-30 11:41:13 +08:00
钱纯净
fab9e92fcd 43开头也是北京交易所的 2025-09-27 22:32:22 +08:00
钱纯净
47084b1112 增加同花顺复权数据计算复权因子 2025-09-27 17:39:11 +08:00
钱纯净
2566ef5cec 增加获取北京交易所股票列表,通达信好像没有北交所股票列表 2025-09-27 17:38:43 +08:00
钱纯净
86404db551 Merge remote-tracking branch 'origin/master' 2025-09-21 15:28:48 +08:00
钱纯净
3f3438fca8 增加北京交易所数据 2025-09-21 15:28:32 +08:00
injoyai
1656b41f02 go1.25版本有点不兼容老版本,增加对go1.25版本的支持 2025-08-29 09:43:00 +08:00
injoyai
8090cc7216 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	go.mod
#	go.sum
2025-08-29 09:41:42 +08:00
injoyai
a3169c67da go1.25版本有点不兼容老版本,增加对go1.25版本的支持 2025-08-29 09:41:01 +08:00
26 changed files with 769 additions and 181 deletions

View File

@@ -220,6 +220,26 @@ func (this *Client) GetCode(exchange protocol.Exchange, start uint16) (*protocol
// GetCodeAll 通过多次请求的方式获取全部证券代码 // GetCodeAll 通过多次请求的方式获取全部证券代码
func (this *Client) GetCodeAll(exchange protocol.Exchange) (*protocol.CodeResp, error) { func (this *Client) GetCodeAll(exchange protocol.Exchange) (*protocol.CodeResp, error) {
resp := &protocol.CodeResp{} resp := &protocol.CodeResp{}
//通达信没有北交所代码列表,通过爬虫的方式从北交所官网获取,放在这里是为了方便业务逻辑
//不放在extend包时防止循环引用
//todo 这是临时方案,等通达信有北交所代码列表时再改
if exchange == protocol.ExchangeBJ {
codes, err := GetBjCodes()
if err != nil {
return nil, err
}
resp.Count = uint16(len(codes))
for _, v := range codes {
resp.List = append(resp.List, &protocol.Code{
Code: v.Code,
Name: v.Name,
LastPrice: v.Last,
})
}
return resp, nil
}
size := uint16(1000) size := uint16(1000)
for start := uint16(0); ; start += size { for start := uint16(0); ; start += size {
r, err := this.GetCode(exchange, start) r, err := this.GetCode(exchange, start)
@@ -238,7 +258,7 @@ func (this *Client) GetCodeAll(exchange protocol.Exchange) (*protocol.CodeResp,
// GetStockAll 获取所有股票代码 // GetStockAll 获取所有股票代码
func (this *Client) GetStockAll() ([]string, error) { func (this *Client) GetStockAll() ([]string, error) {
ls := []string(nil) ls := []string(nil)
for _, ex := range []protocol.Exchange{protocol.ExchangeSH, protocol.ExchangeSZ} { for _, ex := range []protocol.Exchange{protocol.ExchangeSH, protocol.ExchangeSZ, protocol.ExchangeBJ} {
resp, err := this.GetCodeAll(ex) resp, err := this.GetCodeAll(ex)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -402,7 +422,7 @@ func (this *Client) GetHistoryTrade(date, code string, start, count uint16) (*pr
// GetHistoryMinuteTrade 获取历史分时交易 // GetHistoryMinuteTrade 获取历史分时交易
// 只能获取昨天及之前的数据,服务器最多返回2000条,count-start<=2000,如果日期输入错误,则返回0 // 只能获取昨天及之前的数据,服务器最多返回2000条,count-start<=2000,如果日期输入错误,则返回0
// 历史数据sz000001在20241116只能查到21111112,13年差几天,3141天,或者其他规则 // 历史数据只能查到20000609
func (this *Client) GetHistoryMinuteTrade(date, code string, start, count uint16) (*protocol.TradeResp, error) { func (this *Client) GetHistoryMinuteTrade(date, code string, start, count uint16) (*protocol.TradeResp, error) {
code = protocol.AddPrefix(code) code = protocol.AddPrefix(code)
f, err := protocol.MHistoryTrade.Frame(date, code, start, count) f, err := protocol.MHistoryTrade.Frame(date, code, start, count)
@@ -419,13 +439,36 @@ func (this *Client) GetHistoryMinuteTrade(date, code string, start, count uint16
return result.(*protocol.TradeResp), nil return result.(*protocol.TradeResp), nil
} }
func (this *Client) GetHistoryTradeAll(date, code string) (*protocol.TradeResp, error) { // GetHistoryTradeFull 获取上市至今的分时成交
return this.GetHistoryMinuteTradeAll(date, code) func (this *Client) GetHistoryTradeFull(code string) (protocol.Trades, error) {
ls := protocol.Trades(nil)
resp, err := this.GetKlineMonthAll(code)
if err != nil {
return nil, err
}
if len(resp.List) == 0 {
return nil, nil
}
start := time.Date(resp.List[0].Time.Year(), resp.List[0].Time.Month(), 1, 0, 0, 0, 0, resp.List[0].Time.Location())
var res *protocol.TradeResp
for ; start.Before(time.Now()); start = start.Add(time.Hour * 24) {
res, err = this.GetHistoryTradeDay(start.Format("20060102"), code)
if err != nil {
return nil, err
}
ls = append(ls, res.List...)
}
return ls, nil
} }
// GetHistoryMinuteTradeAll 获取历史分时全部交易,通过多次请求来拼接,只能获取昨天及之前的数据 // GetHistoryTradeDay 获取历史某天分时全部交易,通过多次请求来拼接,只能获取昨天及之前的数据
// 历史数据sz000001在20241116只能查到21111112,13年差几天,3141天,或者其他规则 func (this *Client) GetHistoryTradeDay(date, code string) (*protocol.TradeResp, error) {
func (this *Client) GetHistoryMinuteTradeAll(date, code string) (*protocol.TradeResp, error) { return this.GetHistoryMinuteTradeDay(date, code)
}
// GetHistoryMinuteTradeDay 获取历史某天分时全部交易,通过多次请求来拼接,只能获取昨天及之前的数据
// 历史数据只能查到20000609
func (this *Client) GetHistoryMinuteTradeDay(date, code string) (*protocol.TradeResp, error) {
resp := &protocol.TradeResp{} resp := &protocol.TradeResp{}
size := uint16(2000) size := uint16(2000)
for start := uint16(0); ; start += size { for start := uint16(0); ; start += size {

102
client_bj_code.go Normal file
View File

@@ -0,0 +1,102 @@
package tdx
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/injoyai/conv"
"io"
"net/http"
"strings"
"time"
)
const (
// UrlBjCodes 最后跟的是时间戳(ms),但是随便什么时间戳都能请求成功
UrlBjCodes = "https://www.bse.cn/nqhqController/nqhq_en.do?callback=jQuery3710848510589806625_%d"
)
func GetBjCodes() ([]*BjCode, error) {
list := []*BjCode(nil)
//这个200预防下bug,除非北京上市公司有4000个
for page := 0; page < 200; page++ {
ls, done, err := getBjCodes(page)
if err != nil {
return nil, err
}
list = append(list, ls...)
if done {
break
}
<-time.After(time.Millisecond * 100)
}
return list, nil
}
func getBjCodes(page int) (_ []*BjCode, last bool, err error) {
url := fmt.Sprintf(UrlBjCodes, time.Now().UnixMilli())
bodyStr := "page=" + conv.String(page) + "&type_en=%5B%22B%22%5D&sortfield=hqcjsl&sorttype=desc&xxfcbj_en=%5B2%5D&zqdm="
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(bodyStr))
if err != nil {
return nil, false, err
}
req.Header.Set("X-Requested-With", "XMLHttpRequest")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.39 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, false, err
}
defer resp.Body.Close()
bs, err := io.ReadAll(resp.Body)
if err != nil {
return nil, false, err
}
//处理数据
i := bytes.IndexByte(bs, '(')
if len(bs) < 1 || len(bs) <= i {
return nil, false, errors.New("未知错误: " + string(bs))
}
bs = bs[i+1 : len(bs)-1]
ls := []*BjCodes(nil)
err = json.Unmarshal(bs, &ls)
if err != nil {
return nil, false, err
}
if len(ls) == 0 {
return nil, false, errors.New("未知错误: " + string(bs))
}
return ls[0].Data, ls[0].LastPage, nil
}
type BjCodes struct {
Data []*BjCode `json:"content"`
TotalNumber int `json:"totalElements"`
TotalPage int `json:"totalPages"`
LastPage bool `json:"lastPage"`
}
type BjCode struct {
Date string `json:"hqjsrq"` //日期
Code string `json:"hqzqdm"` //代码
Name string `json:"hqzqjc"` //名称
LastClose float64 `json:"hqzrsp"` //前一天收盘价
Open float64 `json:"hqjrkp"` //开盘价
High float64 `json:"hqzgcj"` //最高价
Low float64 `json:"hqzdcj"` //最低价
Last float64 `json:"hqzjcj"` //最新价/收盘价
Volume int `json:"hqcjsl"` //成交量,股
Amount float64 `json:"hqcjje"` //成交额,元
}

129
codes.go
View File

@@ -23,10 +23,22 @@ func DialCodes(filename string, op ...client.Option) (*Codes, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return NewCodes(c, filename) return NewCodesSqlite(c, filename)
} }
func NewCodes(c *Client, filenames ...string) (*Codes, error) { func NewCodesMysql(c *Client, dsn string) (*Codes, error) {
//连接数据库
db, err := xorm.NewEngine("mysql", dsn)
if err != nil {
return nil, err
}
db.SetMapper(core.SameMapper{})
return NewCodes(c, db)
}
func NewCodesSqlite(c *Client, filenames ...string) (*Codes, error) {
//如果没有指定文件名,则使用默认 //如果没有指定文件名,则使用默认
defaultFilename := filepath.Join(DefaultDatabaseDir, "codes.db") defaultFilename := filepath.Join(DefaultDatabaseDir, "codes.db")
@@ -44,6 +56,12 @@ func NewCodes(c *Client, filenames ...string) (*Codes, error) {
} }
db.SetMapper(core.SameMapper{}) db.SetMapper(core.SameMapper{})
db.DB().SetMaxOpenConns(1) db.DB().SetMaxOpenConns(1)
return NewCodes(c, db)
}
func NewCodes(c *Client, db *xorm.Engine) (*Codes, error) {
if err := db.Sync2(new(CodeModel)); err != nil { if err := db.Sync2(new(CodeModel)); err != nil {
return nil, err return nil, err
} }
@@ -53,10 +71,11 @@ func NewCodes(c *Client, filenames ...string) (*Codes, error) {
update := new(UpdateModel) update := new(UpdateModel)
{ //查询或者插入一条数据 { //查询或者插入一条数据
has, err := db.Get(update) has, err := db.Where("`Key`=?", "codes").Get(update)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
update.Key = "codes"
if _, err := db.Insert(update); err != nil { if _, err := db.Insert(update); err != nil {
return nil, err return nil, err
} }
@@ -72,7 +91,8 @@ func NewCodes(c *Client, filenames ...string) (*Codes, error) {
task := cron.New(cron.WithSeconds()) task := cron.New(cron.WithSeconds())
task.AddFunc("10 0 9 * * *", func() { task.AddFunc("10 0 9 * * *", func() {
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
if err := cc.Update(); err == nil { err := cc.Update()
if err == nil {
return return
} }
logs.Err(err) logs.Err(err)
@@ -155,52 +175,8 @@ func (this *Codes) Get(code string) *CodeModel {
return this.Map[code] return this.Map[code]
} }
// GetExchange 获取股票交易所,这里的参数不需要带前缀
func (this *Codes) GetExchange(code string) protocol.Exchange {
if len(code) == 6 {
switch {
case code[:1] == "6":
return protocol.ExchangeSH
case code[:1] == "0":
return protocol.ExchangeSZ
case code[:2] == "30":
return protocol.ExchangeSZ
}
}
var exchange string
exchanges := this.exchanges[code]
if len(exchanges) >= 1 {
exchange = exchanges[0]
}
if len(code) == 8 {
exchange = code[0:2]
}
switch exchange {
case protocol.ExchangeSH.String():
return protocol.ExchangeSH
case protocol.ExchangeSZ.String():
return protocol.ExchangeSZ
default:
return protocol.ExchangeSH
}
}
func (this *Codes) AddExchange(code string) string { func (this *Codes) AddExchange(code string) string {
if exchanges := this.exchanges[code]; len(exchanges) == 1 { return protocol.AddPrefix(code)
return exchanges[0] + code
}
if len(code) == 6 {
switch {
case code[:1] == "6":
return protocol.ExchangeSH.String() + code
case code[:1] == "0":
return protocol.ExchangeSZ.String() + code
case code[:2] == "30":
return protocol.ExchangeSZ.String() + code
}
return this.GetExchange(code).String() + code
}
return code
} }
// Update 更新数据,从服务器或者数据库 // Update 更新数据,从服务器或者数据库
@@ -219,7 +195,7 @@ func (this *Codes) Update(byDB ...bool) error {
this.list = codes this.list = codes
this.exchanges = exchanges this.exchanges = exchanges
//更新时间 //更新时间
_, err = this.db.Update(&UpdateModel{Time: time.Now().Unix()}) _, err = this.db.Where("`Key`=?", "codes").Update(&UpdateModel{Time: time.Now().Unix()})
return err return err
} }
@@ -249,7 +225,7 @@ func (this *Codes) GetCodes(byDatabase bool) ([]*CodeModel, error) {
//3. 从服务器获取所有股票代码 //3. 从服务器获取所有股票代码
insert := []*CodeModel(nil) insert := []*CodeModel(nil)
update := []*CodeModel(nil) update := []*CodeModel(nil)
for _, exchange := range []protocol.Exchange{protocol.ExchangeSH, protocol.ExchangeSZ} { for _, exchange := range []protocol.Exchange{protocol.ExchangeSH, protocol.ExchangeSZ, protocol.ExchangeBJ} {
resp, err := this.Client.GetCodeAll(exchange) resp, err := this.Client.GetCodeAll(exchange)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -282,29 +258,52 @@ func (this *Codes) GetCodes(byDatabase bool) ([]*CodeModel, error) {
} }
} }
//4. 插入或者更新数据库 switch this.db.Dialect().URI().DBType {
err := NewSessionFunc(this.db, func(session *xorm.Session) error { case "mysql":
for _, v := range insert { // 1⃣ 清空
if _, err := session.Insert(v); err != nil { if _, err := this.db.Exec("TRUNCATE TABLE codes"); err != nil {
return err return nil, err
}
data := append(insert, update...)
// 2⃣ 直接批量插入
batchSize := 3000 // 8000(2m16s) 5000(43s) 3000(11s) 1000(59s)
for i := 0; i < len(data); i += batchSize {
end := i + batchSize
if end > len(data) {
end = len(data)
}
slice := conv.Array(data[i:end])
if _, err := this.db.Insert(slice); err != nil {
return nil, err
} }
} }
for _, v := range update { case "sqlite3":
if _, err := session.Where("Exchange=? and Code=? ", v.Exchange, v.Code).Cols("Name,LastPrice").Update(v); err != nil { //4. 插入或者更新数据库
return err err := NewSessionFunc(this.db, func(session *xorm.Session) error {
for _, v := range insert {
if _, err := session.Insert(v); err != nil {
return err
}
} }
for _, v := range update {
if _, err := session.Where("Exchange=? and Code=? ", v.Exchange, v.Code).Cols("Name,LastPrice").Update(v); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
} }
return nil
})
if err != nil {
return nil, err
} }
return list, nil return list, nil
} }
type UpdateModel struct { type UpdateModel struct {
Key string
Time int64 //更新时间 Time int64 //更新时间
} }
@@ -334,7 +333,7 @@ func (this *CodeModel) FullCode() string {
func (this *CodeModel) Price(p protocol.Price) protocol.Price { func (this *CodeModel) Price(p protocol.Price) protocol.Price {
return protocol.Price(float64(p) * math.Pow10(int(2-this.Decimal))) return protocol.Price(float64(p) * math.Pow10(int(2-this.Decimal)))
return p * protocol.Price(math.Pow10(int(2-this.Decimal))) //return p * protocol.Price(math.Pow10(int(2-this.Decimal)))
} }
func NewSessionFunc(db *xorm.Engine, fn func(session *xorm.Session) error) error { func NewSessionFunc(db *xorm.Engine, fn func(session *xorm.Session) error) error {

20
example/CodesHTTP/main.go Normal file
View File

@@ -0,0 +1,20 @@
package main
import (
"github.com/injoyai/logs"
"github.com/injoyai/tdx/extend"
"time"
)
func main() {
go extend.ListenCodesHTTP(10033)
<-time.After(time.Second * 3)
c := extend.DialCodesHTTP("http://localhost:10033")
stocks, err := c.GetStocks()
logs.PanicErr(err)
for _, v := range stocks {
println(v)
}
}

View File

@@ -0,0 +1,18 @@
package main
import (
"github.com/injoyai/logs"
"github.com/injoyai/tdx/extend"
)
func main() {
ls, err := extend.GetBjCodes()
if err != nil {
logs.Err(err)
return
}
for _, v := range ls {
logs.Debug(v)
}
logs.Debug("总数量:", len(ls))
}

View File

@@ -8,7 +8,7 @@ import (
func main() { func main() {
common.Test(func(c *tdx.Client) { common.Test(func(c *tdx.Client) {
resp, err := c.GetHistoryMinuteTrade("20250609", "sz000001", 0, 20) resp, err := c.GetHistoryMinuteTrade("20250929", "bj838971", 0, 20)
logs.PanicErr(err) logs.PanicErr(err)
for _, v := range resp.List { for _, v := range resp.List {

View File

@@ -8,7 +8,7 @@ import (
func main() { func main() {
common.Test(func(c *tdx.Client) { common.Test(func(c *tdx.Client) {
resp, err := c.GetHistoryMinuteTradeAll("20241025", "sz000001") resp, err := c.GetHistoryMinuteTradeDay("20251010", "sh000001")
logs.PanicErr(err) logs.PanicErr(err)
for _, v := range resp.List { for _, v := range resp.List {

View File

@@ -8,7 +8,7 @@ import (
func main() { func main() {
common.Test(func(c *tdx.Client) { common.Test(func(c *tdx.Client) {
resp, err := c.GetKlineDay("000001", 0, 10) resp, err := c.GetKlineDay("838971", 0, 20)
logs.PanicErr(err) logs.PanicErr(err)
for _, v := range resp.List { for _, v := range resp.List {

View File

@@ -0,0 +1,32 @@
package main
import (
"github.com/injoyai/logs"
"github.com/injoyai/tdx"
"github.com/injoyai/tdx/extend"
"time"
)
func main() {
c, err := tdx.DialDefault()
logs.PanicErr(err)
ks, fs, err := extend.GetTHSDayKlineFactorFull("000001", c)
logs.PanicErr(err)
m := map[int64]*extend.THSFactor{}
for _, v := range fs {
m[v.Date] = v
}
for _, v := range ks[0] {
logs.Debugf("%s 不复权:%.2f 前复权:%.2f 后复权:%.2f \n",
time.Unix(v.Date, 0).Format(time.DateOnly),
v.Close.Float64(),
v.Close.Float64()*m[v.Date].QFactor,
v.Close.Float64()*m[v.Date].HFactor,
)
}
}

View File

@@ -10,7 +10,7 @@ func main() {
c, err := tdx.Dial("124.71.187.122:7709", tdx.WithDebug()) c, err := tdx.Dial("124.71.187.122:7709", tdx.WithDebug())
logs.PanicErr(err) logs.PanicErr(err)
tdx.DefaultCodes, err = tdx.NewCodes(c, "./codes.db") tdx.DefaultCodes, err = tdx.NewCodesSqlite(c, "./codes.db")
logs.PanicErr(err) logs.PanicErr(err)
_ = c _ = c

View File

@@ -0,0 +1,17 @@
package main
import (
"github.com/injoyai/logs"
"github.com/injoyai/tdx"
)
func main() {
_, err := tdx.NewManageMysql(&tdx.ManageConfig{
Number: 2,
CodesFilename: "root:root@tcp(192.168.1.105:3306)/stock?charset=utf8mb4&parseTime=True&loc=Local",
WorkdayFileName: "root:root@tcp(192.168.1.105:3306)/stock?charset=utf8mb4&parseTime=True&loc=Local",
Dial: nil,
})
logs.PanicErr(err)
logs.Debug("done")
}

View File

@@ -0,0 +1,22 @@
package main
import (
"github.com/injoyai/logs"
"github.com/injoyai/tdx"
"github.com/injoyai/tdx/example/common"
)
func main() {
common.Test(func(c *tdx.Client) {
resp, err := c.GetHistoryTradeDay("20251010", "sz000001")
logs.PanicErr(err)
ks := resp.List.Klines()
for _, v := range ks {
logs.Debug(v)
}
})
}

View File

@@ -9,11 +9,12 @@ import (
func main() { func main() {
common.Test(func(c *tdx.Client) { common.Test(func(c *tdx.Client) {
_, err := tdx.NewWorkday(c, "./workday.db") _, err := tdx.NewWorkdaySqlite(c) //"./workday.db"
logs.PanicErr(err) logs.PanicErr(err)
_, err = tdx.NewCodes(c, "./codes.db") _, err = tdx.NewCodesSqlite(c) //"./codes.db"
logs.PanicErr(err) logs.PanicErr(err)
c.Close()
}) })
} }

9
extend/codes-bj.go Normal file
View File

@@ -0,0 +1,9 @@
package extend
import (
"github.com/injoyai/tdx"
)
func GetBjCodes() ([]*tdx.BjCode, error) {
return tdx.GetBjCodes()
}

66
extend/codes-server.go Normal file
View File

@@ -0,0 +1,66 @@
package extend
import (
"encoding/json"
"fmt"
"github.com/injoyai/conv"
"github.com/injoyai/tdx"
"io"
"net/http"
"path/filepath"
)
func ListenCodesHTTP(port int, filename ...string) error {
code, err := tdx.DialCodes(conv.Default(filepath.Join(tdx.DefaultDatabaseDir, "codes.db"), filename...))
if err != nil {
return nil
}
return http.ListenAndServe(fmt.Sprintf(":%d", port), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.RequestURI {
case "/stocks":
ls := code.GetStocks()
w.WriteHeader(http.StatusOK)
w.Write(conv.Bytes(ls))
case "/etfs":
ls := code.GetETFs()
w.WriteHeader(http.StatusOK)
w.Write(conv.Bytes(ls))
default:
http.NotFound(w, r)
}
}))
}
func DialCodesHTTP(address string) *CodesHTTP {
return &CodesHTTP{address: address}
}
type CodesHTTP struct {
address string
}
func (this *CodesHTTP) getList(path string) ([]string, error) {
resp, err := http.DefaultClient.Get(this.address + path)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http code:%d", resp.StatusCode)
}
bs, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
ls := []string(nil)
err = json.Unmarshal(bs, &ls)
return ls, err
}
func (this *CodesHTTP) GetStocks() ([]string, error) {
return this.getList("/stocks")
}
func (this *CodesHTTP) GetETFs() ([]string, error) {
return this.getList("/etfs")
}

View File

@@ -56,7 +56,7 @@ func (this *PullTrade) PullYear(ctx context.Context, m *tdx.Manage, year int, co
var resp *protocol.TradeResp var resp *protocol.TradeResp
err = m.Do(func(c *tdx.Client) error { err = m.Do(func(c *tdx.Client) error {
resp, err = c.GetHistoryTradeAll(date, code) resp, err = c.GetHistoryTradeDay(date, code)
return err return err
}) })
if err != nil { if err != nil {
@@ -67,11 +67,7 @@ func (this *PullTrade) PullYear(ctx context.Context, m *tdx.Manage, year int, co
tss = append(tss, resp.List...) tss = append(tss, resp.List...)
//转成分时K线 //转成分时K线
ks, err := resp.List.Klines1() ks := resp.List.Klines()
if err != nil {
logs.Err(err)
return false
}
kss1 = append(kss1, ks...) kss1 = append(kss1, ks...)
kss5 = append(kss5, ks.Merge(5)...) kss5 = append(kss5, ks.Merge(5)...)

View File

@@ -15,10 +15,36 @@ import (
const ( const (
UrlTHSDayKline = "http://d.10jqka.com.cn/v6/line/hs_%s/0%d/all.js" UrlTHSDayKline = "http://d.10jqka.com.cn/v6/line/hs_%s/0%d/all.js"
THS_BFQ uint8 = 0 //不复权
THS_QFQ uint8 = 1 //前复权 THS_QFQ uint8 = 1 //前复权
THS_HFQ uint8 = 2 //后复权 THS_HFQ uint8 = 2 //后复权
) )
// GetTHSDayKlineFactorFull 增加计算复权因子
func GetTHSDayKlineFactorFull(code string, c *tdx.Client) ([3][]*Kline, []*THSFactor, error) {
ks, err := GetTHSDayKlineFull(code, c)
if err != nil {
return [3][]*Kline{}, nil, err
}
mQPrice := make(map[int64]float64)
for _, v := range ks[1] {
mQPrice[v.Date] = v.Close.Float64()
}
mHPrice := make(map[int64]float64)
for _, v := range ks[2] {
mHPrice[v.Date] = v.Close.Float64()
}
fs := make([]*THSFactor, 0, len(ks[0]))
for _, v := range ks[0] {
fs = append(fs, &THSFactor{
Date: v.Date,
QFactor: mQPrice[v.Date] / v.Close.Float64(),
HFactor: mHPrice[v.Date] / v.Close.Float64(),
})
}
return ks, fs, nil
}
/* /*
GetTHSDayKlineFull GetTHSDayKlineFull
获取[不复权,前复权,后复权]数据,并补充成交金额数据 获取[不复权,前复权,后复权]数据,并补充成交金额数据
@@ -70,8 +96,8 @@ GetTHSDayKline
后复权,和通达信,东方财富都对不上 后复权,和通达信,东方财富都对不上
*/ */
func GetTHSDayKline(code string, _type uint8) ([]*Kline, error) { func GetTHSDayKline(code string, _type uint8) ([]*Kline, error) {
if _type != THS_QFQ && _type != THS_HFQ { if _type != THS_BFQ && _type != THS_QFQ && _type != THS_HFQ {
return nil, fmt.Errorf("数据类型错误,例如:前复权1或后复权2") return nil, fmt.Errorf("数据类型错误,例如:不复权0或前复权1或后复权2")
} }
code = protocol.AddPrefix(code) code = protocol.AddPrefix(code)

12
extend/ths-factor.go Normal file
View File

@@ -0,0 +1,12 @@
package extend
//const (
// // UrlTHSFactor https://d.10jqka.com.cn/v6/line/hs_000001/01/2016.js
// UrlTHSFactor = "https://d.10jqka.com.cn/v6/line/hs_%s/0%d/%d.js"
//)
type THSFactor struct {
Date int64 `json:"date"` //时间
QFactor float64 `json:"q_factor"` //前复权因子
HFactor float64 `json:"h_factor"` //后复权因子
}

2
go.mod
View File

@@ -5,7 +5,7 @@ go 1.20
require ( require (
github.com/glebarez/go-sqlite v1.22.0 github.com/glebarez/go-sqlite v1.22.0
github.com/go-sql-driver/mysql v1.7.0 github.com/go-sql-driver/mysql v1.7.0
github.com/injoyai/base v1.2.15 github.com/injoyai/base v1.2.17
github.com/injoyai/conv v1.2.5 github.com/injoyai/conv v1.2.5
github.com/injoyai/ios v1.2.2 github.com/injoyai/ios v1.2.2
github.com/injoyai/logs v1.0.12 github.com/injoyai/logs v1.0.12

2
go.sum
View File

@@ -28,6 +28,8 @@ github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/injoyai/base v1.2.15 h1:K/ysPqZl7vgNUAz/jpG1IdDpzdSMWvUfoJL+1gPdM9g= github.com/injoyai/base v1.2.15 h1:K/ysPqZl7vgNUAz/jpG1IdDpzdSMWvUfoJL+1gPdM9g=
github.com/injoyai/base v1.2.15/go.mod h1:NfCQjml3z2pCvQ3J3YcOXtecqXD0xVPKjo4YTsMLhr8= github.com/injoyai/base v1.2.15/go.mod h1:NfCQjml3z2pCvQ3J3YcOXtecqXD0xVPKjo4YTsMLhr8=
github.com/injoyai/base v1.2.17 h1:+qYeCSeEMWgmTla+LBC0Ozan9ysS4mV0ne5nfMt9opU=
github.com/injoyai/base v1.2.17/go.mod h1:NfCQjml3z2pCvQ3J3YcOXtecqXD0xVPKjo4YTsMLhr8=
github.com/injoyai/conv v1.2.5 h1:G4OCyF0NTZul5W1u9IgXDOhW4/zmIigdPKXFHQGmv1M= github.com/injoyai/conv v1.2.5 h1:G4OCyF0NTZul5W1u9IgXDOhW4/zmIigdPKXFHQGmv1M=
github.com/injoyai/conv v1.2.5/go.mod h1:s05l3fQJQ4mT4VX+KIdbvCWQB0YzZHprmUfUu2uxd1k= github.com/injoyai/conv v1.2.5/go.mod h1:s05l3fQJQ4mT4VX+KIdbvCWQB0YzZHprmUfUu2uxd1k=
github.com/injoyai/ios v1.2.2 h1:fAPWBL6t22DiE2ZEpBgf5bzyVQTcm2ZhLMkM+JFPhZA= github.com/injoyai/ios v1.2.2 h1:fAPWBL6t22DiE2ZEpBgf5bzyVQTcm2ZhLMkM+JFPhZA=

View File

@@ -1,6 +1,7 @@
package tdx package tdx
import ( import (
"errors"
"github.com/injoyai/ios/client" "github.com/injoyai/ios/client"
"github.com/robfig/cron/v3" "github.com/robfig/cron/v3"
"time" "time"
@@ -10,6 +11,57 @@ const (
DefaultDatabaseDir = "./data/database" DefaultDatabaseDir = "./data/database"
) )
func NewManageMysql(cfg *ManageConfig, op ...client.Option) (*Manage, error) {
//初始化配置
if cfg == nil {
cfg = &ManageConfig{}
}
if cfg.CodesFilename == "" {
return nil, errors.New("未配置Codes的数据库")
}
if cfg.WorkdayFileName == "" {
return nil, errors.New("未配置Workday的数据库")
}
if cfg.Dial == nil {
cfg.Dial = DialDefault
}
//通用客户端
commonClient, err := cfg.Dial(op...)
if err != nil {
return nil, err
}
commonClient.Wait.SetTimeout(time.Second * 5)
//代码管理
codes, err := NewCodesMysql(commonClient, cfg.CodesFilename)
if err != nil {
return nil, err
}
//工作日管理
workday, err := NewWorkdayMysql(commonClient, cfg.WorkdayFileName)
if err != nil {
return nil, err
}
//连接池
p, err := NewPool(func() (*Client, error) {
return cfg.Dial(op...)
}, cfg.Number)
if err != nil {
return nil, err
}
return &Manage{
Pool: p,
Config: cfg,
Codes: codes,
Workday: workday,
Cron: cron.New(cron.WithSeconds()),
}, nil
}
func NewManage(cfg *ManageConfig, op ...client.Option) (*Manage, error) { func NewManage(cfg *ManageConfig, op ...client.Option) (*Manage, error) {
//初始化配置 //初始化配置
if cfg == nil { if cfg == nil {
@@ -33,13 +85,13 @@ func NewManage(cfg *ManageConfig, op ...client.Option) (*Manage, error) {
commonClient.Wait.SetTimeout(time.Second * 5) commonClient.Wait.SetTimeout(time.Second * 5)
//代码管理 //代码管理
codes, err := NewCodes(commonClient, cfg.CodesFilename) codes, err := NewCodesSqlite(commonClient, cfg.CodesFilename)
if err != nil { if err != nil {
return nil, err return nil, err
} }
//工作日管理 //工作日管理
workday, err := NewWorkday(commonClient, cfg.WorkdayFileName) workday, err := NewWorkdaySqlite(commonClient, cfg.WorkdayFileName)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -233,6 +233,14 @@ func FixKlineTime(ks []*Kline) []*Kline {
type Klines []*Kline type Klines []*Kline
// LastPrice 获取最后一个K线的收盘价
func (this Klines) LastPrice() Price {
if len(this) == 0 {
return 0
}
return this[len(this)-1].Close
}
func (this Klines) Len() int { func (this Klines) Len() int {
return len(this) return len(this)
} }
@@ -249,12 +257,16 @@ func (this Klines) Sort() {
sort.Sort(this) sort.Sort(this)
} }
// Kline 计算多个K线,成一个K线 func (this Klines) Kline(t time.Time, last Price) *Kline {
func (this Klines) Kline() *Kline { k := &Kline{
if this == nil { Time: t,
return new(Kline) Open: last,
High: last,
Low: last,
Close: last,
Volume: 0,
Amount: 0,
} }
k := new(Kline)
for i, v := range this { for i, v := range this {
switch i { switch i {
case 0: case 0:
@@ -262,34 +274,87 @@ func (this Klines) Kline() *Kline {
k.High = v.High k.High = v.High
k.Low = v.Low k.Low = v.Low
k.Close = v.Close k.Close = v.Close
case len(this) - 1: default:
k.Close = v.Close if k.Open == 0 {
k.Time = v.Time k.Open = v.Open
} }
if v.High > k.High { k.High = conv.Select(k.High < v.High, v.High, k.High)
k.High = v.High k.Low = conv.Select(k.Low > v.Low, v.Low, k.Low)
}
if v.Low < k.Low {
k.Low = v.Low
} }
k.Close = v.Close
k.Volume += v.Volume k.Volume += v.Volume
k.Amount += v.Amount k.Amount += v.Amount
} }
return k return k
} }
// Merge 合并K线,1分钟转成5,15,30分钟等 // Merge 合并成其他类型的K线
func (this Klines) Merge(n int) Klines { func (this Klines) Merge(n int) Klines {
if this == nil { if n <= 1 {
return nil return this
} }
ks := []*Kline(nil) ks := Klines(nil)
for i := 0; i < len(this); i += n { ls := Klines(nil)
if i+n > len(this) { for i := 0; ; i++ {
ks = append(ks, this[i:].Kline()) if len(this) <= i*n {
} else { break
ks = append(ks, this[i:i+n].Kline())
} }
if len(this) < (i+1)*n {
ls = this[i*n:]
} else {
ls = this[i*n : (i+1)*n]
}
if len(ls) == 0 {
break
}
last := ls[len(ls)-1]
k := ls.Kline(last.Time, ls[0].Open)
ks = append(ks, k)
} }
return ks return ks
} }
//// Kline 计算多个K线,成一个K线
//func (this Klines) Kline() *Kline {
// if this == nil {
// return new(Kline)
// }
// k := new(Kline)
// for i, v := range this {
// switch i {
// case 0:
// k.Open = v.Open
// k.High = v.High
// k.Low = v.Low
// k.Close = v.Close
// case len(this) - 1:
// k.Close = v.Close
// k.Time = v.Time
// }
// if v.High > k.High {
// k.High = v.High
// }
// if v.Low < k.Low {
// k.Low = v.Low
// }
// k.Volume += v.Volume
// k.Amount += v.Amount
// }
// return k
//}
//// Merge 合并K线,1分钟转成5,15,30分钟等
//func (this Klines) Merge(n int) Klines {
// if this == nil {
// return nil
// }
// ks := []*Kline(nil)
// for i := 0; i < len(this); i += n {
// if i+n > len(this) {
// ks = append(ks, this[i:].Kline())
// } else {
// ks = append(ks, this[i:i+n].Kline())
// }
// }
// return ks
//}

View File

@@ -3,6 +3,7 @@ package protocol
import ( import (
"errors" "errors"
"fmt" "fmt"
"github.com/injoyai/base/types"
"github.com/injoyai/conv" "github.com/injoyai/conv"
"time" "time"
) )
@@ -121,52 +122,108 @@ func (trade) Decode(bs []byte, c TradeCache) (*TradeResp, error) {
type Trades []*Trade type Trades []*Trade
func (this Trades) Kline() (k *Kline, err error) { // Klines 合并分时成交成k线
k = &Kline{} func (this Trades) Klines() Klines {
for i, v := range this { //按天分割
switch i { m := make(types.SortMap[int64, Trades])
for _, v := range this {
//获取当天零点的时间戳
unix := time.Date(v.Time.Year(), v.Time.Month(), v.Time.Day(), 0, 0, 0, 0, v.Time.Location()).Unix()
m[unix] = append(m[unix], v)
}
//按天排序
mKline := types.SortMap[int64, Klines]{}
for date, v := range m {
//生成一分钟k线
t := time.Unix(date, 0)
mKline[date] = v.klinesForDay(t)
}
//按时间排序
lss := mKline.Sort()
ls := Klines{}
for _, v := range lss {
ls = append(ls, v...)
}
return ls
}
// Kline 合并分时成交成1个k线,注意分时成交时间保持一致
func (this Trades) Kline(t time.Time, last Price) *Kline {
k := &Kline{
Time: t,
Last: last,
Open: last,
High: last,
Low: last,
Close: last,
}
first := 0
for _, v := range this {
if v.Price <= 0 {
continue
}
switch first {
case 0: case 0:
k.Time = v.Time
k.Open = v.Price k.Open = v.Price
k.High = v.Price k.High = v.Price
k.Low = v.Price k.Low = v.Price
k.Close = v.Price k.Close = v.Price
case len(this) - 1: default:
k.Close = v.Price k.High = conv.Select(k.High < v.Price, v.Price, k.High)
k.Low = conv.Select(k.Low > v.Price, v.Price, k.Low)
} }
k.High = conv.Select(v.Price > k.High, v.Price, k.High) k.Close = v.Price
k.Low = conv.Select(v.Price < k.Low, v.Price, k.Low)
k.Volume += int64(v.Volume) k.Volume += int64(v.Volume)
k.Amount += v.Amount() k.Amount += v.Price * Price(v.Volume) * 100
first++
} }
return return k
} }
// Klines1 1分K线 // kline1 生成一分钟k线,一天
func (this Trades) Klines1() (Klines, error) { func (this Trades) klinesForDay(date time.Time) Klines {
m := make(map[int64]Trades) _930 := 570 //9:30 的分钟
for _, v := range this { _1130 := 690 //11:30 的分钟
//小于9点30的数据归类到9点30 _1300 := 780 //13:00 的分钟
if v.Time.Hour() == 9 && v.Time.Minute() < 30 { _1500 := 900 //15:00 的分钟
v.Time = time.Date(v.Time.Year(), v.Time.Month(), v.Time.Day(), 9, 30, 0, 0, v.Time.Location()) keys := []int(nil)
} //早上
//15:00之前和11:30之前+1 m := map[int]Trades{}
if (v.Time.Hour() >= 13 && v.Time.Hour() < 15) || (v.Time.Hour() == 11 && v.Time.Minute() < 30) || v.Time.Hour() < 11 { for i := 1; i <= 120; i++ {
v.Time = v.Time.Add(time.Minute) keys = append(keys, _930+i)
} m[_930+i] = []*Trade{}
m[v.Time.Unix()] = append(m[v.Time.Unix()], v)
} }
//下午
ls := Klines(nil) for i := 1; i <= 120; i++ {
for _, v := range m { keys = append(keys, _1300+i)
k, err := v.Kline() m[_1300+i] = []*Trade{}
if err != nil { }
return nil, err //获取开盘价,有可能前几分钟没有数据,先遍历一遍
var open Price
for _, v := range this {
if v.Price > 0 {
open = v.Price
break
} }
}
//分组,按
for _, v := range this {
ms := minutes(v.Time)
t := conv.Select(ms <= _930, _930, ms)
t++
t = conv.Select(t > _1130 && t <= _1300, _1130, t)
t = conv.Select(t > _1500, _1500, t)
m[t] = append(m[t], v)
}
//合并
ls := []*Kline(nil)
for _, v := range keys {
k := m[v].Kline(time.Date(date.Year(), date.Month(), date.Day(), v/60, v%60, 0, 0, date.Location()), open)
open = k.Close
ls = append(ls, k) ls = append(ls, k)
} }
ls.Sort() return ls
return ls, nil
} }
type TradeCache struct { type TradeCache struct {

View File

@@ -20,8 +20,8 @@ func (this Exchange) String() string {
return "sz" return "sz"
case ExchangeSH: case ExchangeSH:
return "sh" return "sh"
//case ExchangeBJ: case ExchangeBJ:
//return "bj" return "bj"
default: default:
return "unknown" return "unknown"
} }
@@ -33,8 +33,8 @@ func (this Exchange) Name() string {
return "上海" return "上海"
case ExchangeSZ: case ExchangeSZ:
return "深圳" return "深圳"
//case ExchangeBJ: case ExchangeBJ:
//return "北京" return "北京"
default: default:
return "未知" return "未知"
} }
@@ -43,7 +43,7 @@ func (this Exchange) Name() string {
const ( const (
ExchangeSZ Exchange = iota //深圳交易所 ExchangeSZ Exchange = iota //深圳交易所
ExchangeSH //上海交易所 ExchangeSH //上海交易所
//ExchangeBJ //北京交易所 ExchangeBJ //北京交易所
) )
const ( const (

View File

@@ -58,6 +58,8 @@ func DecodeCode(code string) (Exchange, string, error) {
return ExchangeSH, code[2:], nil return ExchangeSH, code[2:], nil
case ExchangeSZ.String(): case ExchangeSZ.String():
return ExchangeSZ, code[2:], nil return ExchangeSZ, code[2:], nil
case ExchangeBJ.String():
return ExchangeBJ, code[2:], nil
default: default:
return 0, "", fmt.Errorf("股票代码错误,例如:SZ000001") return 0, "", fmt.Errorf("股票代码错误,例如:SZ000001")
} }
@@ -125,14 +127,18 @@ func GetTime(bs [4]byte, Type uint8) time.Time {
} }
func basePrice(code string) Price { func basePrice(code string) Price {
if len(code) == 0 { if len(code) < 2 {
return 1
}
switch code[:1] {
case "8":
return 1 return 1
} }
switch code[:2] { switch code[:2] {
case "60", "30", "68", "00": case "60", "30", "68", "00", "92", "43", "39":
return 1 return 1
default: default:
return 10 return 1
} }
} }
@@ -237,20 +243,34 @@ func getVolume2(val uint32) float64 {
// IsStock 是否是股票,示例sz000001 // IsStock 是否是股票,示例sz000001
func IsStock(code string) bool { func IsStock(code string) bool {
if len(code) != 8 { return IsSZStock(code) || IsSHStock(code) || IsBJStock(code)
return false
}
code = strings.ToLower(code)
switch {
case code[0:2] == ExchangeSH.String() &&
(code[2:3] == "6"):
return true
case code[0:2] == ExchangeSZ.String() && //if len(code) != 8 {
(code[2:3] == "0" || code[2:4] == "30"): // return false
return true //}
} //code = strings.ToLower(code)
return false //switch {
//case code[0:2] == ExchangeSH.String() &&
// (code[2:3] == "6"):
// return true
//
//case code[0:2] == ExchangeSZ.String() &&
// (code[2:3] == "0" || code[2:4] == "30"):
// return true
//}
//return false
}
func IsSZStock(code string) bool {
return len(code) == 8 && strings.ToLower(code[0:2]) == ExchangeSZ.String() && (code[2:3] == "0" || code[2:4] == "30")
}
func IsSHStock(code string) bool {
return len(code) == 8 && strings.ToLower(code[0:2]) == ExchangeSH.String() && code[2:3] == "6"
}
func IsBJStock(code string) bool {
return len(code) == 8 && strings.ToLower(code[0:2]) == ExchangeBJ.String() && (code[2:4] == "92" || code[2:4] == "43" || code[2:3] == "8")
} }
// IsETF 是否是基金,示例sz159558 // IsETF 是否是基金,示例sz159558
@@ -290,7 +310,14 @@ func AddPrefix(code string) string {
case code[:3] == "159": case code[:3] == "159":
//深圳基金 //深圳基金
code = ExchangeSZ.String() + code code = ExchangeSZ.String() + code
case code[:1] == "8" || code[:2] == "92" || code[:2] == "43":
//北京股票
code = ExchangeBJ.String() + code
} }
} }
return code return code
} }
func minutes(t time.Time) int {
return t.Hour()*60 + t.Minute()
}

View File

@@ -3,6 +3,7 @@ package tdx
import ( import (
"errors" "errors"
_ "github.com/glebarez/go-sqlite" _ "github.com/glebarez/go-sqlite"
_ "github.com/go-sql-driver/mysql"
"github.com/injoyai/base/maps" "github.com/injoyai/base/maps"
"github.com/injoyai/conv" "github.com/injoyai/conv"
"github.com/injoyai/logs" "github.com/injoyai/logs"
@@ -15,7 +16,22 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
) )
func NewWorkday(c *Client, filename string) (*Workday, error) { func NewWorkdayMysql(c *Client, dsn string) (*Workday, error) {
//连接数据库
db, err := xorm.NewEngine("mysql", dsn)
if err != nil {
return nil, err
}
db.SetMapper(core.SameMapper{})
return NewWorkday(c, db)
}
func NewWorkdaySqlite(c *Client, filenames ...string) (*Workday, error) {
defaultFilename := filepath.Join(DefaultDatabaseDir, "workday.db")
filename := conv.Default(defaultFilename, filenames...)
//如果文件夹不存在就创建 //如果文件夹不存在就创建
dir, _ := filepath.Split(filename) dir, _ := filepath.Split(filename)
@@ -28,6 +44,11 @@ func NewWorkday(c *Client, filename string) (*Workday, error) {
} }
db.SetMapper(core.SameMapper{}) db.SetMapper(core.SameMapper{})
db.DB().SetMaxOpenConns(1) db.DB().SetMaxOpenConns(1)
return NewWorkday(c, db)
}
func NewWorkday(c *Client, db *xorm.Engine) (*Workday, error) {
if err := db.Sync2(new(WorkdayModel)); err != nil { if err := db.Sync2(new(WorkdayModel)); err != nil {
return nil, err return nil, err
} }
@@ -37,12 +58,12 @@ func NewWorkday(c *Client, filename string) (*Workday, error) {
db: db, db: db,
cache: maps.NewBit(), cache: maps.NewBit(),
} }
//设置定时器,每天早上9点更新数据,8点多获取不到今天的数据 //设置定时器,每天早上9点更新数据,8点多获取不到今天的数据
task := cron.New(cron.WithSeconds()) task := cron.New(cron.WithSeconds())
task.AddFunc("0 0 9 * * *", func() { task.AddFunc("0 0 9 * * *", func() {
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
if err := w.Update(); err == nil { err := w.Update()
if err == nil {
return return
} }
logs.Err(err) logs.Err(err)
@@ -50,7 +71,6 @@ func NewWorkday(c *Client, filename string) (*Workday, error) {
} }
}) })
task.Start() task.Start()
return w, w.Update() return w, w.Update()
} }
@@ -84,27 +104,30 @@ func (this *Workday) Update() error {
} }
now := time.Now() now := time.Now()
if lastWorkday == nil || lastWorkday.Unix < IntegerDay(now).Unix() { if lastWorkday.Unix < IntegerDay(now).Unix() {
resp, err := this.Client.GetIndexDayAll("sh000001") resp, err := this.Client.GetIndexDayAll("sh000001")
if err != nil { if err != nil {
logs.Err(err) logs.Err(err)
return err return err
} }
return NewSessionFunc(this.db, func(session *xorm.Session) error { inserts := []any(nil)
for _, v := range resp.List { for _, v := range resp.List {
if unix := v.Time.Unix(); unix > lastWorkday.Unix { if unix := v.Time.Unix(); unix > lastWorkday.Unix {
_, err = session.Insert(&WorkdayModel{Unix: unix, Date: v.Time.Format("20060102"), Is: true}) inserts = append(inserts, &WorkdayModel{Unix: unix, Date: v.Time.Format("20060102")})
if err != nil { this.cache.Set(uint64(unix), true)
return err
}
this.cache.Set(uint64(unix), true)
}
} }
}
if len(inserts) == 0 {
return nil return nil
}) }
_, err = this.db.Insert(inserts)
return err
} }
return nil return nil
} }
@@ -158,7 +181,6 @@ type WorkdayModel struct {
ID int64 `json:"id"` //主键 ID int64 `json:"id"` //主键
Unix int64 `json:"unix"` //时间戳 Unix int64 `json:"unix"` //时间戳
Date string `json:"date"` //日期 Date string `json:"date"` //日期
Is bool `json:"is"` //是否是工作日
} }
func (this *WorkdayModel) TableName() string { func (this *WorkdayModel) TableName() string {