Strategy

StockSharp.Algo.Strategies

The base class for all trade strategies.

Hereda de: BaseLogReceiver

Implementa: INotifyPropertyChangedEx, INotifyPropertyChanged, IMarketRuleContainer, ILogReceiver, ILogSource, IDisposable, ICloneable<Strategy>, ICloneable, IMarketDataProvider, ISubscriptionProvider, ISecurityProvider, ISecurityMessageProvider, ITransactionProvider, IScheduledTask, ICustomTypeDescriptor, ITimeProvider, IPortfolioProvider, IPositionProvider, IReportSource

Constructores

Strategy()

Initializes a new instance of the Strategy.

Propiedades

AggregationInterval : TimeSpan

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 : bool

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

ChildStrategies : INotifyList<Strategy>

Subsidiary trade strategies.

CommentMode : StrategyCommentModes

Set Comment by Name or Id.

Commission : decimal?

Total commission.

Connector : Connector

Connection to the trading system.

CurrentTime : DateTime

Current UTC time.

DisposeOnStop : bool

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

Environment : SettingsStorage

Strategy environment parameters.

ErrorState : LogLevels

The state of an error.

HideSecurityAndPortfolioParameters : bool

Make Security and Portfolio as non-browsable.

HistoryCalculated : TimeSpan?

Calculated from code version of HistorySize.

HistorySize : TimeSpan?

History to initialize the strategy on Live trading.

Id : Guid

Strategy ID.

Indicators : INotifyList<IIndicator>

All indicators used in strategy. Uses in default implementation of IsFormed.

IndicatorSource : Level1Fields?

Default source for indicators when Source is not set.

IsBacktesting : bool

Determines Connector is HistoryEmulationConnector.

IsFormed : bool

Strategy fully formed.

IsOnline : bool

True means that strategy is started and all of its subscriptions are in online state.

IsRulesSuspended : bool

Is rules execution suspended.

KeepStatistics : bool

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

LastError : Exception

The last error that caused the strategy to stop.

Latency : TimeSpan?

Total latency.

LogLevel : LogLevels

The level to perform this rule logging.

MaxOrdersBeforeAggregation : int

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

MaxTradesBeforeAggregation : int

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

MyTrades : IEnumerable<MyTrade>

Trades, matched during the strategy operation.

Name : string

Strategy name.

NameGenerator : StrategyNameGenerator

The generator of strategy name.

OrderBookSources : IEnumerable<IOrderBookSource>

All possible IOrderBookMessage sources that can be received via OrderBookDrawing.

OrderLookup : Subscription

Get global subscription on Order lookup. Can be .

Orders : IEnumerable<Order>

Orders, registered within the strategy framework.

OrdersKeepTime : TimeSpan

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

Parameters : StrategyParameterDictionary

Strategy parameters.

PnL : decimal

The aggregate value of profit-loss without accounting commission Commission.

PnLManager : IPnLManager

The profit-loss manager.

Portfolio : Portfolio

Portfolio.

PortfolioLookup : Subscription

Get global subscription on Portfolio lookup. Can be .

PortfolioProvider : IPortfolioProvider

IPortfolioProvider

Position : decimal

The position aggregate value.

Positions : IEnumerable<Position>

The list of positions.

ProcessState : ProcessStates

The operation state.

ReportSource : ReportSource

Report data source with aggregation support.

RiskFreeRate : decimal

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

RiskManager : IRiskManager

The risks control manager.

RiskRules : IEnumerable<IRiskRule>

The risk rules.

Rules : IMarketRuleList

The list of commission calculating rules.

Security : Security

Security.

Slippage : decimal?

Total slippage.

StartedTime : DateTime

Strategy start time.

StatisticManager : IStatisticManager

The statistics manager.

TargetAlgoFactory : Func<Sides, decimal, IPositionModifyAlgo>

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

TargetPositionManager : PositionTargetManager

Target position manager.

TotalWorkingTime : TimeSpan

The total time of strategy operation less time periods, when strategy was stopped.

UnrealizedPnLInterval : TimeSpan

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

UnsubscribeOnStop : bool

Unsubscribe all active subscription while strategy become stopping.

