Framework Reference
WEALTHLAB FRAMEWORK / CLASS REFERENCE

BarHistory

API documentation, members, signatures, and C# examples.

Search the framework

Find classes, members, and documentation.

NamespaceWealthLab.Core

The BarHistory class represents historical price and volume data for a market. Code-based Strategies receive a BarHistory instance in Initialize, Execute, and other Strategy methods. A bar contains open, high, low, close, and volume values. BarHistory exposes these through the Open, High, Low, Close, and Volume properties, each of which is a TimeSeries synchronized with the inherited DateTimes collection.

Alternate Price Components

7

AveragePriceHL

public TimeSeries AveragePriceHL

Calculates and returns the average price TimeSeries (High + Low) / 2. The series is created on demand and cached by the BarHistory.

AveragePriceHLC

public TimeSeries AveragePriceHLC

Calculates and returns the average price TimeSeries (High + Low + Close) / 3. The series is created on demand and cached by the BarHistory.

AveragePriceHLCC

public TimeSeries AveragePriceHLCC

Calculates and returns the average price TimeSeries (High + Low + Close + Close) / 4. The series is created on demand and cached by the BarHistory.

AveragePriceOC

public TimeSeries AveragePriceOC

Calculates and returns the average price TimeSeries (Open + Close) / 2. The series is created on demand and cached by the BarHistory.

AveragePriceOHLC

public TimeSeries AveragePriceOHLC

Calculates and returns the average price TimeSeries (Open + High + Low + Close) / 4. The series is created on demand and cached by the BarHistory.

GetPriceComponent

public TimeSeries GetPriceComponent(PriceComponent pc)

Returns the TimeSeries corresponding to the specified PriceComponent, including Open, High, Low, Close, Volume, and the supported average-price components. Returns null for an unsupported PriceComponent.

WasPriceComponentCreated

public bool WasPriceComponentCreated(PriceComponent pc)

Returns whether the specified calculated average-price component has already been created. Standard OHLCV components always return true.

Bar Collection

12

Add

public int Add(DateTime dt, double o, double h, double l, double c, double v)

Adds a bar containing the supplied DateTime, open, high, low, close, and volume values and returns the new bar's index. This method is particularly useful when implementing Historical Data Providers.

AddFrom

public void AddFrom(BarHistory source, int idx)

Adds the bar at idx from another BarHistory if its DateTime is later than this BarHistory's current EndDate. Corresponding NamedSeries values are copied when applicable.

Count

public int Count

Returns the number of bars contained in the BarHistory. This property is inherited from TimeSeriesBase. The DateTimes, Open, High, Low, Close, and Volume collections contain the same number of values.

DateTimes

public virtual List<DateTime> DateTimes

Returns the DateTime associated with each bar. This property is inherited from TimeSeriesBase. The OHLCV TimeSeries are synchronized with DateTimes, so the same index can be used with each collection.

EndDate

public DateTime EndDate

Returns the last DateTime in the BarHistory. This property is inherited from TimeSeriesBase.

Insert

public int Insert(int idx, DateTime dt, double o, double h, double l, double c, double v)

Inserts a bar at the specified index and returns idx.

LastActualIndex

public int LastActualIndex

Returns the index of the final actual data bar, excluding bars added through ExtendedBars.

RealEndDate

public DateTime RealEndDate

Returns the DateTime of the last actual bar, excluding bars added through ExtendedBars. Returns DateTime.MinValue if no actual bars remain.

RemoveAt

public void RemoveAt(int idx)

Removes the bar at idx, including its DateTime and synchronized OHLCV values.

RemoveLast

public void RemoveLast()

Removes the final bar if the BarHistory contains at least one bar.

StartDate

public DateTime StartDate

Returns the first DateTime in the BarHistory. This property is inherited from TimeSeriesBase.

TimeSpan

public TimeSpan TimeSpan

Returns the span of time covered by the DateTimes collection. This property is inherited from TimeSeriesBase.

Binary Storage

4

FileBarCount

