Compare commits

..

32 Commits

Author SHA1 Message Date
钱纯净
81c45e76d0 修复Codes,更新数据的时候,少了交易所的条件 2025-03-05 22:54:23 +08:00
钱纯净
a8c248bf9d 修复Codes,更新数据的时候,少了交易所的条件 2025-03-05 22:50:45 +08:00
钱纯净
3e57f54978 增加全局变量ExchangeEstablish(上海交易所成立时间) 2025-03-03 22:35:43 +08:00
钱纯净
50c997f26f 细节优化 2025-03-03 19:35:56 +08:00
injoyai
0740ff7ca0 优化RangeDesc 2025-02-28 10:38:24 +08:00
injoyai
81f2ffcbea 优化RangeDesc 2025-02-28 10:36:13 +08:00
injoyai
8a63c2ff2e 增加RangeDesc,倒序遍历工作日,从今天-1990年12月19日(上海交易所成立时间) 2025-02-28 10:23:11 +08:00
injoyai
71035fb210 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	workday.go
2025-02-28 09:36:45 +08:00
injoyai
f479d99c99 修改沪市指数的数据时间作为是否开市的依据,替换掉平安银行(可能会出现停牌无数据的情况,历史出现过3次) 2025-02-28 09:35:58 +08:00
钱纯净
ddb36b5aa7 增加Workday的方法RangeDesc,用于遍历所有工作日,根据平安银行的日线数据,但是还有比平安银行更早上市的公司,会有些误差 2025-02-26 21:40:41 +08:00
injoyai
ddc4b801bf 增加默认连接 2025-02-26 13:26:10 +08:00
injoyai
e22d2776e7 细节优化 2025-02-24 17:00:02 +08:00
injoyai
f46b97e1e1 细节优化 2025-02-24 16:57:48 +08:00
injoyai
c7c3e42b61 增加manage,方便快速搭建项目,试用 2025-02-21 15:13:51 +08:00
injoyai
2f46a3fb4b 增加manage,方便快速搭建项目,试用 2025-02-21 15:09:52 +08:00
injoyai
cee5270dfc 增加manage,方便快速搭建项目,试用 2025-02-21 15:08:19 +08:00
injoyai
c6f68ee031 优化pool 2025-02-21 15:07:20 +08:00
injoyai
bbc2013cd6 测试通过 2025-02-21 14:45:52 +08:00
injoyai
2976d84bde 拓展示例 2025-02-21 14:44:28 +08:00
injoyai
e9f3d0ac62 增加拓展,封装每日更新代码和工作日信息 2025-02-21 14:27:37 +08:00
injoyai
eb243b4ac7 增加拓展,封装每日更新代码和工作日信息 2025-02-21 14:25:14 +08:00
injoyai
859ea71e8d 增加判断是否是股票代码的判断 2025-02-21 10:44:30 +08:00
injoyai
6e920c7330 增加pool,简易客户端连接池管理 2025-02-21 10:11:24 +08:00
injoyai
821ff1a6e6 简单兼容成功 2025-02-21 10:04:01 +08:00
injoyai
ef42ac32b2 简单兼容成功 2025-02-21 09:55:35 +08:00
injoyai
f6811aca01 准备增加指数 2025-02-21 09:37:33 +08:00
injoyai
38494234cd 准备增加指数 2025-02-19 14:08:16 +08:00
钱纯净
60a8c65c93 合并个股和指数 2025-02-17 23:40:04 +08:00
钱纯净
058e87b9be 合并个股和指数 2025-02-17 23:39:38 +08:00
钱纯净
59a9517a11 合并个股和指数 2025-02-17 23:38:58 +08:00
钱纯净
8e7135eabb 准备增加获取指数函数 2025-02-17 00:27:29 +08:00
injoyai
e5bbb38aee 修复并发请求错误的bug 2024-12-19 16:50:41 +08:00
13 changed files with 688 additions and 22 deletions

View File

