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 Securities
securities
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 OnData
on_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 Format | Slice Property |
---|---|
TradeBar | Bars bars |
QuoteBar | QuoteBars quote_bars |
Tick | Ticks ticks |
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 GetLastData
get_last_data
method on the Security
object.
var data = Securities["SPY"].GetLastData();
data = self.securities["SPY"].get_last_data()
The Cache
cache
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]()