public int FileBarCount

Returns the bar count reported by the most recently read binary file, or the current BarHistory Count when that is greater.

GetFileBarCount

public int GetFileBarCount(string fileName)

Reads the specified WealthLab binary file and returns the total number of bars represented by the file.

ReadFromBinaryFile

public void ReadFromBinaryFile(string fileName, DateTime startDate, DateTime endDate, int maxBars)

Loads historical data from a WealthLab binary file. startDate and endDate restrict the requested range. If maxBars is greater than zero, the load is limited to that number of bars.

WriteToBinaryFile

public void WriteToBinaryFile(string fileName)

Writes the BarHistory to a WealthLab binary historical-data file at fileName.

Constructors

1

BarHistory

public BarHistory(string symbol, HistoryScale scale)
public BarHistory(string symbol, Frequency scale)
public BarHistory(BarHistory parent)

The first constructor creates a BarHistory for the specified symbol and HistoryScale. The second creates the HistoryScale from the supplied Frequency. The third creates a new BarHistory using metadata from parent, including Symbol, Scale, SecurityName, Market, SymbolInfo, EventDataPoints, DataSource, NamedSeries definitions, and other BarHistory metadata. It does not copy the parent's OHLCV bars.

Data Manipulation

6

AdjustTimeStampsToEndOfBar

public void AdjustTimeStampsToEndOfBar()

Adjusts Second and Minute BarHistory timestamps from beginning-of-interval timestamps to end-of-interval timestamps by adding the Scale interval.

AdvanceDailyDatesOneDay

public void AdvanceDailyDatesOneDay()

Advances each DateTime by one day when the Scale is Daily. This method exists primarily for compatibility with historical data-source behavior.

ClearCache

public void ClearCache()

Clears the BarHistory cache, cached average-price TimeSeries, plotting state, and caches associated with the BarHistory's internally managed TimeSeries.

FilterPrePost

public BarHistory FilterPrePost()

For intraday data, returns a new BarHistory containing only bars that occur during the Market's normal trading session. For non-intraday or always-open markets, returns the current BarHistory.

ReverseIfNeeded

public BarHistory ReverseIfNeeded()

Returns the BarHistory in chronological order. If the data is already ordered oldest to newest, returns the current instance.

SplitAdjust

public void SplitAdjust(double splitFactor)

Applies a split adjustment to all bars. OHLC prices are divided by splitFactor, while Volume is multiplied by the split factor.

Data Provider Access

2

GetDataProvider

public DataProviderBase GetDataProvider()

Returns the DataProviderBase associated with the BarHistory's data source, when available.

GetProvider

public IHistoryProvider GetProvider()

Returns the IHistoryProvider associated with the BarHistory's data source, when one can be located.

Data Quality and Price Helpers

14

CalculateReturns

public double CalculateReturns(int idx, int length, bool multiplyBy100 = true)

Calculates the percentage return ending at idx over length bars. Set multiplyBy100 to false to return the result as a decimal rather than a percentage.

HasNonZeroVolume

public bool HasNonZeroVolume

Returns true when the BarHistory contains at least one non-zero Volume value.

HasPrePostData

public bool HasPrePostData

Returns true when the BarHistory appears to contain pre-market or post-market data for its Market and Scale.

HasZeroOrNanValues

public bool HasZeroOrNanValues(int idx)

Returns true when the bar at idx contains zero or Double.NaN values in its price fields.

IsBarSynthetic

public bool IsBarSynthetic(int idx)

Returns true when the bar at idx appears to be synthetic, based on its OHLCV values.

IsGap

public bool IsGap(int bar)

Returns true when bar is either a gap-up or gap-down bar.

IsGapDown

public bool IsGapDown(int bar)

Returns true when the bar opens below the previous bar's low.

IsGapUp

public bool IsGapUp(int bar)

Returns true when the bar opens above the previous bar's high.

IsIllegalWeekendBar

public bool IsIllegalWeekendBar(int idx)