@@ -38,6 +38,11 @@ func Dial(addr string, op ...client.Option) (cli *Client, err error) {
return DialWith(tcp.NewDial(addr), op...)
}
// DialDefault 默认连接方式
func DialDefault(op ...client.Option) (cli *Client, err error) {
return DialWith(NewHostDial(Hosts), op...)
}
// DialHosts 与服务器建立连接,多个服务器轮询,开启重试生效
func DialHosts(hosts []string, op ...client.Option) (cli *Client, err error) {
return DialWith(NewHostDial(hosts), op...)
@@ -130,7 +135,7 @@ func (this *Client) handlerDealMessage(c *client.Client, msg ios.Acker) {
resp, err = protocol.MHistoryMinuteTrade.Decode(f.Data, conv.String(val))
case protocol.TypeKline:
resp, err = protocol.MKline.Decode(f.Data, conv.Uint8(val))
resp, err = protocol.MKline.Decode(f.Data, val.(protocol.KlineCache))
default:
err = fmt.Errorf("通讯类型未解析:0x%X", f.Type)
@@ -155,7 +160,7 @@ func (this *Client) SendFrame(f *protocol.Frame, cache ...any) (any, error) {
if _, err := this.Client.Write(f.Bytes()); err != nil {
return nil, err
}
return this.Wait.Wait(conv.String(this.msgID))
return this.Wait.Wait(conv.String(f.MsgID))
}
// GetCount 获取市场内的股票数量
@@ -298,7 +303,7 @@ func (this *Client) GetKline(Type uint8, code string, start, count uint16) (*pro
if err != nil {
return nil, err
}
result, err := this.SendFrame(f, Type)
result, err := this.SendFrame(f, protocol.KlineCache{Type: Type, Code: code})
if err != nil {
return nil, err
}

191
codes.go Normal file
View File

@@ -0,0 +1,191 @@
package tdx
import (
"github.com/injoyai/logs"
"github.com/injoyai/tdx/protocol"
"github.com/robfig/cron/v3"
"os"
"path/filepath"
"time"
"xorm.io/core"
"xorm.io/xorm"
)
func NewCodes(c *Client, filename string) (*Codes, error) {
//如果文件夹不存在就创建
dir, _ := filepath.Split(filename)
_ = os.MkdirAll(dir, 0777)
//连接数据库
db, err := xorm.NewEngine("sqlite", filename)
if err != nil {
return nil, err
}
db.SetMapper(core.SameMapper{})
db.DB().SetMaxOpenConns(1)
if err := db.Sync2(new(CodeModel)); err != nil {
return nil, err
}
cc := &Codes{
Client: c,
db: db,
Codes: nil,
}
//设置定时器,每天早上9点更新数据
task := cron.New(cron.WithSeconds())
task.AddFunc("0 0 9 * * *", func() {
for i := 0; i < 3; i++ {
if err := cc.Update(); err == nil {
return
}
logs.Err(err)
<-time.After(time.Minute * 5)
}
})
task.Start()
return cc, cc.Update()
}
type Codes struct {
*Client //客户端
db *xorm.Engine //数据库实例
Codes map[string]*CodeModel //股票缓存
}
// GetName 获取股票名称
func (this *Codes) GetName(code string) string {
if v, ok := this.Codes[code]; ok {
return v.Name
}
return "未知"
}
// GetStocks 获取股票代码,sh6xxx sz0xx sz30xx
func (this *Codes) GetStocks() []string {
ls := []string(nil)
for k, _ := range this.Codes {
if protocol.IsStock(k) {
ls = append(ls, k)
}
}
return ls
}
func (this *Codes) Update() error {
codes, err := this.Code(false)
if err != nil {
return err
}
codeMap := make(map[string]*CodeModel)
for _, code := range codes {
codeMap[code.Exchange+code.Code] = code
}
this.Codes = codeMap
return nil
}
// Code 更新股票并返回结果
func (this *Codes) Code(byDatabase bool) ([]*CodeModel, error) {
//2. 查询数据库所有股票
list := []*CodeModel(nil)
if err := this.db.Find(&list); err != nil {
return nil, err
}
//如果是从缓存读取,则返回结果
if byDatabase {
return list, nil
}
mCode := make(map[string]*CodeModel, len(list))
for _, v := range list {
mCode[v.Code] = v
}
//3. 从服务器获取所有股票代码
insert := []*CodeModel(nil)
update := []*CodeModel(nil)
for _, exchange := range []protocol.Exchange{protocol.ExchangeSH, protocol.ExchangeSZ} {
resp, err := this.Client.GetCodeAll(exchange)
if err != nil {
return nil, err
}
for _, v := range resp.List {
if _, ok := mCode[v.Code]; ok {
if mCode[v.Code].Name != v.Name {
mCode[v.Code].Name = v.Name
update = append(update, &CodeModel{
Name: v.Name,
Code: v.Code,
Exchange: exchange.String(),
})
}
} else {
code := &CodeModel{
Name: v.Name,
Code: v.Code,
Exchange: exchange.String(),
}
insert = append(insert, code)
list = append(list, code)
}
}
}
//4. 插入或者更新数据库
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").Update(v); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
return list, nil
}
type CodeModel struct {
ID int64 `json:"id"` //主键
Name string `json:"name"` //名称,有时候名称会变,例STxxx
Code string `json:"code" xorm:"index"` //代码
Exchange string `json:"exchange" xorm:"index"` //交易所
EditDate int64 `json:"editDate" xorm:"updated"` //修改时间
InDate int64 `json:"inDate" xorm:"created"` //创建时间
}
func (c *CodeModel) TableName() string {
return "codes"
}
func NewSessionFunc(db *xorm.Engine, fn func(session *xorm.Session) error) error {
session := db.NewSession()
defer session.Close()
if err := session.Begin(); err != nil {
session.Rollback()
return err
}
if err := fn(session); err != nil {
session.Rollback()
return err
}
if err := session.Commit(); err != nil {
session.Rollback()
return err
}
return nil
}

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

@@ -0,0 +1,20 @@
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.GetKlineDay("sh000001", 0, 10)
logs.PanicErr(err)
for _, v := range resp.List {
logs.Debug(v)
}
logs.Debug("总数:", resp.Count)
})
}

