Strategy
The base class for all trade strategies.
继承自: BaseLogReceiver
实现: INotifyPropertyChangedEx, INotifyPropertyChanged, IMarketRuleContainer, ILogReceiver, ILogSource, IDisposable, ICloneable<Strategy>, ICloneable, IMarketDataProvider, ISubscriptionProvider, ISecurityProvider, ISecurityMessageProvider, ITransactionProvider, IScheduledTask, ICustomTypeDescriptor, ITimeProvider, IPortfolioProvider, IPositionProvider, IReportSource
构造函数
Strategy()
Initializes a new instance of the Strategy.
属性
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.
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.
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.
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.
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.
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.
PnLManager : IPnLManager
The profit-loss manager.
PortfolioLookup : Subscription
Get global subscription on Portfolio lookup. Can be .
PortfolioProvider : IPortfolioProvider
IPortfolioProvider
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.
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.
TradingMode : StrategyTradingModes
Allow trading.
UnrealizedPnLInterval : TimeSpan
The interval for unrealized profit recalculation. The default value is 1 minute.
UnsubscribeOnStop : bool
Unsubscribe all active subscription while strategy become stopping.
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.
方法
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.
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.
返回值: 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.
返回值: The initialized order object.
CanAttach(Order) : bool
Determines the specified order can be owned by the strategy.
- order
- Order.
返回值: 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.
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.
返回值: True if trading is allowed.
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.
返回值: The initialized order object.
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.
返回值: The initialized order object.
CreateTimer(TimeSpan, Action) : ITimerHandler
Create a timer that executes callback at specified intervals.
- interval
- Timer interval.
- callback
- Callback to execute.
返回值: ITimerHandler
DisposeManaged()
Release resources.
DrawCandles(IChartArea, Subscription) : IChartCandleElement
Draw candles on chart.
- area
- IChartArea
- subscription
- Subscription
返回值: IChartCandleElement
DrawCandles``1(IChartArea, ISubscriptionHandler<T>)
Draw candles on chart.
- area
- IChartArea
- subscription
- SubscriptionHandler
返回值: IChartCandleElement
DrawIndicator(IChartArea, IIndicator, Color?, Color?) : IChartIndicatorElement
Draw indicator on chart.
- area
- IChartArea
- indicator
- IIndicator
- color
- Color
- additionalColor
- AdditionalColor
返回值: 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
返回值: IChartOrderElement
DrawOwnTrades(IChartArea) : IChartTradeElement
Draw trades on chart.
- area
- IChartArea
返回值: IChartTradeElement
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.
返回值: Alert notification service.
GetOptionPositionChart() : IOptionPositionChart
To get the IOptionPositionChart associated with the passed strategy.
返回值: Chart.
GetPortfolio() : Portfolio
Get Portfolio or throw InvalidOperationException if not present.
返回值: Portfolio
GetPositionValue(Security, Portfolio) : decimal?
Get position.
- security
- Security.
- portfolio
- Portfolio.
返回值: Position.
GetSecurity() : Security
Get Security or throw InvalidOperationException if not present.
返回值: Security
GetSecurityValue``1(Level1Fields)
To get market data value for the strategy instrument.
- field
- Market-data field.
返回值: 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.
返回值: The parameter value or .
GetTargetPosition(Security, Portfolio) : decimal?
Get target position for specified security and portfolio.
- security
- Security.
- portfolio
- Portfolio.
返回值: Target position, or null if not set.
GetTargetPosition() : decimal?
Get target position for the strategy's Security and Portfolio.
返回值: Target position, or null if not set.
GetWorkingPortfolios() : IEnumerable<Portfolio>
Get all portfolios required for strategy.
返回值: Portfolios.
GetWorkingSecurities() : IEnumerable<ValueTuple<Security, DataType>>
Get all securities required for strategy.
返回值: Securities.
InitStartValues()
Init.
IsFormedAndOnlineAndAllowTrading(StrategyTradingModes) : bool
IsFormedAndOnline and TradingMode.
- required
- Required action.
返回值: Check result.
IsOrderEditable(Order) : bool?
Determines the specified order can be edited by Order).
- order
- Order.
返回值: 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.
返回值: if the order is replaceable, order cannot be replaced, means no information.
LookupByIdAsync(SecurityId, CancellationToken) : ValueTask<Security>
To get the instrument by the identifier.
- id
- Security ID.
- cancellationToken
- CancellationToken
返回值: 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.
OnOrderRegisterFailed(OrderFail, bool)
The method, called at strategy order registration error.
- fail
- Error registering order.
- calcRisk
- Invoke risk manager.
OnOrderReRegistering(Order, Order)
To call the event OrderReRegistering.
- oldOrder
- Cancelling order.
- newOrder
- New order to register.
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.
返回值: 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.
RaiseReseted()
To call the event Reseted.
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.
返回值: Connector.
Save(SettingsStorage, bool, bool)
Save settings.
- storage
- SettingsStorage
- saveStatistics
- KeepStatistics
- saveSystemParameters
- Save system parameters.
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.
返回值: 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.
返回值: The initialized order object.
SetAlertService(IAlertNotificationService)
To set a IAlertNotificationService for the strategy.
- service
- Alert notification service.
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.
返回值: ITimerHandler
Stop()
To stop the trade algorithm.
SubscribeCandles(Subscription) : ISubscriptionHandler<ICandleMessage>
Subscribe to candles.
- subscription
- Subscription
返回值: 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.
返回值: 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.
返回值: SubscriptionHandler
SubscribeLevel1(Subscription) : ISubscriptionHandler<Level1ChangeMessage>
Subscribe to Level1.
- subscription
- Subscription
返回值: SubscriptionHandler
SubscribeLevel1(Security) : ISubscriptionHandler<Level1ChangeMessage>
Subscribe to Level1.
- security
- Security. If security is not passed, then Security value is used.
返回值: SubscriptionHandler
SubscribeOrderBook(Subscription) : ISubscriptionHandler<IOrderBookMessage>
Subscribe to MarketDepth.
- subscription
- Subscription
返回值: SubscriptionHandler
SubscribeOrderBook(Security) : ISubscriptionHandler<IOrderBookMessage>
Subscribe to MarketDepth.
- security
- Security. If security is not passed, then Security value is used.
返回值: SubscriptionHandler
SubscribeTicks(Subscription) : ISubscriptionHandler<ITickTradeMessage>
Subscribe to Ticks.
- subscription
- Subscription
返回值: SubscriptionHandler
SubscribeTicks(Security) : ISubscriptionHandler<ITickTradeMessage>
Subscribe to Ticks.
- security
- Security. If security is not passed, then Security value is used.
返回值: SubscriptionHandler
ToReportValue(object) : object
To convert parameter value to report value.
- value
- The parameter value.
返回值: The report value.
事件
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.
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.
OrderBookDrawing : Action<Subscription, IOrderBookSource, IOrderBookMessage>
IOrderBookMessage).
OrderBookDrawingOrder : Action<Subscription, IOrderBookSource, Order>
Order).
OrderBookDrawingOrderFail : Action<Subscription, IOrderBookSource, OrderFail>
OrderFail).
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.
OwnTradeReceived : Action<Subscription, MyTrade>
MyTrade received.
ParametersChanged : Action
Parameters change event.
PnLChanged : Action
PnL change event.
PnLReceived : Action<Subscription>
PnL change event.
PnLReceived2 : Action<Subscription, Portfolio, DateTime, decimal, decimal?, decimal?>
PnL change event.
PortfolioReceived : Action<Subscription, Portfolio>
Portfolio received.
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.
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.
SubscriptionReceived : Action<Subscription, object>
Value received.
SubscriptionStarted : Action<Subscription>
Subscription is started.
SubscriptionStopped : Action<Subscription, Exception>
Subscription is stopped.
TickTradeReceived : Action<Subscription, ITickTradeMessage>
ITickTradeMessage received.