Volume : decimal

Operational volume.

WaitAllTrades : bool

Stop strategy only after getting all trades by registered orders.

WaitRulesOnStop : bool

Wait Rules to finish before strategy become into Stopped state.

WorkingTime : WorkingTime

The time boundary, within which candles for give series shall be translated.

Métodos

Alert(AlertNotifications, string)

Send alert notification with strategy name as caption.

type
Alert type.
message
Alert text.
Alert(AlertNotifications, string, string)

Send alert notification.

type
Alert type.
caption
Signal header.
message
Alert text.
AlertLog(string)

Send log alert notification.

message
Alert text.
AlertPopup(string)

Send popup alert notification.

message
Alert text.
AlertSound(string)

Send sound alert notification.

message
Alert text.
ApplyCommand(CommandMessage)

Apply incoming command.

cmdMsg
The message contains information about command to change state.
BuyLimit(decimal, decimal?, Security) : Order

To create the initialized order object for buy.

price
Price.
volume
The volume. If value is passed, then Volume value is used.
security
The security. If value is passed, then Security value is used.

Devuelve: The initialized order object.

BuyMarket(decimal?, Security) : Order

To create initialized object of buy order at market price.

volume
The volume. If value is passed, then Volume value is used.
security
The security. If value is passed, then Security value is used.

Devuelve: The initialized order object.

CanAttach(Order) : bool

Determines the specified order can be owned by the strategy.

order
Order.

Devuelve: Check result.

CancelActiveOrders(bool?, Portfolio, Sides?, ExchangeBoard, Security, SecurityTypes?, long?)

To cancel all active orders (to stop and regular).

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.
CancelOrder(Order)

Cancel the order.

order
The order which should be canceled.
CancelTargetPosition(Security, Portfolio)

Cancel target position for specified security and portfolio.

security
Security.
portfolio
Portfolio.
CancelTargetPosition()

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

CanTrade(Security, Portfolio, Sides, decimal, string) : bool

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.

Devuelve: True if trading is allowed.

Clone() : Strategy

Creates a deep copy of a DataSeries

ClosePosition(Security, Portfolio) : Order

To close open position by market (to register the order of the type Market).

security
Security. If not passed the value from Security will be obtain.
portfolio
Portfolio. If not passed the value from Portfolio will be obtain.

Devuelve: The initialized order object.

CopyTo(Strategy)

Copy settings into .

copy
Strategy
CreateChartArea() : IChartArea

Create chart area.

Devuelve: IChartArea

CreateClone() : Strategy

Create clone object (non-initialized).

Devuelve: Strategy

CreateOrder(Sides, decimal, decimal?) : Order

To create the initialized order object.

side
Order side.
price
The price. If value is passed, the order is registered at market price.
volume
The volume. If value is passed, then Volume value is used.

Devuelve: The initialized order object.

CreateTimer(TimeSpan, Action) : ITimerHandler

Create a timer that executes callback at specified intervals.

interval
Timer interval.
callback
Callback to execute.

Devuelve: ITimerHandler

DisposeManaged()

Release resources.

DrawCandles(IChartArea, Subscription) : IChartCandleElement

Draw candles on chart.

area
IChartArea
subscription
Subscription

Devuelve: IChartCandleElement

DrawCandles``1(IChartArea, ISubscriptionHandler<T>)

Draw candles on chart.

area
IChartArea
subscription
SubscriptionHandler

Devuelve: IChartCandleElement

DrawIndicator(IChartArea, IIndicator, Color?, Color?) : IChartIndicatorElement

Draw indicator on chart.

area
IChartArea
indicator
IIndicator
color
Color
additionalColor
AdditionalColor

Devuelve: IChartIndicatorElement

DrawOrderBook(Subscription, IOrderBookSource, IOrderBookMessage)

Draw IOrderBookMessage.

subscription
Subscription
source
IOrderBookSource
book
IOrderBookMessage
DrawOrderBookOrder(Subscription, IOrderBookSource, Order)

Draw order book order.

subscription
Subscription
source
IOrderBookSource
order
Order.
DrawOrderBookOrderFail(Subscription, IOrderBookSource, OrderFail)