View File

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

View File

@@ -0,0 +1,19 @@
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) {
_, err := tdx.NewWorkday(c, "./workday.db")
logs.PanicErr(err)
_, err = tdx.NewCodes(c, "./codes.db")
logs.PanicErr(err)
})
}

17
go.mod
View File

@@ -3,25 +3,40 @@ module github.com/injoyai/tdx
go 1.20
require (
github.com/glebarez/go-sqlite v1.22.0
github.com/injoyai/base v1.0.18
github.com/injoyai/conv v1.1.10
github.com/injoyai/ios v0.0.4
github.com/injoyai/logs v1.0.9
github.com/robfig/cron/v3 v3.0.1
golang.org/x/text v0.16.0
xorm.io/core v0.7.3
xorm.io/xorm v1.3.9
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fatih/color v1.14.1 // indirect
github.com/goccy/go-json v0.8.1 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.1.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/satori/go.uuid v1.2.0 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/syndtr/goleveldb v1.0.0 // indirect
golang.org/x/sys v0.22.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.37.6 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.7.2 // indirect
modernc.org/sqlite v1.28.0 // indirect
xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect
)

77
go.sum
View File

@@ -1,13 +1,33 @@
gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a h1:lSA0F4e9A2NcQSqGqTOXqu2aRi/XEQxDCBwM8yJtE6s=
gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a/go.mod h1:EXuID2Zs0pAQhH8yz+DNjUbjppKQzKFAn28TMYPB6IU=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w=
github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ=
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
github.com/goccy/go-json v0.8.1 h1:4/Wjm0JIJaTDm8K1KcGrLHJoa8EsJ13YWeX+6Kfq6uI=
github.com/goccy/go-json v0.8.1/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/injoyai/base v1.0.18 h1:AMB1NhPe9acvMp04sThE8Ji/SRS1/MHsx19NmSoD8LA=
github.com/injoyai/base v1.0.18/go.mod h1:2JSv8ndJ/FmKyazfhDBewzylEbVfJV0EE/r6kOvnzwU=
github.com/injoyai/conv v1.1.5/go.mod h1:PYoJcbqaz4eyQUovzErRFCuDSPGB4L07AvdmFsTrTew=
@@ -19,6 +39,7 @@ github.com/injoyai/logs v1.0.9 h1:Wq7rCVIQKcPx+z+lzKQb2qyDK4TML/cgmaSZN9tx33c=
github.com/injoyai/logs v1.0.9/go.mod h1:CLchJCGhb39Obyrci816R+KMtbxZhgPs0FuikhyixK4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
@@ -31,47 +52,99 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.4.3 h1:RE1xgDvH7imwFD45h+u2SgIfERHlS2yNG4DObb5BSKU=
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI=
github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE=
github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
lukechampine.com/uint128 v1.3.0 h1:cDdUVfRwDUDovz610ABgFD17nXD4/uDgVHl2sC3+sbo=
modernc.org/cc/v3 v3.41.0 h1:QoR1Sn3YWlmA1T4vLaKZfawdVtSiGx8H+cEojbC7v1Q=
modernc.org/ccgo/v3 v3.16.15 h1:KbDR3ZAVU+wiLyMESPtbtE/Add4elztFyfsWoNTgxS0=
modernc.org/libc v1.37.6 h1:orZH3c5wmhIQFTXF+Nt+eeauyd+ZIt2BX6ARe+kD+aw=
modernc.org/libc v1.37.6/go.mod h1:YAXkAZ8ktnkCKaN9sw/UDeUVkGYJ/YquGO4FTi5nmHE=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=
modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
modernc.org/sqlite v1.28.0 h1:Zx+LyDDmXczNnEQdvPuEfcFVA2ZPyaD7UCZDjef3BHQ=
modernc.org/sqlite v1.28.0/go.mod h1:Qxpazz0zH8Z1xCFyi5GSL3FzbtZ3fvbjmywNogldEW0=
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 h1:bvLlAPW1ZMTWA32LuZMBEGHAUOcATZjzHcotf3SWweM=
xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE=
xorm.io/core v0.7.3 h1:W8ws1PlrnkS1CZU1YWaYLMQcQilwAmQXU0BJDJon+H0=
xorm.io/core v0.7.3/go.mod h1:jJfd0UAEzZ4t87nbQYtVjmqpIODugN6PD2D9E+dJvdM=
xorm.io/xorm v1.3.9 h1:TUovzS0ko+IQ1XnNLfs5dqK1cJl1H5uHpWbWqAQ04nU=
xorm.io/xorm v1.3.9/go.mod h1:LsCCffeeYp63ssk0pKumP6l96WZcHix7ChpurcLNuMw=

