Data Access

The Data Access category contains methods you can use to access the data that the Strategy is currently operating on, and additional data that it might need.

BuyAtMarket

Bars Property

Bars Bars

Returns the Bars object that the Strategy is currently operating on.  Initially, this is the symbol being charted in the chart.  But the Bars object can be changed via calls to SetContext, and the various SetScale methods to work in different time scales.

Remarks

BuyAtMarket

ClearExternalSymbols

int ClearExternalSymbols();
int ClearExternalSymbols(string symbol);

Clears any external (secondary) symbol data. External symbols are obtained from calls to either GetExternalSymbol, SetContext, and from changing the data scale in the script.  When external symbol data is requested in a script, Wealth-Lab caches the symbol data so that it does not have to be loaded again if the same symbol is requested later.  This method allows you to clear this internal cache.  The symbol parameter is optional. If it is specified, only that specific external symbol will be cleared. ClearExternalSymbols returns the number of symbols that were cleared from memory.


Example

protected override void Execute(){
    Bars msft = GetExternalSymbol( "MSFT", true );
    ChartPane msftPane = CreatePane( 50, true, true );
    PlotSymbol( msftPane, msft, Color.Blue, Color.Red );
    PrintDebug ( "Cleared ext. symbols: " + ClearExternalSymbols() );
}
BuyAtMarket

Close Property

DataSeries Close

Returns a DataSeries object that represents the closing prices of the Bars object that the Strategy is currently operating on.  You can also access the closing prices via the Bars.Close property.  Access individual closing prices via the square bracket syntax:

//Access the close of the last bar
double lastClose = Close[Bars.Count - 1];

Remarks


Example

protected override void Execute(){    //Access closing price of the last bar
    double lastClose = Close[Bars.Count-1];
    // The string is output with 2 digits
    DrawLabel( PricePane, "Last close: " + String.Format( "{0:f}", lastClose ), Color.Black );
}
BuyAtMarket

DataSetSymbols Property

IList<string> DataSetSymbols

Returns a list of strings that contain the symbols in the DataSet that contains the symbol currently being processed by the Strategy.

Remarks


Example

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using WealthLab;
using WealthLab.Indicators;
using System.Collections;

namespace WealthLab.Strategies
{
    public class AboveMA : WealthScript
    {
        private StrategyParameter paramPeriod;
        
        public AboveMA()
        {
            paramPeriod = CreateParameter("MA Period", 200, 10, 200, 5);
        }
        
        protected override void Execute()
        {
            int period = paramPeriod.ValueInt;
            DataSeries OverMA = new DataSeries( Bars, String.Concat("Number above MA (",period,")") );
            
            for(int ds = 0; ds < DataSetSymbols.Count; ds++)
            {
                SetContext( DataSetSymbols[ds], true );
                for(int bar = period; bar < Bars.Count; bar++)
                    if( Bars.Close[bar] > SMA.Series( Bars.Close,period )[bar] )
                        OverMA[bar]++;
                RestoreContext();
            }

            ChartPane omaPane = CreatePane(20,true,true);
            ChartPane omapctPane = CreatePane(20,true,true);
            DataSeries PctOverMA = OverMA/DataSetSymbols.Count*100;
            PctOverMA.Description = String.Concat( "Pct above MA (",period," )" );
            PlotSeries( omaPane, OverMA, Color.Blue, LineStyle.Histogram,2 );
            PlotSeries( omapctPane, PctOverMA, Color.DarkGreen, LineStyle.Solid,2 );
        }
    }
}
BuyAtMarket

Date Property

IList<DateTime> Date

Returns a list of DateTime values that represents the historical date/times of the Bars object that the Strategy is currently operating on.  You can also access the Dates via the Bars.Dates property.  Access individual date values via the square bracket syntax:

//Access the last date being charted
DateTime lastDate = Date[Bars.Count - 1];


Example

protected override void Execute(){    //Access the last date being charted
    DateTime lastDate = Date[Bars.Count - 1];
    DrawLabel( PricePane, "Last trading date: " + String.Format( "{0:d}", lastDate ), Color.Black );
}
BuyAtMarket

DateTimeToBar

int DateTimeToBar(DateTime date, bool exactMatch);

Returns the bar number (in the Bars object that the Strategy is currently operating on) that matches the DateTime provided in the date parameter.  If exactMatch is true, the precise DateTime value must be located in the Bars object.  Otherwise, the first bar whose DateTime is greater than or equal to the specified date is returned.


Example

