Stream metadata
Reading and setting a stream’s trading calendar, closures, custom fields and lineage.
StreamMetadata
StreamMetadata is everything a node keeps about a stream besides its data.
type StreamMetadata struct {
// WorkingHours defines the expected trading schedule. When configured,
// gaps outside these hours are classified as OFF_TIME instead of GAP.
WorkingHours *WorkingHours
// GapThresholdLow is the minimum duration before a gap is flagged.
// Gaps shorter than this are ignored (normal jitter).
GapThresholdLow time.Duration
// GapThresholdHigh is the duration above which a gap on a stream WITHOUT
// working hours is classified as OFF_TIME (a halt or delisting). With a
// schedule it has no effect: the schedule and the closures decide.
GapThresholdHigh time.Duration
// Closures are specific ranges the market was closed outside its weekly
// schedule — holidays, halts, a sudden exchange outage. A gap inside one
// is OFF_TIME. Sorted and disjoint (NormalizeClosures) once stored.
Closures []Closure
// Lineage, when set, says this stream is DERIVED (Phase 8 §8.1.5).
Lineage *Lineage
// CacheCapacity, when non-zero, is how many slots this stream's hot cache
// holds, in place of the size the node derives from its timeframe
// (ingestion's cache sizing). An operator sets it with mirexa-cli cache,
// and only Dispatcher.SetStreamCacheCapacity writes it: a metadata update
// keeps the stream's current value, as it keeps the lineage.
CacheCapacity uint32
// CustomFields stores arbitrary user-defined key-value pairs.
// These are persisted but have no effect on system behavior.
CustomFields map[string]string
}
StreamMetadata contains gap classification configuration for a stream. This metadata controls how gaps are detected and classified during cache compaction and storage operations.
func NewStreamMetadata() *StreamMetadata
NewStreamMetadata creates a new StreamMetadata with default values.
func (m *StreamMetadata) Clone() *StreamMetadata
Clone returns a deep copy of the metadata.
func (m *StreamMetadata) GetCacheCapacity() uint32
GetCacheCapacity is the stream’s cache-capacity override, 0 (derive the size) for nil metadata.
func (m *StreamMetadata) HasGapClassification() bool
HasGapClassification returns true if working hours, closures or thresholds are configured.
func (m *StreamMetadata) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler for StreamMetadata: the node’s ON-DISK encoding (streams.meta), little-endian. The data protocol carries metadata in a record of its own (wire.StreamMetadataResponse), so a change here never moves the wire.
func (m *StreamMetadata) NormalizedCopy() (*StreamMetadata, error)
NormalizedCopy validates m and returns a copy holding its closures in normalized form (NormalizeClosures). Every path that stores metadata goes through it, so the classifier can rely on the closures being sorted and disjoint.
func (m *StreamMetadata) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler for StreamMetadata.
func (m *StreamMetadata) Validate() error
Validate checks metadata a caller supplies before it is stored: thresholds are not negative, the schedule’s timezone resolves and its windows are real times of day with open before close, and the closures are well formed. It does not modify m; NormalizedCopy returns the form to store.
WorkingHours
WorkingHours is a weekly schedule in an IANA timezone; outside it a gap is market closure (OFF_TIME), not missing data.
type WorkingHours struct {
// Timezone is an IANA timezone string (e.g., "America/New_York", "UTC").
Timezone string
// Schedule defines active trading windows for each day of the week.
Schedule []DaySchedule
}
WorkingHours defines the expected trading schedule for a stream. Used to distinguish between accidental gaps (missing data during trading) and off-time gaps (no data expected because market is closed).
func NewWorkingHours(timezone string) *WorkingHours
NewWorkingHours creates a new WorkingHours with the given timezone.
func (w *WorkingHours) AddDaySchedule(day time.Weekday, windows ...TimeWindow)
AddDaySchedule adds a schedule for a specific day.
func (w *WorkingHours) Clone() *WorkingHours
Clone returns a deep copy of the working hours.
func (w *WorkingHours) FindNextTransition(ts int64, loc *time.Location) (int64, bool)
FindNextTransition finds the next schedule boundary (open or close) after the given timestamp. Returns the transition timestamp and whether it’s an opening (true) or closing (false). Returns (0, false) if no transition is found within the next week.
func (w *WorkingHours) IsWithinSchedule(ts int64, loc *time.Location) bool
IsWithinSchedule checks if a timestamp falls within the working hours schedule. Returns true if the timestamp is within any active trading window.
func (w *WorkingHours) Location() (*time.Location, error)
Location returns the parsed timezone location.
func (w *WorkingHours) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler for WorkingHours.
func (w *WorkingHours) SplitBySchedule(startTs, endTs int64) ([]WorkingHoursSegment, error)
SplitBySchedule divides [startTs, endTs] at working hours boundaries. Each returned segment is contiguous and either entirely within or entirely outside the schedule. This is the single canonical implementation of the schedule traversal loop; callers map segments to their own output types.
DaySchedule
DaySchedule is one weekday’s trading windows.
type DaySchedule struct {
Day time.Weekday
Windows []TimeWindow
}
DaySchedule defines trading windows for a single day of the week.
func (ds DaySchedule) Clone() DaySchedule
Clone returns a deep copy of the day schedule.
TimeWindow
TimeWindow is one trading window within a day, local time.
func NewTimeWindow(openHour, openMinute, closeHour, closeMinute int) TimeWindow
type TimeWindow struct {
Open TimeOfDay
Close TimeOfDay
}
TimeWindow represents an active trading period within a day.
func NewTimeWindow(openHour, openMin, closeHour, closeMin int) TimeWindow
NewTimeWindow creates a new TimeWindow.
func ParseTimeWindow(spec string) (TimeWindow, error)
ParseTimeWindow parses “HH:MM-HH:MM” into a TimeWindow, open before close.
func (tw TimeWindow) Contains(t time.Time) bool
Contains checks if a time falls within this window.
func (tw TimeWindow) Duration() time.Duration
Duration returns the duration of the time window.
func (tw TimeWindow) String() string
String renders the window as ParseTimeWindow reads it.
NewTimeWindow
func NewTimeWindow(openHour, openMinute, closeHour, closeMinute int) TimeWindow
NewTimeWindow builds a trading window from local open and close times.
TimeOfDay
TimeOfDay is an hour and minute, local time; 24:00 is the day’s end.
type TimeOfDay struct {
Hour int
Minute int
}
TimeOfDay represents a time within a day (hour:minute).
func ParseTimeOfDay(s string) (TimeOfDay, error)
ParseTimeOfDay parses a time string in HH:MM format.
func (t TimeOfDay) Compare(other TimeOfDay) int
Compare compares two TimeOfDay values. Returns -1 if t < other, 0 if equal, 1 if t > other.
func (t TimeOfDay) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for TimeOfDay.
func (t TimeOfDay) String() string
String returns a string representation in HH:MM format.
func (t *TimeOfDay) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler for TimeOfDay.
Closure
Closure is one declared closure — a holiday, a halt — [StartTs, EndTs).
type Closure struct {
StartTs int64
EndTs int64
// Note says why, for a human reading it back. It does not affect
// classification.
Note string
}
Closure is a specific range of time a market was, or will be, closed outside its weekly schedule: a holiday, an early close, a halt, an exchange outage declared after the fact. [StartTs, EndTs) in Unix nanoseconds.
A gap inside a closure is filed as OFF_TIME, exactly as one outside the weekly working hours is: nothing was expected there, so nothing is missing. A closure applies to streams without a weekly schedule too (a 24/7 market’s maintenance window).
func NormalizeClosures(closures []Closure) ([]Closure, error)
NormalizeClosures returns the closures sorted by start, with overlapping or touching closures merged into one. A merge joins distinct notes with “; “. Each closure is validated first; the merged list is the one form metadata holds, so that two lists covering the same time encode to the same bytes.
func (c Closure) Validate() error
Validate checks a single closure’s own shape.
Lineage
Lineage says a stream is derived from a source stream’s ticks or shorter candles.
type Lineage struct {
// Source is the stream derived from. For SourceTicks it may be the
// derived stream's own id: its tick half feeds its candle half.
Source StreamID
// Kind says which half of Source feeds this stream.
Kind SourceKind
// CloseGrace is how long past a bar's natural close late source data
// still joins the bar rather than correcting it. Zero means
// DefaultCloseGrace.
CloseGrace time.Duration
// NoTradeLimit is, for a tick source only, the longest silence between
// trades that is not missing data. Zero means DefaultNoTradeLimit.
NoTradeLimit time.Duration
// Since is when the lineage was declared, Unix nanoseconds: the derived
// stream begins at its source's first trade at or after it (§8.1
// decision 10, "from now on"). Kept in the catalog, so a restart or a
// failover begins at the same place (§8.1.11). Zero when declared means
// "now" (Dispatcher.SetStreamLineage stamps it).
Since int64
// Rederive says the source's history from Since is still being derived,
// as the declaration asked (§8.1.10, LINEAGE_HISTORY_REDERIVE). It is
// cleared once the walk reaches the live cursor; kept with the lineage,
// a restart or a failover resumes it. Set only by SetStreamLineage.
Rederive bool
}
Lineage says a stream’s candles are DERIVED from a source: the same instrument’s ticks, or its candles of a shorter timeframe. It is stream metadata (StreamMetadata.Lineage), set through the control API and carried to every copy with the seed.
func (l *Lineage) Validate(target StreamID) error
Validate checks the lineage of target:
the source is the SAME INSTRUMENT (exchange and symbol), so it shares target’s partition and derivation never crosses the network;
target’s timeframe parses; a candle source’s parses too, and target’s is a whole multiple of it, at least twice as long. That makes a cycle unrepresentable rather than detected: every candle link strictly lengthens the interval, so no chain returns to where it started, and a tick source is a leaf (ticks are never derived);
above a day, the target is a day or a week;
the grace and the no-trade limit are not negative, and a candle source carries no no-trade limit (it would be ignored).
func (l *Lineage) WithDefaults() Lineage
WithDefaults fills what is unset: the grace, and for a tick source the no-trade limit. Explicit values are kept.
SourceKind
SourceKind is what a derived stream is made from.
type SourceKind uint8
SourceKind is what a derived stream is made from.
const (
// SourceTicks derives candles from the source stream's TICKS (trades).
SourceTicks SourceKind = 1
// SourceCandles derives candles from the source stream's shorter candles.
SourceCandles SourceKind = 2
)
func (k SourceKind) String() string
String names the kind as the control API and CLI spell it.
SourceTicks
const (
// SourceTicks derives candles from the source stream's trades.
SourceTicks = SourceTicks
// SourceCandles derives candles from the source stream's shorter candles.
SourceCandles = SourceCandles
// LineageHistoryClear makes a derived stream a plain one again.
LineageHistoryClear = LineageHistoryClear
// LineageHistoryFromNow derives what the source receives from now on.
LineageHistoryFromNow = LineageHistoryFromNow
// LineageHistoryRederive also derives everything the source already holds.
LineageHistoryRederive = LineageHistoryRederive
)
Lineage source kinds and history choices.
SetStreamMetadataRequest
SetStreamMetadataRequest replaces a stream’s metadata, all but its lineage; Create registers a stream the node does not know.
type SetStreamMetadataRequest struct {
StreamID StreamID
Create bool
Metadata *StreamMetadata
}
SetStreamMetadataRequest replaces a stream’s metadata — everything but its lineage, which the node keeps. Create registers a stream the node does not know; without it an unknown stream is answered not found.
func ParseSetStreamMetadataPayload(p []byte) (SetStreamMetadataRequest, error)
ParseSetStreamMetadataPayload decodes a SET_STREAM_METADATA payload.
AddStreamClosureRequest
AddStreamClosureRequest declares one closure.
type AddStreamClosureRequest struct {
StreamID StreamID
Closure Closure
}
AddStreamClosureRequest declares one closure on a known stream.
func ParseAddStreamClosurePayload(p []byte) (AddStreamClosureRequest, error)
ParseAddStreamClosurePayload decodes an ADD_STREAM_CLOSURE payload.
RemoveStreamClosureRequest
RemoveStreamClosureRequest removes a range from the declared closures.
type RemoveStreamClosureRequest struct {
StreamID StreamID
StartTs int64
EndTs int64
}
RemoveStreamClosureRequest removes [StartTs, EndTs) from a stream’s declared closures, cutting any closure the range overlaps.
func ParseRemoveStreamClosurePayload(p []byte) (RemoveStreamClosureRequest, error)
ParseRemoveStreamClosurePayload decodes a REMOVE_STREAM_CLOSURE payload.
SetStreamLineageRequest
SetStreamLineageRequest declares or clears a stream’s lineage.
type SetStreamLineageRequest struct {
StreamID StreamID
History LineageHistory
Lineage *Lineage
}
SetStreamLineageRequest declares a stream derived, or (History Clear, Lineage nil) makes it a plain stream again. Only Source, Kind, CloseGrace and NoTradeLimit are sent: the node stamps Since, and History decides Rederive.
func ParseSetStreamLineagePayload(p []byte) (SetStreamLineageRequest, error)
ParseSetStreamLineagePayload decodes a SET_STREAM_LINEAGE payload.
LineageHistory
LineageHistory says what a lineage declaration does with the source’s existing history.
type LineageHistory uint8
LineageHistory says what SET_STREAM_LINEAGE does with the source’s history — the control API’s LineageHistory, one byte.
const (
// LineageHistoryClear removes the stream's lineage; it carries none.
LineageHistoryClear LineageHistory = 0
// LineageHistoryFromNow derives from the declaration on.
LineageHistoryFromNow LineageHistory = 1
// LineageHistoryRederive also derives the source's whole history.
LineageHistoryRederive LineageHistory = 2
)
LineageHistoryClear
const (
// SourceTicks derives candles from the source stream's trades.
SourceTicks = SourceTicks
// SourceCandles derives candles from the source stream's shorter candles.
SourceCandles = SourceCandles
// LineageHistoryClear makes a derived stream a plain one again.
LineageHistoryClear = LineageHistoryClear
// LineageHistoryFromNow derives what the source receives from now on.
LineageHistoryFromNow = LineageHistoryFromNow
// LineageHistoryRederive also derives everything the source already holds.
LineageHistoryRederive = LineageHistoryRederive
)
Lineage source kinds and history choices.
StreamMetadataResponse
StreamMetadataResponse is a stream’s metadata after a request; Status QueryStatusStreamNotFound for a stream the node does not know.
type StreamMetadataResponse struct {
// Status is QueryStatusOK, or QueryStatusStreamNotFound for a stream the
// node does not know (and was not asked to create).
Status QueryStatus
// Created says a SET_STREAM_METADATA registered the stream.
Created bool
// RefiledNanos is how much filed gap time the change re-classified.
RefiledNanos int64
// Metadata is the stream's metadata; nil unless Status is OK.
Metadata *StreamMetadata
}
StreamMetadataResponse answers every metadata frame: the metadata as it stands after the request.
func ParseStreamMetadataResponsePayload(p []byte) (StreamMetadataResponse, error)
ParseStreamMetadataResponsePayload decodes a STREAM_METADATA payload.