-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoptions_strikes.go
243 lines (218 loc) · 10.7 KB
/
options_strikes.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
package models
import (
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/MarketDataApp/sdk-go/helpers/dates"
"github.com/iancoleman/orderedmap"
)
/*
Example API Response JSON:
{
"s":"ok",
"updated":1706791474,
"2024-02-02":[50.0,60.0,65.0,70.0,75.0,80.0,85.0,90.0,95.0,100.0,105.0,110.0,115.0,120.0,125.0,130.0,135.0,140.0,145.0,150.0,152.5,155.0,157.5,160.0,162.5,165.0,167.5,170.0,172.5,175.0,177.5,180.0,182.5,185.0,187.5,190.0,192.5,195.0,197.5,200.0,202.5,205.0,207.5,210.0,212.5,215.0,217.5,220.0,222.5,225.0,230.0,235.0,240.0,245.0,250.0,255.0,260.0,265.0],
"2024-02-09":[95.0,100.0,105.0,110.0,115.0,120.0,125.0,130.0,135.0,140.0,145.0,150.0,155.0,160.0,162.5,165.0,167.5,170.0,172.5,175.0,177.5,180.0,182.5,185.0,187.5,190.0,192.5,195.0,197.5,200.0,202.5,205.0,207.5,210.0,212.5,215.0,217.5,220.0,222.5,225.0,230.0,235.0,240.0,245.0,250.0,255.0,260.0,265.0],
"2024-02-16":[50.0,55.0,60.0,65.0,70.0,75.0,80.0,85.0,90.0,95.0,100.0,105.0,110.0,115.0,120.0,125.0,130.0,135.0,140.0,145.0,150.0,155.0,160.0,162.5,165.0,167.5,170.0,172.5,175.0,177.5,180.0,182.5,185.0,187.5,190.0,192.5,195.0,197.5,200.0,202.5,205.0,207.5,210.0,212.5,215.0,217.5,220.0,222.5,225.0,230.0,235.0,240.0,245.0,250.0,255.0,260.0,265.0,270.0,275.0,280.0,285.0,290.0,295.0,300.0,305.0,310.0,315.0,320.0],
"2024-02-23":[100.0,105.0,110.0,115.0,120.0,125.0,130.0,135.0,140.0,145.0,150.0,155.0,160.0,165.0,170.0,175.0,180.0,185.0,190.0,195.0,200.0,205.0,210.0,215.0,220.0,225.0,230.0,235.0,240.0,245.0,250.0,255.0,260.0,265.0]
}
*/
// OptionStrikes encapsulates the expiration date and available strike prices for an option contract.
//
// # Generated By
//
// - OptionStrikesResponse.Unpack(): Converts an ordered map of strikes into a slice of OptionStrikes.
//
// # Methods
//
// - String() string: Returns a string representation of the OptionStrikes, detailing its expiration and formatted strike prices.
//
// # Notes
//
// - This struct is primarily used to represent the structured data of option strikes and their expiration dates after unpacking from a JSON response.
type OptionStrikes struct {
Expiration time.Time // Expiration is the date and time when the option expires.
Strikes []float64 // Strikes is a slice of strike prices available for the option.
}
// OptionStrikesResponse encapsulates the response structure for a request to retrieve option strikes, including the last update timestamp and a map of strikes organized by expiration date. The map uses ordered keys to maintain the chronological order of expiration dates.
//
// # Generated By
//
// - OptionStrikesRequest.Packed(): Makes the OptionStrikesRequest and unmarshals JSON data into the OptionStrikesResponse struct.
//
// # Methods
//
// - UnmarshalJSON(data []byte) error: Custom unmarshals JSON data, initializing the Strikes map with ordered expiration dates and their corresponding strike prices.
// - IsValid() bool: Checks if the OptionStrikesResponse contains valid data.
// - Validate() error: Validates the integrity of the OptionStrikesResponse, ensuring it contains valid strikes data.
// - String() string: Returns a string representation of the OptionStrikesResponse, detailing strikes and their prices.
// - Unpack() ([]OptionStrikes, error): Converts the ordered map of strikes into a slice of OptionStrikes, each representing a set of strikes and their corresponding expiration date.
//
// # Notes
//
// - The Strikes field is represented as an ordered map to maintain the order of dates, which is crucial.
// - The Updated field uses a UNIX timestamp to indicate the last time the data was updated.
type OptionStrikesResponse struct {
Updated int `json:"updated"` // Updated is a UNIX timestamp indicating when the data was last updated.
Strikes *orderedmap.OrderedMap `json:"-"` // Strikes is a map where each key is a date string and the value is a slice of strike prices for that date.
}
// UnmarshalJSON custom unmarshals the JSON data into the OptionStrikesResponse struct.
//
// # Parameters
//
// - data []byte: The JSON data to be unmarshaled.
//
// # Returns
//
// - error: An error if unmarshaling fails, nil otherwise.
func (osr *OptionStrikesResponse) UnmarshalJSON(data []byte) error {
var aux map[string]interface{}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
// Initialize the OrderedMap
osr.Strikes = orderedmap.New()
// Extract and sort the keys (excluding "updated" and "s")
var keys []string
for key := range aux {
if key != "updated" && key != "s" {
keys = append(keys, key)
}
}
sort.Strings(keys) // Sorts the keys alphabetically, which works well for ISO 8601 dates
// Iterate over the sorted keys and add them to the OrderedMap
for _, key := range keys {
values, ok := aux[key].([]interface{})
if !ok {
return fmt.Errorf("unexpected type for key %s", key)
}
floats := make([]float64, len(values))
for i, v := range values {
floatVal, ok := v.(float64)
if !ok {
return fmt.Errorf("unexpected type for value in key %s", key)
}
floats[i] = floatVal
}
osr.Strikes.Set(key, floats)
}
// Handle the "updated" key separately
if updated, ok := aux["updated"].(float64); ok {
osr.Updated = int(updated)
} else {
return fmt.Errorf("unexpected type or missing 'updated' key")
}
return nil
}
// String provides a human-readable representation of the OptionStrikes struct, including its expiration and strike prices. This method is primarily used for logging, debugging, or displaying the OptionStrikes in a format that is easy to read and understand.
//
// # Returns
//
// - string: A formatted string encapsulating the details of the OptionStrikes, particularly its expiration and formatted strike prices.
//
// # Notes
//
// - This method formats strike prices to two decimal places and joins them with a space for readability.
func (os OptionStrikes) String() string {
// Convert each strike price to a string with two decimal places
var strikesStrParts []string
for _, strike := range os.Strikes {
strikesStrParts = append(strikesStrParts, fmt.Sprintf("%.2f", strike))
}
// Join the formatted strike prices with a space
strikesStr := strings.Join(strikesStrParts, " ")
return fmt.Sprintf("OptionStrikes{Expiration: %s, Strikes: [%s]}", dates.TimeString(os.Expiration), strikesStr)
}
// IsValid determines the validity of the OptionStrikesResponse object by invoking the Validate method. This method is primarily used to quickly assess whether the response received from an options strikes request adheres to the expected structure and contains valid data. It simplifies error handling by providing a boolean indicator of validity, which can be particularly useful in conditional logic where a binary valid/invalid decision is required.
//
// # Returns
//
// - bool: Indicates whether the OptionStrikesResponse is valid. A return value of true signifies a valid response, while false indicates an invalid response.
//
// # Notes
//
// - This method is a convenience wrapper around the Validate method, offering a simplified interface for validity checking.
func (osr *OptionStrikesResponse) IsValid() bool {
return osr.Validate() == nil
}
// Validate assesses the integrity of the OptionStrikesResponse object. It is primarily used to ensure that the response received from an options strikes request contains valid and expected data, such as non-empty strikes data. This method is crucial for error handling and data validation in financial market data applications, preventing the further processing of invalid responses.
//
// # Returns
//
// - error: An error indicating that the OptionStrikesResponse is invalid, typically due to missing strikes data, or nil if the response is valid.
//
// # Notes
//
// - This method is a fundamental part of the data validation process, ensuring that only responses with valid strikes data are processed.
func (osr *OptionStrikesResponse) Validate() error {
if len(osr.Strikes.Keys()) == 0 {
return fmt.Errorf("invalid OptionStrikesResponse: no strikes data")
}
return nil
}
// String returns a string representation of the OptionStrikesResponse struct, encapsulating the details of strikes and their corresponding prices in a human-readable format. This method is primarily used for logging, debugging, or any scenario where a textual representation of the OptionStrikesResponse data is necessary for understanding or analysis.
//
// # Returns
//
// - string: The string representation of the OptionStrikesResponse, detailing the strikes and their prices.
//
// # Notes
//
// - This method formats the strikes data into a string, making it easier to visualize the structure and content of the OptionStrikesResponse.
func (osr *OptionStrikesResponse) String() string {
var sb strings.Builder
sb.WriteString("OptionStrikesResponse{Strikes: [")
first := true
for _, key := range osr.Strikes.Keys() {
if !first {
sb.WriteString(", ")
}
first = false
value, _ := osr.Strikes.Get(key)
strikes, _ := value.([]float64) // Assuming the type assertion is always successful.
// Convert strike prices to strings and join them
var strikeStrs []string
for _, strike := range strikes {
strikeStrs = append(strikeStrs, fmt.Sprintf("%.2f", strike))
}
strikesStr := strings.Join(strikeStrs, " ")
sb.WriteString(fmt.Sprintf("%s:[%s]", key, strikesStr))
}
sb.WriteString(fmt.Sprintf("], Updated: %d}", osr.Updated))
return sb.String()
}
// Unpack converts the ordered map of strikes contained within the OptionStrikesResponse into a slice of OptionStrikes. This method is primarily used when a user needs to work with a structured list of strikes and their expiration dates, rather than dealing with the map data structure. It simplifies the process of iterating over strikes and performing operations on them.
//
// # Returns
//
// - []OptionStrikes: A slice of OptionStrikes, each representing a set of strikes and their corresponding expiration date.
// - error: An error if the validation of the OptionStrikesResponse fails or if there are issues parsing the dates.
//
// # Notes
//
// - This method first validates the OptionStrikesResponse to ensure it contains valid data before attempting to unpack the strikes.
func (osr *OptionStrikesResponse) Unpack() ([]OptionStrikes, error) {
if err := osr.Validate(); err != nil {
return nil, err
}
loc, err := time.LoadLocation("America/New_York")
if err != nil {
return nil, fmt.Errorf("error loading location: %v", err)
}
var unpackedStrikes []OptionStrikes
for _, key := range osr.Strikes.Keys() {
value, _ := osr.Strikes.Get(key)
strikes := value.([]float64)
date, err := time.ParseInLocation("2006-01-02", key, loc)
if err != nil {
return nil, fmt.Errorf("error parsing date %s: %v", key, err)
}
unpackedStrikes = append(unpackedStrikes, OptionStrikes{
Expiration: date,
Strikes: strikes,
})
}
return unpackedStrikes, nil
}