86
manage.go Normal file
View File

@@ -0,0 +1,86 @@
package tdx
import (
"github.com/injoyai/ios/client"
"github.com/robfig/cron/v3"
"path/filepath"
"time"
)
func NewManage(cfg *ManageConfig, op ...client.Option) (*Manage, error) {
//初始化配置
if cfg == nil {
cfg = &ManageConfig{}
}
if len(cfg.Hosts) == 0 {
cfg.Hosts = Hosts
}
if cfg.CodesDir == "" {
cfg.CodesDir = "./data/database"
}
if cfg.WorkdayDir == "" {
cfg.WorkdayDir = "./data/database"
}
//连接池
p, err := NewPool(func() (*Client, error) {
return DialHosts(cfg.Hosts, op...)
}, cfg.Number)
if err != nil {
return nil, err
}
//代码
codesClient, err := DialHosts(cfg.Hosts, op...)
if err != nil {
return nil, err
}
codesClient.Wait.SetTimeout(time.Second * 5)
codes, err := NewCodes(codesClient, filepath.Join(cfg.CodesDir, "codes.db"))
if err != nil {
return nil, err
}
//工作日
workdayClient, err := DialHosts(cfg.Hosts, op...)
if err != nil {
return nil, err
}
workdayClient.Wait.SetTimeout(time.Second * 5)
workday, err := NewWorkday(workdayClient, filepath.Join(cfg.WorkdayDir, "workday.db"))
if err != nil {
return nil, err
}
return &Manage{
Pool: p,
Config: cfg,
Codes: codes,
Workday: workday,
Cron: cron.New(cron.WithSeconds()),
}, nil
}
type Manage struct {
*Pool
Config *ManageConfig
Codes *Codes
Workday *Workday
Cron *cron.Cron
}
// AddWorkdayTask 添加工作日任务
func (this *Manage) AddWorkdayTask(spec string, f func(m *Manage)) {
this.Cron.AddFunc(spec, func() {
if this.Workday.TodayIs() {
f(this)
}
})
}
type ManageConfig struct {
Hosts []string //服务端IP
Number int //客户端数量
CodesDir string //代码数据库位置
WorkdayDir string //工作日数据库位置
}

75
pool.go Normal file
View File

