Table of Contents

Class BaseConnector<TMessage, TPortfolioKey, TSecurityKey, TSecurityPositionManager>

Namespace
ATAS.DataFeedsCore
Assembly
ATAS.DataFeedsCore.dll

The base class of a connector. It implements the connection lifecycle of IDataFeedConnector (connect, automatic reconnection, connect and disconnect timeouts), keeps the securities, portfolios, positions, orders and own trades, counts the market data subscriptions and restores them after a reconnect, and tracks the order actions until the broker answers them.
A derived connector implements the transport in the On... methods: OnConnect() (or OnConnectAsync()) reports the outcome with OnConnected() or OnDisconnected(); the market data, search and order requests go to the broker in OnSubscribeMarketData, OnSearchSecurities, OnRegisterOrder(Order) and OnCancelOrder(Order, long). The data received is queued with Enqueue(TMessage), handled in OnProcess(TMessage) on the connector's queue thread and reported with the Process... and Raise... methods, which update the entities and raise the events.

public abstract class BaseConnector<TMessage, TPortfolioKey, TSecurityKey, TSecurityPositionManager> : BaseLoggerSource, IDataFeedConnector, ILoggerSource, ISupportChangePosition, IMarketDataPublisher where TMessage : class where TPortfolioKey : notnull where TSecurityKey : notnull where TSecurityPositionManager : ISecurityPositionManager

Type Parameters

TMessage

The type of the messages processed by the connector's queue.

TPortfolioKey

The connector's key of a portfolio.

TSecurityKey

The connector's key of a security.

TSecurityPositionManager

The type of the managers that calculate the positions.

Inheritance
object
BaseLoggerSource
BaseConnector<TMessage, TPortfolioKey, TSecurityKey, TSecurityPositionManager>
Implements
Derived
Extension Methods

Constructors

BaseConnector()

Initializes the connector; the id generator starts from the milliseconds elapsed since local midnight.

protected BaseConnector()

BaseConnector(long)

Initializes the connector with the initial value of its id generator. The defaults: a SimpleMessageQueue<TMessage>, the market data stream on, ConnectTimeout 60 seconds, DisconnectTimeout 10 seconds, MaxDelistedSecuritiesRatio 5%.

protected BaseConnector(long initialId)

Parameters

initialId long

The initial value of IdGenerator.

Properties

AllowUpdatePositionsPnL

Whether the best bid/ask updates recalculate the open PnL of the positions in the security. Set from the connection settings; true by default.

public bool AllowUpdatePositionsPnL { get; set; }

Property Value

bool

ConnectTimeout

Maximum time a single connect attempt may take before it is aborted. Guards against a remote that accepts the socket but never completes the login/handshake (a half-open connection): without this the connect Task would hang forever and, because ReconnectionTimer only re-arms on a failed attempt, auto-reconnect would wedge permanently. Set to System.TimeSpan.Zero to disable (not recommended). Connectors that legitimately need a longer handshake may raise this value.

Added in ATAS 8.0.15.

public TimeSpan ConnectTimeout { get; set; }

Property Value

TimeSpan

ConnectionState

Current connection state of the connector.

public ConnectionStates ConnectionState { get; }

Property Value

ConnectionStates

DataPath

The folder for the connector's own files (on the platform, a folder per connector type in the connectors data folder), set when the connector is created.

public string DataPath { get; set; }

Property Value

string

DefaultTimeSyncManager

Default ITimeSyncManager to get time difference with NTP server.

public ITimeSyncManager? DefaultTimeSyncManager { get; set; }

Property Value

ITimeSyncManager

DisconnectTimeout

Maximum time a single disconnect attempt may take before it is forced to completion. The disconnect handshake (e.g. waiting for the peer to acknowledge a logout and close the socket) can hang forever against a silent/half-open peer, wedging the connector in the Disconnecting state. On timeout the disconnect is forced so the connector reaches Disconnected. Set to System.TimeSpan.Zero to disable (not recommended).

Added in ATAS 8.0.15.

public TimeSpan DisconnectTimeout { get; set; }

Property Value

TimeSpan

ExchangeInfoProvider

Added in ATAS 8.0.15.

public IConnectorExchangeInfoProvider ExchangeInfoProvider { get; set; }

Property Value

IConnectorExchangeInfoProvider

Factory

Factory used to create Security, Portfolio, and other entity objects.

public IEntityFactory Factory { get; set; }

Property Value

IEntityFactory

HasPendingActions

Whether an order action (register, modify, cancel) has been waiting for the broker's answer for more than a second. The platform asks the user before closing positions while it is true.

public virtual bool HasPendingActions { get; }

Property Value

bool

Remarks

Override to add requests of the connector's own that are waiting for the broker.

HeartbeatTimeout

Interval of the OnSendHeartbeat() calls while connected; System.TimeSpan.Zero (the default) disables them. Passed to the MessageQueue when ConnectAsync() starts it.

public TimeSpan HeartbeatTimeout { get; set; }

Property Value

TimeSpan

Id

Unique id of the connector instance, created with it.

public Guid Id { get; }

Property Value

Guid

IdGenerator

Generates the external ids of the orders and the cancel requests and the ids of the search requests.

protected IIdGenerator IdGenerator { get; }

Property Value

IIdGenerator

IsConnected

Returns true when all connections are established.

public bool IsConnected { get; protected set; }

Property Value

bool

IsFullLicense

License type

public bool IsFullLicense { get; set; }

Property Value

bool

IsSupportedAmericanFutures

Indicates whether the connector supports American futures.

public abstract bool IsSupportedAmericanFutures { get; }

Property Value

bool

IsSupportedAmericanStocks

Indicates whether the connector supports American stocks.

public abstract bool IsSupportedAmericanStocks { get; }

Property Value

bool

IsSupportedCfd

Added in ATAS 8.0.15.

public virtual bool IsSupportedCfd { get; }

Property Value

bool

IsSupportedCrypto

Indicates whether the connector supports crypto instruments.

public virtual bool IsSupportedCrypto { get; }

Property Value

bool

IsSupportedGoFlat

Not in ATAS 8.0.15 yet: available from the next version.

public virtual bool IsSupportedGoFlat { get; }

Property Value

bool

IsSupportedMaxOrderCalculation

Does connector support max order calculation for the instrument
This feature enables percentage slider under the volume input box
Affects CalcMaxOrderVolume(OrderTypes, Security, Portfolio, OrderDirections, decimal?) and CalcOrderCost(OrderTypes, Security, Portfolio, OrderDirections, decimal?, decimal, out object?, bool) methods

public virtual bool IsSupportedMaxOrderCalculation { get; }

Property Value

bool

IsSupportedRussianMarket

Indicates whether the connector supports Russian market instruments.

public abstract bool IsSupportedRussianMarket { get; }

Property Value

bool

IsSupportedServerOCO

Indicates whether the connector supports server-side OCO orders.

public abstract bool IsSupportedServerOCO { get; }

Property Value

bool

IsSupportedServerTime

Does connector supports getting exchange server time.

public virtual bool IsSupportedServerTime { get; }

Property Value

bool

IsSupportedStopOrders

Indicates whether the connector supports stop orders.

public abstract bool IsSupportedStopOrders { get; }

Property Value

bool

IsSupportedTradingFunctions

Indicates whether the connector supports trading functions.

public abstract bool IsSupportedTradingFunctions { get; }

Property Value

bool

LatencyManager

Latency manager.

public IConnectorLatencyManager LatencyManager { get; }

Property Value

IConnectorLatencyManager

MarketDataDelayPeriod

Gets or sets delay period for market data.

public MarketDataDelayPeriods MarketDataDelayPeriod { get; set; }

Property Value

MarketDataDelayPeriods

MarketDataStreamEnabled

Indicates whether to raise market data through BestBidAskUpdates, MarketDepthsUpdate, and NewTrades events.

public bool MarketDataStreamEnabled { get; set; }

Property Value

bool

MaxDelistedSecuritiesRatio

Upper bound on the share of the known securities a single refresh may delist. A refresh that would drop more than this is treated as an incomplete snapshot (a failed request, one market of several not answered, a response still being processed) and is skipped with a warning instead of removing the securities. The exchanges with a nightly refresh delist a handful of symbols a day out of hundreds, so the default of 5% leaves room for a batch clean-up and still catches a half-registered snapshot. Set to 1 to disable the check.

Not in ATAS 8.0.15 yet: available from the next version.

public double MaxDelistedSecuritiesRatio { get; set; }

Property Value

double

MessageQueue

The queue that runs OnProcess(TMessage) and the queued actions on the connector's thread; a SimpleMessageQueue<TMessage> with a thread of its own by default. It is started when the connector connects and stopped when it ends up disconnected; replace it only while disconnected. Its Heartbeat calls OnSendHeartbeat().

public IMessageQueue<TMessage> MessageQueue { get; set; }

Property Value

IMessageQueue<TMessage>

MyTrades

The own trades received by the connector.

public IEnumerable<MyTrade> MyTrades { get; }

Property Value

IEnumerable<MyTrade>

NeedRebatesCheck

Has rebate check feature

public bool NeedRebatesCheck { get; set; }

Property Value

bool

Orders

The orders known to the connector.

public IEnumerable<Order> Orders { get; }

Property Value

IEnumerable<Order>

PendingOrdersCheckPeriod

Delay after a (re)connect before the orders left pending by a connection loss are checked: the ones the broker has not reported by then are failed.

Added in ATAS 8.0.15.

protected TimeSpan PendingOrdersCheckPeriod { get; set; }

Property Value

TimeSpan

Portfolios

The portfolios (accounts) known to the connector.

public IEnumerable<Portfolio> Portfolios { get; }

Property Value

IEnumerable<Portfolio>

PositionManagers

The managers of the positions the connector has processed, created by CreatePositionManager(Position).

protected IEnumerable<TSecurityPositionManager> PositionManagers { get; }

Property Value

IEnumerable<TSecurityPositionManager>

Positions

The positions known to the connector.

public IEnumerable<Position> Positions { get; }

Property Value

IEnumerable<Position>

ReconnectOnFirstConnect

Reconnect after a failed first connect instead of failing ConnectAsync(). Set only by the unattended server hosts (DataSender, DataRepeater), and it means more than the name says: the host has nobody to fix the settings, so a connection refusal (see ConnectionRefusalReason) keeps reconnecting too instead of stopping and reporting to the user as it does on the platform.

