-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
347 lines (299 loc) · 8.78 KB
/
utils.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package ibsync
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"unicode"
)
// TickTypesToString converts a variadic number of TickType values to a comma-separated string representation.
func TickTypesToString(tt ...TickType) string {
var strs []string
for _, t := range tt {
strs = append(strs, fmt.Sprintf("%d", t))
}
return strings.Join(strs, ",")
}
// isDigit checks if the provided string consists only of digits.
func isDigit(s string) bool {
for _, r := range s {
if !unicode.IsDigit(r) {
return false
}
}
return true
}
// FormatIBTime formats a time.Time value into the string format required by IB API.
//
// The returned string is in the format "YYYYMMDD HH:MM:SS", which is used by Interactive Brokers for specifying date and time.
// As no time zone is provided IB will use your local time zone so we enforce local time zone first.
// It returns "" if time is zero.
func FormatIBTime(t time.Time) string {
if t.IsZero() {
return ""
}
return t.In(time.Local).Format("20060102 15:04:05")
}
// FormatIBTimeUTC sets a time.Time value to UTC time zone and formats into the string format required by IB API.
//
// Note that there is a dash between the date and time in UTC notation.
// The returned string is in the format "YYYYMMDD HH:MM:SS UTC", which is used by Interactive Brokers for specifying date and time.
// It returns "" if time is zero.
func FormatIBTimeUTC(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format("20060102-15:04:05") + " UTC"
}
// FormatIBTimeUSEastern sets a time.Time value to US/Eastern time zone and formats into the string format required by IB API.
//
// The returned string is in the format "YYYYMMDD HH:MM:SS US/Eastern", which is used by Interactive Brokers for specifying date and time.
// It returns "" if time is zero.
func FormatIBTimeUSEastern(t time.Time) string {
if t.IsZero() {
return ""
}
loc, _ := time.LoadLocation("America/New_York")
return t.In(loc).Format("20060102 15:04:05") + " US/Eastern"
}
// ParseIBTime parses an IB string representation of time into a time.Time object.
// It supports various IB formats, including:
// 1. "YYYYMMDD"
// 2. Unix timestamp ("1617206400")
// 3. "YYYYMMDD HH:MM:SS Timezone"
// 4. // "YYYYmmdd HH:MM:SS", "YYYY-mm-dd HH:MM:SS.0" or "YYYYmmdd-HH:MM:SS"
func ParseIBTime(s string) (time.Time, error) {
var layout string
// "YYYYMMDD"
if len(s) == 8 {
layout = "20060102"
return time.Parse(layout, s)
}
// "1617206400"
if isDigit(s) {
ts, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return time.Time{}, err
}
return time.Unix(ts, 0), nil
}
// "20221125 10:00:00 Europe/Amsterdam"
if strings.Count(s, " ") >= 2 && !strings.Contains(s, " ") {
split := strings.Split(s, " ")
layout = "20060102 15:04:05"
t, err := time.Parse(layout, split[0]+" "+split[1])
if err != nil {
return time.Time{}, err
}
loc, err := time.LoadLocation(split[2])
if err != nil {
return time.Time{}, err
}
return t.In(loc), nil
}
// "YYYYmmdd HH:MM:SS", "YYYY-mm-dd HH:MM:SS.0" or "YYYYmmdd-HH:MM:SS"
s = strings.ReplaceAll(s, "-", "")
s = strings.ReplaceAll(s, " ", "")
s = strings.ReplaceAll(s, " ", "")
if len(s) > 15 {
s = s[:16]
}
layout = "2006010215:04:05"
return time.Parse(layout, s)
}
// LastWednesday12EST returns time.Time correspondong to last wednesday 12:00 EST
// Without checking holidays this a high probability time for open market. Usefull for testing historical data
func LastWednesday12EST() time.Time {
// last Wednesday
offset := (int(time.Now().Weekday()) - int(time.Wednesday) + 7) % 7
if offset == 0 {
offset = 7
}
lw := time.Now().AddDate(0, 0, -offset)
EST, _ := time.LoadLocation("America/New_York")
return time.Date(lw.Year(), lw.Month(), lw.Day(), 12, 0, 0, 0, EST)
}
// UpdateStruct copies non-zero fields from src to dest.
// dest must be a pointer to a struct so that it can be updated;
// src can be either a struct or a pointer to a struct.
func UpdateStruct(dest, src any) error {
destVal := reflect.ValueOf(dest)
srcVal := reflect.Indirect(reflect.ValueOf(src)) // Handles both struct and *struct for src
// Ensure that dest is a pointer to a struct
if destVal.Kind() != reflect.Ptr || destVal.Elem().Kind() != reflect.Struct {
return errors.New("dest must be a pointer to a struct")
}
// Ensure src is a struct (after dereferencing if it's a pointer)
if srcVal.Kind() != reflect.Struct {
return errors.New("src must be a struct or a pointer to a struct")
}
destVal = destVal.Elem() // Dereference dest to the actual struct
srcType := srcVal.Type()
// Iterate over each field in src struct
for i := 0; i < srcVal.NumField(); i++ {
srcField := srcVal.Field(i)
fieldName := srcType.Field(i).Name
destField := destVal.FieldByName(fieldName)
// Update if field exists in dest and src field is non-zero
if destField.IsValid() && destField.CanSet() && !srcField.IsZero() {
destField.Set(srcField)
}
}
return nil
}
// Stringify converts a struct or pointer to a struct into a string representation
// Skipping fields with zero or nil values and dereferencing pointers.
// It is recursive and will apply to nested structs.
// It can NOT handle unexported fields.
func Stringify(obj interface{}) string {
return stringifyValue(reflect.ValueOf(obj))
}
// isEmptyValue checks if a value is considered "empty"
func isEmptyValue(v reflect.Value) bool {
// Handle nil pointers
if v.Kind() == reflect.Ptr {
return v.IsNil()
}
// Dereference pointer if needed
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
switch v.Kind() {
case reflect.Struct:
// Special handling for Time struct
if v.Type().String() == "time.Time" {
return v.Interface().(time.Time).IsZero()
}
// Check if all fields are empty
for i := 0; i < v.NumField(); i++ {
if !isEmptyValue(v.Field(i)) {
return false
}
}
return true
case reflect.Slice, reflect.Map:
return v.Len() == 0
case reflect.String:
return v.String() == ""
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int32, reflect.Int64:
return v.Int() == 0 || v.Int() == UNSET_INT || v.Int() == UNSET_LONG
case reflect.Float32, reflect.Float64:
return v.Float() == 0 || v.Float() == UNSET_FLOAT
case reflect.Ptr:
return v.IsNil()
case reflect.Interface:
return v.IsNil()
}
return false
}
// stringifyValue handles the recursive stringification of values
func stringifyValue(v reflect.Value) string {
// Handle pointer types by dereferencing
if v.Kind() == reflect.Ptr {
// If nil, return empty string
if v.IsNil() {
return ""
}
v = v.Elem()
}
switch v.Kind() {
case reflect.Struct:
return stringifyStruct(v)
case reflect.Slice:
return stringifySlice(v)
case reflect.Map:
return stringifyMap(v)
default:
return fmt.Sprintf("%v", v.Interface())
}
}
// stringifyStruct handles struct-specific stringification
func stringifyStruct(v reflect.Value) string {
// Get the type of the struct
t := v.Type()
// Skip completely empty structs
if isEmptyValue(v) {
return ""
}
// Build the string representation
var fields []string
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
fieldName := t.Field(i).Name
// Skip unexported (private) fields
if !field.CanInterface() {
continue
}
// Skip empty values
if isEmptyValue(field) {
continue
}
// Recursively get the stringified value
fieldValueStr := stringifyValue(field)
// Add to fields if not empty
if fieldValueStr != "" {
fields = append(fields, fmt.Sprintf("%s=%s", fieldName, fieldValueStr))
}
}
// Construct the final string
if len(fields) == 0 {
return ""
}
return fmt.Sprintf("%s{%s}", t.Name(), strings.Join(fields, ", "))
}
// stringifySlice handles slice stringification
func stringifySlice(v reflect.Value) string {
// If slice is empty or nil
if v.Len() == 0 {
return ""
}
// Convert slice elements to strings
var elements []string
for i := 0; i < v.Len(); i++ {
elem := v.Index(i)
// Skip empty values
if isEmptyValue(elem) {
continue
}
elemStr := stringifyValue(elem)
if elemStr != "" {
elements = append(elements, elemStr)
}
}
// If no non-zero elements, return empty
if len(elements) == 0 {
return ""
}
return fmt.Sprintf("[%s]", strings.Join(elements, ", "))
}
// stringifyMap handles map stringification
func stringifyMap(v reflect.Value) string {
// If map is empty or nil
if v.Len() == 0 {
return ""
}
// Convert map elements to strings
var elements []string
iter := v.MapRange()
for iter.Next() {
k := iter.Key()
val := iter.Value()
// Skip empty values
if isEmptyValue(val) {
continue
}
valStr := stringifyValue(val)
if valStr != "" {
elements = append(elements, fmt.Sprintf("%v=%s", k.Interface(), valStr))
}
}
// If no non-zero elements, return empty
if len(elements) == 0 {
return ""
}
return fmt.Sprintf("map[%s]", strings.Join(elements, ", "))
}