Market Data Subscriptions in Strategies
In StockSharp, strategies use a subscription mechanism to receive market data. This approach is the primary and preferred method of obtaining data in trading strategies.
Subscription Basics
Subscriptions in strategies are based on the general StockSharp subscription mechanism. They provide a centralized and unified way of obtaining all types of market data.
Creating a Subscription in a Strategy
In the OnStarted method of the strategy, you can create and start a subscription for the required data:
protected override void OnStarted(DateTimeOffset time)
{
base.OnStarted(time);
// Creating a subscription for 5-minute candles directly through DataType
var subscription = new Subscription(
DataType.TimeFrame(TimeSpan.FromMinutes(5)),
Security);
// If additional parameters are required, you can configure the subscription
subscription.From = DateTimeOffset.Now.Subtract(TimeSpan.FromDays(7));
// Creating a rule to process incoming candles
Connector
.WhenCandlesFinished(subscription)
.Do(ProcessCandle)
.Apply(this);
// Starting the subscription
Connector.Subscribe(subscription);
}
In this example, a subscription is created for 5-minute candles using a convenient constructor that accepts DataType
and Security
. If necessary, you can additionally configure subscription parameters, such as the history period.
Advantages of Subscriptions in Strategies
Using subscriptions in strategies has several advantages compared to direct subscription to Strategy.Connector events:
Isolation - each subscription works independently, allowing different types of data to be received for different instruments without mutual interference.
State Management - subscriptions have clear states (SubscriptionStates), which allow precise determination of whether historical data is currently being received or the subscription has already transitioned to online mode.
Automatic Strategy State Control - the strategy automatically tracks the state of all its subscriptions and transitions to online mode (IsOnline) only when all subscriptions have gone online.
Code Uniformity - subscriptions use a unified approach, independent of the type of requested data.
Integration with Rules - subscriptions easily integrate with strategy event model through rules.
Automatic Subscription Management - when the strategy stops, all its subscriptions are automatically canceled, freeing up resources.
Historical Data Support - ability to load historical data before transitioning to real-time data.
Monitoring Subscription States
The strategy automatically tracks the state of all subscriptions to control its operating mode:
private void CheckRefreshOnlineState()
{
bool nowOnline = ProcessState == ProcessStates.Started;
if (nowOnline)
nowOnline = _subscriptions.CachedKeys
.Where(s => !s.SubscriptionMessage.IsHistoryOnly())
.All(s => s.State == SubscriptionStates.Online);
// Update strategy's IsOnline state
IsOnline = nowOnline;
}
The Strategy.IsOnline property will be true
only when all strategy subscriptions have transitioned to the SubscriptionStates.Online state. This allows the strategy to understand the moment when it is working with current market data.
Types of Subscriptions
In strategies, you can use subscriptions to various types of market data:
// Subscription to candles
var candleSubscription = new Subscription(
DataType.TimeFrame(TimeSpan.FromMinutes(1)),
Security);
// Subscription to market depth
var depthSubscription = new Subscription(
DataType.MarketDepth,
Security);
// Subscription to tick trades
var tickSubscription = new Subscription(
DataType.Ticks,
Security);
// Subscription to Level1 (best bid/ask and other basic information)
var level1Subscription = new Subscription(
DataType.Level1,
Security);
Processing Subscription Data Through Rules
To process data coming through a subscription, it is recommended to use rules:
// Subscription to candles
var subscription = new Subscription(DataType.TimeFrame(TimeSpan.FromMinutes(5)), Security);
// Creating a rule for processing incoming candles
Connector
.WhenCandlesFinished(subscription) // Rule activation when a completed candle is received
.Do(ProcessCandle) // Call processing method
.Apply(this); // Apply rule to strategy
// Start subscription
Connector.Subscribe(subscription);
In the example above, a rule is created that will call the ProcessCandle
method when each completed candle is received.
Requesting Historical Data
The strategy automatically sets the history load period through the Strategy.HistorySize property:
// Set history load period to 30 days
strategy.HistorySize = TimeSpan.FromDays(30);
When creating a subscription, the strategy automatically sets the From
parameter to load history if it was not explicitly specified.
Canceling Subscriptions
Subscriptions can be manually canceled by calling the UnSubscribe method:
// Cancel subscription
Connector.UnSubscribe(subscription);
When stopping the strategy, if the UnsubscribeOnStop parameter is set to true
(default), all subscriptions will be automatically canceled.