Strategy

StockSharp.Algo.Strategies

The base class for all trade strategies.

Inherits: BaseLogReceiver

Implements: IStrategyHost, IPositionProvider, INotifyPropertyChangedEx, INotifyPropertyChanged, ITimeProvider, IStrategy, IMarketRuleContainer, ILogReceiver, ILogSource, IDisposable, IMarketDataProvider, ISubscriptionProvider, ISecurityProvider, ISecurityMessageProvider, ITransactionProvider, IPortfolioProvider, IReportSource, ICustomTypeDescriptor, IScheduledTask

Constructors

Strategy
public Strategy()
strategy = Strategy()

Initializes a new instance Strategy.

Strategy
public Strategy(IPnLManager pnlManager, IStatisticManager stats)
strategy = Strategy(pnlManager, stats)

Initializes a new instance Strategy.

pnlManager
PnL manager.
stats
Statistic manager.

Properties

AggregationInterval
public TimeSpan AggregationInterval { get; set; }
value = strategy.AggregationInterval
strategy.AggregationInterval = value

Time interval for aggregation. Orders/trades within the same interval are grouped together. Default is 1 hour. Set to Zero to disable time-based grouping.

CancelOrdersWhenStopping
public bool CancelOrdersWhenStopping { get; set; }
value = strategy.CancelOrdersWhenStopping
strategy.CancelOrdersWhenStopping = value

To cancel active orders at stop. Is On by default.

ChildStrategies
public INotifyList<Strategy> ChildStrategies { get; }
value = strategy.ChildStrategies

Child strategies.

CommentMode
public StrategyCommentModes CommentMode { get; set; }
value = strategy.CommentMode
strategy.CommentMode = value

Set Comment by Name or Id.

Commission
public decimal? Commission { get; }
value = strategy.Commission

Total accumulated commission (from orders + trades).

Connector
public virtual IConnector Connector { get; set; }
value = strategy.Connector
strategy.Connector = value

Connector (via interface for testability).

CurrentTime
public override DateTime CurrentTime { get; }
value = strategy.CurrentTime

Current UTC time.

DisposeOnStop
public bool DisposeOnStop { get; set; }
value = strategy.DisposeOnStop
strategy.DisposeOnStop = value

Automatically to clear resources, used by the strategy, when it stops (state ProcessState becomes equal to Stopped).

Engine
public StrategyEngine Engine { get; }
value = strategy.Engine

State machine + message routing.

Environment
public SettingsStorage Environment { get; }
value = strategy.Environment

Strategy environment parameters.

ErrorState
public LogLevels ErrorState { get; set; }
value = strategy.ErrorState
strategy.ErrorState = value

Error state.

HideSecurityAndPortfolioParameters
public static bool HideSecurityAndPortfolioParameters { get; set; }
value = Strategy.HideSecurityAndPortfolioParameters
Strategy.HideSecurityAndPortfolioParameters = value

Make Security and Portfolio as non-browsable.

HistoryCalculated
protected virtual TimeSpan? HistoryCalculated { get; }
value = strategy.HistoryCalculated

The history period required before the strategy can start, or .

HistoryCalculatedForSubscribe
protected virtual TimeSpan? HistoryCalculatedForSubscribe { get; }
value = strategy.HistoryCalculatedForSubscribe

Code-calculated warm-up history span, if any.

HistorySize
public TimeSpan? HistorySize { get; set; }
value = strategy.HistorySize
strategy.HistorySize = value

History to initialize the strategy on Live trading.

HistorySizeForSubscribe
protected virtual TimeSpan? HistorySizeForSubscribe { get; }
value = strategy.HistorySizeForSubscribe

Configured live-trading warm-up history span, if any.

Id
public override Guid Id { get; set; }
value = strategy.Id
strategy.Id = value

Strategy ID.

Indicators
public INotifyList<IIndicator> Indicators { get; }
value = strategy.Indicators

All indicators registered via the high-level ISubscriptionHandler binders.

IndicatorSource
public Level1Fields? IndicatorSource { get; set; }
value = strategy.IndicatorSource
strategy.IndicatorSource = value

Default source for indicators when Source is not set.

IsBacktesting
public bool IsBacktesting { get; }
value = strategy.IsBacktesting

The strategy is executed in the history (backtesting) mode.

IsBacktestingForSubscribe
protected virtual bool IsBacktestingForSubscribe { get; }
value = strategy.IsBacktestingForSubscribe

Whether the strategy currently runs in backtesting (history emulation) mode.

IsFormed
public virtual bool IsFormed { get; }
value = strategy.IsFormed

Whether the strategy is formed.

IsOnline
public bool IsOnline { get; private set; }
value = strategy.IsOnline
strategy.IsOnline = value

Is online.

IsRulesSuspended
public bool IsRulesSuspended { get; }
value = strategy.IsRulesSuspended

Is rules execution suspended.

KeepStatistics
public bool KeepStatistics { get; set; }
value = strategy.KeepStatistics
strategy.KeepStatistics = value

Keep trading statistics (orders, trades, profit etc.) after restart.

LastError
public Exception LastError { get; private set; }
value = strategy.LastError
strategy.LastError = value

The last error that occurred in the strategy.

Latency
public TimeSpan? Latency { get; set; }
value = strategy.Latency
strategy.Latency = value

Latency.

LogLevel
public override LogLevels LogLevel { get; set; }
value = strategy.LogLevel
strategy.LogLevel = value

The logging level for the source.

MaxOrdersBeforeAggregation
public int MaxOrdersBeforeAggregation { get; set; }
value = strategy.MaxOrdersBeforeAggregation
strategy.MaxOrdersBeforeAggregation = value

Maximum number of orders before automatic aggregation is triggered. Default is 10000. Set to 0 to disable automatic aggregation.

MaxTradesBeforeAggregation
public int MaxTradesBeforeAggregation { get; set; }
value = strategy.MaxTradesBeforeAggregation
strategy.MaxTradesBeforeAggregation = value

Maximum number of trades before automatic aggregation is triggered. Default is 10000. Set to 0 to disable automatic aggregation.

