2 Star 4 Fork 10

王布衣/engine

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
rule.go 2.18 KB
一键复制 编辑 原始数据 按行查看 历史
王布衣 提交于 2023-10-25 10:04 . 优化规则引擎
package rules
import (
"errors"
"fmt"
"gitee.com/quant1x/engine/models"
"gitee.com/quant1x/gox/runtime"
bitmap "github.com/bits-and-blooms/bitset"
"golang.org/x/exp/maps"
"slices"
"sync"
)
// Kind 规则类型
type Kind = uint
const (
Pass Kind = 0
)
//const (
// RuleMiss Kind = iota //规则未命中
// RuleHit // 命中
// RuleCancel // 撤回
// RulePassed // 成功
// RuleFailed // 失败
//)
const (
engineBaseRule Kind = 1
RuleSubNewStock = engineBaseRule + 0 // 次新股
)
// Rule 规则接口
type Rule interface {
// Kind 类型
Kind() Kind
// Name 名称
Name() string
// Exec 执行, 返回nil即为成功
Exec(snapshot models.QuoteSnapshot) error
}
var (
mutex sync.RWMutex
mapRules = map[Kind]Rule{}
)
var (
ErrAlreadyExists = errors.New("rule is already exists") // 规则已经存在
ErrExecuteFailed = errors.New("rule execute failed") // 规则执行失败
)
// Register 注册规则
func Register(rule Rule) error {
mutex.Lock()
defer mutex.Unlock()
_, ok := mapRules[rule.Kind()]
if ok {
return ErrAlreadyExists
}
mapRules[rule.Kind()] = rule
return nil
}
// RegisterFunc 注册规则回调函数
func RegisterFunc(kind Kind, name string, cb func(snapshot models.QuoteSnapshot) error) error {
rule := RuleImpl{kind: kind, name: name, exec: cb}
return Register(rule)
}
// Each 遍历所有规则
func Each(snapshot models.QuoteSnapshot) (passed []uint64, failed Kind) {
mutex.RLock()
defer mutex.RUnlock()
if len(mapRules) == 0 {
return
}
var bitset bitmap.BitSet
// 规则按照kind排序
kinds := maps.Keys(mapRules)
slices.Sort(kinds)
for _, kind := range kinds {
if rule, ok := mapRules[kind]; ok {
err := rule.Exec(snapshot)
if err != nil {
failed = rule.Kind()
break
}
bitset.Set(rule.Kind())
}
}
return bitset.Bytes(), failed
}
func PrintRuleList() {
fmt.Println("规则总数:", len(mapRules))
// 规则按照kind排序
kinds := maps.Keys(mapRules)
slices.Sort(kinds)
for _, kind := range kinds {
if rule, ok := mapRules[kind]; ok {
fmt.Printf("kind: %d, name: %s, method: %s\n", rule.Kind(), rule.Name(), runtime.FuncName(rule.Exec))
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/quant1x/engine.git
git@gitee.com:quant1x/engine.git
quant1x
engine
engine
v0.6.2

搜索帮助

Cb406eda 1850385 E526c682 1850385