Returns true when the bar occurs on a weekend day that is not included in the Market's configured trading days.

IsSpike

public bool IsSpike(int idx, double threshold)

Returns true when the bar at idx contains a price movement that exceeds the supplied spike threshold.

NonZeroValue

public double NonZeroValue(int idx)

Returns a non-zero price value from the bar at idx, using available OHLC values.

OCOutsideRange

public bool OCOutsideRange(int idx)

Returns true when the bar's Open or Close lies outside its High/Low range.

TrueHigh

public double TrueHigh(int idx)

Returns the greater of the current bar's High and the previous bar's Close. For the first bar, returns the current High.

TrueLow

public double TrueLow(int idx)

Returns the lesser of the current bar's Low and the previous bar's Close. For the first bar, returns the current Low.

Event Data

3

AddEventDataPoint

public EventDataPoint AddEventDataPoint(string name, DateTime dt, double value)

Creates an EventDataPoint with the specified name, date, and value, adds it to EventDataPoints, and returns it. This method is retained for backward compatibility.

EventDataPoints

public List<EventDataPoint> EventDataPoints

Returns the EventDataPoint instances associated with the BarHistory.

GetEventDataPoints

public List<EventDataPoint> GetEventDataPoints(string name)
public List<EventDataPoint> GetEventDataPoints(string name, int idx)
public List<EventDataPoint> GetEventDataPoints<T>() where T : EventDataPoint
public List<EventDataPoint> GetEventDataPoints<T>(int idx) where T : EventDataPoint

Returns EventDataPoint instances matching the specified event name or derived EventDataPoint type. The overloads that accept idx return events applicable to that bar. Results returned by the non-indexed overloads are sorted chronologically.

Executable Ranges

4

AddExecutableRange

public void AddExecutableRange(DateTime startDate, DateTime endDate)

Adds an executable DateRange. Dynamic index DataSets can use executable ranges to identify the dates during which a symbol was a valid index constituent.

ExecutableRanges

public List<DateRange> ExecutableRanges

Returns the DateRanges during which the BarHistory is considered executable. A null collection indicates that all dates are executable.

InExecutableRange

public bool InExecutableRange(DateTime dt)

Returns true if dt falls within one of the BarHistory's ExecutableRanges. Returns true for all dates when no executable ranges have been defined.

IsLastDayOfExecutableRange

public bool IsLastDayOfExecutableRange(DateTime dt)

Returns true when dt is the final date of a finite executable range.

Extended and Streaming Bars

3

ExtendedBars

public int ExtendedBars

Gets or sets the number of projected bars added to the end of the BarHistory. WealthLab generates future DateTimes according to the HistoryScale and Market calendar and fills the projected OHLCV values with Double.NaN. Reducing ExtendedBars removes excess projected bars.

HasStreamingBar

public bool HasStreamingBar

Returns true when StreamingBar is not null. This property exists for backward compatibility; Extension code should generally use StreamingBar directly.

StreamingBar

public BarData StreamingBar

Gets or sets the current partial streaming BarData. Assigning this property also updates the StreamingValue of Open, High, Low, Close, and Volume.

Inherited Members

0

Market Calendar

16

AddTradingDays

public DateTime AddTradingDays(int bar, int days)
public DateTime AddTradingDays(DateTime date, int days)

Returns the trading date obtained by adding the specified number of trading days.

GetNextBarsDate

public DateTime GetNextBarsDate(int bar)
public DateTime GetNextBarsDate(DateTime date)

Returns the timestamp of the next bar according to the BarHistory's Scale and Market calendar. For compressed scales, the result represents the trading date corresponding to the end of the next complete interval.

GetNextTradingDate

public DateTime GetNextTradingDate(int bar)
public DateTime GetNextTradingDate(DateTime date)

Returns the next trading date according to the BarHistory's Market calendar.

GetTimeAsInt

public int GetTimeAsInt(int bar)

Returns the time portion of the specified bar as an integer. For example, 9:30 AM returns 930 and 9:30 PM returns 2130.