MyTrades
public IEnumerable<MyTrade> MyTrades { get; }
value = strategy.MyTrades

Trades, matched during the strategy operation.

Name
public override string Name { get; set; }
value = strategy.Name
strategy.Name = value

Strategy name. Re-declared to unify the name inherited from both ILogSource and IReportSource, which are otherwise ambiguous through this interface.

NameGenerator
public StrategyNameGenerator NameGenerator { get; }
value = strategy.NameGenerator

Strategy name generator.

OrderBookSources
public virtual IEnumerable<IOrderBookSource> OrderBookSources { get; }
value = strategy.OrderBookSources

Order book sources used by the strategy.

OrderLookup
public Subscription OrderLookup { get; }
value = strategy.OrderLookup

Get global subscription on Order lookup. Can be .

OrderProcessor
public OrderPipeline OrderProcessor { get; }
value = strategy.OrderProcessor

Order tracking and processing pipeline.

Orders
public IEnumerable<Order> Orders { get; }
value = strategy.Orders

Strategy orders.

OrdersKeepTime
public TimeSpan OrdersKeepTime { get; set; }
value = strategy.OrdersKeepTime
strategy.OrdersKeepTime = value

The time for storing Orders in memory. By default it equals to 1 day. If value is set in Zero, orders will not be deleted.

Parameters
public StrategyParameterDictionary Parameters { get; }
value = strategy.Parameters

Strategy parameters.

PnL
public decimal PnL { get; }
value = strategy.PnL

Current profit-loss.

PnLManager
public IPnLManager PnLManager { get; set; }
value = strategy.PnLManager
strategy.PnLManager = value

PnL manager.

Portfolio
public Portfolio Portfolio { get; set; }
value = strategy.Portfolio
strategy.Portfolio = value

Portfolio.

PortfolioLookup
public Subscription PortfolioLookup { get; }
value = strategy.PortfolioLookup

Portfolio lookup subscription.

PortfolioProvider
public IPortfolioProvider PortfolioProvider { get; set; }
value = strategy.PortfolioProvider
strategy.PortfolioProvider = value

IPortfolioProvider used to resolve portfolios by name.

Position
public decimal Position { get; set; }
value = strategy.Position
strategy.Position = value

Current position (primary security).

Positions
public PositionPipeline Positions { get; }
value = strategy.Positions

Position event handling.

PositionsList
public IReadOnlyDictionary<ValueTuple<SecurityId, string>, decimal> PositionsList { get; }
value = strategy.PositionsList

All tracked positions.

ProcessState
public ProcessStates ProcessState { get; }
value = strategy.ProcessState

Current process state.

RandomProvider
public IRandomProvider RandomProvider { get; set; }
value = strategy.RandomProvider
strategy.RandomProvider = value

Where anything in the strategy that draws at random takes its draws from.

ReportSource
public ReportSource ReportSource { get; }
value = strategy.ReportSource

Report data source with aggregation support.

RiskFreeRate
public decimal RiskFreeRate { get; set; }
value = strategy.RiskFreeRate
strategy.RiskFreeRate = value

Annual risk-free rate (e.g., 0.03 = 3%).

RiskManager
public IRiskManager RiskManager { get; set; }
value = strategy.RiskManager
strategy.RiskManager = value

Risk manager.

RiskRules
public IEnumerable<IRiskRule> RiskRules { get; set; }
value = strategy.RiskRules
strategy.RiskRules = value

The risk rules.

Rules
public IMarketRuleList Rules { get; }
value = strategy.Rules

Registered rules.

Security
public Security Security { get; set; }
value = strategy.Security
strategy.Security = value

Security.

Slippage
public decimal? Slippage { get; }
value = strategy.Slippage

Total accumulated slippage.

StartedTime
public DateTime StartedTime { get; private set; }
value = strategy.StartedTime
strategy.StartedTime = value

Strategy start time.

StatisticManager
public IStatisticManager StatisticManager { get; protected set; }
value = strategy.StatisticManager
strategy.StatisticManager = value

Statistics manager.

Subscriptions
public SubscriptionRegistry Subscriptions { get; }
value = strategy.Subscriptions

Subscription management.

TargetAlgoFactory
public Func<Sides, decimal, IPositionModifyAlgo> TargetAlgoFactory { get; set; }
value = strategy.TargetAlgoFactory
strategy.TargetAlgoFactory = value

Factory to create position modify algorithms for TargetPositionManager. Default creates MarketOrderAlgo.

TargetPositionManager
public PositionTargetManager TargetPositionManager { get; }
value = strategy.TargetPositionManager

Target position manager.

TotalWorkingTime
public TimeSpan TotalWorkingTime { get; private set; }
value = strategy.TotalWorkingTime
strategy.TotalWorkingTime = value

Total working time.

Trades
public TradePipeline Trades { get; }
value = strategy.Trades

Trade processing and PnL.

TradingMode
public StrategyTradingModes TradingMode { get; set; }
value = strategy.TradingMode
strategy.TradingMode = value

Allow trading.

UnrealizedPnLInterval
public TimeSpan UnrealizedPnLInterval { get; set; }
value = strategy.UnrealizedPnLInterval
strategy.UnrealizedPnLInterval = value

The interval for unrealized profit recalculation. The default value is 1 minute.

UnsubscribeOnStop
public bool UnsubscribeOnStop { get; set; }
value = strategy.UnsubscribeOnStop
strategy.UnsubscribeOnStop = value

Unsubscribe all active subscription while strategy become stopping.

Volume
public virtual decimal Volume { get; set; }
value = strategy.Volume
strategy.Volume = value

Operational volume.

WaitAllTrades
public bool WaitAllTrades { get; set; }
value = strategy.WaitAllTrades
strategy.WaitAllTrades = value

Stop strategy only after getting all trades by registered orders.

WaitRulesOnStop
public bool WaitRulesOnStop { get; set; }
value = strategy.WaitRulesOnStop
strategy.WaitRulesOnStop = value

Wait Rules to finish before strategy become into Stopped state.