Draw order book order fail.

subscription
Subscription
source
IOrderBookSource
fail
Order fail.
DrawOrders(IChartArea) : IChartOrderElement

Draw orders on chart.

area
IChartArea

Devuelve: IChartOrderElement

DrawOwnTrades(IChartArea) : IChartTradeElement

Draw trades on chart.

area
IChartArea

Devuelve: IChartTradeElement

EditOrder(Order, Order)

Edit the order.

order
Order.
changes
Order changes.
EnsureOrderMetadata(Order, DateTime)

Ensures the order has metadata required by strategy surfaces.

order
Order.
fallbackTime
Fallback time.
GetAlertService() : IAlertNotificationService

To get the IAlertNotificationService associated with the passed strategy.

Devuelve: Alert notification service.

GetChart() : IChart

To get the IChart associated with the passed strategy.

Devuelve: Chart.

GetOptionDesk() : IOptionDesk

To get the IOptionDesk.

Devuelve: IOptionDesk.

GetOptionPositionChart() : IOptionPositionChart

To get the IOptionPositionChart associated with the passed strategy.

Devuelve: Chart.

GetParameters() : IStrategyParam[]

Get parameters.

Devuelve: Parameters.

GetPortfolio() : Portfolio

Get Portfolio or throw InvalidOperationException if not present.

Devuelve: Portfolio

GetPositionValue(Security, Portfolio) : decimal?

Get position.

security
Security.
portfolio
Portfolio.

Devuelve: Position.

GetSecurity() : Security

Get Security or throw InvalidOperationException if not present.

Devuelve: Security

GetSecurityValue``1(Level1Fields)

To get market data value for the strategy instrument.

field
Market-data field.

Devuelve: The field value. If no data, the will be returned.

GetStatValue``2(T)

Get the value of a statistic parameter by its type.

fallback
Fallback value if the parameter is not found.

Devuelve: The parameter value or .

GetTargetPosition(Security, Portfolio) : decimal?

Get target position for specified security and portfolio.

security
Security.
portfolio
Portfolio.

Devuelve: Target position, or null if not set.

GetTargetPosition() : decimal?

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

Devuelve: Target position, or null if not set.

GetWorkingPortfolios() : IEnumerable<Portfolio>

Get all portfolios required for strategy.

Devuelve: Portfolios.

GetWorkingSecurities() : IEnumerable<ValueTuple<Security, DataType>>

Get all securities required for strategy.

Devuelve: Securities.

InitStartValues()

Init.

IsFormedAndOnline() : bool

IsFormed and IsOnline.

Devuelve: Check result.

IsFormedAndOnlineAndAllowTrading(StrategyTradingModes) : bool

IsFormedAndOnline and TradingMode.

required
Required action.

Devuelve: Check result.

IsOrderEditable(Order) : bool?

Determines the specified order can be edited by Order).

order
Order.

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

IsOrderReplaceable(Order) : bool?

Determines the specified order can be replaced by Order).

order
Order.

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

Load(SettingsStorage)

Load settings.

storage
Settings storage.
LookupByIdAsync(SecurityId, CancellationToken) : ValueTask<Security>

To get the instrument by the identifier.

id
Security ID.
cancellationToken
CancellationToken

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

OnError(Strategy, Exception)

Processing of error, occurred as result of strategy operation.

strategy
Strategy.
error
Error.
OnOrderReceived(Order)

Order received.

order
Order
OnOrderRegistered(Order)

To call the event OrderRegistered.

order
Order.
OnOrderRegisterFailed(OrderFail, bool)

The method, called at strategy order registration error.

fail
Error registering order.
calcRisk
Invoke risk manager.
OnOrderRegistering(Order)

To call the event OrderRegistering.

order
Order.
OnOrderReRegistering(Order, Order)

To call the event OrderReRegistering.

oldOrder
Cancelling order.
newOrder
New order to register.
OnOwnTradeReceived(MyTrade)

Own trade received.

trade
MyTrade
OnPositionReceived(Position)

Position received.

position
Position
OnReseted()

It is called from the Reset method.