public bool ReconnectOnFirstConnect { get; set; }

Property Value

bool

ReconnectionTimer

The timer that repeats the connect attempts after a connection loss until one succeeds.

public ReconnectionTimer ReconnectionTimer { get; }

Property Value

ReconnectionTimer

RefreshSecuritiesTime

Local time of day of the daily refresh of the security list while connected: the securities the refresh does not report again are removed (RemoveSecurities). null turns the refresh off. Set from the connection settings.

public TimeOnly? RefreshSecuritiesTime { get; set; }

Property Value

TimeOnly?

Securities

The securities known to the connector.

public IEnumerable<Security> Securities { get; }

Property Value

IEnumerable<Security>

ServerMode

Set when the connector runs inside a server that relays orders of its own clients (the emulation server): the connector does not subscribe to market data, keeps the external ids of the orders as given and ignores the updates of the done or failed orders and of the own trades that its entity factory already had. false on the platform.

public bool ServerMode { get; set; }

Property Value

bool

ServerUtcNow

The current UTC time on the server's clock: the computer's clock corrected by the time sync manager (zero correction until it has measured). Data the server sends without a time of its own (a REST snapshot) is stamped with it, so it compares with the server's event times - the latency manager subtracts a stamp from this same corrected time, and a stamp of the computer's clock gives a negative or a false delay when the clock is off.

Not in ATAS 8.0.15 yet: available from the next version.

protected DateTime ServerUtcNow { get; }

Property Value

DateTime

SubscriptionStatistics

Added in ATAS 8.0.15.

public SubscriptionStatistics? SubscriptionStatistics { get; }

Property Value

SubscriptionStatistics

TimeSyncManager

The clock correction of the connector, set on the first connect: a manager that asks the exchange (GetApiServerTime(CancellationToken)) when IsSupportedServerTime is set, otherwise DefaultTimeSyncManager or an NTP one. null before the first connect.

protected ITimeSyncManager TimeSyncManager { get; }

Property Value

ITimeSyncManager

Methods

BeginProcessingDelistedSecurities()

Starts collecting the securities processed with ProcessSecurity as the current listing.

Added in ATAS 8.0.15.

protected void BeginProcessingDelistedSecurities()

Exceptions

InvalidOperationException

Collecting has already started.

CalcIsolatedMarginChangeRange(Position)

Calculates possible changes of the isolated margin of a position (only for leveraged trading)

public virtual (decimal? maxAddable, decimal? maxRemovable) CalcIsolatedMarginChangeRange(Position position)

Parameters

position Position

Returns

(decimal? maxAddable, decimal? maxRemovable)

Remarks

The base does not support the calculation and returns null for both values.

CalcLiquidationPrice(Position, decimal)

Allows to estimate Liquidation Price change for a margin

public virtual decimal? CalcLiquidationPrice(Position position, decimal margin)

Parameters

position Position

Position to calculate for

margin decimal

Absolute margin for calculation

Returns

decimal?

null if calculation is not supported

Remarks

The base does not support the calculation and returns null.

CalcMaxOrderVolume(OrderTypes, Security, Portfolio, OrderDirections, decimal?)

Gets max possible volume for the order
This function is always return null if IsSupportedMaxOrderCalculation is false

public decimal? CalcMaxOrderVolume(OrderTypes orderType, Security security, Portfolio portfolio, OrderDirections direction, decimal? limitPrice = null)

Parameters

orderType OrderTypes
security Security

The security to calculate the volume for.

portfolio Portfolio

The portfolio to calculate the volume for.

direction OrderDirections
limitPrice decimal?

optional limit price to calculate volume at. If null market price will be used

Returns

decimal?

Remarks

Exceptions

ArgumentNullException

security or portfolio is null.

CalcOrderCost(OrderTypes, Security, Portfolio, OrderDirections, decimal?, decimal, out object?, bool)

Calculates total order cost including commissions and initial margin and everything else
This function is always return null if IsSupportedMaxOrderCalculation is false

public decimal? CalcOrderCost(OrderTypes orderType, Security security, Portfolio portfolio, OrderDirections direction, decimal? limitPrice, decimal volume, out object? detailing, bool giveDetailing = false)

Parameters

orderType OrderTypes
security Security

The security of the order.

portfolio Portfolio

The portfolio the order is placed from.

direction OrderDirections
limitPrice decimal?

pass null to use market price for calculation

volume decimal

Desired volume of contracts to make order

detailing object

An object explaining each item which builds up the final price

giveDetailing bool

true for request detailing

Returns

decimal?

Complete order cost including requested volume and all commissions and margins

Remarks

Returns 0 for a zero price or volume; otherwise calls OnCalcOrderCost(OrderTypes, Security, Portfolio, OrderDirections, decimal?, decimal, out object?, bool) with the market price when no limit price is given.

Exceptions

ArgumentNullException

security or portfolio is null.

ArgumentOutOfRangeException

volume is negative.

CanSetPositionAveragePrice(Position)

Whether the average price of a position can be set by the user: its manager is a SecurityPositionManager that calculates the average price.

public bool CanSetPositionAveragePrice(Position position)

Parameters

position Position

The position.

Returns

bool

true when SetPositionAveragePrice(Position, decimal) applies to the position.

Exceptions

ArgumentNullException

position is null.

CancelOrder(Order)

Starts CancelOrderAsync(Order) without waiting for it.

public void CancelOrder(Order order)

Parameters

order Order

The order.

CancelOrderAsync(Order)

Cancels an active order.

public Task CancelOrderAsync(Order order)

Parameters

order Order

The order.

Returns

Task

A task that completes when the order is done (cancelled or filled) and faults when the cancellation fails, after OrdersCancelFailed.

Remarks

Generates a new external id for the cancel request, maps it to the order and calls OnCancelOrder(Order, long) on the caller's thread. A failure before the request is sent is reported on the connector's thread.

Exceptions

ArgumentNullException

order is null.

ChangeIsolatedMarginAsync(Position, decimal)

Adds or removes to isolated margin of a position. This method does not apply for crossed margin mode
This method works only if Risk property is not null

public Task ChangeIsolatedMarginAsync(Position position, decimal value)

Parameters

position Position
value decimal

Use positive value to add margin and negative to reduce

Returns

Task

ChangeMarginParametersAsync(Position, bool?, decimal?)

Switches position margin mode (isolated/cross) and/or trading leverage for it

Pass null if parameter should not be changed

This method works only if Risk property is not null

public Task ChangeMarginParametersAsync(Position position, bool? isIsolated, decimal? leverage)

Parameters

position Position
isIsolated bool?
leverage decimal?

Returns

Task

ClearDataForPortfolio(Portfolio)

Forgets the orders, the own trades and the pending order actions of a portfolio, without raising events; the portfolio and its positions are kept. The pending actions are dropped without completing their tasks.

protected void ClearDataForPortfolio(Portfolio portfolio)

Parameters

portfolio Portfolio

The portfolio.

ClosePositionAsync(Position)

Closes a position; does nothing for a flat one. By default a market order of the opposite direction is placed.

public Task ClosePositionAsync(Position position)

Parameters

position Position

The position.

Returns

Task

A task that completes when the closing order is confirmed.

Remarks

Exceptions

ArgumentNullException

position is null.

ClosePositionsAsync(Portfolio)

Closes all open positions of a portfolio; by default one by one, as ClosePositionAsync(Position).

public Task ClosePositionsAsync(Portfolio portfolio)

Parameters

portfolio Portfolio

The portfolio.

Returns

Task

A task that completes when the positions have been closed.

Remarks

Exceptions

ArgumentNullException

portfolio is null.

CompleteProcessingDelistedSecurities()

Removes the known securities that were not processed since BeginProcessingDelistedSecurities(): unsubscribes them and raises RemoveSecurities. Nothing is removed when no security was processed or when more than MaxDelistedSecuritiesRatio of the known ones would be.

Added in ATAS 8.0.15.

protected void CompleteProcessingDelistedSecurities()

Exceptions

InvalidOperationException

Collecting has not started.

Connect()

Asynchronously starts connection process
Connected event will fire indicating successful connection

[Obsolete("Use ConnectAsync instead.")]
public void Connect()

ConnectAsync()

Asynchronously starts connection process.

public Task ConnectAsync()

Returns

Task

ConvertCurrency(Security, string, string, decimal, decimal?, bool)

Converts volume from one currency to another Used for Notional value calculation

public decimal ConvertCurrency(Security security, string currencyFrom, string currencyTo, decimal volume, decimal? limitPrice = null, bool roundToLotSize = true)

Parameters

security Security
currencyFrom string
currencyTo string
volume decimal
limitPrice decimal?

optional value in QuoteCurrency

roundToLotSize bool

Round result to LotSize/Precision

Returns

decimal

Remarks

Both currencies must be the base or the quote currency of the security; the same currency returns the volume unchanged. The conversion itself is done by OnConvertCurrency(Security, string, string, decimal, decimal?, bool).

Exceptions

ArgumentNullException
ArgumentException
NotSupportedException

The security has no base or quote currency, or a currency is neither of them.

CreateOrderToClosePosition(Position)

Creates the order that closes a position, used by OnClosePosition(Position); by default a market order of the opposite direction for the position's volume.

protected virtual Order CreateOrderToClosePosition(Position pos)

Parameters

pos Position

The position.

Returns

Order

The closing order.

CreatePositionManager(Position)

Creates the manager that calculates a position from the connector's updates and the own trades. Called the first time a position is processed; the managers are recreated on each ConnectAsync(). A connector that processes positions must override it (typically with a SecurityPositionManager); the base throws System.NotImplementedException.

protected virtual TSecurityPositionManager CreatePositionManager(Position position)

Parameters

position Position

The position to manage.

Returns

TSecurityPositionManager

The position manager.

Disconnect()

Starts DisconnectAsync() without waiting for it; the fault of its task is swallowed.

[Obsolete("Use DisconnectAsync instead.")]
public void Disconnect()

DisconnectAsync()

Asynchronously starts disconnection process.

public Task DisconnectAsync()

Returns

Task

Enqueue(Action)

Queues an action to run on the connector's thread, in order with the queued messages.

protected void Enqueue(Action action)

Parameters

action Action

The action.

Exceptions

ArgumentNullException

action is null.

Enqueue(TMessage)