WorkingTime
public WorkingTime WorkingTime { get; set; }
value = strategy.WorkingTime
strategy.WorkingTime = value

Working time settings.

Methods

Alert
protected void Alert(AlertNotifications type, string caption, string message)
strategy.Alert(type, caption, message)

Send alert notification.

type
Alert type.
caption
Signal header.
message
Alert text.
Alert
protected void Alert(AlertNotifications type, string message)
strategy.Alert(type, message)

Send alert notification with strategy name as caption.

type
Alert type.
message
Alert text.
AlertLog
protected void AlertLog(string message)
strategy.AlertLog(message)

Send log alert notification.

message
Alert text.
AlertPopup
protected void AlertPopup(string message)
strategy.AlertPopup(message)

Send popup alert notification.

message
Alert text.
AlertSound
protected void AlertSound(string message)
strategy.AlertSound(message)

Send sound alert notification.

message
Alert text.
ApplyCommand
public void ApplyCommand(CommandMessage cmdMsg)
strategy.ApplyCommand(cmdMsg)

Apply an incoming remote command to the strategy.

cmdMsg
CommandMessage.
ApplyCommandAsync
public virtual ValueTask ApplyCommandAsync(CommandMessage cmdMsg, CancellationToken cancellationToken)
result = strategy.ApplyCommandAsync(cmdMsg, cancellationToken)

Apply an incoming remote command to the strategy.

cmdMsg
CommandMessage.
cancellationToken
CancellationToken

Returns: ValueTask

BuyLimit
public Order BuyLimit(decimal price, decimal? volume, Security security)
result = strategy.BuyLimit(price, volume, security)

Buy at limit price.

price
Price.
volume
Volume. If null, Volume is used.
security
Security. If null, Security is used.
BuyMarket
public Order BuyMarket(decimal? volume, Security security)
result = strategy.BuyMarket(volume, security)

Buy at market price.

volume
Volume. If null, Volume is used.
security
Security. If null, Security is used.
CanAttach
protected virtual bool CanAttach(Order order)
result = strategy.CanAttach(order)

Whether the order can be attached (tracked) by this strategy.

order
Order to check.

Returns: if the order belongs to this strategy.

CancelActiveOrders
public void CancelActiveOrders(bool? isStopOrder, Portfolio portfolio, Sides? direction, ExchangeBoard board, Security security, SecurityTypes? securityType, long? transactionId)
strategy.CancelActiveOrders(isStopOrder, portfolio, direction, board, security, securityType, transactionId)

Cancel active orders matching the specified filter.

isStopOrder
, if cancel only a stop orders, - if regular orders, - both.
portfolio
Portfolio. If the value is equal to , then the portfolio does not match the orders cancel filter.
direction
Order side. If the value is , the direction does not use.
board
Trading board. If the value is equal to , then the board does not match the orders cancel filter.
security
Instrument. If the value is equal to , then the instrument does not match the orders cancel filter.
securityType
Security type. If the value is , the type does not use.
transactionId
Order cancellation transaction id.
CancelAllActiveOrders
private void CancelAllActiveOrders()
strategy.CancelAllActiveOrders()

Cancel all active orders unconditionally (used internally on stop and risk actions, where the public Int64}) would be skipped because the strategy is no longer in the Started state).

CancelOrder
public void CancelOrder(Order order)
strategy.CancelOrder(order)

Cancel an order via the connector.

CancelOrderHandler
private void CancelOrderHandler(Order order)
strategy.CancelOrderHandler(order)

Dispatch a cancel without the public guards (stop-time teardown); the caller handles the IsCanceled dedup.

CancelTargetPosition
public void CancelTargetPosition()
strategy.CancelTargetPosition()

Cancel target position for the strategy's Security and Portfolio.

CancelTargetPosition
public void CancelTargetPosition(Security security, Portfolio portfolio)
strategy.CancelTargetPosition(security, portfolio)

Cancel target position for specified security and portfolio.

security
Security.
portfolio
Portfolio.
CanFinalStop
private bool CanFinalStop()
result = strategy.CanFinalStop()

Final-stop gate: deny the Stopping -> Stopped transition only while WaitRulesOnStop is set and there are outstanding rules to drain.

CanTrade
protected virtual bool CanTrade(Security security, Portfolio portfolio, Sides side, decimal volume, string noTradeReason)
result = strategy.CanTrade(security, portfolio, side, volume, noTradeReason)

Check if can trade with order information.

security
Security to trade.
portfolio
Portfolio to trade.
side
Order side.
volume
Order volume.
noTradeReason
Reason why trading is not allowed.

Returns: True if trading is allowed.

Clone
public Strategy Clone()
result = strategy.Clone()

Create a copy of the strategy.

Returns: Copy.

CloneAsync
public virtual ValueTask<Strategy> CloneAsync(CancellationToken cancellationToken)
result = strategy.CloneAsync(cancellationToken)

Create a copy of the strategy.

cancellationToken
CancellationToken

Returns: Copy.

ClosePosition
public Order ClosePosition(Security security, Portfolio portfolio)
result = strategy.ClosePosition(security, portfolio)

Close open position by market (register a Market order).

security
Security. If not passed, the value from Security is used.
portfolio
Portfolio. If not passed, the value from Portfolio is used.

Returns: The initialized order object, or when there is no position to close.

CopyToAsync
protected virtual ValueTask CopyToAsync(Strategy copy, CancellationToken cancellationToken)
result = strategy.CopyToAsync(copy, cancellationToken)

Copy settings into .

copy
Strategy
cancellationToken
CancellationToken

Returns: ValueTask

CreateChartArea
protected IChartArea CreateChartArea()
result = strategy.CreateChartArea()

Create chart area.

Returns: IChartArea

CreateClone
protected virtual Strategy CreateClone()
result = strategy.CreateClone()

Create clone object (non-initialized).

Returns: Strategy

CreateOrder
public Order CreateOrder(Sides side, decimal price, decimal? volume, Security security)
result = strategy.CreateOrder(side, price, volume, security)

