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.
Calculates and returns the average price TimeSeries (High + Low) / 2. The series is created on demand and cached by the BarHistory.
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using WealthLab.ChartWPF; using System.Drawing; using System.Collections.Generic; namespace WealthScript3 { public class MyStrategy : UserStrategyBase { public override void Initialize(BarHistory bars) { PlotTimeSeries(bars.AveragePriceHL, "Average Price", "Price", WLColor.Blue, PlotStyle.Line); PlotTimeSeries(bars.AveragePriceHLC, "Average Price w/Close", "Price", WLColor.Red, PlotStyle.Line); } public override void Execute(BarHistory bars, int idx) { } } }
Calculates and returns the average price TimeSeries (High + Low + Close) / 3. The series is created on demand and cached by the BarHistory.
Calculates and returns the average price TimeSeries (High + Low + Close + Close) / 4. The series is created on demand and cached by the BarHistory.
Calculates and returns the average price TimeSeries (Open + Close) / 2. The series is created on demand and cached by the BarHistory.
Calculates and returns the average price TimeSeries (Open + High + Low + Close) / 4. The series is created on demand and cached by the BarHistory.
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.
Returns whether the specified calculated average-price component has already been created. Standard OHLCV components always return true.
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.
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.
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.
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using WealthLab.ChartWPF; using System.Drawing; using System.Collections.Generic; namespace WealthLab { public class MyStrategy : UserStrategyBase { public override void Initialize(BarHistory bars) { DrawHeaderText($"The BarHistory contains {bars.Count:N0} bars."); } public override void Execute(BarHistory bars, int idx) { } } }
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.
Returns the last DateTime in the BarHistory. This property is inherited from TimeSeriesBase.
Inserts a bar at the specified index and returns idx.
Returns the index of the final actual data bar, excluding bars added through ExtendedBars.
Returns the DateTime of the last actual bar, excluding bars added through ExtendedBars. Returns DateTime.MinValue if no actual bars remain.
Removes the bar at idx, including its DateTime and synchronized OHLCV values.
Removes the final bar if the BarHistory contains at least one bar.
Returns the first DateTime in the BarHistory. This property is inherited from TimeSeriesBase.
Returns the span of time covered by the DateTimes collection. This property is inherited from TimeSeriesBase.
Returns the bar count reported by the most recently read binary file, or the current BarHistory Count when that is greater.
Reads the specified WealthLab binary file and returns the total number of bars represented by the file.
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.
Writes the BarHistory to a WealthLab binary historical-data file at fileName.
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.
Adjusts Second and Minute BarHistory timestamps from beginning-of-interval timestamps to end-of-interval timestamps by adding the Scale interval.
Advances each DateTime by one day when the Scale is Daily. This method exists primarily for compatibility with historical data-source behavior.
Clears the BarHistory cache, cached average-price TimeSeries, plotting state, and caches associated with the BarHistory's internally managed TimeSeries.
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.
Returns the BarHistory in chronological order. If the data is already ordered oldest to newest, returns the current instance.
Applies a split adjustment to all bars. OHLC prices are divided by splitFactor, while Volume is multiplied by the split factor.
Returns the DataProviderBase associated with the BarHistory's data source, when available.
Returns the IHistoryProvider associated with the BarHistory's data source, when one can be located.
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.
Returns true when the BarHistory contains at least one non-zero Volume value.
Returns true when the BarHistory appears to contain pre-market or post-market data for its Market and Scale.
Returns true when the bar at idx contains zero or Double.NaN values in its price fields.
Returns true when the bar at idx appears to be synthetic, based on its OHLCV values.
Returns true when bar is either a gap-up or gap-down bar.
Returns true when the bar opens below the previous bar's low.
Returns true when the bar opens above the previous bar's high.
Returns true when the bar occurs on a weekend day that is not included in the Market's configured trading days.
Returns true when the bar at idx contains a price movement that exceeds the supplied spike threshold.
Returns a non-zero price value from the bar at idx, using available OHLC values.
Returns true when the bar's Open or Close lies outside its High/Low range.
Returns the greater of the current bar's High and the previous bar's Close. For the first bar, returns the current High.
Returns the lesser of the current bar's Low and the previous bar's Close. For the first bar, returns the current Low.
Creates an EventDataPoint with the specified name, date, and value, adds it to EventDataPoints, and returns it. This method is retained for backward compatibility.
Returns the EventDataPoint instances associated with the BarHistory.
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Data; using WealthLab.Indicators; using WealthLab.ChartWPF; using System.Drawing; using System.Collections.Generic; namespace WealthLab { public class MyStrategy : UserStrategyBase { public override void Initialize(BarHistory bars) { if (bars.EventDataPoints.Count == 0) return; EventDataPoint edp = bars.EventDataPoints[bars.EventDataPoints.Count - 1]; DrawHeaderText($"Most recent event data occurred on {edp.Date:yyyy-MM-dd}", WLColor.Red, 14); DrawHeaderText($"It was of type {edp.Name} and value: {edp.Value:N4}", WLColor.Red, 14); } public override void Execute(BarHistory bars, int idx) { } } }
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.
Adds an executable DateRange. Dynamic index DataSets can use executable ranges to identify the dates during which a symbol was a valid index constituent.
Returns the DateRanges during which the BarHistory is considered executable. A null collection indicates that all dates are executable.
Returns true if dt falls within one of the BarHistory's ExecutableRanges. Returns true for all dates when no executable ranges have been defined.
Returns true when dt is the final date of a finite executable range.
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.
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using WealthLab.ChartWPF; using System.Drawing; using System.Collections.Generic; namespace WealthLab { public class MyStrategy : UserStrategyBase { public override void Initialize(BarHistory bars) { if (bars.Count < 20) return; int x1 = bars.Count - 20; double y1 = bars.Close[x1]; int x2 = bars.Count - 1; double y2 = bars.Close[x2]; DrawLine(x1, y1, x2, y2, WLColor.Teal, 2, LineStyle.Solid, "Price", false, true); bars.ExtendedBars = 20; } public override void Execute(BarHistory bars, int idx) { } } }
Returns true when StreamingBar is not null. This property exists for backward compatibility; Extension code should generally use StreamingBar directly.
Gets or sets the current partial streaming BarData. Assigning this property also updates the StreamingValue of Open, High, Low, Close, and Volume.
Returns the trading date obtained by adding the specified number of trading days.
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.
Returns the next trading date according to the BarHistory's Market calendar.
using System; using WealthLab.Backtest; using WealthLab.Core; using WealthLab.Indicators; namespace WealthScript5 { public class MyStrategy : UserStrategyBase { SMA _ma; public override void Initialize(BarHistory bars) { _ma = SMA.Series(bars.Close, 20); StartIndex = 20; } public override void Execute(BarHistory bars, int idx) { if (!HasOpenPosition(bars, PositionType.Long)) { if (bars.Close.CrossesOver(_ma, idx)) { PlaceTrade(bars, TransactionType.Buy, OrderType.Market); WriteToDebugLog($"Signal date: {bars.DateTimes[idx]:yyyy-MM-dd}, Trade date: {bars.GetNextTradingDate(idx):yyyy-MM-dd}"); } } else { Position p = LastPosition; if (idx - p.EntryBar + 1 > 10) ClosePosition(p, OrderType.Market); } } } }
Returns the time portion of the specified bar as an integer. For example, 9:30 AM returns 930 and 9:30 PM returns 2130.
Returns the zero-based intraday bar number within the trading day. Returns -1 for non-intraday data or an invalid index.
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.
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.
Returns true when bar is the final trading day of its calendar month.
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.
Returns the trading date obtained by subtracting the specified number of trading days.
Returns true when the next trading session after bar is the final trading day of the calendar month.
Returns true when the next trading session after bar is the final trading day of the week.
Returns the number of trading days between the two dates according to the BarHistory's Market calendar.
Returns the number of trading days between two DateTimes with fractional-day precision.
Returns the number of trading days that have elapsed in the specified interval as of bar. Possible values are:
- Weekly
- Quarterly
- Monthly
Returns the number of trading days remaining in the specified calendar interval as of bar.
Copies NamedSeries values from source at idx into matching NamedSeries in this BarHistory. Pass -1 for idx to append Double.NaN instead.
Returns the Named TimeSeries registered under name, or null if no matching series exists.
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.
Registers a Named TimeSeries and returns it. If a series with the specified name is already registered, returns the existing TimeSeries.
Gets or sets optional colors associated with the individual bars.
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.
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using WealthLab.ChartWPF; using System.Drawing; using System.Collections.Generic; namespace WealthLab { public class MyStrategy : UserStrategyBase { private static List<BarHistory> buys = new List<BarHistory>(); private RSI rsi; public override void Initialize(BarHistory bars) { rsi = new RSI(bars.Close, 14); bars.Cache["RSI"] = rsi; } public override void PreExecute(DateTime dt, List<BarHistory> participants) { foreach (BarHistory bh in participants) { RSI rsi = (RSI)bh.Cache["RSI"]; int idx = GetCurrentIndex(bh); bh.UserData = rsi[idx]; } participants.Sort((a, b) => a.UserDataAsDouble.CompareTo(b.UserDataAsDouble)); buys.Clear(); for (int n = 0; n < 3 && n < participants.Count; n++) buys.Add(participants[n]); } public override void Execute(BarHistory bars, int idx) { bool inBuyList = buys.Contains(bars); if (!HasOpenPosition(bars, PositionType.Long)) { if (inBuyList) PlaceTrade(bars, TransactionType.Buy, OrderType.Market); } else { if (!inBuyList) PlaceTrade(bars, TransactionType.Sell, OrderType.Market); } } } }
Creates and returns a BarHistory representing an empty index component for the supplied symbol and scale.
Returns a formatted string representing the DateTime at idx.
Gets or sets whether the BarHistory represents an empty index component.
Returns whether the BarHistory is considered up to date as of endDate, using its Market and HistoryScale.
Gets or sets an arbitrary object used to associate MetaStrategy-specific information with the BarHistory.
Gets or sets an index used internally when the BarHistory is processed by the Strategy Monitor.
Returns a summary containing the Symbol, bar count, and, when data is present, the StartDate and EndDate.
Gets or sets arbitrary user data associated with the BarHistory. This property is inherited from TimeSeriesBase.
Returns UserData converted to a double. This property is inherited from TimeSeriesBase.
Returns UserData converted to an int. This property is inherited from TimeSeriesBase.
Returns the TimeSeries containing closing prices.
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using WealthLab.ChartWPF; using System.Drawing; using System.Collections.Generic; namespace WealthLab { public class MyStrategy : UserStrategyBase { public override void Initialize(BarHistory bars) { DrawHeaderText($"Closing price for the most recent trading day was: {bars.Close[bars.Count - 1]:C2}", WLColor.Red, 14); } public override void Execute(BarHistory bars, int idx) { } } }
Returns the security's currency from SymbolInfo when available, otherwise the Market's currency. Defaults to "USD".
Gets or sets the DataSet that was used to load the BarHistory, when applicable.
Gets or sets a description of the data source that loaded the BarHistory.
Gets or sets a message associated with the most recent data update.
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.
Returns true when SymbolInfo is available and indicates that the symbol can use Futures Mode.
Returns true when the BarHistory's Scale is intraday.
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.
Returns the number of decimal places used for quantities. The value comes from SymbolInfo when available, otherwise from the BarHistory's Market.
Gets or sets the descriptive security name, if available. WealthLab normalizes several common corporate-name suffixes when this property is assigned.
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
Gets or sets the symbol represented by the BarHistory.
using WealthLab.Backtest; using System; using WealthLab.Core; using WealthLab.Indicators; using WealthLab.ChartWPF; using System.Drawing; using System.Collections.Generic; namespace WealthLab { public class MyStrategy : UserStrategyBase { public override void Initialize(BarHistory bars) { DrawHeaderText("Symbol " + bars.Symbol + " has " + bars.Count + " bars of data"); } public override void Execute(BarHistory bars, int idx) { } } }
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.
Returns a key that combines the BarHistory's Symbol and Scale.