OnStarted(DateTimeOffset)

The method is called when the Start method has been called and the ProcessState state has been taken the Started value.

OnStarted()

The method is called when the Start method has been called and the ProcessState state has been taken the Started value.

OnStarted2(DateTime)

The method is called when the Start method has been called and the ProcessState state has been taken the Started value.

OnStopped()

The method is called when the ProcessState process state has been taken the Stopped value.

OnStopping()

The method is called when the ProcessState process state has been taken the Stopping value.

Param``1(string, T)

Initializes a new instance of the StrategyParam.

id
Parameter identifier.
initialValue
The initial value.

Devuelve: The strategy parameter.

Prepare()

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

ProcessOrder(Order, bool)

To add the order to the strategy.

order
Order.
isChanging
The order came from the change event.
RaiseLog(LogMessage)
RaiseParametersChanged(string)

To call events ParametersChanged and PropertyChanged.

name
Parameter name.
RaiseProcessStateChanged(Strategy)

To call the event ProcessStateChanged.

strategy
Strategy.
RaiseReseted()

To call the event Reseted.

RegisterOrder(Order)

Register new order.

order
Registration details.
ReRegisterOrder(Order, Order)

Reregister the order.

oldOrder
Cancelling order.
newOrder
New order to register.
Reset()

To re-initialize the trade algorithm. It is called after initialization of the strategy object and loading stored parameters.

SafeGetConnector() : IConnector

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

Devuelve: Connector.

Save(SettingsStorage, bool, bool)

Save settings.

storage
SettingsStorage
saveStatistics
KeepStatistics
saveSystemParameters
Save system parameters.
Save(SettingsStorage)

Save settings.

storage
Settings storage.
SellLimit(decimal, decimal?, Security) : Order

To create the initialized order object for sell.

price
Price.
volume
The volume. If value is passed, then Volume value is used.
security
The security. If value is passed, then Security value is used.

Devuelve: The initialized order object.

SellMarket(decimal?, Security) : Order

To create the initialized order object of sell order at market price.

volume
The volume. If value is passed, then Volume value is used.
security
The security. If value is passed, then Security value is used.

Devuelve: The initialized order object.

SetAlertService(IAlertNotificationService)

To set a IAlertNotificationService for the strategy.

service
Alert notification service.
SetChart(IChart)

To set a IChart for the strategy.

chart
Chart.
SetOptionDesk(IOptionDesk)

To set the IOptionDesk.

desk
IOptionDesk.
SetOptionPositionChart(IOptionPositionChart)

To set a IChart for the strategy.

chart
Chart.
SetPositionValue(Security, Portfolio, decimal, DateTime)

Set position.

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

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

target
Target position value.
SetTargetPosition(Security, Portfolio, decimal)

Set target position for specified security and portfolio.

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

To start the trade algorithm.

StartProtection(Unit, Unit, bool, TimeSpan?, TimeSpan?, bool, bool)

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(TimeSpan, Action) : ITimerHandler

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

interval
Timer interval.
callback
Callback to execute.

Devuelve: ITimerHandler

Stop()

To stop the trade algorithm.

Stop(Exception)

To stop the trade algorithm by error reason.

error
Error.
Subscribe(Subscription)

Subscribe.

subscription
Subscription.
SubscribeCandles(Subscription) : ISubscriptionHandler<ICandleMessage>

Subscribe to candles.

subscription
Subscription

Devuelve: SubscriptionHandler

SubscribeCandles(DataType, bool, Security) : ISubscriptionHandler<ICandleMessage>

Subscribe to candles.

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

Devuelve: SubscriptionHandler

SubscribeCandles(TimeSpan, bool, Security) : ISubscriptionHandler<ICandleMessage>

Subscribe to candles.

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

Devuelve: SubscriptionHandler

SubscribeLevel1(Subscription) : ISubscriptionHandler<Level1ChangeMessage>

Subscribe to Level1.

subscription
Subscription

Devuelve: SubscriptionHandler

SubscribeLevel1(Security) : ISubscriptionHandler<Level1ChangeMessage>

Subscribe to Level1.

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

Devuelve: SubscriptionHandler