Create an initialized order object.

side
Order side.
price
Price. 0 for market order.
volume
Volume. If null, Volume is used.
security
Security. If null, Security is used.

Returns: Order.

CreateTimer
protected ITimerHandler CreateTimer(TimeSpan interval, Action callback)
result = strategy.CreateTimer(interval, callback)

Create a timer that executes callback at specified intervals.

interval
Timer interval.
callback
Callback to execute.

Returns: ITimerHandler

DisposeManaged
protected override void DisposeManaged()
strategy.DisposeManaged()

Disposes the managed resources. Override this method to add custom clean up of managed resources.

DrawCandles
protected IChartCandleElement DrawCandles(IChartArea area, Subscription subscription)
result = strategy.DrawCandles(area, subscription)

Draw candles on chart.

area
IChartArea
subscription
Subscription

Returns: IChartCandleElement

DrawCandles``1
protected IChartCandleElement DrawCandles<T>(IChartArea area, ISubscriptionHandler<T> subscription)
result = strategy.DrawCandles(area, subscription)

Draw candles on chart.

area
IChartArea
subscription
Subscription handler.

Returns: IChartCandleElement

DrawIndicator
protected IChartIndicatorElement DrawIndicator(IChartArea area, IIndicator indicator, Color? color, Color? additionalColor)
result = strategy.DrawIndicator(area, indicator, color, additionalColor)

Draw indicator on chart.

area
IChartArea
indicator
IIndicator
color
Color
additionalColor
AdditionalColor

Returns: IChartIndicatorElement

DrawOrderBook
public void DrawOrderBook(Subscription subscription, IOrderBookSource source, IOrderBookMessage book)
strategy.DrawOrderBook(subscription, source, book)

Draw order book.

subscription
Subscription
source
IOrderBookSource
book
IOrderBookMessage
DrawOrderBookOrder
public void DrawOrderBookOrder(Subscription subscription, IOrderBookSource source, Order order)
strategy.DrawOrderBookOrder(subscription, source, order)

Draw order book order.

subscription
Subscription
source
IOrderBookSource
order
Order.
DrawOrderBookOrderFail
public void DrawOrderBookOrderFail(Subscription subscription, IOrderBookSource source, OrderFail fail)
strategy.DrawOrderBookOrderFail(subscription, source, fail)

Draw order book order fail.

subscription
Subscription
source
IOrderBookSource
fail
Order fail.
DrawOrders
protected IChartOrderElement DrawOrders(IChartArea area)
result = strategy.DrawOrders(area)

Draw orders on chart.

area
IChartArea

Returns: IChartOrderElement

DrawOwnTrades
protected IChartTradeElement DrawOwnTrades(IChartArea area)
result = strategy.DrawOwnTrades(area)

Draw trades on chart.

area
IChartArea

Returns: IChartTradeElement

EditOrder
public void EditOrder(Order order, Order changes)
strategy.EditOrder(order, changes)

Edit an order via the connector.

order
Original order.
changes
Order changes.
EnsureTxEventsHooked
private void EnsureTxEventsHooked()
strategy.EnsureTxEventsHooked()

Ensure the internal pipeline hooks that feed the transaction-provider NewOrder/OrderChanged streams are installed exactly once. Wired lazily on first subscription so the cost is avoided for consumers that never listen to the obsolete order events.

GetAlertService
public IAlertNotificationService GetAlertService()
result = strategy.GetAlertService()

To get the IAlertNotificationService associated with the strategy.

Returns: Alert notification service.

GetChart
public IChart GetChart()
result = strategy.GetChart()

To get the IChart associated with the strategy.

Returns: Chart.

GetOptionDesk
public IOptionDesk GetOptionDesk()
result = strategy.GetOptionDesk()

To get the IOptionDesk associated with the strategy.

Returns: IOptionDesk.

GetOptionPositionChart
public IOptionPositionChart GetOptionPositionChart()
result = strategy.GetOptionPositionChart()

To get the IOptionPositionChart associated with the strategy.

Returns: IOptionPositionChart.

GetParameters
public virtual IStrategyParam[] GetParameters()
result = strategy.GetParameters()

Get parameters.

Returns: Parameters.

GetPortfolio
public Portfolio GetPortfolio()
result = strategy.GetPortfolio()

Get Portfolio or throw InvalidOperationException if not present.

Returns: Portfolio

GetPositionValue
public decimal? GetPositionValue(Security sec, Portfolio pf)
result = strategy.GetPositionValue(sec, pf)

Get position value for specific security and portfolio.

GetSecurity
public Security GetSecurity()
result = strategy.GetSecurity()

Get Security or throw InvalidOperationException if not present.

Returns: Security

GetSubscribeHistoryPreroll
private TimeSpan GetSubscribeHistoryPreroll()
result = strategy.GetSubscribeHistoryPreroll()

Optional history pre-roll applied to market-data subscriptions during live trading, so the strategy is warmed up with the configured amount of history before "now". Returns Zero by default; subsystems that own a history setting (e.g. HistorySize / HistoryCalculated) and a backtesting flag override the wiring points below.

Returns: History span to subtract from CurrentTime, or zero to disable.

GetTargetPosition
public decimal? GetTargetPosition(Security security, Portfolio portfolio)
result = strategy.GetTargetPosition(security, portfolio)

Get target position for specified security and portfolio.

security
Security.
portfolio
Portfolio.

Returns: Target position, or null if not set.

GetTargetPosition
public decimal? GetTargetPosition()
result = strategy.GetTargetPosition()

Get target position for the strategy's Security and Portfolio.

Returns: Target position, or null if not set.

GetWorkingPortfolios
public virtual IEnumerable<Portfolio> GetWorkingPortfolios()
result = strategy.GetWorkingPortfolios()

Get all portfolios required for strategy.

Returns: Portfolios.

GetWorkingSecurities
public virtual IEnumerable<ValueTuple<Security, DataType>> GetWorkingSecurities()
result = strategy.GetWorkingSecurities()

Get all securities required for the strategy.

Returns: Securities.

InitStartValues
protected void InitStartValues()
strategy.InitStartValues()

Seed the start-of-run values that the statistic parameters and the orders-keep window depend on.

IsFormedAndOnline
public bool IsFormedAndOnline()
result = strategy.IsFormedAndOnline()

IsFormed and IsOnline.

Returns: Check result.

IsFormedAndOnlineAndAllowTrading
public bool IsFormedAndOnlineAndAllowTrading(StrategyTradingModes required)
result = strategy.IsFormedAndOnlineAndAllowTrading(required)

IsFormedAndOnline and TradingMode.

required
Required action.

Returns: Check result.

IsOrderEditable
public bool? IsOrderEditable(Order order)
result = strategy.IsOrderEditable(order)

Determines the specified order can be edited by Order).

order
Order.

Returns: if the order is editable, order cannot be changed, means no information.

IsOrderReplaceable
public bool? IsOrderReplaceable(Order order)
result = strategy.IsOrderReplaceable(order)

Determines the specified order can be replaced by Order).

order
Order.

Returns: if the order is replaceable, order cannot be replaced, means no information.

LoadAsync
public override Task LoadAsync(SettingsStorage storage, CancellationToken cancellationToken)
result = strategy.LoadAsync(storage, cancellationToken)

Load settings.

storage
SettingsStorage
cancellationToken
CancellationToken

Returns: Task

LookupByIdAsync
public ValueTask<Security> LookupByIdAsync(SecurityId id, CancellationToken cancellationToken)
result = strategy.LookupByIdAsync(id, cancellationToken)

To get the instrument by the identifier.

id
Security ID.
cancellationToken
CancellationToken

Returns: The got instrument. If there is no instrument by given criteria, is returned.

OnConnectorOrderReceived
public void OnConnectorOrderReceived(Subscription sub, Order order)
strategy.OnConnectorOrderReceived(sub, order)

Handle order received from the connector. This is the pipeline callback wired to OrderReceived; the user-overridable hook is Order).

OnCurrentPriceUpdated
protected virtual void OnCurrentPriceUpdated(SecurityId secId, decimal price, DateTime serverTime, DateTime localTime)
strategy.OnCurrentPriceUpdated(secId, price, serverTime, localTime)

Called when current price updated from market data.

OnError
protected virtual void OnError(Exception error)
strategy.OnError(error)

Processing of error, occurred as result of strategy operation.

error
Error.
OnNewMessage
public ValueTask OnNewMessage(Message msg, CancellationToken ct)
result = strategy.OnNewMessage(msg, ct)

Handle new outgoing message from connector.

OnNewPosition
protected virtual void OnNewPosition(Position position)
strategy.OnNewPosition(position)

Called when new position appears.

position
New position.
OnOrderCancelFailReceived
public void OnOrderCancelFailReceived(Subscription sub, OrderFail fail)
strategy.OnOrderCancelFailReceived(sub, fail)

Handle order cancellation failure from connector.

OnOrderChanged
protected virtual void OnOrderChanged(Order order)
strategy.OnOrderChanged(order)

Called when order state changed. Driven by the order-tracking pipeline on every non-registration change of a tracked order (the obsolete OrderChanged counterpart). Distinct from Order), which fires for any update of one of the strategy's own orders arriving from the connector's order-lookup subscription.

order
Changed order.
OnOrderEditFailReceived
public void OnOrderEditFailReceived(Subscription sub, OrderFail fail)
strategy.OnOrderEditFailReceived(sub, fail)

Handle order edit failure from connector.

OnOrderReceived
protected virtual void OnOrderReceived(Order order)
strategy.OnOrderReceived(order)

Called when one of the strategy's own orders is updated via the connector's order-lookup subscription. See Order) for the difference between the two.

order
Received order.
OnOrderRegistered
protected virtual void OnOrderRegistered(Order order)
strategy.OnOrderRegistered(order)

Called when order registered (transitioned from Pending to Active/Done).

order
Registered order.
OnOrderRegisterFailed
protected virtual void OnOrderRegisterFailed(OrderFail fail)
strategy.OnOrderRegisterFailed(fail)

Called when order registration fails.

fail
Order failure info.
OnOrderRegisterFailReceived
public void OnOrderRegisterFailReceived(Subscription sub, OrderFail fail)
strategy.OnOrderRegisterFailReceived(sub, fail)

Handle order registration failure from connector.

OnOrderRegistering
protected virtual void OnOrderRegistering(Order order)
strategy.OnOrderRegistering(order)

Called just before an order is registered via the connector. Raises OrderRegistering.

order
Order about to be registered.
OnOrderReRegistering
protected virtual void OnOrderReRegistering(Order oldOrder, Order newOrder)
strategy.OnOrderReRegistering(oldOrder, newOrder)

Called just before an order is re-registered (cancel + register new) via the connector. Raises OrderReRegistering.

oldOrder
Order being cancelled.
newOrder
New order to register.
OnOwnTradeReceived
protected virtual void OnOwnTradeReceived(MyTrade trade)
strategy.OnOwnTradeReceived(trade)

Called when one of the strategy's own trades is received. This is the single user-overridable hook: the obsolete NewMyTrade event is raised alongside it for the same trade (both wired from the trade pipeline's add), so user code is never invoked twice for one trade.

trade
Received trade.
OnPositionChanged
protected virtual void OnPositionChanged(Position position)
strategy.OnPositionChanged(position)

Called when position changes.

position
Changed position.
OnPositionReceived
protected virtual void OnPositionReceived(Position position)
strategy.OnPositionReceived(position)

Position received.

position
Position
OnPositionReceived
public void OnPositionReceived(Subscription sub, Position pos)
strategy.OnPositionReceived(sub, pos)

Handle position received from connector.

OnReseted
protected virtual void OnReseted()
strategy.OnReseted()

The method is called at the strategy reset.

OnStarted2
protected virtual void OnStarted2(DateTime time)
strategy.OnStarted2(time)

The method is called when the strategy has entered the started state.

