Strategy
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
public Strategy(IPnLManager pnlManager, IStatisticManager stats)
strategy = Strategy(pnlManager, stats)
Initializes a new instance Strategy.
- pnlManager
- PnL manager.
- stats
- Statistic manager.
Properties
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.
public bool CancelOrdersWhenStopping { get; set; }
value = strategy.CancelOrdersWhenStopping
strategy.CancelOrdersWhenStopping = value
To cancel active orders at stop. Is On by default.
public INotifyList<Strategy> ChildStrategies { get; }
value = strategy.ChildStrategies
Child strategies.
public StrategyCommentModes CommentMode { get; set; }
value = strategy.CommentMode
strategy.CommentMode = value
Set Comment by Name or Id.
public decimal? Commission { get; }
value = strategy.Commission
Total accumulated commission (from orders + trades).
public virtual IConnector Connector { get; set; }
value = strategy.Connector
strategy.Connector = value
Connector (via interface for testability).
public override DateTime CurrentTime { get; }
value = strategy.CurrentTime
Current UTC time.
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).
public StrategyEngine Engine { get; }
value = strategy.Engine
State machine + message routing.
public SettingsStorage Environment { get; }
value = strategy.Environment
Strategy environment parameters.
public LogLevels ErrorState { get; set; }
value = strategy.ErrorState
strategy.ErrorState = value
Error state.
public static bool HideSecurityAndPortfolioParameters { get; set; }
value = Strategy.HideSecurityAndPortfolioParameters
Strategy.HideSecurityAndPortfolioParameters = value
Make Security and Portfolio as non-browsable.
protected virtual TimeSpan? HistoryCalculated { get; }
value = strategy.HistoryCalculated
The history period required before the strategy can start, or .
protected virtual TimeSpan? HistoryCalculatedForSubscribe { get; }
value = strategy.HistoryCalculatedForSubscribe
Code-calculated warm-up history span, if any.
public TimeSpan? HistorySize { get; set; }
value = strategy.HistorySize
strategy.HistorySize = value
History to initialize the strategy on Live trading.
protected virtual TimeSpan? HistorySizeForSubscribe { get; }
value = strategy.HistorySizeForSubscribe
Configured live-trading warm-up history span, if any.
public INotifyList<IIndicator> Indicators { get; }
value = strategy.Indicators
All indicators registered via the high-level ISubscriptionHandler binders.
public Level1Fields? IndicatorSource { get; set; }
value = strategy.IndicatorSource
strategy.IndicatorSource = value
Default source for indicators when Source is not set.
public bool IsBacktesting { get; }
value = strategy.IsBacktesting
The strategy is executed in the history (backtesting) mode.
protected virtual bool IsBacktestingForSubscribe { get; }
value = strategy.IsBacktestingForSubscribe
Whether the strategy currently runs in backtesting (history emulation) mode.
public virtual bool IsFormed { get; }
value = strategy.IsFormed
Whether the strategy is formed.
public bool IsOnline { get; private set; }
value = strategy.IsOnline
strategy.IsOnline = value
Is online.
public bool IsRulesSuspended { get; }
value = strategy.IsRulesSuspended
Is rules execution suspended.
public bool KeepStatistics { get; set; }
value = strategy.KeepStatistics
strategy.KeepStatistics = value
Keep trading statistics (orders, trades, profit etc.) after restart.
public Exception LastError { get; private set; }
value = strategy.LastError
strategy.LastError = value
The last error that occurred in the strategy.
public TimeSpan? Latency { get; set; }
value = strategy.Latency
strategy.Latency = value
Latency.
public override LogLevels LogLevel { get; set; }
value = strategy.LogLevel
strategy.LogLevel = value
The logging level for the source.
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.
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.
public IEnumerable<MyTrade> MyTrades { get; }
value = strategy.MyTrades
Trades, matched during the strategy operation.
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.
public StrategyNameGenerator NameGenerator { get; }
value = strategy.NameGenerator
Strategy name generator.
public virtual IEnumerable<IOrderBookSource> OrderBookSources { get; }
value = strategy.OrderBookSources
Order book sources used by the strategy.
public Subscription OrderLookup { get; }
value = strategy.OrderLookup
Get global subscription on Order lookup. Can be .
public OrderPipeline OrderProcessor { get; }
value = strategy.OrderProcessor
Order tracking and processing pipeline.
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.
public StrategyParameterDictionary Parameters { get; }
value = strategy.Parameters
Strategy parameters.
public IPnLManager PnLManager { get; set; }
value = strategy.PnLManager
strategy.PnLManager = value
PnL manager.
public Portfolio Portfolio { get; set; }
value = strategy.Portfolio
strategy.Portfolio = value
Portfolio.
public Subscription PortfolioLookup { get; }
value = strategy.PortfolioLookup
Portfolio lookup subscription.
public IPortfolioProvider PortfolioProvider { get; set; }
value = strategy.PortfolioProvider
strategy.PortfolioProvider = value
IPortfolioProvider used to resolve portfolios by name.
public decimal Position { get; set; }
value = strategy.Position
strategy.Position = value
Current position (primary security).
public PositionPipeline Positions { get; }
value = strategy.Positions
Position event handling.
public IReadOnlyDictionary<ValueTuple<SecurityId, string>, decimal> PositionsList { get; }
value = strategy.PositionsList
All tracked positions.
public ProcessStates ProcessState { get; }
value = strategy.ProcessState
Current process state.
public IRandomProvider RandomProvider { get; set; }
value = strategy.RandomProvider
strategy.RandomProvider = value
Where anything in the strategy that draws at random takes its draws from.
public ReportSource ReportSource { get; }
value = strategy.ReportSource
Report data source with aggregation support.
public decimal RiskFreeRate { get; set; }
value = strategy.RiskFreeRate
strategy.RiskFreeRate = value
Annual risk-free rate (e.g., 0.03 = 3%).
public IRiskManager RiskManager { get; set; }
value = strategy.RiskManager
strategy.RiskManager = value
Risk manager.
public IEnumerable<IRiskRule> RiskRules { get; set; }
value = strategy.RiskRules
strategy.RiskRules = value
The risk rules.
public Security Security { get; set; }
value = strategy.Security
strategy.Security = value
Security.
public DateTime StartedTime { get; private set; }
value = strategy.StartedTime
strategy.StartedTime = value
Strategy start time.
public IStatisticManager StatisticManager { get; protected set; }
value = strategy.StatisticManager
strategy.StatisticManager = value
Statistics manager.
public SubscriptionRegistry Subscriptions { get; }
value = strategy.Subscriptions
Subscription management.
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.
public PositionTargetManager TargetPositionManager { get; }
value = strategy.TargetPositionManager
Target position manager.
public TimeSpan TotalWorkingTime { get; private set; }
value = strategy.TotalWorkingTime
strategy.TotalWorkingTime = value
Total working time.
public StrategyTradingModes TradingMode { get; set; }
value = strategy.TradingMode
strategy.TradingMode = value
Allow trading.
public TimeSpan UnrealizedPnLInterval { get; set; }
value = strategy.UnrealizedPnLInterval
strategy.UnrealizedPnLInterval = value
The interval for unrealized profit recalculation. The default value is 1 minute.
public bool UnsubscribeOnStop { get; set; }
value = strategy.UnsubscribeOnStop
strategy.UnsubscribeOnStop = value
Unsubscribe all active subscription while strategy become stopping.
public virtual decimal Volume { get; set; }
value = strategy.Volume
strategy.Volume = value
Operational volume.
public bool WaitAllTrades { get; set; }
value = strategy.WaitAllTrades
strategy.WaitAllTrades = value
Stop strategy only after getting all trades by registered orders.
public bool WaitRulesOnStop { get; set; }
value = strategy.WaitRulesOnStop
strategy.WaitRulesOnStop = value
Wait Rules to finish before strategy become into Stopped state.
public WorkingTime WorkingTime { get; set; }
value = strategy.WorkingTime
strategy.WorkingTime = value
Working time settings.
Methods
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.
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.
protected void AlertLog(string message)
strategy.AlertLog(message)
Send log alert notification.
- message
- Alert text.
protected void AlertPopup(string message)
strategy.AlertPopup(message)
Send popup alert notification.
- message
- Alert text.
protected void AlertSound(string message)
strategy.AlertSound(message)
Send sound alert notification.
- message
- Alert text.
public void ApplyCommand(CommandMessage cmdMsg)
strategy.ApplyCommand(cmdMsg)
Apply an incoming remote command to the strategy.
- cmdMsg
- CommandMessage.
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
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.
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.
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.
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.
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).
public void CancelOrder(Order order)
strategy.CancelOrder(order)
Cancel an order via the connector.
private void CancelOrderHandler(Order order)
strategy.CancelOrderHandler(order)
Dispatch a cancel without the public guards (stop-time teardown); the caller handles the IsCanceled dedup.
public void CancelTargetPosition()
strategy.CancelTargetPosition()
Cancel target position for the strategy's Security and Portfolio.
public void CancelTargetPosition(Security security, Portfolio portfolio)
strategy.CancelTargetPosition(security, portfolio)
Cancel target position for specified security and portfolio.
- security
- Security.
- portfolio
- Portfolio.
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.
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.
public Strategy Clone()
result = strategy.Clone()
Create a copy of the strategy.
Returns: Copy.
public virtual ValueTask<Strategy> CloneAsync(CancellationToken cancellationToken)
result = strategy.CloneAsync(cancellationToken)
Create a copy of the strategy.
- cancellationToken
- CancellationToken
Returns: Copy.
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.
protected virtual ValueTask CopyToAsync(Strategy copy, CancellationToken cancellationToken)
result = strategy.CopyToAsync(copy, cancellationToken)
Copy settings into .
- copy
- Strategy
- cancellationToken
- CancellationToken
Returns: ValueTask
protected IChartArea CreateChartArea()
result = strategy.CreateChartArea()
Create chart area.
Returns: IChartArea
protected virtual Strategy CreateClone()
result = strategy.CreateClone()
Create clone object (non-initialized).
Returns: Strategy
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.
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
protected override void DisposeManaged()
strategy.DisposeManaged()
Disposes the managed resources. Override this method to add custom clean up of managed resources.
protected IChartCandleElement DrawCandles(IChartArea area, Subscription subscription)
result = strategy.DrawCandles(area, subscription)
Draw candles on chart.
- area
- IChartArea
- subscription
- Subscription
Returns: IChartCandleElement
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
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
public void DrawOrderBook(Subscription subscription, IOrderBookSource source, IOrderBookMessage book)
strategy.DrawOrderBook(subscription, source, book)
Draw order book.
- subscription
- Subscription
- source
- IOrderBookSource
- book
- IOrderBookMessage
public void DrawOrderBookOrder(Subscription subscription, IOrderBookSource source, Order order)
strategy.DrawOrderBookOrder(subscription, source, order)
Draw order book order.
- subscription
- Subscription
- source
- IOrderBookSource
- order
- Order.
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.
protected IChartOrderElement DrawOrders(IChartArea area)
result = strategy.DrawOrders(area)
Draw orders on chart.
- area
- IChartArea
Returns: IChartOrderElement
protected IChartTradeElement DrawOwnTrades(IChartArea area)
result = strategy.DrawOwnTrades(area)
Draw trades on chart.
- area
- IChartArea
Returns: IChartTradeElement
public void EditOrder(Order order, Order changes)
strategy.EditOrder(order, changes)
Edit an order via the connector.
- order
- Original order.
- changes
- Order changes.
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.
public IAlertNotificationService GetAlertService()
result = strategy.GetAlertService()
To get the IAlertNotificationService associated with the strategy.
Returns: Alert notification service.
public IChart GetChart()
result = strategy.GetChart()
To get the IChart associated with the strategy.
Returns: Chart.
public IOptionDesk GetOptionDesk()
result = strategy.GetOptionDesk()
To get the IOptionDesk associated with the strategy.
Returns: IOptionDesk.
public IOptionPositionChart GetOptionPositionChart()
result = strategy.GetOptionPositionChart()
To get the IOptionPositionChart associated with the strategy.
Returns: IOptionPositionChart.
public virtual IStrategyParam[] GetParameters()
result = strategy.GetParameters()
Get parameters.
Returns: Parameters.
public Portfolio GetPortfolio()
result = strategy.GetPortfolio()
Get Portfolio or throw InvalidOperationException if not present.
Returns: Portfolio
public decimal? GetPositionValue(Security sec, Portfolio pf)
result = strategy.GetPositionValue(sec, pf)
Get position value for specific security and portfolio.
public Security GetSecurity()
result = strategy.GetSecurity()
Get Security or throw InvalidOperationException if not present.
Returns: Security
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.
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.
public decimal? GetTargetPosition()
result = strategy.GetTargetPosition()
Get target position for the strategy's Security and Portfolio.
Returns: Target position, or null if not set.
public virtual IEnumerable<Portfolio> GetWorkingPortfolios()
result = strategy.GetWorkingPortfolios()
Get all portfolios required for strategy.
Returns: Portfolios.
public virtual IEnumerable<ValueTuple<Security, DataType>> GetWorkingSecurities()
result = strategy.GetWorkingSecurities()
Get all securities required for the strategy.
Returns: Securities.
protected void InitStartValues()
strategy.InitStartValues()
Seed the start-of-run values that the statistic parameters and the orders-keep window depend on.
public bool IsFormedAndOnline()
result = strategy.IsFormedAndOnline()
IsFormed and IsOnline.
Returns: Check result.
public bool IsFormedAndOnlineAndAllowTrading(StrategyTradingModes required)
result = strategy.IsFormedAndOnlineAndAllowTrading(required)
IsFormedAndOnline and TradingMode.
- required
- Required action.
Returns: Check result.
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.
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.
public override Task LoadAsync(SettingsStorage storage, CancellationToken cancellationToken)
result = strategy.LoadAsync(storage, cancellationToken)
Load settings.
- storage
- SettingsStorage
- cancellationToken
- CancellationToken
Returns: Task
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.
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).
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.
protected virtual void OnError(Exception error)
strategy.OnError(error)
Processing of error, occurred as result of strategy operation.
- error
- Error.
public ValueTask OnNewMessage(Message msg, CancellationToken ct)
result = strategy.OnNewMessage(msg, ct)
Handle new outgoing message from connector.
protected virtual void OnNewPosition(Position position)
strategy.OnNewPosition(position)
Called when new position appears.
- position
- New position.
public void OnOrderCancelFailReceived(Subscription sub, OrderFail fail)
strategy.OnOrderCancelFailReceived(sub, fail)
Handle order cancellation failure from connector.
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.
public void OnOrderEditFailReceived(Subscription sub, OrderFail fail)
strategy.OnOrderEditFailReceived(sub, fail)
Handle order edit failure from connector.
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.
protected virtual void OnOrderRegistered(Order order)
strategy.OnOrderRegistered(order)
Called when order registered (transitioned from Pending to Active/Done).
- order
- Registered order.
protected virtual void OnOrderRegisterFailed(OrderFail fail)
strategy.OnOrderRegisterFailed(fail)
Called when order registration fails.
- fail
- Order failure info.
public void OnOrderRegisterFailReceived(Subscription sub, OrderFail fail)
strategy.OnOrderRegisterFailReceived(sub, fail)
Handle order registration failure from connector.
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.
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.
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.
protected virtual void OnPositionChanged(Position position)
strategy.OnPositionChanged(position)
Called when position changes.
- position
- Changed position.
protected virtual void OnPositionReceived(Position position)
strategy.OnPositionReceived(position)
Position received.
- position
- Position
public void OnPositionReceived(Subscription sub, Position pos)
strategy.OnPositionReceived(sub, pos)
Handle position received from connector.
protected virtual void OnReseted()
strategy.OnReseted()
The method is called at the strategy reset.
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.
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
protected virtual void OnStateChanged(ProcessStates state)
strategy.OnStateChanged(state)
Called when process state changes.
- state
- New state.
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.
protected virtual void OnStopped()
strategy.OnStopped()
The method is called when the strategy has entered the stopped state.
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.
public void OnTradeReceived(Subscription sub, MyTrade trade)
strategy.OnTradeReceived(sub, trade)
Handle trade received from connector.
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.
public void Prepare()
strategy.Prepare()
Prepare data for report generation. Call this before accessing any data to ensure all values are up-to-date.
protected override void RaiseLog(LogMessage message)
strategy.RaiseLog(message)
To call the event Log.
- message
- A debug message.
public void RaiseParametersChanged(string name)
strategy.RaiseParametersChanged(name)
Raise the parameters-changed notification for the parameter with the specified name.
- name
- Parameter name.
public void RegisterOrder(Order order)
strategy.RegisterOrder(order)
Register an order via the connector.
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.
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.
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.
public void Reset()
strategy.Reset()
Reset all state (orders, trades, positions, PnL, subscriptions).
public IConnector SafeGetConnector()
result = strategy.SafeGetConnector()
To get the strategy getting Connector. If it is not initialized, the exception will be discarded.
Returns: Connector.
public void Save(SettingsStorage storage, bool saveStatistics, bool saveSystemParameters)
strategy.Save(storage, saveStatistics, saveSystemParameters)
Save settings.
- storage
- SettingsStorage
- saveStatistics
- KeepStatistics
- saveSystemParameters
- Save system parameters.
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
public override Task SaveAsync(SettingsStorage storage, CancellationToken cancellationToken)
result = strategy.SaveAsync(storage, cancellationToken)
Save settings.
- storage
- SettingsStorage
- cancellationToken
- CancellationToken
Returns: Task
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.
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.
public void SetAlertService(IAlertNotificationService service)
strategy.SetAlertService(service)
To set a IAlertNotificationService for the strategy.
- service
- Alert notification service.
public void SetChart(IChart chart)
strategy.SetChart(chart)
To set a IChart for the strategy.
- chart
- Chart.
public void SetOptionDesk(IOptionDesk desk)
strategy.SetOptionDesk(desk)
To set the IOptionDesk.
- desk
- IOptionDesk.
public void SetOptionPositionChart(IOptionPositionChart chart)
strategy.SetOptionPositionChart(chart)
To set the IOptionPositionChart.
- chart
- IOptionPositionChart.
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.
public void SetTargetPosition(decimal target)
strategy.SetTargetPosition(target)
Set target position for the strategy's Security and Portfolio.
- target
- Target position value.
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.
public ValueTask StartAsync(CancellationToken cancellationToken)
result = strategy.StartAsync(cancellationToken)
Start the strategy.
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.
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
public void Stop(Exception error)
strategy.Stop(error)
Stop the strategy because of the specified error.
- error
- Error.
public ValueTask StopAsync(CancellationToken cancellationToken)
result = strategy.StopAsync(cancellationToken)
Stop the strategy.
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.
public void Subscribe(Subscription subscription)
strategy.Subscribe(subscription)
Subscribe.
- subscription
- Subscription.
protected ISubscriptionHandler<ICandleMessage> SubscribeCandles(Subscription subscription)
result = strategy.SubscribeCandles(subscription)
Subscribe to candles.
- subscription
- Subscription
Returns: ISubscriptionHandler
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
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
protected ISubscriptionHandler<Level1ChangeMessage> SubscribeLevel1(Subscription subscription)
result = strategy.SubscribeLevel1(subscription)
Subscribe to Level1.
- subscription
- Subscription
Returns: ISubscriptionHandler
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
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
protected ISubscriptionHandler<IOrderBookMessage> SubscribeOrderBook(Subscription subscription)
result = strategy.SubscribeOrderBook(subscription)
Subscribe to MarketDepth.
- subscription
- Subscription
Returns: ISubscriptionHandler
protected ISubscriptionHandler<ITickTradeMessage> SubscribeTicks(Subscription subscription)
result = strategy.SubscribeTicks(subscription)
Subscribe to Ticks.
- subscription
- Subscription
Returns: ISubscriptionHandler
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
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.
private Subscription ToSubscription<TLookupMessage>()
result = strategy.ToSubscription()
Build a global lookup subscription stamped with this strategy's identifier.
Returns: Subscription.
public bool TryAddMyTrade(MyTrade trade)
result = strategy.TryAddMyTrade(trade)
Try add own trade.
- trade
- MyTrade
Returns: Operation result.
public void UnSubscribe(Subscription subscription)
strategy.UnSubscribe(subscription)
Unsubscribe.
- subscription
- Subscription.
Events
public event Action<Subscription, ExchangeBoard> BoardReceived
strategy.BoardReceived += handler
Board value received.
public event Action<Subscription, ICandleMessage> CandleReceived
strategy.CandleReceived += handler
Candle value received.
public event Action CommissionChanged
strategy.CommissionChanged += handler
Commission changed event.
public event Action ConnectorChanged
strategy.ConnectorChanged += handler
Connector changed event.
public event Action<Subscription, DataType> DataTypeReceived
strategy.DataTypeReceived += handler
Data type value received.
public event Action<Strategy> IsOnlineChanged
strategy.IsOnlineChanged += handler
Online state changed.
public event Action LatencyChanged
strategy.LatencyChanged += handler
Latency changed event.
public event Action<Subscription, Level1ChangeMessage> Level1Received
strategy.Level1Received += handler
Level1 value received.
public event Action<MyTrade> NewMyTrade
strategy.NewMyTrade += handler
The event of new own trade occurring.
public event Action<Subscription, News> NewsReceived
strategy.NewsReceived += handler
News value received.
public event Action<Subscription, IOrderBookSource, IOrderBookMessage> OrderBookDrawing
strategy.OrderBookDrawing += handler
IOrderBookMessage).
public event Action<Subscription, IOrderBookSource, Order> OrderBookDrawingOrder
strategy.OrderBookDrawingOrder += handler
Order).
public event Action<Subscription, IOrderBookSource, OrderFail> OrderBookDrawingOrderFail
strategy.OrderBookDrawingOrderFail += handler
OrderFail).
public event Action<Subscription, IOrderBookMessage> OrderBookReceived
strategy.OrderBookReceived += handler
Order book value received.
public event Action<OrderFail> OrderCancelFailed
strategy.OrderCancelFailed += handler
Order cancellation failed.
public event Action<Subscription, OrderFail> OrderCancelFailReceived
strategy.OrderCancelFailReceived += handler
Order cancel failure.
public event Action<Order> OrderCanceling
strategy.OrderCanceling += handler
Order is about to be canceled.
public event Action<Order> OrderChanged
strategy.OrderChanged += handler
The event of order change.
public event Action<long, Order> OrderEdited
strategy.OrderEdited += handler
Order edited.
public event Action<long, OrderFail> OrderEditFailed
strategy.OrderEditFailed += handler
Order edit failed.
public event Action<Subscription, OrderFail> OrderEditFailReceived
strategy.OrderEditFailReceived += handler
Order edit failure.
public event Action<Subscription, IOrderLogMessage> OrderLogReceived
strategy.OrderLogReceived += handler
Order log value received.
public event Action<Subscription, Order> OrderReceived
strategy.OrderReceived += handler
Order value received.
public event Action<Order> OrderRegistered
strategy.OrderRegistered += handler
The event of order successful registration.
public event Action<OrderFail> OrderRegisterFailed
strategy.OrderRegisterFailed += handler
Order registration failed.
public event Action<Subscription, OrderFail> OrderRegisterFailReceived
strategy.OrderRegisterFailReceived += handler
Order registration failure.
public event Action<Order> OrderRegistering
strategy.OrderRegistering += handler
Order is about to be registered.
public event Action<Order, Order> OrderReRegistering
strategy.OrderReRegistering += handler
Order is about to be re-registered.
public event Action<Subscription, MyTrade> OwnTradeReceived
strategy.OwnTradeReceived += handler
Own trade value received.
public event Action ParametersChanged
strategy.ParametersChanged += handler
Strategy parameters changed event.
public event Action<Subscription> PnLReceived
strategy.PnLReceived += handler
PnL received event.
public event Action<Subscription, Portfolio, DateTime, decimal, decimal?, decimal?> PnLReceived2
strategy.PnLReceived2 += handler
PnL received event.
public event Action<Subscription, Portfolio> PortfolioReceived
strategy.PortfolioReceived += handler
Portfolio value received.
public event Action PositionChanged
strategy.PositionChanged += handler
Position changed.
public event Action<Subscription, Position> PositionReceived
strategy.PositionReceived += handler
Position value received.
public event Action<IStrategy> ProcessStateChanged
strategy.ProcessStateChanged += handler
ProcessState change event.
public event PropertyChangedEventHandler PropertyChanged
strategy.PropertyChanged += handler
PropertyChanged.
public event Action<Subscription, Security> SecurityReceived
strategy.SecurityReceived += handler
Security value received.
public event Action SlippageChanged
strategy.SlippageChanged += handler
Slippage changed event.
public event Action<Subscription, Exception, bool> SubscriptionFailed
strategy.SubscriptionFailed += handler
Subscription failed.
public event Action<Subscription> SubscriptionOnline
strategy.SubscriptionOnline += handler
Subscription is online.
public event Action<Subscription, object> SubscriptionReceived
strategy.SubscriptionReceived += handler
Subscription value received.
public event Action<Subscription> SubscriptionStarted
strategy.SubscriptionStarted += handler
Subscription is started.
public event Action<Subscription, Exception> SubscriptionStopped
strategy.SubscriptionStopped += handler
Subscription is stopped.
public event Action<Subscription, ITickTradeMessage> TickTradeReceived
strategy.TickTradeReceived += handler
Tick trade value received.