Queues a message for OnProcess(TMessage) on the connector's thread. Call it from the transport's threads with the data received. A message queued while the connector is disconnected waits for the next connect.

protected void Enqueue(TMessage message)

Parameters

message TMessage

The message.

Exceptions

ArgumentNullException

message is null.

EnqueueContinuation(Action)

Queues an await continuation of the connector's thread. Unlike a message or an action queued while the connector is disconnected, a continuation posted after its connection session ended never runs in a later session (see EnqueueContinuation(IDataFeedConnector, Action)).

Not in ATAS 8.0.15 yet: available from the next version.

protected void EnqueueContinuation(Action continuation)

Parameters

continuation Action

FailPendingSearchSecurities(Exception)

Completes all pending SearchSecuritiesAsync(SecurityFilter) operations with the given error so callers do not hang when the connector disconnects or a search pipeline fails.

Added in ATAS 8.0.15.

protected void FailPendingSearchSecurities(Exception error)

Parameters

error Exception

GetApiServerTime(CancellationToken)

Requests the exchange's server time, to correct the computer's clock; used only when IsSupportedServerTime is set. The clock offset is taken as serverTime + latency - localTime.

protected virtual Task<(DateTime serverTime, DateTime localTime, TimeSpan latency)> GetApiServerTime(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Cancels the request.

Returns

Task<(DateTime serverTime, DateTime localTime, TimeSpan latency)>

The UTC server time from the response, the local UTC time when the response was received and the one-way latency (typically half of the round trip). The base returns the current time twice and zero latency.

GetCurrentSubscription(Security)

Gets the market data subscription types currently counted for a security.

protected SubscriptionType GetCurrentSubscription(Security security)

Parameters

security Security

The security.

Returns

SubscriptionType

The subscribed types; None when nothing is subscribed.

GetMyTradesAsync(Portfolio, Security, DateTime, DateTime)

Get a list of my trades.

public Task<IEnumerable<MyTrade>> GetMyTradesAsync(Portfolio portfolio, Security security, DateTime from, DateTime to)

Parameters

portfolio Portfolio

Portfolio.

security Security

Security.

from DateTime

From date.

to DateTime

To date.

Returns

Task<IEnumerable<MyTrade>>

Remarks

Exceptions

ArgumentNullException

portfolio or security is null.

GetPortfolio(TPortfolioKey)

Finds a portfolio by the connector's key.

protected Portfolio? GetPortfolio(TPortfolioKey portfolioKey)

Parameters

portfolioKey TPortfolioKey

The connector's key of the portfolio.

Returns

Portfolio

The portfolio, or null when it is not known.

GetPortfolios(Security)

Gets the portfolios that can trade a security.

public IEnumerable<Portfolio> GetPortfolios(Security security)

Parameters

security Security

The security.

Returns

IEnumerable<Portfolio>

The portfolios; by default all of Portfolios.

Exceptions

ArgumentNullException

security is null.

GetPosition(Portfolio, Security, TPlusLimits?)

Returns the connector's position of a portfolio in a security, creating an empty one (without raising NewPositions) when the connector has none.

public Position GetPosition(Portfolio portfolio, Security security, TPlusLimits? tPlusLimit)

Parameters

portfolio Portfolio

The portfolio.

security Security

The security.

tPlusLimit TPlusLimits?

The settlement (T+) limit of the position; null for an ordinary position.

Returns

Position

The position.

Exceptions

ArgumentNullException

portfolio or security is null.

GetRoutes(Security)

Gets the order routes the broker offers for a security.

public IEnumerable<string> GetRoutes(Security security)

Parameters

security Security

The security.

Returns

IEnumerable<string>

The names of the routes; empty when the connector has no routes.

Exceptions

ArgumentNullException

security is null.

GetSecurity(TSecurityKey)

Finds a security by the connector's key.

protected Security? GetSecurity(TSecurityKey securityId)

Parameters

securityId TSecurityKey

The connector's key of the security.

Returns

Security

The security, or null when it is not known.

GetSecurityTradingOptions(Security)

Gets possible TimeInForce for order and optional flags that may be passed when order is created
If null default behaviour is expected:
TimeInForce = DAY, GTC, FOK
No order flags

public ISecurityTradingOptions? GetSecurityTradingOptions(Security security)

Parameters

security Security

Returns

ISecurityTradingOptions

Remarks

Exceptions

ArgumentNullException

security is null.

GetTradingPortfolio(Portfolio, Security)

Added in ATAS 8.0.15.

public Portfolio GetTradingPortfolio(Portfolio portfolio, Security security)

Parameters

portfolio Portfolio

The portfolio selected by the user.

security Security

The security to be traded.

Returns

Portfolio

The portfolio that receives order and position updates for the security.

Exceptions

ArgumentNullException

portfolio or security is null.

GoFlatAsync(Portfolio)

Not in ATAS 8.0.15 yet: available from the next version.

public Task GoFlatAsync(Portfolio portfolio)

Parameters

portfolio Portfolio

Returns

Task

Remarks

Exceptions

ArgumentNullException

portfolio is null.

NotSupportedException

IsSupportedGoFlat is not set (through the task).

IsMarketDataSubscribed(Security, SubscriptionType)

Not in ATAS 8.0.15 yet: available from the next version.

public bool? IsMarketDataSubscribed(Security security, SubscriptionType subscriptionType)

Parameters

security Security
subscriptionType SubscriptionType

Returns

bool?

ModifyOrder(Order, Order)

Starts ModifyOrderAsync(Order, Order) without waiting for it.

public void ModifyOrder(Order order, Order newOrder)

Parameters

order Order

The order to modify.

newOrder Order

The order with the new parameters.

ModifyOrderAsync(Order, Order)

Replaces an active order with a new one (price, volume and so on). A market order cannot be modified. A connector whose broker cannot modify orders cancels the order and places the new one after the cancellation.

public Task ModifyOrderAsync(Order order, Order newOrder)

Parameters

order Order

The active order to modify.

newOrder Order

The order with the new parameters.

Returns

Task

A task that completes when the new order is confirmed and faults when the modification fails, after OrderModifyFailed.

Remarks

Resets the broker id, the state and the time of the new order, assigns its external id and calls OnModifyOrder(Order, Order) on the caller's thread. A failure before the request is sent is reported on the connector's thread.

Exceptions

ArgumentNullException

order or newOrder is null.

OnCalcMaxOrderVolume(OrderTypes, Security, Portfolio, OrderDirections, decimal?)

Calculates the maximum order volume. The default searches for the largest volume, in lot size steps, whose OnCalcOrderCost(OrderTypes, Security, Portfolio, OrderDirections, decimal?, decimal, out object?, bool) fits into the portfolio's available balance, taking the leverage of the position, and limits it to the security's maximum lot size.

protected virtual decimal? OnCalcMaxOrderVolume(OrderTypes orderType, Security security, Portfolio portfolio, OrderDirections direction, decimal? limitPrice = null)

Parameters

orderType OrderTypes

The order type.

security Security

The security.

portfolio Portfolio

The portfolio.

direction OrderDirections

The order direction.

limitPrice decimal?

The price to calculate at; null takes the market price.

Returns

decimal?

The volume; 0 when the price or the balance is 0, null when it cannot be calculated (no available balance, a negative price or balance, no order cost).

OnCalcOrderCost(OrderTypes, Security, Portfolio, OrderDirections, decimal?, decimal, out object?, bool)

Calculates the total cost of an order (with the commissions and the initial margin); called for a positive price and volume when IsSupportedMaxOrderCalculation is set, and by OnCalcMaxOrderVolume(OrderTypes, Security, Portfolio, OrderDirections, decimal?). The base returns null.

protected virtual decimal? OnCalcOrderCost(OrderTypes orderType, Security security, Portfolio portfolio, OrderDirections direction, decimal? limitPrice, decimal volume, out object? detailing, bool giveDetailing = false)

Parameters

orderType OrderTypes

The order type.

security Security

The security.

portfolio Portfolio

The portfolio.

direction OrderDirections

The order direction.

limitPrice decimal?

The price to calculate at.

volume decimal

The order volume.

detailing object

An object explaining the parts of the cost, when requested.

giveDetailing bool

Whether to return the detailing.

Returns

decimal?

The cost, or null when it cannot be calculated.

OnCancelOrder(Order, long)

Sends the cancellation of an active order to the broker; called on the thread that cancels the order, after the checks. The cancellation completes when the order is reported done; a rejection is reported with ProcessOrderError(long, string). An exception fails the cancellation.

protected abstract void OnCancelOrder(Order order, long extId)

Parameters

order Order

The order to cancel.

extId long

A new external id of the cancel request; it is mapped to the same order, so the reports by either id find it.

OnChangeIsolatedMarginAsync(Position, decimal)

Adds margin to or removes it from the isolated margin of a position at the broker; called by ChangeIsolatedMarginAsync(Position, decimal) while connected, for a non-zero value. The base throws System.NotSupportedException.

protected virtual Task OnChangeIsolatedMarginAsync(Position position, decimal value)

Parameters

position Position

The position.

value decimal

A positive value to add, a negative one to remove.

Returns

Task

The task of the request.

OnChangeMarginParametersAsync(Position, bool?, decimal?)

Changes the margin mode and/or the leverage of a position at the broker; called by ChangeMarginParametersAsync(Position, bool?, decimal?) while connected, when at least one value is given and differs from the position's risk. The base throws System.NotSupportedException.

protected virtual Task OnChangeMarginParametersAsync(Position position, bool? isIsolated, decimal? leverage)

Parameters

position Position

The position.

isIsolated bool?

True for the isolated margin, false for the cross margin; null to keep the mode.

leverage decimal?

The new leverage; null to keep it.

Returns

Task

The task of the request.

OnClosePosition(Position)

Closes a non-flat position; called by ClosePositionAsync(Position) after the connection check. The default places the order of CreateOrderToClosePosition(Position) and waits for its confirmation. Override it when the broker has a request of its own for closing a position.

protected virtual Task OnClosePosition(Position position)

Parameters

position Position

The position.

Returns

Task

The task of the closing.

OnClosePositions(Portfolio)

Closes all non-flat positions of a portfolio; called by ClosePositionsAsync(Portfolio) after the connection check. The default closes them one by one with OnClosePosition(Position).

protected virtual Task OnClosePositions(Portfolio portfolio)

Parameters

portfolio Portfolio

The portfolio.

Returns

Task

The task of the closing.

OnConnect()

A place for connection routines
Executed on thread-pool thread

Following automatic reconnection MUST only happen if connection was successfully established.

protected virtual void OnConnect()

OnConnectAsync()

Starts a connect attempt; called on a thread-pool thread by ConnectAsync() and by each reconnection. The default creates the attempt and calls OnConnect(); the attempt succeeds when the connector calls OnConnected() and fails when it calls OnDisconnected() (with the error remembered by OnConnectionError(Exception)), when OnConnect() throws or after ConnectTimeout.
Override it to do asynchronous work before the transport starts; the override must return the task of the base (await it). An attempt that reaches the base after its connect has ended is not started: the base returns a cancelled task.

protected virtual Task OnConnectAsync()

Returns

Task

The task of the attempt.

OnConnectTimedOut(Exception)

Called when a connect attempt exceeds ConnectTimeout. The default implementation faults the pending default connect task. Override to additionally tear down any half-open transport (socket/session) created during the attempt so it is not leaked.

Added in ATAS 8.0.15.

protected virtual void OnConnectTimedOut(Exception error)

Parameters

error Exception

OnConnected()

Raises Connected event
The event must be called when the connector have all necessary connections established and authenticated
All security objects must be processed before this call if possible
If there were any subscriptions, search for that securities will be performed

protected void OnConnected()

OnConnectionError(Exception)

Remember the error that will be handled when the ATAS.DataFeedsCore.BaseConnector`4.OnDisconnected(System.Exception) is called.

protected void OnConnectionError(Exception error)

Parameters

error Exception

Remarks

A later error replaces the remembered one, except that a refusal (ConnectionRefusedException: the credentials rejected, the session taken over) is not replaced by an error that is not a refusal. A server that refuses the session closes the connection right after saying so, and the transport reports the close as an error of its own (AtasWebSocket: "Websocket connection was closed"); that error is the consequence of the refusal, and replacing the refusal with it turned the stop of the reconnection into one more reconnection (PLAT-5183). The remembered error is dropped, as before, when the end of the connection is handled and when a new connect attempt begins (PLAT-5177).

OnConvertCurrency(Security, string, string, decimal, decimal?, bool)

Converts volume from one currency to another Used for Notional value calculation

protected virtual decimal OnConvertCurrency(Security security, string currencyFrom, string currencyTo, decimal volume, decimal? limitPrice = null, bool roundToLotSize = true)

Parameters

security Security
currencyFrom string
currencyTo string
volume decimal
limitPrice decimal?

optional value in QuoteCurrency

roundToLotSize bool

Round volume to LotSize/Precision

Returns

decimal

OnDisconnect()

Called on thread-pool thread when Disconnect() method is invoked

protected virtual void OnDisconnect()

OnDisconnectAsync()

Starts the disconnect; called on a thread-pool thread by DisconnectAsync(). The default calls OnDisconnect() and completes when the connector calls OnDisconnected() (faulted when an error was remembered by OnConnectionError(Exception)), when OnDisconnect() throws (faulted) or after DisconnectTimeout.

protected virtual Task OnDisconnectAsync()

Returns

Task

The task of the disconnect.

OnDisconnectTimedOut()

Called when a disconnect attempt exceeds DisconnectTimeout. The default implementation force-completes the pending default disconnect task so the connector reaches the Disconnected state. Override to additionally tear down any transport (socket/session) that the peer never closed.

Added in ATAS 8.0.15.

protected virtual void OnDisconnectTimedOut()

OnDisconnected()

Cleans up base resources and raises Disconnected event

protected void OnDisconnected()

Remarks

A transport may report the end of one attempt more than once at the same time: the socket close and the rejected logon on two threads, a report from code that the first completion runs inline (task continuations, state handlers), a drop racing the logon confirmation. The pending attempt and the error are taken together under a lock, so exactly one report ends an attempt; until the attempt's flow has handled that end (torn down after a failure, or reached Connected), further reports are the same end reported again and are not torn down a second time, except a loss after the confirmation, which is handled once the flow has reached Connected. Before, a second report completed the attempt task again and the exception escaped into the transport's (often async void) callback (PLAT-5170).

OnGetMyTradesAsync(Portfolio, Security, DateTime, DateTime)

Loads the history of the own trades of a portfolio in a security from the broker. The base returns no trades.

protected virtual Task<IEnumerable<MyTrade>> OnGetMyTradesAsync(Portfolio portfolio, Security security, DateTime from, DateTime to)

Parameters

portfolio Portfolio

The portfolio.

security Security

The security.

from DateTime

The start of the period.

to DateTime

The end of the period.

Returns

Task<IEnumerable<MyTrade>>

The trades of the period.

OnGetPortfolios(Security)

Implements GetPortfolios(Security); returns all Portfolios by default.

protected virtual IEnumerable<Portfolio> OnGetPortfolios(Security security)

Parameters

security Security

The security.

Returns

IEnumerable<Portfolio>

The portfolios that can trade the security.

OnGetRoutes(Security)

Implements GetRoutes(Security); returns no routes by default.

protected virtual IEnumerable<string> OnGetRoutes(Security security)

Parameters

security Security

The security.

Returns

IEnumerable<string>

The names of the routes.

OnGetSecurityTradingOptions(Security)

Implements GetSecurityTradingOptions(Security); the base returns null (the default options). The stop orders are checked against its trigger price types when they are placed.

protected virtual ISecurityTradingOptions? OnGetSecurityTradingOptions(Security security)

Parameters

security Security

The security.

Returns

ISecurityTradingOptions

The trading options of the security, or null for the default ones.

OnGetTradingPortfolio(Portfolio, Security)

Implements GetTradingPortfolio(Portfolio, Security); returns the portfolio itself by default. Override it in a connector that keeps the orders and positions of a security in a sub-portfolio of the selected one.

Added in ATAS 8.0.15.

protected virtual Portfolio OnGetTradingPortfolio(Portfolio portfolio, Security security)

Parameters

portfolio Portfolio

The portfolio selected by the user.

security Security

The security to be traded.

Returns

Portfolio

The portfolio that receives the order and position updates for the security.

OnGoFlat(Portfolio)

Flattens a portfolio (cancels its orders and closes its positions) with the connector's own request; called by GoFlatAsync(Portfolio) after the connection check. Override it in a connector that sets IsSupportedGoFlat; the base throws System.NotSupportedException.

Not in ATAS 8.0.15 yet: available from the next version.

protected virtual Task OnGoFlat(Portfolio portfolio)

Parameters

portfolio Portfolio

The portfolio to flatten.

Returns

Task

The task of the request.

OnModifyOrder(Order, Order)

Sends the replacement of an active order to the broker; called on the thread that modifies the order, after the checks. The default modifies by cancel and register: it cancels the order (OnCancelOrder(Order, long)) and, when the cancellation is done with a volume left, registers the new order (OnRegisterOrder(Order)), for the volume left when it keeps the original quantity; a fully filled order fails the modification. Override it when the broker can replace orders. An exception fails the modification.

protected virtual void OnModifyOrder(Order order, Order newOrder)

Parameters

order Order

The active order to modify.

newOrder Order

The order with the new parameters; its external id is set.

OnProcess(TMessage)

Handles queued messages by the MessageQueue
In case of SimpleMessageQueue it allows to process all messages in the special connector's queue thread

protected abstract void OnProcess(TMessage message)

Parameters

message TMessage

OnRefreshSecuritiesAsync()

Requests the full security list from the broker for the daily refresh and processes it with ProcessSecurity before the returned task completes: the securities not processed by then are treated as delisted. The base only logs a warning.

protected virtual Task OnRefreshSecuritiesAsync()

Returns

Task

The task of the refresh.

OnRegisterOrder(Order)

Sends a new order to the broker; called on the thread that places the order, after the checks, with the order's external id set (also for the new order of a modification done by cancel and register). Report the broker's answer with ProcessOrder<T>(TPortfolioKey, TSecurityKey, long, T, Action<T, bool, Order>) by the external id (the order becomes known with its broker id and state) or with ProcessOrderError(long, string). An exception fails the order.

protected abstract void OnRegisterOrder(Order order)

Parameters

order Order

The order.

OnSearchSecurities(SecurityFilter)

Sends a security search to the broker. Called by SearchSecuritiesAsync(SecurityFilter) (on the caller's thread, only while connected) and after each connect for every subscribed security, to restore its subscription. The connector must answer with RaiseSearchSecuritiesResult(SecurityFilter, Exception?, IEnumerable<Security>) for the same filter object, creating the securities found with ProcessSecurity; an exception fails the search.

protected abstract void OnSearchSecurities(SecurityFilter filter)

Parameters

filter SecurityFilter

The search filter.

OnSearchSecurities(TSecurityKey)

Requests the security with the connector's key from the broker, to create it with ProcessSecurity; see OnSearchSecurities(TSecurityKey, TMessage).

protected abstract void OnSearchSecurities(TSecurityKey securityId)

Parameters

securityId TSecurityKey

The connector's key of the security.

OnSearchSecurities(TSecurityKey, TMessage)

Called on the connector's thread when a message refers to a security the connector does not know yet; the message is delayed until the security is created with ProcessSecurity. Called once per key. The default calls OnSearchSecurities(TSecurityKey).

protected virtual void OnSearchSecurities(TSecurityKey securityId, TMessage message)

Parameters

securityId TSecurityKey

The connector's key of the security.

message TMessage

The message that refers to it.

OnSendHeartbeat()

Called on the connector's thread every HeartbeatTimeout while the queue runs: from the connect until the connector ends up disconnected, also while it reconnects. Send a keep-alive or check the connection here. Does nothing by default.

protected virtual void OnSendHeartbeat()

OnSubscribeMarketData(Security, SubscriptionType)

Subscribes to the market data of a security at the broker; called while connected, on the thread that subscribes. The data is reported with ProcessBestBidAsk, ProcessTick, ProcessMarketDepths and the other Process... methods; the broker's answer may be reported with RaiseRegisterSecurityResult(Security, SubscriptionType, Exception?). An exception is handled as by OnSubscribeMarketData(IEnumerable<Security>, SubscriptionType).

protected abstract void OnSubscribeMarketData(Security security, SubscriptionType subscriptionTypes)

Parameters

security Security

The security.

subscriptionTypes SubscriptionType

The subscription types to request: the ones nobody held before.

OnSubscribeMarketData(IEnumerable<Security>, SubscriptionType)

Subscribes to the market data of several securities at the broker; called while connected, on the thread that subscribes, also when the subscriptions are restored after a connect. Override it to send one batch request; the default calls OnSubscribeMarketData(Security, SubscriptionType) for each security. An exception is reported through SubscribeMarketDataResult, except during the restore after a connect, where it is not caught.

protected virtual void OnSubscribeMarketData(IEnumerable<Security> securities, SubscriptionType subscription)

Parameters

securities IEnumerable<Security>

The securities.

subscription SubscriptionType

The subscription types to request: the ones nobody held before.

OnUnsubscribeFromMarketData(IEnumerable<Security>, SubscriptionType)

Unsubscribes from the market data of several securities at the broker; called while connected, on the thread that unsubscribes. Override it to send one batch request; the default calls OnUnsubscribeMarketData(Security, SubscriptionType) for each security. An exception is reported through UnsubscribeMarketDataResult.

protected virtual void OnUnsubscribeFromMarketData(IEnumerable<Security> securities, SubscriptionType subscription)

Parameters

securities IEnumerable<Security>

The securities.

subscription SubscriptionType

The subscription types to cancel: the ones nobody holds anymore.

OnUnsubscribeMarketData(Security, SubscriptionType)

Unsubscribes from the market data of a security at the broker; called while connected, on the thread that unsubscribes. An exception is reported through UnsubscribeMarketDataResult.

protected abstract void OnUnsubscribeMarketData(Security security, SubscriptionType subscriptionTypes)

Parameters

security Security

The security.

subscriptionTypes SubscriptionType

The subscription types to cancel: the ones nobody holds anymore.

PositionPnLChanged(Position)

Called when a position has been recalculated by a market price (its open PnL) or by an own trade, right before PositionsChanged. Override to update dependent values, e.g. the portfolio's. Does nothing by default.

protected virtual void PositionPnLChanged(Position position)

Parameters

position Position

The position.

ProcessAutoRefreshSecurities()

Runs the daily refresh of the security list until the connection ends: every day at RefreshSecuritiesTime (local time) it calls OnRefreshSecuritiesAsync() between BeginProcessingDelistedSecurities() and CompleteProcessingDelistedSecurities(). Does nothing when the time is not set or a refresh loop already runs. The base starts it after each connect.

protected Task ProcessAutoRefreshSecurities()

Returns

Task

A task that completes when the loop ends.

ProcessBestBidAsk(MarketDepth)

Publishes a ready best bid or best ask of its security, subscribed to Best: sets the security's best bid or ask price, recalculates the open PnL of its positions and, while MarketDataStreamEnabled is on, raises BestBidAskUpdates with the object itself. Without the subscription the quote only feeds the latency measurement.

protected void ProcessBestBidAsk(MarketDepth marketDepth)

Parameters

marketDepth MarketDepth

The quote with its security set; its type is bid or ask.

Exceptions

ArgumentOutOfRangeException

The type of the quote is neither bid nor ask.

ProcessBestBidAsk(Security, DateTime, MarketDataType, decimal, decimal, string)

Publishes a best bid or best ask of a security subscribed to Best: sets the security's best bid or ask price, recalculates the open PnL of its positions (see AllowUpdatePositionsPnL) and, while MarketDataStreamEnabled is on, raises BestBidAskUpdates. Without the subscription the quote only feeds the latency measurement.

protected void ProcessBestBidAsk(Security security, DateTime time, MarketDataType type, decimal price, decimal volume, string ecn = "")

Parameters

security Security

The security.

time DateTime

The time of the quote.

type MarketDataType

Bid or Ask.

price decimal

The price.

volume decimal

The volume at the price.

ecn string

The venue (ECN) of the quote; empty when not applicable.

Exceptions

ArgumentOutOfRangeException

type is neither bid nor ask.

ProcessBestBidAsk(TSecurityKey, MarketDepth)

Publishes a ready best bid or best ask of the security with the key: sets its Security and processes it as ProcessBestBidAsk(MarketDepth). Does nothing for an unknown key.

protected void ProcessBestBidAsk(TSecurityKey securityId, MarketDepth marketDepth)

Parameters

securityId TSecurityKey

The connector's key of the security.

marketDepth MarketDepth

The quote; its type is bid or ask.

ProcessBestBidAsk(TSecurityKey, DateTime, MarketDataType, decimal, decimal, string)

Publishes a best bid or best ask of the security with the key; does nothing for an unknown key, otherwise as the overload that takes the security.

protected void ProcessBestBidAsk(TSecurityKey securityId, DateTime time, MarketDataType type, decimal price, decimal volume, string ecn = "")

Parameters

securityId TSecurityKey

The connector's key of the security.

time DateTime

The time of the quote.

type MarketDataType

Bid or Ask.

price decimal

The price.

volume decimal

The volume at the price.

ecn string

The venue (ECN) of the quote; empty when not applicable.

ProcessMarketByOrder(MarketByOrder)

Publishes an order-by-order (MBO) book update through MarketByOrderChanged when MBO of its security is subscribed and the market data stream is on. A zero ReceivedTime is set to the current UTC time.

protected void ProcessMarketByOrder(MarketByOrder mbo)

Parameters

mbo MarketByOrder

The update with its security set.

ProcessMarketDepths(Security, ICollection<MarketDepth>)

Publishes a ready batch of market depth updates of a security through MarketDepthsUpdate when its depth is subscribed. Nothing is published while the market data stream is off or for an empty batch.

Not in ATAS 8.0.15 yet: available from the next version.

protected void ProcessMarketDepths(Security security, ICollection<MarketDepth> depths)

Parameters

security Security

The security.

depths ICollection<MarketDepth>

The updates.

ProcessMarketDepths(Security, Func<Security, ICollection<MarketDepth>>)

Publishes a batch of market depth updates of a security, built only when its depth is subscribed, through MarketDepthsUpdate. Nothing is published while the market data stream is off or for an empty batch.

protected void ProcessMarketDepths(Security security, Func<Security, ICollection<MarketDepth>> action)

Parameters

security Security

The security.

action Func<Security, ICollection<MarketDepth>>

Builds the batch for the security.

ProcessMarketDepths(TSecurityKey, Func<Security, ICollection<MarketDepth>>)

Publishes a batch of market depth updates of the security with the key: does nothing for an unknown key, otherwise as ProcessMarketDepths(Security, Func<Security, ICollection<MarketDepth>>).

protected void ProcessMarketDepths(TSecurityKey securityId, Func<Security, ICollection<MarketDepth>> action)

Parameters

securityId TSecurityKey

The connector's key of the security.

action Func<Security, ICollection<MarketDepth>>

Builds the batch for the security; called only when the depth of the security is subscribed.

ProcessMarketDepthsReset(TSecurityKey, ICollection<MarketDepth>)

Removes order book levels of the security with the key: sets the volume of each level to zero and publishes them as ProcessMarketDepths(TSecurityKey, Func<Security, ICollection<MarketDepth>>) does. Does not raise MarketDepthsReset; use RaiseMarketDepthsReset(Security) for a rebuilt book.

protected void ProcessMarketDepthsReset(TSecurityKey securityId, ICollection<MarketDepth> depth)

Parameters

securityId TSecurityKey

The connector's key of the security.

depth ICollection<MarketDepth>

The levels to remove; they are changed in place.

ProcessMboTrade(Trade)

Publishes a trade of the order-by-order (MBO) stream when MBO of its security is subscribed. Does nothing while the market data stream is off.

Not in ATAS 8.0.15 yet: available from the next version.

protected void ProcessMboTrade(Trade trade)

Parameters

trade Trade

The trade.

ProcessMyTrade<T>(long, string, string, T, Action<T, MyTrade>)

Creates an own trade of the order found by the external id or else by the broker's order id and raises NewMyTrades; the positions of the order's portfolio and security are updated by it. A trade id seen already is ignored. While the order is unknown, the message is delayed and processed again when the order is raised as new. Call it on the connector's thread.

protected void ProcessMyTrade<T>(long extId, string orderId, string tradeId, T message, Action<T, MyTrade> update) where T : TMessage

Parameters

extId long

The external (ATAS) id of the order; 0 when unknown.

orderId string

The broker's id of the order.

tradeId string

The broker's id of the trade.

message T

The message with the trade data, passed to update; when null, a trade of an unknown order is skipped instead of delayed.

update Action<T, MyTrade>

Fills the new trade from the message.

Type Parameters

T

The type of the message.

ProcessMyTrade<T>(long, string, T, Action<T, MyTrade>)

Creates an own trade of the order with the external id as ProcessMyTrade<T>(long, string, string, T, Action<T, MyTrade>) does, without the lookup by the broker's order id.

protected void ProcessMyTrade<T>(long extId, string tradeId, T message, Action<T, MyTrade> update) where T : TMessage

Parameters

extId long

The external (ATAS) id of the order.

tradeId string

The broker's id of the trade.

message T

The message with the trade data, passed to update; when null, a trade of an unknown order is skipped instead of delayed.

update Action<T, MyTrade>

Fills the new trade from the message.

Type Parameters

T

The type of the message.

ProcessMyTrade<T>(TPortfolioKey, TSecurityKey, long, string, string, T, Action<T, MyTrade>)

Processes an own trade as ProcessMyTrade<T>(long, string, string, T, Action<T, MyTrade>) once its portfolio and security are known; until then the message is delayed (an unknown security is searched with OnSearchSecurities).

protected void ProcessMyTrade<T>(TPortfolioKey accountId, TSecurityKey securityId, long extId, string orderId, string tradeId, T message, Action<T, MyTrade> update) where T : TMessage

Parameters

accountId TPortfolioKey

The connector's key of the portfolio.

securityId TSecurityKey

The connector's key of the security.

extId long

The external (ATAS) id of the order; 0 when unknown.

orderId string

The broker's id of the order.

tradeId string

The broker's id of the trade.

message T

The message with the trade data, passed to update.

update Action<T, MyTrade>

Fills the new trade from the message.

Type Parameters

T

The type of the message.

ProcessOrder(long, Action<Order>)

Runs an action on the known order with the external id; for an unknown id a warning is logged. Raises no event: call RaiseOrder(Order, bool) when the action changes the order.

protected void ProcessOrder(long extId, Action<Order> process)

Parameters

extId long

The external (ATAS) id of the order.

process Action<Order>

The action.

ProcessOrderError(Order, string)

Reports a broker error for an order, as RaiseOrderFailed(Order, string).

protected void ProcessOrderError(Order order, string error)

Parameters

order Order

The order.

error string

The error message.

ProcessOrderError(long, string)

Reports a broker error for the order with the external id, as RaiseOrderFailed(Order, string); for an unknown id the error is only logged.

protected void ProcessOrderError(long extId, string error)

Parameters

extId long

The external (ATAS) id of the order or of its cancel request.

error string

The error message.

ProcessOrder<T>(long, T, Action<T, Order>)

Updates the known order with the external id and raises OrderChanged, completing a pending action of the order when the update settles it. Call it on the connector's thread.

protected void ProcessOrder<T>(long extId, T message, Action<T, Order> update) where T : TMessage

Parameters

extId long

The external (ATAS) id of the order.

message T

The message with the order data, passed to update.

update Action<T, Order>

Updates the order from the message.

Type Parameters

T

The type of the message.

Exceptions

InvalidOperationException

No order has the external id.

ProcessOrder<T>(TPortfolioKey, TSecurityKey, long, T, Action<T, bool, Order>)

Creates or updates the order with the external id and raises NewOrders or OrderChanged, completing a pending register, modify or cancel of the order when the update settles it. While the portfolio or the security is unknown, the message is delayed (an unknown security is searched with OnSearchSecurities) and processed again when it becomes known. Call it on the connector's thread.

protected void ProcessOrder<T>(TPortfolioKey accountId, TSecurityKey securityId, long extId, T message, Action<T, bool, Order> update) where T : TMessage

Parameters

accountId TPortfolioKey

The connector's key of the order's portfolio.

securityId TSecurityKey

The connector's key of the order's security.

extId long

The external (ATAS) id of the order: for an order the platform placed, the one it assigned (Order.ExtId).

message T

The message with the order data, passed to update.

update Action<T, bool, Order>

Updates the order from the message; gets whether the order is new to the connector.

Type Parameters

T

The type of the message.

ProcessOrder<T>(TPortfolioKey, TSecurityKey, long, T, Func<T, bool, Order, bool?>)

Creates or updates the order with the external id as the overload with an action does, but lets the update decide about the events.

protected void ProcessOrder<T>(TPortfolioKey accountId, TSecurityKey securityId, long extId, T message, Func<T, bool, Order, bool?> update) where T : TMessage

Parameters

accountId TPortfolioKey

The connector's key of the order's portfolio.

securityId TSecurityKey

The connector's key of the order's security.

extId long

The external (ATAS) id of the order.

message T

The message with the order data, passed to update.

update Func<T, bool, Order, bool?>

Updates the order from the message; gets whether the order is new to the connector. Returns null to raise nothing, otherwise whether to raise the order as new (NewOrders) rather than changed (OrderChanged).

Type Parameters

T

The type of the message.

ProcessPortfolio<T>(TPortfolioKey, string, T, Action<T, Portfolio>)

Creates or updates a portfolio and raises NewPortfolios or PortfoliosChanged. When the portfolio is new, the messages that were delayed because it was unknown are processed again (OnProcess(TMessage)). Call it on the connector's thread.

protected Portfolio ProcessPortfolio<T>(TPortfolioKey id, string accountId, T message, Action<T, Portfolio> update)

Parameters

id TPortfolioKey

The connector's key of the portfolio.

accountId string

The account id of a new portfolio.

message T

The message with the portfolio data, passed to update.

update Action<T, Portfolio>

Fills the portfolio from the message.

Returns

Portfolio

The portfolio.

Type Parameters

T

The type of the message.

ProcessPortfolio<T>(TPortfolioKey, T, Action<T, Portfolio>, bool)

Updates a known portfolio and raises PortfoliosChanged; an unknown one is skipped or, when throwIfNotFound is set, fails. Call it on the connector's thread.

protected void ProcessPortfolio<T>(TPortfolioKey id, T message, Action<T, Portfolio> update, bool throwIfNotFound = false)

Parameters

id TPortfolioKey

The connector's key of the portfolio.

message T

The message with the portfolio data, passed to update.

update Action<T, Portfolio>

Updates the portfolio from the message.

throwIfNotFound bool

Whether an unknown portfolio is an error.

Type Parameters

T

The type of the message.

Exceptions

InvalidOperationException

The portfolio is not known and throwIfNotFound is set.

ProcessPosition<T>(TPortfolioKey, TSecurityKey, TPlusLimits?, T, Func<T, bool, TSecurityPositionManager, bool>)

Creates or updates the position of a portfolio in a security through its manager and raises NewPositions or PositionsChanged. A new position is replayed the own trades of its portfolio and security received before; when the manager asks for it, the security is subscribed to the best bid/ask to calculate the open PnL. While the portfolio or the security is unknown, the message is delayed (an unknown security is searched with OnSearchSecurities) and processed again when it becomes known. Call it on the connector's thread.

protected void ProcessPosition<T>(TPortfolioKey accountId, TSecurityKey securityId, TPlusLimits? tPlusLimit, T message, Func<T, bool, TSecurityPositionManager, bool> update) where T : TMessage

Parameters

accountId TPortfolioKey

The connector's key of the portfolio.

securityId TSecurityKey

The connector's key of the security.

tPlusLimit TPlusLimits?

The settlement (T+) limit of the position; null for an ordinary position.

message T

The message with the position data, passed to update.

update Func<T, bool, TSecurityPositionManager, bool>

Updates the position manager from the message; gets whether the position is new and returns whether it changed. A new position is raised in any case.

Type Parameters

T

The type of the message.

ProcessPosition<T>(TPortfolioKey, TSecurityKey, T, Func<T, bool, TSecurityPositionManager, bool>)

Creates or updates an ordinary position (without a T+ limit) of a portfolio in a security, as the overload with the T+ limit does.

Added in ATAS 8.0.15.

protected void ProcessPosition<T>(TPortfolioKey accountId, TSecurityKey securityId, T message, Func<T, bool, TSecurityPositionManager, bool> update) where T : TMessage

Parameters

accountId TPortfolioKey

The connector's key of the portfolio.

securityId TSecurityKey

The connector's key of the security.

message T

The message with the position data, passed to update.

update Func<T, bool, TSecurityPositionManager, bool>

Updates the position manager from the message; gets whether the position is new and returns whether it changed.

Type Parameters

T

The type of the message.

ProcessSecurity(TSecurityKey, Action<Security>)

Runs an action on a known security; an unknown one is skipped. Raises no event: call RaiseSecurityChanged(Security) when the action changes the security.

protected void ProcessSecurity(TSecurityKey id, Action<Security> action)

Parameters

id TSecurityKey

The connector's key of the security.

action Action<Security>

The action.

ProcessSecurity<T>(TSecurityKey, string, T, Action<T, bool, Security>)

Converts internal security object of the connector into the ATAS-security visible to the system

protected void ProcessSecurity<T>(TSecurityKey id, string securityId, T message, Action<T, bool, Security> update)

Parameters

id TSecurityKey

Connector's internal id of the security

securityId string

ATAS public id of the security in form of internal-id@exchange-id like BTCUSD@ByBit

message T

Connector's specific message with security data

update Action<T, bool, Security>

Callback where Security object must be populated

Type Parameters

T

Type of the connector's security object

ProcessSummary(TSecurityKey, Action<SecuritySummary>)

Updates the summary (daily statistics) of the security with the key and publishes it when the summary is subscribed. Does nothing for a security without a summary.

protected void ProcessSummary(TSecurityKey id, Action<SecuritySummary> action)

Parameters

id TSecurityKey

The connector's key of the security.

action Action<SecuritySummary>

Changes the summary.

ProcessSummary<TValue>(TSecurityKey, TValue, Action<SecuritySummary, TValue>)

Updates the summary (daily statistics) of the security with the key from a value and publishes it when the summary is subscribed; the value is passed to the action, so a static lambda needs no closure.

Not in ATAS 8.0.15 yet: available from the next version.

protected void ProcessSummary<TValue>(TSecurityKey id, TValue value, Action<SecuritySummary, TValue> action)

Parameters

id TSecurityKey

The connector's key of the security.

value TValue

The value the action applies.

action Action<SecuritySummary, TValue>

Changes the summary.

Type Parameters

TValue

The type of the value.

ProcessTick(Security, Trade)

Sets the security of a ready trade and publishes it as ProcessTick(Trade).

protected void ProcessTick(Security security, Trade trade)

Parameters

security Security

The security.

trade Trade

The trade.

ProcessTick(Security, long, DateTime, TradeDirection, decimal, decimal, string, decimal?)

Publishes a trade (tick) of a security: sets the security's last trade price and volume and, for a security subscribed to Prints while MarketDataStreamEnabled is on, raises NewTrades. A trade with Between gets its side from the best bid and ask when its price reaches one of them.

protected void ProcessTick(Security security, long id, DateTime time, TradeDirection direction, decimal price, decimal volume, string ecn = "", decimal? openInterest = null)

Parameters

security Security

The security.

id long

The id of the trade.

time DateTime

The time of the trade.

direction TradeDirection

The aggressor side.

price decimal

The price.

volume decimal

The volume.

ecn string

The venue (ECN) of the trade; empty when not applicable.

openInterest decimal?

The open interest after the trade; null takes the security's.

ProcessTick(Trade)

Publishes a ready trade with its security set: raises NewTrades for a security subscribed to Prints while MarketDataStreamEnabled is on. Unlike the overload that builds the trade, it does not update the security's last trade price and volume.

protected void ProcessTick(Trade trade)

Parameters

trade Trade

The trade.

ProcessTick(TSecurityKey, Trade)

Publishes a ready trade of the security with the key as ProcessTick(Trade); does nothing for an unknown key.

protected void ProcessTick(TSecurityKey securityId, Trade trade)

Parameters

securityId TSecurityKey

The connector's key of the security.

trade Trade

The trade.

ProcessTick(TSecurityKey, long, DateTime, TradeDirection, decimal, decimal, string, decimal?)

Publishes a trade (tick) of the security with the key; does nothing for an unknown key, otherwise as the overload that takes the security.

protected void ProcessTick(TSecurityKey securityId, long id, DateTime time, TradeDirection direction, decimal price, decimal volume, string ecn = "", decimal? openInterest = null)

Parameters

securityId TSecurityKey

The connector's key of the security.

id long

The id of the trade.

time DateTime

The time of the trade.

direction TradeDirection

The aggressor side.

price decimal

The price.

volume decimal

The volume.

ecn string

The venue (ECN) of the trade; empty when not applicable.

openInterest decimal?

The open interest after the trade; null takes the security's.

RaiseConnected()

Marks the connector connected and raises Connected, starting the search of the subscribed securities that restores their subscriptions. Does nothing when already connected. The base calls it when the connect attempt succeeds; a connector reports the success with OnConnected() instead.

protected void RaiseConnected()

RaiseDisconnected()

Marks the connector disconnected and raises Disconnected; does nothing when not connected. The base calls it when the connection ends; a connector reports the end with OnDisconnected() instead.

protected void RaiseDisconnected()

RaiseMarketByOrdersReset(Security)

Tells the subscribers that the order-by-order (MBO) book of a security starts over (MarketByOrdersReset), for example after a reconnect. Does nothing while the market data stream is off or MBO is not subscribed.

Not in ATAS 8.0.15 yet: available from the next version.

protected void RaiseMarketByOrdersReset(Security security)

Parameters

security Security

The security.

RaiseMarketDepthsReset(Security)

Tells the subscribers that the order book of a security is rebuilt from scratch (MarketDepthsReset), e.g. before the levels of a fresh snapshot after a reconnect. Does nothing while the market data stream is off or the depth of the security is not subscribed.

Added in ATAS 8.0.15.

protected void RaiseMarketDepthsReset(Security security)

Parameters

security Security

The security.

Exceptions

ArgumentNullException

security is null.

RaiseNews(News)

Logs a news message and raises NewNews.

protected void RaiseNews(News news)

Parameters

news News

The news message.

RaiseOrder(Order, bool)

Reports the current state of an order: completes the pending register, modify or cancel of the order when the state settles it and raises NewOrders or OrderChanged accordingly; an order without a pending action is raised as new when isNew is set.

protected void RaiseOrder(Order order, bool isNew)

Parameters

order Order

The order.

isNew bool

Whether the order is new to the connector.

RaiseOrderCancellationReason(Order, string)

Publishes broker metadata without completing a pending register/modify/cancel action.

        <p>Not in ATAS 8.0.15 yet: available from the next version.</p>
protected void RaiseOrderCancellationReason(Order order, string reason)

Parameters

order Order
reason string

RaiseOrderFailed(Order, string)

Reports a broker error for an order. A pending action of the order fails: a register raises OrdersRegisterFailed (the order becomes Failed), a modify OrderModifyFailed, a cancel OrdersCancelFailed, and the action's task faults. Without a pending action the error becomes the order's cancellation reason: an order in the None or Active state fails with OrdersRegisterFailed, any other is raised through OrderChanged.

protected void RaiseOrderFailed(Order order, string error)

Parameters

order Order

The order.

error string

The error message.

RaisePosition(TSecurityPositionManager, bool)

Raises NewPositions or PositionsChanged for the position of a manager.

protected void RaisePosition(TSecurityPositionManager posManager, bool isNew)

Parameters

posManager TSecurityPositionManager

The manager of the position.

isNew bool

Whether to raise the position as new.

RaiseRebateResult(RebateResult)

Reports the result of the referral (rebate) check of the account through RebateReceived.

protected void RaiseRebateResult(RebateResult result)

Parameters

result RebateResult

The result.

RaiseRegisterSecurityResult(Security, SubscriptionType, Exception?)

Reports the broker's answer to a market data subscription through RegisterSecurityResult. On an error the subscription of the types is no longer counted, so it is not restored after a reconnect.

protected void RaiseRegisterSecurityResult(Security security, SubscriptionType subscriptionType, Exception? error)

Parameters

security Security

The security.

subscriptionType SubscriptionType

The subscription types the answer is for.

error Exception

The rejection; null when the subscription is accepted.

RaiseSearchSecuritiesResult(SecurityFilter, Exception?, IEnumerable<Security>)

Reports the result of a search started by OnSearchSecurities(SecurityFilter): raises SearchSecuritiesResult, completes the task of SearchSecuritiesAsync(SecurityFilter) for the filter and, after a reconnect, continues restoring the subscriptions of the securities found. Call it once per search, with the same filter object.

protected void RaiseSearchSecuritiesResult(SecurityFilter filter, Exception? error, IEnumerable<Security> securities)

Parameters

filter SecurityFilter

The filter of the search.

error Exception

The error of the search; null on success.

securities IEnumerable<Security>

The securities found.

RaiseSecurityChanged(Security)

Raises SecurityChanged after the connector has changed a security's properties.

protected void RaiseSecurityChanged(Security security)

Parameters

security Security

The security.

RaiseSecuritySummaryChanged(SecuritySummary)

Raises SecuritySummaryChanged; unlike ProcessSummary it does not check the subscription.

protected void RaiseSecuritySummaryChanged(SecuritySummary summary)

Parameters

summary SecuritySummary

The summary.

RaiseSubscribeMarketDataResult(IEnumerable<Security>, Exception?)

Raises SubscribeMarketDataResult. The base raises it after sending the subscription requests and when a subscription fails or is refused.

protected void RaiseSubscribeMarketDataResult(IEnumerable<Security> securities, Exception? error = null)

Parameters

securities IEnumerable<Security>

The securities.

error Exception

The error; null when the request was sent.

RaiseUnsubscribeMarketDataResult(IEnumerable<Security>, Exception)

Raises UnsubscribeMarketDataResult for a failed unsubscription.

protected void RaiseUnsubscribeMarketDataResult(IEnumerable<Security> securities, Exception error)

Parameters

securities IEnumerable<Security>

The securities.

error Exception

The error.

RegisterOrder(Order)

Starts RegisterOrderAsync(Order) without waiting for it.

public void RegisterOrder(Order order)

Parameters

order Order

The order.

RegisterOrderAsync(Order)

Places an order. The order needs Security and Portfolio and no broker id yet; the connector assigns its external id (ExtId) when it is 0.

public Task RegisterOrderAsync(Order order)

Parameters

order Order

The order.

Returns

Task

A task that completes when the broker confirms the order (NewOrders) and faults when the order is rejected or cannot be sent (not connected, invalid, already being processed), after OrdersRegisterFailed.

Remarks

Clears the cancellation flags of the order, sets its unfilled volume to the quantity when it is 0 and calls OnRegisterOrder(Order) on the caller's thread. A failure before the request is sent is reported on the connector's thread.

Exceptions

ArgumentNullException

order is null.

RememberPendingOrders()

Moves the order actions waiting for the broker to the list checked after the reconnect: a later report of the broker settles each of them, and the ones not reported within PendingOrdersCheckPeriod after the connector reconnects are failed. The base calls it on each end of a connection; call it when the transport loses the connection and restores it by itself, without OnDisconnected().

protected void RememberPendingOrders()

SearchSecurities(SecurityFilter)

Searches for securities matching the specified filter.

public void SearchSecurities(SecurityFilter filter)

Parameters

filter SecurityFilter

SearchSecuritiesAsync(SecurityFilter)

Searches for securities matching the filter; the result is also raised through SearchSecuritiesResult. A filter without a request id gets one.

public Task<IEnumerable<Security>> SearchSecuritiesAsync(SecurityFilter filter)

Parameters

filter SecurityFilter

The search filter.

Returns

Task<IEnumerable<Security>>

A task with the securities found. It faults with the error of the search, e.g. when the connector is not connected or disconnects before the answer.

Exceptions

ArgumentNullException

filter is null.

SetPositionAveragePrice(Position, decimal)

Sets the average price of a position on the connector's thread and raises PositionsChanged; a position without a manager is ignored.

public void SetPositionAveragePrice(Position position, decimal avgPrice)

Parameters

position Position

The position.

avgPrice decimal

The average price.

Exceptions

ArgumentNullException

position is null.

SubscribeToMarketData(Security, SubscriptionType)

Subscribes to market data for a security.

public void SubscribeToMarketData(Security security, SubscriptionType subscriptionTypes)

Parameters

security Security

The security to subscribe to.

subscriptionTypes SubscriptionType

The subscription type flags.

SubscribeToMarketData(IEnumerable<Security>, SubscriptionType)

Subscribes to market data for securities. Subscriptions are counted per security and type: only the types nobody holds yet are requested from the broker, and while the connector is disconnected they are only counted and requested on the next connect. The counted subscriptions are restored after a reconnect. The outcome is reported through SubscribeMarketDataResult of IMarketDataPublisher.

public void SubscribeToMarketData(IEnumerable<Security> securities, SubscriptionType subscriptionTypes)

Parameters

securities IEnumerable<Security>

The securities.

subscriptionTypes SubscriptionType

The subscription type flags.

Remarks

Does nothing in the ServerMode.

Exceptions

ArgumentNullException

securities is null.

TryAdmitOptionLookup(string, out Exception?)

For IOptionsDataFeed implementations: call first in every option series and chain lookup, before anything is sent and before the first await, and fail the lookup with the returned error when it is refused (see OptionRequestGuard).

Added in ATAS 8.0.15.

protected bool TryAdmitOptionLookup(string request, out Exception? error)

Parameters

request string
error Exception

Returns

bool

TryGetOrder(long)

Finds an order by its external (ATAS) id.

public Order TryGetOrder(long extId)

Parameters

extId long

The external id of the order, or of a cancel request of the order.

Returns

Order

The order, or null when the connector does not know the id.

TryGetOrder(string, out Order?)

Finds an order by the broker's id (Id).

public bool TryGetOrder(string marketOrderId, out Order? order)

Parameters

marketOrderId string

The broker's id of the order.

order Order

The order, or null when none has the id.

Returns

bool

true when the order is found.

TryGetPosition(Order, out Position?)

Finds the ordinary position (without a T+ limit) of an order's portfolio in its security.

Added in ATAS 8.0.15.

protected bool TryGetPosition(Order order, out Position? position)

Parameters

order Order

The order.

position Position

The position, or null when there is none.

Returns

bool

true when the position is found.

TryGetPosition(Portfolio, Security, out Position?)

Finds the ordinary position (without a T+ limit) of a portfolio in a security.

Added in ATAS 8.0.15.

protected bool TryGetPosition(Portfolio portfolio, Security security, out Position? position)

Parameters

portfolio Portfolio

The portfolio.

security Security

The security.

position Position

The position, or null when there is none.

Returns

bool

true when the position is found.

TryGetPosition(Portfolio, Security, TPlusLimits, out Position?)

Finds the position of a portfolio in a security with a T+ limit.

Added in ATAS 8.0.15.

protected bool TryGetPosition(Portfolio portfolio, Security security, TPlusLimits limits, out Position? position)

Parameters

portfolio Portfolio

The portfolio.

security Security

The security.

limits TPlusLimits

The settlement (T+) limit of the position.

position Position

The position, or null when there is none.

Returns

bool

true when the position is found.

UnsubscribeFromMarketData(Security, SubscriptionType)

Unsubscribes from market data for a security.

public void UnsubscribeFromMarketData(Security security, SubscriptionType subscriptionTypes)

Parameters

security Security

The security to unsubscribe from.

subscriptionTypes SubscriptionType

The subscription type flags.

UnsubscribeFromMarketData(IEnumerable<Security>, SubscriptionType)

Releases market data subscriptions of securities: the counts are decreased and the broker is asked to unsubscribe only the types nobody holds anymore. A failure is reported through UnsubscribeMarketDataResult of IMarketDataPublisher.

public void UnsubscribeFromMarketData(IEnumerable<Security> securities, SubscriptionType subscriptionTypes)

Parameters

securities IEnumerable<Security>

The securities.

subscriptionTypes SubscriptionType

The subscription type flags.

Remarks

Does nothing in the ServerMode.

Exceptions

ArgumentNullException

securities is null.

UpdatePositionsPnL(Security, MarketDataType, decimal)

Recalculates the open PnL of the positions in a security by a best bid or ask price and, for each position that changed, calls PositionPnLChanged(Position) and raises PositionsChanged. Does nothing when AllowUpdatePositionsPnL is off. The best bid/ask processing calls it.

protected void UpdatePositionsPnL(Security security, MarketDataType type, decimal price)

Parameters

security Security

The security.

type MarketDataType

Whether the price is the best bid or the best ask.

price decimal

The price.

ValidateTradesHistoryRequestDates(ref DateTime, DateTime, int)

Limits the start of a trades history request to the depth the broker keeps: a start earlier than depthLimitMonths months before the current UTC date is moved to that date, with a warning.

protected void ValidateTradesHistoryRequestDates(ref DateTime from, DateTime to, int depthLimitMonths)

Parameters

from DateTime

The start of the period; moved forward when it is too early.

to DateTime

The end of the period.

depthLimitMonths int

How many months of history the broker keeps.

Exceptions

ArgumentOutOfRangeException

to is not after the earliest possible date.

Events

BestBidAskUpdates

Raised for a best bid or best ask update of a security subscribed to Best, while MarketDataStreamEnabled is on.

public event ConnectorEventHandler<MarketDepth>? BestBidAskUpdates

Event Type

ConnectorEventHandler<MarketDepth>

Connected

Raised when the connection is established (also after a reconnect), before ConnectionState becomes Connected. An exception of a handler is logged and does not fail the connect.

public event ConnectorEventHandler? Connected

Event Type

ConnectorEventHandler

ConnectionStateChanged

Raised on every actual change of ConnectionState; the arguments carry the old and the new state and the error that caused the change, if any. Right after it, PortfoliosChanged is raised for every portfolio, whose connection state follows the connector's.

public event ConnectorEventHandler<ConnectionStateEventArgs>? ConnectionStateChanged

Event Type

ConnectorEventHandler<ConnectionStateEventArgs>

Disconnected

Raised when an established connection ends (lost or closed), before the state changes to Reconnecting or Disconnected. Not raised for a connect attempt that failed.

public event ConnectorEventHandler? Disconnected

Event Type

ConnectorEventHandler

Error

Raised when an error occurs.

public event ConnectorEventHandler<Exception>? Error

Event Type

ConnectorEventHandler<Exception>

Remarks

Raised for every failure that ends a connection or a connect attempt, including each attempt of an ongoing reconnection, before the state change that follows from it.

MarketByOrderChanged

Added in ATAS 8.0.15.

public event ConnectorEventHandler<MarketByOrder>? MarketByOrderChanged

Event Type

ConnectorEventHandler<MarketByOrder>

MarketByOrdersReset

Not in ATAS 8.0.15 yet: available from the next version.

public event ConnectorEventHandler<Security>? MarketByOrdersReset

Event Type

ConnectorEventHandler<Security>

MarketDepthsReset

Added in ATAS 8.0.15.

public event ConnectorEventHandler<Security>? MarketDepthsReset

Event Type

ConnectorEventHandler<Security>

MarketDepthsUpdate

Raised for a batch of order book updates of one security subscribed to Quotes, while MarketDataStreamEnabled is on. A level with zero volume is removed from the book.

public event ConnectorEventHandler<IEnumerable<MarketDepth>>? MarketDepthsUpdate

Event Type

ConnectorEventHandler<IEnumerable<MarketDepth>>

NewMboTrade

Not in ATAS 8.0.15 yet: available from the next version.

public event ConnectorEventHandler<Trade>? NewMboTrade

Event Type

ConnectorEventHandler<Trade>

NewMyTrades

Raised for each new own trade (fill) of an order, with a single trade. A trade with an id seen already is not raised again.

public event ConnectorEventHandler<IEnumerable<MyTrade>>? NewMyTrades

Event Type

ConnectorEventHandler<IEnumerable<MyTrade>>

NewNews

Raised for a news message of the broker.

public event ConnectorEventHandler<News>? NewNews

Event Type

ConnectorEventHandler<News>

NewOrders

Raised when an order appears: an order placed by the platform is confirmed by the broker, or the broker reports an order the connector did not know (placed elsewhere or loaded on connect).

public event ConnectorEventHandler<IEnumerable<Order>>? NewOrders

Event Type

ConnectorEventHandler<IEnumerable<Order>>

NewPortfolios

Raised when a portfolio (account) is created.

public event ConnectorEventHandler<IEnumerable<Portfolio>>? NewPortfolios

Event Type

ConnectorEventHandler<IEnumerable<Portfolio>>

NewPositions

Raised when the connector reports a position of a portfolio in a security for the first time.

public event ConnectorEventHandler<IEnumerable<Position>>? NewPositions

Event Type

ConnectorEventHandler<IEnumerable<Position>>

NewSecurities

Raised when a security becomes known to the connector.

public event ConnectorEventHandler<IEnumerable<Security>>? NewSecurities

Event Type

ConnectorEventHandler<IEnumerable<Security>>

NewTrades

Raised for a trade (tick) of a security subscribed to Prints, while MarketDataStreamEnabled is on; the collection holds a single trade.

public event ConnectorEventHandler<IEnumerable<Trade>>? NewTrades

Event Type

ConnectorEventHandler<IEnumerable<Trade>>

OrderChanged

Raised when a known order changes (state, fill, cancellation).

public event ConnectorEventHandler<Order>? OrderChanged

Event Type

ConnectorEventHandler<Order>

OrderModifyFailed

Raised when a modification of an order fails; the arguments are the original order, the new order (in the Failed state) and the error message.

public event ConnectorEventHandler<Order, Order, string>? OrderModifyFailed

Event Type

ConnectorEventHandler<Order, Order, string>

OrdersCancelFailed

Raised when a cancellation of an order fails; the arguments are the error message and the order.

public event ConnectorEventHandler<string, Order>? OrdersCancelFailed

Event Type

ConnectorEventHandler<string, Order>

OrdersRegisterFailed

Raised when an order is rejected or fails to be placed; the arguments are the error message and the order, whose state is Failed.

public event ConnectorEventHandler<string, Order>? OrdersRegisterFailed

Event Type

ConnectorEventHandler<string, Order>

PortfoliosChanged

Raised when a portfolio changes, and for every portfolio on each change of the connection state.

public event ConnectorEventHandler<IEnumerable<Portfolio>>? PortfoliosChanged

Event Type

ConnectorEventHandler<IEnumerable<Portfolio>>

PositionsChanged

Raised when a position changes, including the changes of its open PnL by the market prices.

public event ConnectorEventHandler<IEnumerable<Position>>? PositionsChanged

Event Type

ConnectorEventHandler<IEnumerable<Position>>

RebateReceived

Raised with the result of the check of the account's referral (rebate) program. On WrongRefCode the platform reports a license error for the connection.

public event ConnectorEventHandler<RebateResult>? RebateReceived

Event Type

ConnectorEventHandler<RebateResult>

RegisterSecurityResult

Raised when the broker answers a market data subscription of a security; the error is null when the subscription is accepted. A rejected subscription is no longer counted.

public event ConnectorEventHandler<Security, Exception?>? RegisterSecurityResult

Event Type

ConnectorEventHandler<Security, Exception>

RemoveSecurities

Added in ATAS 8.0.15.

public event ConnectorEventHandler<IEnumerable<Security>>? RemoveSecurities

Event Type

ConnectorEventHandler<IEnumerable<Security>>

SearchSecuritiesResult

Raised when a security search completes; the arguments are the filter of the request, the error (null on success) and the securities found (empty on an error).

public event ConnectorEventHandler<SecurityFilter, Exception?, IEnumerable<Security>>? SearchSecuritiesResult

Event Type

ConnectorEventHandler<SecurityFilter, Exception, IEnumerable<Security>>

SecurityChanged

Raised when the connector reports a change of a known security's properties.

public event ConnectorEventHandler<Security>? SecurityChanged

Event Type

ConnectorEventHandler<Security>

SecuritySummaryChanged

Raised when the summary (daily statistics) of a security subscribed to Summary changes.

public event ConnectorEventHandler<SecuritySummary>? SecuritySummaryChanged

Event Type

ConnectorEventHandler<SecuritySummary>

SubscribeMarketDataResult

Raised after a subscription request has been sent to the broker (the error is null) and when a subscription fails or is refused (with the error); the arguments are the securities and the error.

public event ConnectorEventHandler<IEnumerable<Security>, Exception?>? SubscribeMarketDataResult

Event Type

ConnectorEventHandler<IEnumerable<Security>, Exception>

UnsubscribeMarketDataResult

Raised when an unsubscription request fails; the arguments are the securities and the error.

public event ConnectorEventHandler<IEnumerable<Security>, Exception?>? UnsubscribeMarketDataResult

Event Type

ConnectorEventHandler<IEnumerable<Security>, Exception>