Securities

Handling Data

Introduction

If you create a data subscription, your algorithm receives data updates for that security or custom data source.

Get Prices

LEAN uses data updates to set the current prices of a security and compute the contribution of securities you hold to the portfolio value. To get the current prices of a security, find the Security object in the Securitiessecurities dictionary and access the price attributes.

var security = Securities["SPY"];
var price = security.Price;
var bidPrice = security.BidPrice;
var askPrice = security.AskPrice;
security = self.securities["SPY"]
price = security.price
bid_price = security.bid_price
ask_price = security.ask_price

Data Events

The Slice that LEAN passes to the OnDataon_data method represents all of the data for your subscriptions at a single point in time. The Slice object contains data like Tick objects, TradeBar objects, QuoteBar objects, corporate actions, and chains for Option and Future contracts. You can use the data in the Slice to make trading decisions.

To access data in the Slice, index it with the security Symbol. If you use the security ticker instead of the Symbol, LEAN automatically finds the Symbol.

public override void OnData(Slice slice)
{
    if (slice.ContainsKey(_symbol))
    {
        var myData = slice[_symbol];
    }
}
def on_data(self, slice: Slice) -> None:
    if slice.contains_key(self._symbol):
        my_data = slice[self._symbol]

The following table shows the Slice property to index based on the data format you want:

Data FormatSlice Property
TradeBarBarsbars
QuoteBarQuoteBarsquote_bars
TickTicksticks
public override void OnData(Slice slice)
{
    if (slice.ContainsKey(_symbol))
    {
        var bar = slice.Bars[_symbol];
    }
}
def on_data(self, slice: Slice) -> None:
    if slice.contains_key(self._symbol):
        bar = slice.bars[self._symbol]

If you just index the Slice instead of the preceding properties, it returns the correct object. For instance, if your data subscription provides QuoteBar objects and you index the Slice with the security Symbol, it returns the QuoteBar.

For more information about the Slice class, see Timeslices.

Cache

To get the most recent data for a security, call the GetLastDataget_last_data method on the Security object.

var data = Securities["SPY"].GetLastData();
data = self.securities["SPY"].get_last_data()

The Cachecache property of a Security object provides additional price information since you can access TradeBar, QuoteBar, and Tick data.

var cache = Securities["SPY"].Cache;
var tradeBar = cache.GetData();
var quoteBar = cache.GetData();
var ticks = cache.GetAll();
cache = self.securities["SPY"].cache
trade_bar = cache.get_data[TradeBar]()
quote_bar = cache.get_data[QuoteBar]()
ticks = cache.get_all[Tick]()

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: