Skip to content

Commit

Permalink
Merge branch 'master' of github.com:oldfritter/goDCE
Browse files Browse the repository at this point in the history
  • Loading branch information
oldfritter committed Nov 7, 2019
2 parents e387867 + f7185e4 commit 17d1698
Show file tree
Hide file tree
Showing 7 changed files with 67 additions and 50 deletions.
76 changes: 29 additions & 47 deletions api/v1/kLine.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,8 @@ type chart struct {
}

func V1GetK(context echo.Context) error {
var market Market
mainDB := utils.MainDbBegin()
defer mainDB.DbRollback()
if mainDB.Where("code = ?", context.QueryParam("market")).First(&market).RecordNotFound() {
market, err := FindMarketByCode(context.QueryParam("market"))
if err != nil {
return utils.BuildError("1021")
}
limit := 100
Expand All @@ -41,73 +39,57 @@ func V1GetK(context echo.Context) error {
limit = 10000
}
}
period := 1
periodstr, _ := strconv.Atoi(context.QueryParam("period"))
periods := []int{1, 5, 15, 30, 60, 120, 240, 360, 720, 1440, 4320, 10080}
periodBool := false
for _, per := range periods {
if periodstr == per {
periodBool = true
period = per
}
}
if !periodBool {
period, _ := strconv.ParseInt(context.QueryParam("period"), 10, 64)
if period == 0 {
return utils.BuildError("1053")
}

kRedis := utils.GetRedisConn("k")
defer kRedis.Close()

var timestamp int
var timestamp int64
if context.QueryParam("timestamp") == "" {
timestamp = int(time.Now().Unix())
timestamp = time.Now().Unix()
} else {
timestamp, _ = strconv.Atoi(context.QueryParam("timestamp"))
timestamp, _ = strconv.ParseInt(context.QueryParam("timestamp"), 10, 64)
}
minTimestamp := timestamp - period*60*limit

values, _ := redis.Values(
kRedis.Do(
"ZREVRANGEBYSCORE",
market.KLineRedisKey(period),
timestamp,
minTimestamp,
),
)

var result []interface{}
for _, value := range values {
var item []string
json.Unmarshal(value.([]byte), &item)
result = append(result, item)
kRedis := utils.GetRedisConn("data")
defer kRedis.Close()
values, _ := redis.Values(kRedis.Do("ZREVRANGEBYSCORE", market.KLineRedisKey(period), timestamp, 0, "limit", 0, limit, "withscores"))
var line []KLine
var k KLine
for i, value := range values {
if i%2 == 0 {
json.Unmarshal(value.([]byte), &k)
} else {
k.Timestamp, _ = strconv.ParseInt(string(value.([]byte)), 10, 64)
line = append(line, k)
}
}
response := utils.SuccessResponse
response.Body = result
response.Body = line
return context.JSON(http.StatusOK, response)
}

func V1GetChart(context echo.Context) error {
var market Market
mainDB := utils.MainDbBegin()
defer mainDB.DbRollback()
if mainDB.Where("code = ?", context.QueryParam("market")).First(&market).RecordNotFound() {
market, err := FindMarketByCode(context.QueryParam("market"))
if err != nil {
return utils.BuildError("1021")
}
kRedis := utils.GetRedisConn("k")
defer kRedis.Close()
limit := 100
timestamp := int(time.Now().Unix())
timestamp := time.Now().Unix()

var c chart
periods := []int{1, 5, 15, 30, 60, 120, 240, 360, 720, 1440, 4320, 10080}
periods := []int64{1, 5, 15, 30, 60, 120, 240, 360, 720, 1440, 4320, 10080}
for _, period := range periods {
minTimestamp := timestamp - period*60*limit

values, _ := redis.Values(
kRedis.Do(
"ZREVRANGEBYSCORE",
market.KLineRedisKey(period),
timestamp,
minTimestamp,
0,
"limit",
0,
limit,
),
)
var items []interface{}
Expand Down
4 changes: 4 additions & 0 deletions initializers/locales/error_code.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
success_code:
'1000': Success.
error_code:
'1021': 没有匹配的market。

'1053': 无效的 period.

'3020': No record can be found.
'3021': 暂不开放用户注册。
'3022': 下单失败。
Expand Down
4 changes: 4 additions & 0 deletions initializers/locales/error_code.zh-CN.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
success_code:
'1000': 成功。
error_code:
'1021': 没有匹配的market。

'1053': 无效的 period.

'3020': 找不到记录。
'3021': 暂不开放用户注册。
'3022': 下单失败。
Expand Down
7 changes: 6 additions & 1 deletion models/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ type Account struct {

func (account *Account) AfterSave(db *gorm.DB) {}

func (account *Account) Amount() (amount decimal.Decimal) {
amount = account.Balance.Add(account.Locked)
return
}

func (account *Account) PlusFunds(db *utils.GormDB, amount, fee decimal.Decimal, reason, modifiableId int, modifiableType string) (err error) {
if amount.LessThan(decimal.Zero) || fee.GreaterThan(amount) {
err = fmt.Errorf("cannot add funds (amount: %v)", amount)
Expand Down Expand Up @@ -179,7 +184,7 @@ func (account *Account) after(db *utils.GormDB, fun int, amount decimal.Decimal,
"fun": strconv.Itoa(fun),
"fee": fee.String(),
"reason": strconv.Itoa(reason),
"amount": amount.String(),
"amount": account.Amount().String(),
"currency_id": strconv.Itoa(account.CurrencyId),
"user_id": strconv.Itoa(account.UserId),
"account_id": strconv.Itoa(account.Id),
Expand Down
12 changes: 11 additions & 1 deletion models/market.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ func FindMarketById(id int) (Market, error) {
return market, fmt.Errorf("No market can be found.")
}

func FindMarketByCode(code string) (Market, error) {
for _, market := range Markets {
if market.Code == code {
return market, nil
}
}
var market Market
return market, fmt.Errorf("No market can be found.")
}

func (market *Market) AfterCreate(db *gorm.DB) {
tickerRedis := utils.GetRedisConn("ticker")
defer tickerRedis.Close()
Expand Down Expand Up @@ -100,7 +110,7 @@ func (market *Market) LatestTradesRedisKey() string {
func (market *Market) TickerRedisKey() string {
return "goDCE:ticker:" + market.Code
}
func (market *Market) KLineRedisKey(period int) string {
func (market *Market) KLineRedisKey(period int64) string {
return fmt.Sprintf("goDCE:k:%v:%v", market.Id, period)
}

Expand Down
12 changes: 12 additions & 0 deletions workers/sneakerWorkers/kLineWorker.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ func calculateInDB(marketId int, period, begin, end int64) (k KLine) {
}
backupDB.Save(&k)
backupDB.DbCommit()
synToRedis(&k)
return
}

Expand Down Expand Up @@ -102,6 +103,7 @@ func calculateInBackupDB(marketId int, period, begin, end int64) (k KLine) {
backupDB.Model(KLine{}).Where("market_id = ?", marketId).Where("period = ?", lastPeriod).Where("? <= timestamp AND timestamp < ?", begin, end).Order("timestamp DESC").Limit(1).Select("close as close").Scan(&k)
backupDB.Save(&k)
backupDB.DbCommit()
synToRedis(&k)
return
}

Expand Down Expand Up @@ -148,3 +150,13 @@ func synFromRedis(marketId int, period, begin, end int64) (k KLine) {
}
return
}

func synToRedis(k *KLine) {
kRedis := utils.GetRedisConn("k")
defer kRedis.Close()

b, _ := json.Marshal((*k).Data())
kRedis.Send("ZREMRANGEBYSCORE", (*k).RedisKey(), (*k).Timestamp)
kRedis.Do("ZADD", k.RedisKey(), (*k).Timestamp, string(b))

}
2 changes: 1 addition & 1 deletion workers/sneakerWorkers/rebuildkLineToRedisWorker.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func (worker *Worker) RebuildKLineToRedisWorker(payloadJson *[]byte) (queueName
if mainDB.Where("market_id = ?", payload.MarketId).Where("period = ?", payload.Period).Find(&ks).RecordNotFound() {
return
}

mainDB.DbRollback()
kRedis := utils.GetRedisConn("k")
defer kRedis.Close()
for i, k := range ks {
Expand Down

0 comments on commit 17d1698

Please sign in to comment.