IntradayBarNumber

public int IntradayBarNumber(int bar)

Returns the zero-based intraday bar number within the trading day. Returns -1 for non-intraday data or an invalid index.

IsFirstBarOfDay

public bool IsFirstBarOfDay(int idx)

Returns true when idx represents the first bar of a trading day. For non-intraday BarHistory instances, returns true for valid bars. The method accounts for markets whose sessions trade through midnight.

IsLastBarOfDay

public bool IsLastBarOfDay(int idx)

Returns true when idx represents the final bar of the trading day. The calculation uses the BarHistory's Market hours and supports always-open and sessions that trade through midnight.

IsLastTradingDayOfMonth

public bool IsLastTradingDayOfMonth(int bar)

Returns true when bar is the final trading day of its calendar month.

NextOptionExpiryDate

public DateTime NextOptionExpiryDate(int bar)
public DateTime NextOptionExpiryDate(DateTime date, bool includeWeeklies = false)

Returns the next option expiration date as of the specified bar or DateTime. By default, the method finds the next standard monthly expiration. Set includeWeeklies to true to consider weekly expirations. If the normal expiration date is a market holiday, the preceding valid trading date is used.

SubtractTradingDays

public DateTime SubtractTradingDays(int bar, int days)
public DateTime SubtractTradingDays(DateTime date, int days)

Returns the trading date obtained by subtracting the specified number of trading days.

TomorrowIsLastTradingDayOfMonth

public bool TomorrowIsLastTradingDayOfMonth(int bar)

Returns true when the next trading session after bar is the final trading day of the calendar month.

TomorrowIsLastTradingDayOfWeek

public bool TomorrowIsLastTradingDayOfWeek(int bar)

Returns true when the next trading session after bar is the final trading day of the week.

TradingDaysBetweenDates

public int TradingDaysBetweenDates(DateTime dt1, DateTime dt2)

Returns the number of trading days between the two dates according to the BarHistory's Market calendar.

TradingDaysBetweenDatesPrecise

public double TradingDaysBetweenDatesPrecise(DateTime dt1, DateTime dt2)

Returns the number of trading days between two DateTimes with fractional-day precision.

TradingDaysElapsed

public int TradingDaysElapsed(int bar, TradingDayChoice interval)

Returns the number of trading days that have elapsed in the specified interval as of bar. Possible values are:

  • Weekly
  • Quarterly
  • Monthly

TradingDaysRemaining

public int TradingDaysRemaining(int bar, Frequency interval)

Returns the number of trading days remaining in the specified calendar interval as of bar.

Members

0

Named Series

4

AddNamedSeriesValues

public void AddNamedSeriesValues(BarHistory source, int idx)

Copies NamedSeries values from source at idx into matching NamedSeries in this BarHistory. Pass -1 for idx to append Double.NaN instead.

GetNamedSeries

public TimeSeries GetNamedSeries(string name)

Returns the Named TimeSeries registered under name, or null if no matching series exists.

NamedSeries

public Dictionary<string, TimeSeries> NamedSeries

Returns the Named TimeSeries registered with the BarHistory. Historical Data Providers can use NamedSeries for additional synchronized fields such as open interest or custom ASCII data columns.

RegisterNamedSeries

public TimeSeries RegisterNamedSeries(string name)

Registers a Named TimeSeries and returns it. If a series with the specified name is already registered, returns the existing TimeSeries.

Other Members

12

BarColors

public DateSynchedList<WLColor> BarColors

Gets or sets optional colors associated with the individual bars.

Cache

public ConcurrentDictionary<string, object> Cache

Returns a thread-safe general-purpose cache inherited from TimeSeriesBase. Strategies and Indicators can use it to associate calculated objects with the BarHistory during a backtest.

CreateEmptyIndexComponent

public static BarHistory CreateEmptyIndexComponent(string symbol, HistoryScale scale)

Creates and returns a BarHistory representing an empty index component for the supplied symbol and scale.

DateString