SubscribeOrderBook(Subscription) : ISubscriptionHandler<IOrderBookMessage>

Subscribe to MarketDepth.

subscription
Subscription

Devuelve: SubscriptionHandler

SubscribeOrderBook(Security) : ISubscriptionHandler<IOrderBookMessage>

Subscribe to MarketDepth.

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

Devuelve: SubscriptionHandler

SubscribeTicks(Subscription) : ISubscriptionHandler<ITickTradeMessage>

Subscribe to Ticks.

subscription
Subscription

Devuelve: SubscriptionHandler

SubscribeTicks(Security) : ISubscriptionHandler<ITickTradeMessage>

Subscribe to Ticks.

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

Devuelve: SubscriptionHandler

ToReportValue(object) : object

To convert parameter value to report value.

value
The parameter value.

Devuelve: The report value.

TryAddMyTrade(MyTrade) : bool

Try add own trade.

trade
MyTrade

Devuelve: Operation result.

UnSubscribe(Subscription)

Unsubscribe.

subscription
Subscription.

Eventos

BoardReceived : Action<Subscription, ExchangeBoard>

ExchangeBoard received.

CandleReceived : Action<Subscription, ICandleMessage>

ICandleMessage received.

CommissionChanged : Action

Commission change event.

ConnectorChanged : Action

The event of strategy connection change.

CurrentTimeChanged : Action<TimeSpan>

Server time changed CurrentTime. It passed the time difference since the last call of the event. The first time the event passes the value Zero.

DataTypeReceived : Action<Subscription, DataType>

DataType received.

Error : Action<Strategy, Exception>

The event of error occurrence in the strategy.

IsOnlineChanged : Action<Strategy>

The event of strategy online state change.

LatencyChanged : Action

Latency change event.

Level1Received : Action<Subscription, Level1ChangeMessage>

Level1ChangeMessage received.

NewMyTrade : Action<MyTrade>

Own trade received.

NewsReceived : Action<Subscription, News>

News received.

OrderBookReceived : Action<Subscription, IOrderBookMessage>

IOrderBookMessage received.

OrderCancelFailed : Action<OrderFail>

Order cancellation error event.

OrderCancelFailReceived : Action<Subscription, OrderFail>

OrderFail cancellation event.

OrderCanceling : Action<Order>

The event of sending order for cancelling.

OrderChanged : Action<Order>

Order changed (cancelled, matched).

OrderEdited : Action<long, Order>

Order) success result event.

OrderEditFailed : Action<long, OrderFail>

Order) error result event.

OrderEditFailReceived : Action<Subscription, OrderFail>

OrderFail edition event.

OrderLogReceived : Action<Subscription, IOrderLogMessage>

IOrderLogMessage received.

OrderReceived : Action<Subscription, Order>

Order received.

OrderRegistered : Action<Order>

The event of order successful registration.

OrderRegisterFailed : Action<OrderFail>

Order registration error event.

OrderRegisterFailReceived : Action<Subscription, OrderFail>

OrderFail registration event.

OrderRegistering : Action<Order>

The event of sending order for registration.

OrderReRegistering : Action<Order, Order>

The event of sending order for re-registration.

ParametersChanged : Action

Parameters change event.

PnLChanged : Action

PnL change event.

PnLReceived : Action<Subscription>

PnL change event.

PositionChanged : Action

Position change event.

PositionReceived : Action<Subscription, Position>

Position received.

ProcessStateChanged : Action<Strategy>

ProcessState change event.

PropertyChanged : PropertyChangedEventHandler

The diagram element properties value change event.

Reseted : Action

The event of the strategy re-initialization.

SecurityReceived : Action<Subscription, Security>

Security received.

SlippageChanged : Action

Slippage change event.

SubscriptionFailed : Action<Subscription, Exception, bool>

Subscription is failed.

SubscriptionOnline : Action<Subscription>

Subscription is online.

SubscriptionStarted : Action<Subscription>

Subscription is started.

SubscriptionStopped : Action<Subscription, Exception>

Subscription is stopped.

TickTradeReceived : Action<Subscription, ITickTradeMessage>

ITickTradeMessage received.