protected override void Execute(){
    ClearDebug();
    DateTime d = new DateTime( 2008, 07, 15 );
    int Bar = DateTimeToBar( d, true );

    if( Bar == -1 )
        PrintDebug( "This bar does not exist in the chart" );
    else
    {
        for(int bar = 1; bar < Bars.Count; bar++)
            if ( bar == Bar )
                BuyAtClose( bar, "Buy" );
    }
}
BuyAtMarket

GetExternalSymbol

Bars GetExternalSymbol(string symbol, bool synchronize);
Bars GetExternalSymbol(string dataSetName, string symbol, bool synchronize);

Returns a Bars object for the specified stock/futures symbol.  The Bars object will be returned in the same data scale as the Bars object that the Strategy is currently operating on.  If data for the specified symbol is not available, this method will raise an error.  The synchronize method controls whether the returned Bars object will be automatically synchronized to the current Bars object.  This is important if you want to plot the Bars, or indicators that are created from it.  You can defer the synchronization by calling the Synchronize method at some later time.

Optional parameter dataSetName allows to specify the DataSet that will be searched when an external symbol is requested, which can differ from the DataSet of the symbol on which the Strategy is being executed.

Note: By specifying a DataSet with dataSetName, you are essentially specifying the associated Provider. If symbol is missing in the specified DataSet, but it's possible to find it in another DataSet of the same Provider, then it can be returned. This is in contrast to not specifying a DataSet in which case an alphabetical search through DataSets of any Provider is used to return the data.


Example

protected override void Execute(){
try
    {
        // Create a DataSeries with the relative strength of the current symbol vs. S&P 500
        Bars spy = GetExternalSymbol("SPY", true);
        DataSeries rs = DataSeries.Abs( Close / spy.Close );
        DataSeries rs3 = rs>>(21 * 3);
        rs.Description = "Relative strength " + Bars.Symbol + "/" + spy.Symbol;
        rs3.Description = "Relative strength " + Bars.Symbol + "/" + spy.Symbol + " (3 months ago)";

        HideVolume();
        ChartPane spyPane = CreatePane( 40, false, true );
        ChartPane rsPane = CreatePane( 40, false, true );
        PlotSymbol( spyPane, spy, Color.Blue,Color.Red);
        PlotSeries( rsPane, rs, Color.Black, LineStyle.Solid, 1 );
        PlotSeries( rsPane, rs3, Color.Blue, LineStyle.Solid, 1 );
    
        // Compare relative strength today and then 3 months ago
        for(int bar = 21 * 3; bar < Bars.Count; bar++)
        {
            // Highlight when the ratio today is greater than 3 months ago 
            // and is also breaking a new 3 month relative high
            
            if( rs[bar] == Highest.Series( rs, 21 * 3 )[bar] )
                if( rs[bar] > rs3[bar] )
                {
                    SetBarColor( bar, Color.Blue );
                    rsPane.SetBackgroundColor( bar, Color.FromArgb(30,Color.Blue) );
                }
        }
    }
    catch
    {
        PrintDebug( "No data or could not find series" );
    }            
}
GetSessionOpen

GetSessionOpen Property

double GetSessionOpen(string symbol)

Returns current trading session's opening price for the specifed symbol. Returns 0 if the session's open price is not available or if the method is not supported by the DataSet's Data Provider.

GetSessionOpen() is designed primarily for EOD Strategies that require action based on the trading session's opening price (see Example). While it's still recommended to perform a Daily price update beforehand, you can schedule the Strategy Monitor to execute on the open of the market session. If you require a short delay to ensure all stocks have opened, you can right click the Strategy and choose "Run this Strategy now" or run the backtest in a Strategy Window.

Remarks

  • GetSessionOpen() employs the Static Data Provider to return the session's opening price; implementations vary by Provider. For example, in response to the first call to GetSessionOpen(), the Fidelity Static Provider requests and caches the opening prices for all symbols in the DataSet. If the DataSet is large, processing the first symbol in the DataSet will appear slow while opening prices are collected.
  • Intraday Strategies can directly obtain the opening price by finding the open price of the first bar of the current day, given by Open[bar - Bars.IntradayBarNumber(bar)] in a bar-indexed loop. Nonetheless, if the open price is required prior to the completion of the first intraday bar, consider using GetSessionOpen().

Example

This example shows how to employ GetSessionOpen() in a trading Strategy. For all bars prior to the last bar of the chart, the Strategy can access the opening price of the next bar. However, when processing the final bar of the chart, the open is obtained by calling GetSessionOpen(). If the value returned is not greater than 0, then the result is invalid and a trading Alert will not be processed. Otherwise, the Strategy will enable the BuyAtLimit order if the opening price of the "trade bar" is below the low of the last complete bar.


Example