time
The strategy start time.
OnStartedAsync
protected virtual ValueTask OnStartedAsync(DateTime time, CancellationToken cancellationToken)
result = strategy.OnStartedAsync(time, cancellationToken)

The method is called when the strategy has entered the started state, before DateTime). An exception stops the strategy the same way as one thrown from DateTime).

time
The strategy start time.
cancellationToken
Cancellation token.

Returns: ValueTask

OnStateChanged
protected virtual void OnStateChanged(ProcessStates state)
strategy.OnStateChanged(state)

Called when process state changes.

state
New state.
OnStateChangedAsync
protected virtual ValueTask OnStateChangedAsync(ProcessStates state, CancellationToken cancellationToken)
result = strategy.OnStateChangedAsync(state, cancellationToken)

Called asynchronously when process state changes.

state
New state.
cancellationToken
Cancellation token.

Returns: A task representing the state transition.

OnStopped
protected virtual void OnStopped()
strategy.OnStopped()

The method is called when the strategy has entered the stopped state.

OnStopping
protected virtual void OnStopping()
strategy.OnStopping()

The method is called when the ProcessState has taken the Stopping value. The base unsubscription is performed by the engine before this call; override to release strategy-specific resources on stop.

OnTradeReceived
public void OnTradeReceived(Subscription sub, MyTrade trade)
strategy.OnTradeReceived(sub, trade)

Handle trade received from connector.

Param``1
public StrategyParam<T> Param<T>(string id, T initialValue)
result = strategy.Param(id, initialValue)

Create and register a strategy parameter.

id
Parameter identifier.
initialValue
The initial value.

Returns: The strategy parameter.

Prepare
public void Prepare()
strategy.Prepare()

Prepare data for report generation. Call this before accessing any data to ensure all values are up-to-date.

RaiseLog
protected override void RaiseLog(LogMessage message)
strategy.RaiseLog(message)

To call the event Log.

message
A debug message.
RaiseParametersChanged
public void RaiseParametersChanged(string name)
strategy.RaiseParametersChanged(name)

Raise the parameters-changed notification for the parameter with the specified name.

name
Parameter name.
RegisterOrder
public void RegisterOrder(Order order)
strategy.RegisterOrder(order)

Register an order via the connector.

RequestStop
protected void RequestStop()
strategy.RequestStop()

Ask the strategy to stop from code that cannot wait for CancellationToken), such as a handler of market data. New orders are refused from this call on; the strategy is stopped when it handles the next message of the connector.

RequestStop
protected void RequestStop(Exception error)
strategy.RequestStop(error)

Ask the strategy to stop because of the error, from code that cannot wait for CancellationToken). The error is reported at once.

error
The error that caused the stop.
ReRegisterOrder
public void ReRegisterOrder(Order oldOrder, Order newOrder)
strategy.ReRegisterOrder(oldOrder, newOrder)

Re-register (cancel + register new) an order via the connector.

oldOrder
Order to cancel.
newOrder
New order to register.
Reset
public void Reset()
strategy.Reset()

Reset all state (orders, trades, positions, PnL, subscriptions).

SafeGetConnector
public IConnector SafeGetConnector()
result = strategy.SafeGetConnector()

To get the strategy getting Connector. If it is not initialized, the exception will be discarded.

Returns: Connector.

Save
public void Save(SettingsStorage storage, bool saveStatistics, bool saveSystemParameters)
strategy.Save(storage, saveStatistics, saveSystemParameters)

Save settings.

storage
SettingsStorage
saveStatistics
KeepStatistics
saveSystemParameters
Save system parameters.
SaveAsync
public Task SaveAsync(SettingsStorage storage, bool saveStatistics, bool saveSystemParameters, CancellationToken cancellationToken)
result = strategy.SaveAsync(storage, saveStatistics, saveSystemParameters, cancellationToken)

Save settings.

storage
SettingsStorage
saveStatistics
KeepStatistics
saveSystemParameters
Save system parameters.
cancellationToken
CancellationToken

Returns: Task

SaveAsync
public override Task SaveAsync(SettingsStorage storage, CancellationToken cancellationToken)
result = strategy.SaveAsync(storage, cancellationToken)

Save settings.

storage
SettingsStorage
cancellationToken
CancellationToken

Returns: Task

SellLimit
public Order SellLimit(decimal price, decimal? volume, Security security)
result = strategy.SellLimit(price, volume, security)

Sell at limit price.

price
Price.
volume
Volume. If null, Volume is used.
security
Security. If null, Security is used.
SellMarket
public Order SellMarket(decimal? volume, Security security)
result = strategy.SellMarket(volume, security)

Sell at market price.

volume
Volume. If null, Volume is used.
security
Security. If null, Security is used.
SetAlertService
public void SetAlertService(IAlertNotificationService service)
strategy.SetAlertService(service)

To set a IAlertNotificationService for the strategy.

service
Alert notification service.
SetChart
public void SetChart(IChart chart)
strategy.SetChart(chart)

To set a IChart for the strategy.

chart
Chart.
SetOptionDesk
public void SetOptionDesk(IOptionDesk desk)
strategy.SetOptionDesk(desk)

To set the IOptionDesk.

desk
IOptionDesk.
SetOptionPositionChart
public void SetOptionPositionChart(IOptionPositionChart chart)
strategy.SetOptionPositionChart(chart)

To set the IOptionPositionChart.

chart
IOptionPositionChart.
SetPositionValue
public void SetPositionValue(Security security, Portfolio portfolio, decimal value, DateTime time)
strategy.SetPositionValue(security, portfolio, value, time)

Set position.

security
Security.
portfolio
Portfolio.
value
Position.
time
Timestamp to assign into LocalTime and ServerTime if position is created anew.
SetTargetPosition
public void SetTargetPosition(decimal target)
strategy.SetTargetPosition(target)

Set target position for the strategy's Security and Portfolio.

target
Target position value.
SetTargetPosition
public void SetTargetPosition(Security security, Portfolio portfolio, decimal target)
strategy.SetTargetPosition(security, portfolio, target)

Set target position for specified security and portfolio.