@@ -0,0 +1,75 @@
package tdx
import (
"errors"
"github.com/injoyai/base/safe"
)
func NewPool(dial func() (*Client, error), number int) (*Pool, error) {
if number <= 0 {
number = 1
}
ch := make(chan *Client, number)
p := &Pool{
ch: ch,
Closer: safe.NewCloser().SetCloseFunc(func(err error) error {
close(ch)
return nil
}),
}
for i := 0; i < number; i++ {
c, err := dial()
if err != nil {
return nil, err
}
p.ch <- c
}
return p, nil
}
type Pool struct {
ch chan *Client
*safe.Closer
}
func (this *Pool) Get() (*Client, error) {
select {
case <-this.Done():
return nil, this.Err()
case c, ok := <-this.ch:
if !ok {
return nil, errors.New("已关闭")
}
return c, nil
}
}
func (this *Pool) Put(c *Client) {
select {
case <-this.Done():
c.Close()
return
case this.ch <- c:
}
}
func (this *Pool) Do(fn func(c *Client) error) error {
c, err := this.Get()
if err != nil {
return err
}
defer this.Put(c)
return fn(c)
}
func (this *Pool) Go(fn func(c *Client)) error {
c, err := this.Get()
if err != nil {
return err
}
go func(c *Client) {
defer this.Put(c)
fn(c)
}(c)
return nil
}

View File

@@ -1,5 +1,7 @@
package protocol
import "time"
const (
TypeConnect = 0x000D //建立连接
TypeHeart = 0x0004 //心跳
@@ -12,6 +14,11 @@ const (
TypeKline = 0x052D //K线图
)
var (
// ExchangeEstablish 交易所成立时间
ExchangeEstablish = time.Date(1990, 12, 19, 0, 0, 0, 0, time.Local)
)
/*
从其他地方复制
const (

View File

@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"github.com/injoyai/base/g"
"github.com/injoyai/conv"
"time"
)
@@ -45,14 +46,17 @@ type Kline struct {
Volume int64 //成交量
Amount Price //成交额
Time time.Time //时间
UpCount int //上涨数量,指数有效
DownCount int //下跌数量,指数有效
}
func (this *Kline) String() string {
return fmt.Sprintf("%s 昨收盘:%s 开盘价:%s 最高价:%s 最低价:%s 收盘价:%s 涨跌:%s 涨跌幅:%0.2f 成交量:%s 成交额:%s",
return fmt.Sprintf("%s 昨收盘:%s 开盘价:%s 最高价:%s 最低价:%s 收盘价:%s 涨跌:%s 涨跌幅:%0.2f 成交量:%s 成交额:%s 涨跌数: %d/%d",
this.Time.Format("2006-01-02 15:04:05"),
this.Last, this.Open, this.High, this.Low, this.Close,
this.RisePrice(), this.RiseRate(),
Int64UnitString(this.Volume), FloatUnitString(this.Amount.Float64()),
this.UpCount, this.DownCount,
)
}
@@ -103,7 +107,7 @@ func (kline) Frame(Type uint8, code string, start, count uint16) (*Frame, error)
}, nil
}
func (kline) Decode(bs []byte, Type uint8) (*KlineResp, error) {
func (kline) Decode(bs []byte, c KlineCache) (*KlineResp, error) {
if len(bs) < 2 {
return nil, errors.New("数据长度不足")
@@ -112,13 +116,12 @@ func (kline) Decode(bs []byte, Type uint8) (*KlineResp, error) {
resp := &KlineResp{
Count: Uint16(bs[:2]),
}
bs = bs[2:]
var last Price //上条数据(昨天)的收盘价
for i := uint16(0); i < resp.Count; i++ {
k := &Kline{
Time: GetTime([4]byte(bs[:4]), Type),
Time: GetTime([4]byte(bs[:4]), c.Type),
}
var open Price
@@ -152,15 +155,29 @@ func (kline) Decode(bs []byte, Type uint8) (*KlineResp, error) {
*/
k.Volume = int64(getVolume(Uint32(bs[:4])))
switch Type {
bs = bs[4:]
switch c.Type {
case TypeKlineMinute, TypeKline5Minute, TypeKlineMinute2, TypeKline15Minute, TypeKline30Minute, TypeKlineHour, TypeKlineDay2:
k.Volume /= 100
}
k.Amount = Price(getVolume(Uint32(bs[4:8])) * 100) //从元转为分,并去除多余的小数
k.Amount = Price(getVolume(Uint32(bs[:4])) * 100) //从元转为分,并去除多余的小数
bs = bs[4:]
//指数和股票的差别,指数多解析4字节,并处理成交量*100
if !IsStock(c.Code) {
k.Volume *= 100
k.UpCount = conv.Int([]byte{bs[1], bs[0]})
k.DownCount = conv.Int([]byte{bs[3], bs[2]})
bs = bs[4:]
}
bs = bs[8:]
resp.List = append(resp.List, k)
}
return resp, nil
}
type KlineCache struct {
Type uint8
Code string
}