protected override void Execute(){
double openTradeBar = 0;
            int lastCompleteBar = Bars.Count - 1;
   
            for (int bar = 0; bar < Bars.Count; bar++)
            {
                if (IsLastPositionActive)
                {
                    Position p = LastPosition;
                    if (bar - p.EntryBar > 1)
                        SellAtMarket(bar + 1, p);
                }
                else
                {                   
                    if (bar == lastCompleteBar)
                    {
                        openTradeBar = GetSessionOpen(Bars.Symbol);
                        DrawLabel(PricePane,"Today's Opening Price = " + openTradeBar.ToString("0.00"));
                    }
                    else
                        openTradeBar = Open[bar+1];
                               
                    if (openTradeBar > 0 && openTradeBar < Low[bar])
                        BuyAtLimit(bar + 1, Low[bar] * 0.95);
                }
            }
        }
    }
}
BuyAtMarket

High Property

DataSeries High

Returns a DataSeries object that represents the high prices of the Bars object that the Strategy is currently operating on.  You can also access the high prices via the Bars.High property.  Access individual high prices via the square bracket syntax:

//Access high price of the last bar
double lastHigh = High[Bars.Count - 1];

Remarks

  • See the DataSeries object reference for a listing of available properties and methods on the DataSeries object.

Example

protected override void Execute(){    // Print high price of the last bar
    double high = High[Bars.Count-1];
    DrawLabel( PricePane, "High: " + String.Format( "{0:f}", high ), Color.Black );
}
BuyAtMarket

Low Property

DataSeries Low

Returns a DataSeries object that represents the low prices of the Bars object that the Strategy is currently operating on.  You can also access the low prices via the Bars.Low property.  Access individual low prices via the square bracket syntax:

//Access low price of the last bar
double lastLow = Low[Bars.Count - 1];

Remarks

  • See the DataSeries object reference for a listing of available properties and methods on the DataSeries object.

Example

protected override void Execute(){    // Print low price of the last bar
    double low = Low[Bars.Count-1];
    DrawLabel( PricePane, "Low: " + String.Format( "{0:f}", low ), Color.Black );
}
BuyAtMarket

Open Property

DataSeries Open

Returns a DataSeries object that represents the open prices of the Bars object that the Strategy is currently operating on.  You can also access the open prices via the Bars.Open property.  Access individual open prices via the square bracket syntax:

//Access open price of the last bar
double lastOpen = Open[Bars.Count - 1];

Remarks

  • See the DataSeries object reference for a listing of available properties and methods on the DataSeries object.

Example

protected override void Execute(){    // Print open price of the last bar
    double open = Open[Bars.Count-1];
    DrawLabel( PricePane, "Open price: " + String.Format( "{0:f}", open ), Color.Black );
}
BuyAtMarket

RestoreContext

void RestoreContext();

Changes the context of the Strategy back to the Bars object that it was originally invoked on.  In a Strategy window, this is the symbol that you are charting.  The context can change to a different symbol by calling SetContext.

Remarks

  • RestoreContext restores the context symbol only, but preserves changes in data scale that were made by calling the various SetScale methods.
  • After you are through using an external symbol, you should call RestoreContext to restore the Strategy back to the original symbol.

Example

protected override void Execute(){
    // Compare the RSI of the stock with the RSI of QQQQ
    DataSeries QQQQ_RSI;
    SetContext( "QQQQ", true );
    QQQQ_RSI = RSI.Series( Close, 30 );
    RestoreContext();
    HideVolume();
    ChartPane qqqq = CreatePane( 50, true, true );
    ChartPane rsi = CreatePane( 50, false, true );
    PlotSeries( qqqq, QQQQ_RSI, Color.Red, WealthLab.LineStyle.Solid, 2 );
    PlotSeries( rsi, RSI.Series( Close, 30 ), Color.Blue, WealthLab.LineStyle.Solid, 2 );
}
BuyAtMarket

SetContext

void SetContext(string symbol, bool synchronize);
void SetContext(Bars bars);

Sets the "context" of the Strategy to the symbol specified.  This means that subsequent Positions (BuyAtMarket, ShortAtMarket, etc.) will be entered on the new symbol.  Use this technique to backtest pairs trading Strategies, for example.  The synchronize parameter specifies whether the data for the new symbol will be automatically date-synchronized with the primary symbol (the one that the Strategy was originally executed on, and charted.)  If you defer synchronization, you can synchronize at a future point using the Synchronize function.  This is required if you want to plot the symbol, or indicators produced from it.  If data for the specified symbol is not available, SetContext will throw an error.