security
Security.
portfolio
Portfolio.
target
Target position value.
Start
public void Start()
strategy.Start()

Start the strategy.

StartAsync
public ValueTask StartAsync(CancellationToken cancellationToken)
result = strategy.StartAsync(cancellationToken)

Start the strategy.

StartProtection
public void StartProtection(Unit takeProfit, Unit stopLoss, bool isStopTrailing, TimeSpan? takeTimeout, TimeSpan? stopTimeout, bool useMarketOrders, bool isLocalStop)
strategy.StartProtection(takeProfit, stopLoss, isStopTrailing, takeTimeout, stopTimeout, useMarketOrders, isLocalStop)

Start position protection.

takeProfit
Take offset.
stopLoss
Stop offset.
isStopTrailing
Whether to use a trailing technique.
takeTimeout
Time limit. If protection has not worked by this time, the position will be closed on the market.
stopTimeout
Time limit. If protection has not worked by this time, the position will be closed on the market.
useMarketOrders
Whether to use market orders.
isLocalStop
Force local stop processing regardless of adapter capabilities.
StartTimer
protected ITimerHandler StartTimer(TimeSpan interval, Action callback)
result = strategy.StartTimer(interval, callback)

Create a timer that executes callback at specified intervals and starts it immediately.

interval
Timer interval.
callback
Callback to execute.

Returns: ITimerHandler

Stop
public void Stop(Exception error)
strategy.Stop(error)

Stop the strategy because of the specified error.

error
Error.
Stop
public void Stop()
strategy.Stop()

Stop the strategy.

StopAsync
public ValueTask StopAsync(CancellationToken cancellationToken)
result = strategy.StopAsync(cancellationToken)

Stop the strategy.

StopAsync
public ValueTask StopAsync(Exception error, CancellationToken cancellationToken)
result = strategy.StopAsync(error, cancellationToken)

Stop the strategy with error.

error
The error that caused the stop.
cancellationToken
Cancellation token.
Subscribe
public void Subscribe(Subscription subscription)
strategy.Subscribe(subscription)

Subscribe.

subscription
Subscription.
SubscribeCandles
protected ISubscriptionHandler<ICandleMessage> SubscribeCandles(Subscription subscription)
result = strategy.SubscribeCandles(subscription)

Subscribe to candles.

subscription
Subscription

Returns: ISubscriptionHandler

SubscribeCandles
protected ISubscriptionHandler<ICandleMessage> SubscribeCandles(DataType dt, bool isFinishedOnly, Security security)
result = strategy.SubscribeCandles(dt, isFinishedOnly, security)

Subscribe to candles.

dt
DataType
isFinishedOnly
IsFinishedOnly
security
Security. If security is not passed, then Security value is used.

Returns: ISubscriptionHandler

SubscribeCandles
protected ISubscriptionHandler<ICandleMessage> SubscribeCandles(TimeSpan tf, bool isFinishedOnly, Security security)
result = strategy.SubscribeCandles(tf, isFinishedOnly, security)

Subscribe to candles.

tf
Time-frame.
isFinishedOnly
IsFinishedOnly
security
Security. If security is not passed, then Security value is used.

Returns: ISubscriptionHandler

SubscribeLevel1
protected ISubscriptionHandler<Level1ChangeMessage> SubscribeLevel1(Subscription subscription)
result = strategy.SubscribeLevel1(subscription)

Subscribe to Level1.

subscription
Subscription

Returns: ISubscriptionHandler

SubscribeLevel1
protected ISubscriptionHandler<Level1ChangeMessage> SubscribeLevel1(Security security)
result = strategy.SubscribeLevel1(security)

Subscribe to Level1.

security
Security. If security is not passed, then Security value is used.

Returns: ISubscriptionHandler

SubscribeOrderBook
protected ISubscriptionHandler<IOrderBookMessage> SubscribeOrderBook(Security security)
result = strategy.SubscribeOrderBook(security)

Subscribe to MarketDepth.

security
Security. If security is not passed, then Security value is used.

Returns: ISubscriptionHandler

SubscribeOrderBook
protected ISubscriptionHandler<IOrderBookMessage> SubscribeOrderBook(Subscription subscription)
result = strategy.SubscribeOrderBook(subscription)

Subscribe to MarketDepth.

subscription
Subscription

Returns: ISubscriptionHandler

SubscribeTicks
protected ISubscriptionHandler<ITickTradeMessage> SubscribeTicks(Subscription subscription)
result = strategy.SubscribeTicks(subscription)

Subscribe to Ticks.

subscription
Subscription

Returns: ISubscriptionHandler

SubscribeTicks
protected ISubscriptionHandler<ITickTradeMessage> SubscribeTicks(Security security)
result = strategy.SubscribeTicks(security)

Subscribe to Ticks.

security
Security. If security is not passed, then Security value is used.

Returns: ISubscriptionHandler

ToReportValue
protected virtual object ToReportValue(object value)
result = strategy.ToReportValue(value)

To convert parameter value to report value.

value
The parameter value.

Returns: The report value.

ToSubscription``1
private Subscription ToSubscription<TLookupMessage>()
result = strategy.ToSubscription()

Build a global lookup subscription stamped with this strategy's identifier.

Returns: Subscription.

TryAddMyTrade
public bool TryAddMyTrade(MyTrade trade)
result = strategy.TryAddMyTrade(trade)

Try add own trade.

trade
MyTrade

Returns: Operation result.

UnSubscribe
public void UnSubscribe(Subscription subscription)
strategy.UnSubscribe(subscription)

Unsubscribe.

subscription
Subscription.

Events

BoardReceived
public event Action<Subscription, ExchangeBoard> BoardReceived
strategy.BoardReceived += handler

Board value received.

CandleReceived
public event Action<Subscription, ICandleMessage> CandleReceived
strategy.CandleReceived += handler

Candle value received.

CommissionChanged
public event Action CommissionChanged
strategy.CommissionChanged += handler

Commission changed event.

ConnectorChanged
public event Action ConnectorChanged
strategy.ConnectorChanged += handler

Connector changed event.