public string DateString(int idx)

Returns a formatted string representing the DateTime at idx.

IsEmptyIndexComponent

public bool IsEmptyIndexComponent

Gets or sets whether the BarHistory represents an empty index component.

IsUpToDate

public override bool IsUpToDate(DateTime endDate)

Returns whether the BarHistory is considered up to date as of endDate, using its Market and HistoryScale.

MetaTag

public object MetaTag

Gets or sets an arbitrary object used to associate MetaStrategy-specific information with the BarHistory.

SMLastBar

public int SMLastBar

Gets or sets an index used internally when the BarHistory is processed by the Strategy Monitor.

ToString

public override string ToString()

Returns a summary containing the Symbol, bar count, and, when data is present, the StartDate and EndDate.

UserData

public object UserData

Gets or sets arbitrary user data associated with the BarHistory. This property is inherited from TimeSeriesBase.

UserDataAsDouble

public double UserDataAsDouble

Returns UserData converted to a double. This property is inherited from TimeSeriesBase.

UserDataAsInt

public int UserDataAsInt

Returns UserData converted to an int. This property is inherited from TimeSeriesBase.

Price and Volume Series

5

Close

public TimeSeries Close

Returns the TimeSeries containing closing prices.

High

public TimeSeries High

Returns the TimeSeries containing high prices.

Low

public TimeSeries Low

Returns the TimeSeries containing low prices.

Open

public TimeSeries Open

Returns the TimeSeries containing opening prices.

Volume

public TimeSeries Volume

Returns the TimeSeries containing volume values.

Security and Market Information

15

Currency

public string Currency

Returns the security's currency from SymbolInfo when available, otherwise the Market's currency. Defaults to "USD".

DataSet

public DataSet DataSet

Gets or sets the DataSet that was used to load the BarHistory, when applicable.

DataSource

public string DataSource

Gets or sets a description of the data source that loaded the BarHistory.

DataUpdateMessage

public string DataUpdateMessage

Gets or sets a message associated with the most recent data update.

DisplayDecimals

public int DisplayDecimals

Returns the number of decimal places WealthLab should use when displaying price values. The value comes from SymbolInfo when available, otherwise from the BarHistory's Market, and defaults to 2.

FuturesModeEnabled

public bool FuturesModeEnabled

Returns true when SymbolInfo is available and indicates that the symbol can use Futures Mode.

IsIntraday

public bool IsIntraday

Returns true when the BarHistory's Scale is intraday.

Market

public MarketDetails Market

Gets or sets the MarketDetails describing the market in which the symbol trades. If a Market was not explicitly assigned, WealthLab attempts to obtain it from SymbolInfo and otherwise defaults to the U.S. stock market.

QuantityDecimals

public int QuantityDecimals

Returns the number of decimal places used for quantities. The value comes from SymbolInfo when available, otherwise from the BarHistory's Market.

SecurityName

public string SecurityName

Gets or sets the descriptive security name, if available. WealthLab normalizes several common corporate-name suffixes when this property is assigned.

SecurityType

public SecurityType SecurityType

Gets or sets the security type represented by the BarHistory. The getter uses SymbolInfo.SecurityType when SymbolInfo is available, otherwise the Market's SecurityType, and finally defaults to SecurityType.Stock. Possible values are:

  • Stock
  • ETF
  • Index
  • Fund
  • Future
  • Option
  • Forex
  • Crypto
  • Bond
  • SSF
  • CFD
  • ContinuousFuture
  • FuturesOption
  • Unknown
  • Combo

Symbol

public string Symbol

Gets or sets the symbol represented by the BarHistory.

SymbolInfo

public SymbolInfo SymbolInfo

Gets or sets the SymbolInfo associated with the BarHistory. SymbolInfo contains symbol-specific information such as security type, market, price and quantity precision, futures margin, point value, and tick size.

SymbolKey

public string SymbolKey

Returns a key that combines the BarHistory's Symbol and Scale.

Need help with this API?

Ask the community or explore custom development services.