/
strategy.go
168 lines (146 loc) · 5.11 KB
/
strategy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Copyright 2021-2023
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package handler
import (
"context"
"encoding/hex"
"fmt"
"runtime/debug"
"time"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"github.com/penny-vault/pv-api/backtest"
"github.com/penny-vault/pv-api/common"
"github.com/penny-vault/pv-api/data"
"github.com/penny-vault/pv-api/observability/opentelemetry"
"github.com/penny-vault/pv-api/strategies"
"github.com/rs/zerolog/log"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
// ListStrategies get a list of all strategies
func ListStrategies(c *fiber.Ctx) error {
log.Info().Msg("ListStrategies")
return c.JSON(strategies.StrategyList)
}
// GetStrategy get configuration for a specific strategy
func GetStrategy(c *fiber.Ctx) error {
shortcode := c.Params("shortcode")
if strategy, ok := strategies.StrategyMap[shortcode]; ok {
return c.JSON(strategy)
}
return fiber.ErrNotFound
}
// RunStrategy executes the strategy
func RunStrategy(c *fiber.Ctx) (resp error) {
attrs := opentelemetry.SpanAttributesFromFiber(c)
ctx, span := otel.Tracer(opentelemetry.Name).Start(context.Background(), "RunStrategy", trace.WithAttributes(attrs...))
defer span.End()
shortcode := c.Params("shortcode")
startDateStr := c.Query("startDate", "1980-01-01")
endDateStr := c.Query("endDate", "now")
benchmarkStr := c.Query("benchmark", "BBG000BHTMY2")
subLog := log.With().Str("Bechmark", benchmarkStr).Str("Shortcode", shortcode).Str("StartDateQueryStr", startDateStr).Str("EndDateQueryStr", endDateStr).Logger()
benchmark, err := data.SecurityFromFigi(benchmarkStr)
if err != nil {
subLog.Error().Err(err).Msg("could not get benchmark Security")
return fiber.ErrBadRequest
}
span.SetAttributes(
attribute.KeyValue{
Key: "pv.shortcode",
Value: attribute.StringValue(shortcode),
},
attribute.KeyValue{
Key: "pv.StartDate",
Value: attribute.StringValue(startDateStr),
},
attribute.KeyValue{
Key: "pv.EndDate",
Value: attribute.StringValue(endDateStr),
},
)
var startDate time.Time
var endDate time.Time
tz := common.GetTimezone()
startDate, err = time.ParseInLocation("2006-01-02", startDateStr, tz)
if err != nil {
subLog.Warn().Stack().Msg("cannot parse start date query parameter")
return fiber.ErrNotAcceptable
}
if endDateStr == "now" {
endDate = time.Now()
year, month, day := endDate.Date()
endDate = time.Date(year, month, day, 0, 0, 0, 0, tz)
} else {
var err error
endDate, err = time.ParseInLocation("2006-01-02", endDateStr, tz)
if err != nil {
subLog.Warn().Stack().Msg("cannot parse end date query parameter")
return fiber.ErrNotAcceptable
}
}
defer func() {
if err := recover(); err != nil {
log.Error().Stack().Msg("caught exception")
fmt.Println(err)
debug.PrintStack()
resp = fiber.ErrInternalServerError
}
}()
manager := data.GetManagerInstance()
params := map[string]json.RawMessage{}
if err := json.Unmarshal(c.Body(), ¶ms); err != nil {
log.Warn().Stack().Err(err).Msg("could not unmarshal body message")
return fiber.ErrBadRequest
}
b, err := backtest.New(ctx, shortcode, params, benchmark, startDate, endDate)
if err != nil {
log.Error().Err(err).Msg("error encountered when creating backtest")
if err.Error() == "strategy not found" {
return fiber.ErrNotFound
}
return fiber.ErrBadRequest
}
permanent := false
if c.Query("permanent", "false") == "true" {
permanent = true
}
go b.Save(ctx, c.Locals("userID").(string), permanent)
portfolioIDStr := hex.EncodeToString(b.PortfolioModel.Portfolio.ID)
serializedPortfolio, err := b.PortfolioModel.Portfolio.MarshalBinary()
if err != nil {
subLog.Error().Stack().Err(err).Str("PortfolioID", portfolioIDStr).Msg("serialization failed for portfolio")
return err
}
manager.SetLRU(portfolioIDStr, serializedPortfolio)
serializedPerformance, err := b.Performance.MarshalBinary()
if err != nil {
subLog.Error().Stack().Err(err).Str("PortfolioID", portfolioIDStr).Msg("serialization failed for portfolio")
return err
}
manager.SetLRU(fmt.Sprintf("%s:performance", portfolioIDStr), serializedPerformance)
measurements := b.Performance.Measurements
b.Performance.Measurements = nil // set measurements to nil for serialization
serialized, err := b.Performance.MarshalBinary()
if err != nil {
subLog.Error().Stack().Err(err).Str("PortfolioID", portfolioIDStr).Msg("serialization failed for performance")
return fiber.ErrInternalServerError
}
b.Performance.Measurements = measurements
c.Set("Content-type", "application/x-colfer")
return c.Send(serialized)
}