DataTypeReceived
public event Action<Subscription, DataType> DataTypeReceived
strategy.DataTypeReceived += handler

Data type value received.

Error
public event Action<IStrategy, Exception> Error
strategy.Error += handler

Error event.

IsOnlineChanged
public event Action<Strategy> IsOnlineChanged
strategy.IsOnlineChanged += handler

Online state changed.

LatencyChanged
public event Action LatencyChanged
strategy.LatencyChanged += handler

Latency changed event.

Level1Received
public event Action<Subscription, Level1ChangeMessage> Level1Received
strategy.Level1Received += handler

Level1 value received.

NewMyTrade
public event Action<MyTrade> NewMyTrade
strategy.NewMyTrade += handler

The event of new own trade occurring.

NewsReceived
public event Action<Subscription, News> NewsReceived
strategy.NewsReceived += handler

News value received.

OrderBookDrawing
public event Action<Subscription, IOrderBookSource, IOrderBookMessage> OrderBookDrawing
strategy.OrderBookDrawing += handler

IOrderBookMessage).

OrderBookDrawingOrder
public event Action<Subscription, IOrderBookSource, Order> OrderBookDrawingOrder
strategy.OrderBookDrawingOrder += handler

Order).

OrderBookDrawingOrderFail
public event Action<Subscription, IOrderBookSource, OrderFail> OrderBookDrawingOrderFail
strategy.OrderBookDrawingOrderFail += handler

OrderFail).

OrderBookReceived
public event Action<Subscription, IOrderBookMessage> OrderBookReceived
strategy.OrderBookReceived += handler

Order book value received.

OrderCancelFailed
public event Action<OrderFail> OrderCancelFailed
strategy.OrderCancelFailed += handler

Order cancellation failed.

OrderCancelFailReceived
public event Action<Subscription, OrderFail> OrderCancelFailReceived
strategy.OrderCancelFailReceived += handler

Order cancel failure.

OrderCanceling
public event Action<Order> OrderCanceling
strategy.OrderCanceling += handler

Order is about to be canceled.

OrderChanged
public event Action<Order> OrderChanged
strategy.OrderChanged += handler

The event of order change.

OrderEdited
public event Action<long, Order> OrderEdited
strategy.OrderEdited += handler

Order edited.

OrderEditFailed
public event Action<long, OrderFail> OrderEditFailed
strategy.OrderEditFailed += handler

Order edit failed.

OrderEditFailReceived
public event Action<Subscription, OrderFail> OrderEditFailReceived
strategy.OrderEditFailReceived += handler

Order edit failure.

OrderLogReceived
public event Action<Subscription, IOrderLogMessage> OrderLogReceived
strategy.OrderLogReceived += handler

Order log value received.

OrderReceived
public event Action<Subscription, Order> OrderReceived
strategy.OrderReceived += handler

Order value received.

OrderRegistered
public event Action<Order> OrderRegistered
strategy.OrderRegistered += handler

The event of order successful registration.

OrderRegisterFailed
public event Action<OrderFail> OrderRegisterFailed
strategy.OrderRegisterFailed += handler

Order registration failed.

OrderRegisterFailReceived
public event Action<Subscription, OrderFail> OrderRegisterFailReceived
strategy.OrderRegisterFailReceived += handler

Order registration failure.

OrderRegistering
public event Action<Order> OrderRegistering
strategy.OrderRegistering += handler

Order is about to be registered.

OrderReRegistering
public event Action<Order, Order> OrderReRegistering
strategy.OrderReRegistering += handler

Order is about to be re-registered.

OwnTradeReceived
public event Action<Subscription, MyTrade> OwnTradeReceived
strategy.OwnTradeReceived += handler

Own trade value received.

ParametersChanged
public event Action ParametersChanged
strategy.ParametersChanged += handler

Strategy parameters changed event.

PnLChanged
public event Action PnLChanged
strategy.PnLChanged += handler

PnL changed event.

PnLReceived
public event Action<Subscription> PnLReceived
strategy.PnLReceived += handler

PnL received event.

PnLReceived2
public event Action<Subscription, Portfolio, DateTime, decimal, decimal?, decimal?> PnLReceived2
strategy.PnLReceived2 += handler

PnL received event.

PortfolioReceived
public event Action<Subscription, Portfolio> PortfolioReceived
strategy.PortfolioReceived += handler

Portfolio value received.

PositionChanged
public event Action PositionChanged
strategy.PositionChanged += handler

Position changed.

PositionReceived
public event Action<Subscription, Position> PositionReceived
strategy.PositionReceived += handler

Position value received.

ProcessStateChanged
public event Action<IStrategy> ProcessStateChanged
strategy.ProcessStateChanged += handler

ProcessState change event.

PropertyChanged
public event PropertyChangedEventHandler PropertyChanged
strategy.PropertyChanged += handler

PropertyChanged.

Reseted
public event Action Reseted
strategy.Reseted += handler

Strategy reset event.

SecurityReceived
public event Action<Subscription, Security> SecurityReceived
strategy.SecurityReceived += handler

Security value received.

SlippageChanged
public event Action SlippageChanged
strategy.SlippageChanged += handler

Slippage changed event.

SubscriptionFailed
public event Action<Subscription, Exception, bool> SubscriptionFailed
strategy.SubscriptionFailed += handler

Subscription failed.

SubscriptionOnline
public event Action<Subscription> SubscriptionOnline
strategy.SubscriptionOnline += handler

Subscription is online.

SubscriptionReceived
public event Action<Subscription, object> SubscriptionReceived
strategy.SubscriptionReceived += handler

Subscription value received.

SubscriptionStarted
public event Action<Subscription> SubscriptionStarted
strategy.SubscriptionStarted += handler

Subscription is started.

SubscriptionStopped
public event Action<Subscription, Exception> SubscriptionStopped
strategy.SubscriptionStopped += handler

Subscription is stopped.

TickTradeReceived
public event Action<Subscription, ITickTradeMessage> TickTradeReceived
strategy.TickTradeReceived += handler

Tick trade value received.