View File

@@ -194,3 +194,21 @@ func getVolume(val uint32) (volume float64) {
volume = dbl_xmm6 + dbl_xmm4 + dbl_xmm3 + dbl_xmm1
return
}
// IsStock 是否是股票,示例sz000001
func IsStock(code string) bool {
if len(code) != 8 {
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() &&
(code[2:3] == "0" || code[2:4] == "30"):
return true
}
return false
}

140
workday.go Normal file
View File

@@ -0,0 +1,140 @@
package tdx
import (
_ "github.com/glebarez/go-sqlite"
"github.com/injoyai/base/maps"
"github.com/injoyai/logs"
"github.com/robfig/cron/v3"
"os"
"path/filepath"
"time"
"xorm.io/core"
"xorm.io/xorm"
)
func NewWorkday(c *Client, filename string) (*Workday, error) {
//如果文件夹不存在就创建
dir, _ := filepath.Split(filename)
_ = os.MkdirAll(dir, 0777)
//连接数据库
db, err := xorm.NewEngine("sqlite", filename)
if err != nil {
return nil, err
}
db.SetMapper(core.SameMapper{})
db.DB().SetMaxOpenConns(1)
if err := db.Sync2(new(WorkdayModel)); err != nil {
return nil, err
}
w := &Workday{
Client: c,
db: db,
cache: maps.NewBit(),
}
//设置定时器,每天早上9点更新数据,8点多获取不到今天的数据
task := cron.New(cron.WithSeconds())
task.AddFunc("0 0 9 * * *", func() {
for i := 0; i < 3; i++ {
if err := w.Update(); err == nil {
return
}
logs.Err(err)
<-time.After(time.Minute * 5)
}
})
task.Start()
return w, w.Update()
}
type Workday struct {
*Client
db *xorm.Engine
cache maps.Bit
}
// Update 更新
func (this *Workday) Update() error {
//获取沪市指数的日K线,用作历史是否节假日的判断依据
//判断日K线是否拉取过
//获取全部工作日
all := []*WorkdayModel(nil)
if err := this.db.Find(&all); err != nil {
return err
}
var lastWorkday = &WorkdayModel{}
if len(all) > 0 {
lastWorkday = all[len(all)-1]
}
for _, v := range all {
this.cache.Set(uint64(v.Unix), true)
}
now := time.Now()
if lastWorkday == nil || lastWorkday.Unix < IntegerDay(now).Unix() {
resp, err := this.Client.GetKlineDayAll("sh000001")
if err != nil {
logs.Err(err)
return err
}
return NewSessionFunc(this.db, func(session *xorm.Session) error {
for _, v := range resp.List {
if unix := v.Time.Unix(); unix > lastWorkday.Unix {
_, err = session.Insert(&WorkdayModel{Unix: unix, Date: v.Time.Format("20060102"), Is: true})
if err != nil {
return err
}
this.cache.Set(uint64(unix), true)
}
}
return nil
})
}
return nil
}
// Is 是否是工作日
func (this *Workday) Is(t time.Time) bool {
return this.cache.Get(uint64(IntegerDay(t).Add(time.Hour * 15).Unix()))
}
// TodayIs 今天是否是工作日
func (this *Workday) TodayIs() bool {
return this.Is(time.Now())
}
// RangeDesc 倒序遍历工作日,从今天-1990年12月19日(上海交易所成立时间)
func (this *Workday) RangeDesc(f func(t time.Time) bool) {
t := IntegerDay(time.Now())
for ; t.After(time.Date(1990, 12, 18, 0, 0, 0, 0, time.Local)); t = t.Add(-time.Hour * 24) {
if this.Is(t) {
if !f(t) {
return
}
}
}
}
// WorkdayModel 工作日
type WorkdayModel struct {
ID int64 `json:"id"` //主键
Unix int64 `json:"unix"` //时间戳
Date string `json:"date"` //日期
Is bool `json:"is"` //是否是工作日
}
func (this *WorkdayModel) TableName() string {
return "workday"
}
func IntegerDay(t time.Time) time.Time {
year, month, day := t.Date()
return time.Date(year, month, day, 0, 0, 0, 0, t.Location())
}