Remarks

  • Call the method without the optional synchronize parameter for automatic synchronization.
  • Call RestoreContext to restore the context to the original symbol.
  • The SetContext(Bars) overload was introduced to allow trades on the synthetic option symbol (but is not limited to this scenario). It's always synchronized to the primary symbol.

Example

using System;
using System.Collections;
using System.Text;
using System.Drawing;
using WealthLab;

namespace WealthLab.Strategies
{
    public class MyStrategy : WealthScript
    {
        protected override void Execute()
        {
            SortedList Vlst = new SortedList( DataSetSymbols.Count );
            
            // Collect turnover values for the DataSet
            for(int ds = 0; ds < DataSetSymbols.Count; ds++)
            {
                SetContext( DataSetSymbols[ds], true );
                Vlst.Add( ds, Close[Bars.Count-1] * Volume[Bars.Count-1] );
                RestoreContext();
            }
            
            ICollection v = Vlst.Keys;
            foreach( int str in v )
                PrintDebug( DataSetSymbols[str] + " -- $" + Vlst[str] );
        }
    }
}
BuyAtMarket

Synchronize

DataSeries Synchronize(DataSeries source);
Bars Synchronize(Bars source);

Returns a new DataSeries or Bars object, based on the source DataSeries or Bars object.  The new DataSeries or Bars object is date-synchronized to the primary symbol that the Strategy was executed on.  Use this method when you need to synchronize an external symbol acquired by calling SetContext or GetExternalSymbol, or any indicators created from them, for plotting.  Also, use this method to expand a compressed DataSeries or Bars object, such as those obtained after calls to SetScaleWeekly or SetScaleMonthly.  You must synchronize DataSeries and Bars objects if you want to plot them on the chart, or use them in operations with the primary Bars object, or indicators created from it.

Remarks

  • If the primary symbol contains dates that occur before the first date in the source DataSeries or Bars, the new DataSeries or Bars will contain zero values for these dates.
  • If the primary symbol contains dates that do not occur within the source DataSeries or Bars, they will be inserted, and the previous available value used for these dates.
  • If the source contains dates that do not occur in the primary symbol, these values will be eliminated from the new DataSeries or Bars.

Example

protected override void Execute(){
    Bars msft = new Bars( "MSFT", BarScale.Daily, 1 );
    try
    {
        msft = GetExternalSymbol( "MSFT", false );
    }
    catch
    {
        PrintDebug( "No MSFT data?" );
    }

    msft = Synchronize( msft );
    ChartPane msftPane = CreatePane( 50, true, true );
    PlotSymbol( msftPane, msft, Color.Blue, Color.Red );
    PlotSeries( msftPane, SMA.Series( msft.Close,10 ), Color.Red, WealthLab.LineStyle.Solid, 1 );            
}
BuyAtMarket

TrendlineValue

double TrendlineValue(int bar, string trendlineName);

Provides access to the specified manually drawn trendline by name, and returns the value of that trendline at the specified bar on the chart.  If the named trendline could not be found for the current symbol and time scale, the method returns 0.

Remarks

  • In a Strategy that loops through DataSet symbols using SetContext, TrendlineValue is not working. If you click on the symbol with the trendline, TrendlineValue code is executed whereas when you click on another symbol to start the Strategy, TrendlineValue returns zero.

    This is by design, and the reason is that it's not possible to access a Trendline Value for other symbols through SetContext since the TrendLine(s) don't exist in the current chart.


Example

protected override void Execute(){
    double res;
    for(int bar = 1; bar < Bars.Count; bar++)
    {
        res = TrendlineValue( bar-1, "Resistance" );
        if ( Close[bar-1] < res )
        {
            res = TrendlineValue( bar, "Resistance" );
            if ( Close[bar] >= res )
            {
                SetBarColor( bar, Color.Green );
                DrawCircle( PricePane, 5, bar, res, Color.Red, Color.Red, WealthLab.LineStyle.Solid, 5, false );
            }
        }

    }
}
BuyAtMarket

Volume Property

DataSeries Volume

Returns a DataSeries object that represents the volume of the Bars object that the Strategy is currently operating on.  You can also access the volume via the Bars.Volume property.  Access individual volume values via the square bracket syntax:

//Access the volume of the first bar
double firstBarVolume = Volume[0];

Remarks

  • See the DataSeries object reference for a listing of available properties and methods on the DataSeries object.

Example

protected override void Execute(){    // Get turnover on the last bar ( close * volume )
    double turnover = Close[Bars.Count-1] * Volume[Bars.Count-1];
    // Print stock turnover
    DrawLabel( PricePane, "Turnover: " + String.Format( "${0:0,0}", turnover ), Color.Black );
}