namespace StockSharp.Fix.Dialects;
using FixTimeInForce = Native.FixTimeInForce;
partial class BaseFixDialect
{
///
/// Write value.
///
/// Writer.
/// Message.
/// Cancellation token.
protected async ValueTask WriteAccountAsync(IFixWriter writer, IPortfolioNameMessage message, CancellationToken cancellationToken)
{
if (writer is null)
throw new ArgumentNullException(nameof(writer));
if (message is null)
throw new ArgumentNullException(nameof(message));
var pf = message.PortfolioName;
if (DoNotSendAccount || pf.IsEmpty() || IsSyntheticPortfolioName(pf))
return;
await writer.WriteAsync(FixTags.Account, cancellationToken);
await writer.WriteAsync(message.PortfolioName, cancellationToken);
}
///
/// Get synthetic portfolio name for mode.
///
/// Portfolio code name.
protected string GetSyntheticPortfolioName()
{
var pf = Login;
if (pf.IsEmpty())
pf = SenderCompId;
return pf;
}
///
/// Is the specified portfolio name generated by .
///
/// Portfolio code name.
/// Check result.
protected bool IsSyntheticPortfolioName(string portfolioName)
{
return LoginAsPortfolioName && portfolioName.EqualsIgnoreCase(GetSyntheticPortfolioName());
}
private string GetAccountId(string account)
{
return LoginAsPortfolioName ? GetSyntheticPortfolioName() : account;
}
private async IAsyncEnumerable ReadPositionReportAsync(IFixReader reader, [EnumeratorCancellation]CancellationToken cancellationToken)
{
string account = null;
int? posReqResult = null;
var sendingTime = default(DateTime);
DateTime? transactTime = null;
CurrencyTypes? currency = null;
string symbol = null;
string securityExchange = null;
string exDestination = null;
string tradingSessionId = null;
decimal? contractMultiplier = null;
//SecurityTypes? securityType = null;
TPlusLimits? limit = null;
string clientCode = null;
string strategyId = null;
char? side = null;
long? posReqId = null;
var positionAmts = Array.Empty>();
var positions = Array.Empty>();
var posIndex = 0;
var posAmtIndex = 0;
char? buildFromType = null;
string buildFromArg = null;
string depoName = null;
string description = null;
var isOk = await reader.ReadMessageAsync(async (tag, ct) =>
{
switch (tag)
{
case FixTags.Account:
account = await reader.ReadStringAsync(ct);
return true;
case FixTags.PosReqResult:
posReqResult = await reader.ReadIntAsync(ct);
return true;
case FixTags.SendingTime:
sendingTime = await reader.ReadUtcAsync(TimeStampParser, ct);
return true;
case FixTags.TransactTime:
transactTime = await reader.ReadUtcAsync(TimeStampParser, ct);
return true;
case FixTags.Currency:
currency = (await reader.ReadStringAsync(ct)).FromMicexCurrencyName(LogError);
return true;
case FixTags.Symbol:
symbol = await reader.ReadStringAsync(ct);
return true;
case FixTags.SecurityExchange:
securityExchange = await reader.ReadStringAsync(ct);
return true;
case FixTags.ExDestination:
exDestination = await reader.ReadStringAsync(ct);
return true;
case FixTags.TradingSessionID:
tradingSessionId = await reader.ReadStringAsync(ct);
return true;
case FixTags.ContractMultiplier:
contractMultiplier = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.SecurityType:
/*securityType = */(await reader.ReadStringAsync(ct)).FromFixType();
return true;
case FixTags.AcctIDSource:
limit = (await reader.ReadIntAsync(ct)).To();
return true;
case FixTags.ClientID:
clientCode = await reader.ReadStringAsync(ct);
return true;
case FixTags.StrategyTypeId:
strategyId = await reader.ReadStringAsync(ct);
return true;
case FixTags.Side:
side = await reader.ReadCharAsync(ct);
return true;
case FixTags.PosReqID:
posReqId = (await reader.ReadStringAsync(ct)).To();
return true;
case FixTags.BuildFromType:
buildFromType = await reader.ReadCharAsync(ct);
return true;
case FixTags.BuildFromArg:
buildFromArg = await reader.ReadStringAsync(ct);
return true;
case FixTags.NoPosAmt:
positionAmts = new RefPair[await reader.ReadIntAsync(ct)];
for (var i = 0; i < positionAmts.Length; i++)
positionAmts[i] = new RefPair();
return true;
case FixTags.NoPositions:
positions = new RefTriple[await reader.ReadIntAsync(ct)];
for (var i = 0; i < positions.Length; i++)
positions[i] = new RefTriple();
return true;
case FixTags.PosAmtType:
if (positionAmts[posAmtIndex].First != null)
posAmtIndex++;
positionAmts[posAmtIndex].First = await reader.ReadStringAsync(ct);
return true;
case FixTags.PosAmt:
if (positionAmts[posAmtIndex].Second != null)
posAmtIndex++;
positionAmts[posAmtIndex].Second = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.PosType:
if (positions[posIndex].First != null)
posIndex++;
positions[posIndex].First = await reader.ReadStringAsync(ct);
return true;
case FixTags.LongQty:
if (positions[posIndex].Second != null)
posIndex++;
positions[posIndex].Second = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.ShortQty:
if (positions[posIndex].Third != null)
posIndex++;
positions[posIndex].Third = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.ExecBroker:
depoName = await reader.ReadStringAsync(ct);
return true;
case FixTags.Text:
description = await reader.ReadStringAsync(ct);
return true;
default:
return false;
}
}, cancellationToken);
if (!isOk)
yield break;
if (posReqResult != null && posReqResult != 0)
{
yield return LocalizedStrings.RecvPosRejected.Put(account, posReqResult).ToErrorMessage();
yield break;
}
account = GetAccountId(account);
var posMsg = new PositionChangeMessage
{
PortfolioName = account,
ServerTime = transactTime ?? sendingTime,
ClientCode = clientCode,
StrategyId = strategyId,
Side = side?.FromFixSide(true),
BuildFrom = buildFromType?.ToDataType(buildFromArg),
DepoName = depoName,
Description = description,
};
if (symbol == SecurityId.Money.SecurityCode)
{
posMsg.SecurityId = SecurityId.Money;
posMsg.OriginalTransactionId = posReqId ?? 0;
if (currency != null)
posMsg.Add(PositionChangeTypes.Currency, currency.Value);
posMsg.BoardCode = securityExchange;
foreach (var position in positionAmts)
{
switch (position.First)
{
case PosAmtType.StartOfDayMarkToMarketAmount:
posMsg.Add(PositionChangeTypes.BeginValue, position.Second);
break;
case PosAmtType.CashResidualAmount:
posMsg.Add(PositionChangeTypes.CurrentValue, position.Second);
break;
case PosAmtType.ValueAdjustedAmount:
posMsg.Add(PositionChangeTypes.BlockedValue, position.Second);
break;
case PosAmtType.TradeVariationAmount:
posMsg.Add(PositionChangeTypes.VariationMargin, position.Second);
break;
case PosAmtType.CashAmount:
posMsg.Add(PositionChangeTypes.AveragePrice, position.Second);
break;
case Native.Extensions.Commission:
posMsg.Add(PositionChangeTypes.Commission, position.Second);
break;
case Native.Extensions.RealizedPnL:
posMsg.Add(PositionChangeTypes.RealizedPnL, position.Second);
break;
case Native.Extensions.UnrealizedPnL:
posMsg.Add(PositionChangeTypes.UnrealizedPnL, position.Second);
break;
case Native.Extensions.Leverage:
posMsg.Add(PositionChangeTypes.Leverage, position.Second);
break;
case PosAmtType.TotalCollateralizedAmount:
posMsg.Add(PositionChangeTypes.CurrentPrice, position.Second);
break;
case Native.Extensions.LiquidationPrice:
posMsg.Add(PositionChangeTypes.LiquidationPrice, position.Second);
break;
}
}
if (!account.IsEmpty())
{
yield return new PortfolioMessage
{
PortfolioName = account,
ClientCode = clientCode,
OriginalTransactionId = posReqId ?? 0,
};
}
yield return posMsg;
}
else
{
var multiplier = contractMultiplier ?? 1;
//var posMsg = new PositionMessage
//{
// PortfolioName = account,
// SecurityId = new SecurityId
// {
// SecurityCode = symbol,
// BoardCode = GetBoardCode(securityExchange, tradingSessionId),
// SecurityType = securityType
// },
// LimitType = limit,
// ClientCode = clientCode,
// OriginalTransactionId = posReqId ?? 0
//};
//messageHandler(posMsg);
posMsg.SecurityId = new SecurityId
{
SecurityCode = symbol,
BoardCode = GetBoardCode(exDestination, securityExchange, tradingSessionId),
};
posMsg.LimitType = limit;
posMsg.OriginalTransactionId = posReqId ?? 0;
foreach (var position in positions)
{
var value = position.Second;
if (position.Third != null)
{
if (value == null || value == 0)
{
value = position.Third;
if (value > 0)
value -= value;
}
}
if (value == null)
continue;
switch (position.First)
{
case PosType.StartOfDayQty:
posMsg.Add(PositionChangeTypes.BeginValue, value.Value / multiplier);
break;
case PosType.ExchangeForPhysicalQty:
posMsg.Add(PositionChangeTypes.CurrentValue, value.Value / multiplier);
break;
case PosType.AdjustmentQty:
posMsg.Add(PositionChangeTypes.BlockedValue, value.Value / multiplier);
break;
case PosType.DeliveryQty:
posMsg.Add(PositionChangeTypes.AveragePrice, value.Value);
break;
case Native.Extensions.Commission:
posMsg.Add(PositionChangeTypes.Commission, value.Value);
break;
case Native.Extensions.RealizedPnL:
posMsg.Add(PositionChangeTypes.RealizedPnL, value.Value);
break;
case Native.Extensions.UnrealizedPnL:
posMsg.Add(PositionChangeTypes.UnrealizedPnL, value.Value);
break;
case Native.Extensions.Leverage:
posMsg.Add(PositionChangeTypes.Leverage, value.Value);
break;
case Native.PosType.TotalTransactionQty:
posMsg.Add(PositionChangeTypes.CurrentPrice, value.Value);
break;
case Native.Extensions.LiquidationPrice:
posMsg.Add(PositionChangeTypes.LiquidationPrice, value.Value);
break;
}
}
if (posMsg.HasChanges())
yield return posMsg;
}
}
private static async IAsyncEnumerable ReadOrderMassCancelReportAsync(IFixReader reader, [EnumeratorCancellation]CancellationToken cancellationToken)
{
char? massCancelResponse = null;
int? massCancelRejectReason = null;
string text = null;
var isOk = await reader.ReadMessageAsync(async (tag, ct) =>
{
switch (tag)
{
case FixTags.MassCancelResponse:
massCancelResponse = await reader.ReadCharAsync(ct);
return true;
case FixTags.MassCancelRejectReason:
massCancelRejectReason = await reader.ReadIntAsync(ct);
return true;
case FixTags.Text:
text = await reader.ReadStringAsync(ct);
return true;
default:
return false;
}
}, cancellationToken);
if (!isOk)
yield break;
if (massCancelResponse == MassCancelResponse.CancelRequestRejected)
yield return LocalizedStrings.MassOrderCancelNotProcessed.Put(text, massCancelRejectReason).ToErrorMessage();
}
///
/// Read the message.
///
/// The reader of data recorded in the FIX protocol format.
/// instance.
/// Parser for field.
///
///
/// , if the messages was read successfully, to skip unknown message, null to break connection.
protected virtual async ValueTask ReadExecutionReportAsync(IFixReader reader, ExecutionReport report, FastDateTimeParser transactTimeParser, Func> extraTagProcess, CancellationToken cancellationToken)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
if (report == null)
throw new ArgumentNullException(nameof(report));
if (transactTimeParser == null)
throw new ArgumentNullException(nameof(transactTimeParser));
if (extraTagProcess == null)
throw new ArgumentNullException(nameof(extraTagProcess));
var partyIndex = 0;
var isOk = await reader.ReadMessageAsync(async (tag, ct) =>
{
switch (tag)
{
case FixTags.PossDupFlag:
report.PossDupFlag = await reader.ReadBoolAsync(ct);
return true;
case FixTags.ExecType:
report.ExecType = await reader.ReadCharAsync(ct);
return true;
case FixTags.OrigClOrdID:
report.OrigClOrdId = await reader.ReadStringAsync(ct);
return true;
case FixTags.OrderID:
report.OrderId = await reader.ReadStringAsync(ct);
return true;
case FixTags.ClOrdID:
report.ClOrdId = await reader.ReadStringAsync(ct);
return true;
case FixTags.OrderQty:
report.OrderQty = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.LeavesQty:
report.LeavesQty = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.CumQty:
report.CumQty = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.Symbol:
report.Symbol = await reader.ReadStringAsync(ct);
return true;
case FixTags.SecurityExchange:
report.SecurityExchange = await reader.ReadStringAsync(ct);
return true;
case FixTags.SecurityID:
report.SecurityId = await reader.ReadStringAsync(ct);
return true;
case FixTags.IDSource:
report.SecurityIdSource = await reader.ReadStringAsync(ct);
return true;
case FixTags.TradingSessionID:
report.TradingSessionId = await reader.ReadStringAsync(ct);
return true;
case FixTags.ExDestination:
report.ExDestination = await reader.ReadStringAsync(ct);
return true;
case FixTags.SendingTime:
report.SendingTime = await reader.ReadUtcAsync(TimeStampParser, ct);
return true;
case FixTags.OrdType:
report.OrdType = await reader.ReadCharAsync(ct);
return true;
case FixTags.Price:
report.Price = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.TradeDate:
report.TradeDate = (await reader.ReadDateTimeAsync(DateParser, ct)).ApplyTimeZone(TimeZone).UtcDateTime;
return true;
case FixTags.TransactTime:
report.TransactTime = await reader.ReadUtcAsync(transactTimeParser, ct);
return true;
case FixTags.Account:
report.Account = await reader.ReadStringAsync(ct);
return true;
case FixTags.ClientID:
report.ClientId = await reader.ReadStringAsync(ct);
return true;
case FixTags.ExecBroker:
report.ExecBroker = await reader.ReadStringAsync(ct);
return true;
case FixTags.NoPartyIDs:
report.Parties = new Party[await reader.ReadIntAsync(ct)];
return true;
case FixTags.PartyID:
{
if (report.Parties[partyIndex]?.PartyId != null)
partyIndex++;
var party = report.Parties[partyIndex] ?? (report.Parties[partyIndex] = new Party());
party.PartyId = await reader.ReadStringAsync(ct);
return true;
}
case FixTags.PartyRole:
{
if (report.Parties[partyIndex]?.PartyRole != null)
partyIndex++;
var party = report.Parties[partyIndex] ?? (report.Parties[partyIndex] = new Party());
party.PartyRole = (PartyRole?)await reader.ReadIntAsync(ct);
return true;
}
case FixTags.OrdStatus:
report.OrdStatus = await reader.ReadCharAsync(ct);
return true;
case FixTags.Side:
report.Side = await reader.ReadCharAsync(ct);
return true;
case FixTags.TimeInForce:
report.TimeInForce = await reader.ReadCharAsync(ct);
return true;
case FixTags.ExpireDate:
report.ExpireDate = (await reader.ReadDateTimeAsync(DateParser, ct)).ApplyTimeZone(TimeZone).UtcDateTime;
return true;
case FixTags.ExpireTime:
report.ExpireTime = await reader.ReadUtcAsync(TimeStampParser, ct);
return true;
case FixTags.LastPx:
report.LastPx = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.LastQty:
report.LastQty = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.MaxFloor:
report.MaxFloor = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.DisplayQty:
report.DisplayQty = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.Commission:
report.Commission = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.Text:
report.Text = await reader.ReadStringAsync(ct);
return true;
case FixTags.ExecID:
report.ExecId = await reader.ReadStringAsync(ct);
return true;
case FixTags.NoTrdRegTimestamps:
// This is a count field, skip it (timestamps will be read by TrdRegTimestamp tag)
await reader.ReadIntAsync(ct);
return true;
case FixTags.TrdRegTimestamp:
report.TrdRegTimestamp = await reader.ReadUtcAsync(transactTimeParser, ct);
return true;
case FixTags.TrdRegTimestampType:
report.TrdRegTimestampType = (TrdRegTimestampType)await reader.ReadIntAsync(ct);
return true;
case FixTags.MassStatusReqID:
report.MassStatusReqId = await reader.ReadStringAsync(ct);
return true;
case FixTags.OrdStatusReqID:
report.OrdStatusReqId = await reader.ReadStringAsync(ct);
return true;
case FixTags.LastCapacity:
report.LastCapacity = await reader.ReadCharAsync(ct);
return true;
case FixTags.OrderCapacity:
report.OrderCapacity = await reader.ReadCharAsync(ct);
return true;
case FixTags.OrderRestrictions:
report.OrderRestrictions = await reader.ReadStringAsync(ct);
return true;
case FixTags.ExtendedOrderStatus:
report.ExtendedOrderStatus = await reader.ReadLongAsync(ct);
return true;
case FixTags.ExtendedTradeStatus:
report.ExtendedTradeStatus = await reader.ReadIntAsync(ct);
return true;
case FixTags.LastLiquidityInd:
report.LastLiquidityInd = await reader.ReadIntAsync(ct);
return true;
case FixTags.CashMargin:
report.CashMargin = await reader.ReadCharAsync(ct);
return true;
case FixTags.AvgPx:
report.AvgPx = (await reader.ReadDecimalAsync(ct)).DefaultAsNull();
return true;
case FixTags.MinQty:
report.MinQty = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.Yield:
report.Yield = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.StopPx:
report.StopPx = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.TakeProfit:
report.TakeProfit = await reader.ReadDecimalAsync(ct);
return true;
case FixTags.PositionEffect:
report.PositionEffect = await reader.ReadCharAsync(ct);
return true;
case FixTags.AggressorIndicator:
report.AggressorIndicator = await reader.ReadBoolAsync(ct);
return true;
case FixTags.ManualOrderIndicator:
report.ManualOrderIndicator = await reader.ReadBoolAsync(ct);
return true;
case FixTags.OrigSendingTime:
report.OrigSendingTime = await reader.ReadUtcAsync(transactTimeParser, ct);
return true;
case FixTags.MsgSeqNum:
report.MsgSeqNum = await reader.ReadLongAsync(ct);
return true;
case FixTags.SecondaryOrderID:
report.SecondaryOrderId = await reader.ReadStringAsync(ct);
return true;
case FixTags.StrategyTypeId:
report.StrategyTypeId = await reader.ReadStringAsync(ct);
return true;
case FixTags.Leverage:
report.Leverage = await reader.ReadIntAsync(ct);
return true;
case FixTags.MarketPrice:
report.MarketPrice = await reader.ReadDecimalAsync(ct);
return true;
default:
return await extraTagProcess(tag, reader, report, ct);
}
}, cancellationToken);
if (!isOk)
return false;
return true;
}
private async IAsyncEnumerable ReadExecutionReportAsync(IFixReader reader, [EnumeratorCancellation]CancellationToken cancellationToken)
{
var report = new ExecutionReport();
var result = await ReadExecutionReportAsync(reader, report, TimeStampParser, ProcessExecutionReportExtraTagAsync, cancellationToken);
if (!result)
yield break;
await foreach (var msg in ProcessExecutionReportAsync(report, ProcessExecutionReportAsync, cancellationToken).WithEnforcedCancellation(cancellationToken))
yield return msg;
}
///
/// Process extra tags for .
///
/// Tag.
/// The reader of data recorded in the FIX protocol format.
/// Execution report.
///
/// Result.
protected virtual ValueTask ProcessExecutionReportExtraTagAsync(FixTags tag, IFixReader reader, ExecutionReport report, CancellationToken cancellationToken)
=> new(false);
///
/// Process instance.
///
/// instance.
///
///
protected virtual async IAsyncEnumerable ProcessExecutionReportAsync(ExecutionReport report, ExecutionMessage message, [EnumeratorCancellation]CancellationToken cancellationToken)
{
await Task.Yield();
yield return message;
}
///
/// Get order type.
///
/// Execution report.
/// Base order condition (for example, for stop order algo orders).
/// Order type.
protected virtual OrderTypes GetOrderType(ExecutionReport report, out OrderCondition condition)
{
if (report is null)
throw new ArgumentNullException(nameof(report));
condition = null;
switch (report.OrdType)
{
case OrdType.Limit:
return OrderTypes.Limit;
case OrdType.Market:
return OrderTypes.Market;
default:
condition = new FixOrderCondition { StopLoss = report.StopPx, TakeProfit = report.TakeProfit };
return OrderTypes.Conditional;
}
}
///
/// Process .
///
/// Execution report.
protected virtual void ProcessParties(ExecutionReport report)
{
report.ClientId ??= report.Parties.FirstOrDefault(p => p.PartyRole == PartyRole.ClientId)?.PartyId;
report.ExecBroker ??= report.Parties.FirstOrDefault(p => p.PartyRole == PartyRole.ExecutingFirm)?.PartyId;
}
///
/// Get .
///
/// value.
/// value.
protected virtual string GetOrderStringId(string orderId)
{
if (orderId.IsEmpty())
return orderId;
return orderId.EqualsIgnoreCase("none") ? null : orderId;
}
///
/// Get execution time.
///
protected virtual DateTime GetExecutionTime(ExecutionReport report)
=> report.TransactTime ?? report.TrdRegTimestamp ?? report.TradeDate ?? report.OrigSendingTime ?? report.SendingTime;
///
/// Process instance.
///
/// instance.
/// Post handle an instance.
///
protected virtual async IAsyncEnumerable ProcessExecutionReportAsync(ExecutionReport report, Func> processExecMsg, [EnumeratorCancellation]CancellationToken cancellationToken)
{
if (report is null)
throw new ArgumentNullException(nameof(report));
if (processExecMsg is null)
throw new ArgumentNullException(nameof(processExecMsg));
// TODO OrderLog
//long? originalTransactionId = null;
//if (long.TryParse(report.OrigClOrdId, out temp))
// originalTransactionId = temp;
//long? transactionId = null;
//if (long.TryParse(report.ClOrdId, out temp))
// transactionId = temp;
long? clOrdId = null;
if (!report.ClOrdId.IsEmpty())
{
if (long.TryParse(report.ClOrdId, out var c))
clOrdId = c;
else if (SupportUnknownExecutions)
{
if (_clOrdIds.TryGetKey(report.ClOrdId, out c))
clOrdId = c;
else
{
clOrdId = _transactionIdGenerator.GetNextId();
_clOrdIds[clOrdId.Value] = report.ClOrdId;
}
}
}
var isOrderStatus = false;
long? originalTransactionId = null;
if (long.TryParse(report.OrdStatusReqId, out var temp))
{
originalTransactionId = temp;
isOrderStatus = true;
}
else if (long.TryParse(report.MassStatusReqId, out temp))
{
originalTransactionId = temp;
isOrderStatus = true;
}
else if (report.PossDupFlag == true) // ResendRequest reports
{
if (long.TryParse(report.OrigClOrdId, out temp))
{
originalTransactionId = temp;
if (report.ExecType == ExecType.Canceled)
{
clOrdId = originalTransactionId;
originalTransactionId = LastResendRequest;
isOrderStatus = true;
}
}
else
{
if (report.ExecType == ExecType.Trade)
{
if (long.TryParse(report.ClOrdId, out temp))
originalTransactionId = temp;
else if (long.TryParse(report.OrigClOrdId, out temp))
originalTransactionId = temp;
}
else
{
originalTransactionId = LastResendRequest;
isOrderStatus = true;
}
}
}
else if (clOrdId != null)
originalTransactionId = clOrdId.Value;
else if (long.TryParse(report.OrigClOrdId, out temp))
originalTransactionId = temp;
if (report.Parties != null)
ProcessParties(report);
if (report.ClientId.IsEmpty())
report.ClientId = ClientCode;
var time = GetExecutionTime(report);
async IAsyncEnumerable CreateOrderMsg()
{
//if (originalTransactionId == null)
// originalTransactionId = transactionId;
//if (originalTransactionId == null && ignoreIfTransIdNull)
// return null;
// если сообщение не содержит объем или баланс, значит нет информации по заявке
//if (orderQty == null && leavesQty == null)
// return null;
if (report.OrderQty == 0)
report.OrderQty = null;
if (report.OrdStatus == OrdStatus.Canceled)
{
if (report.LeavesQty == 0)
report.LeavesQty = null;
}
var msg = new ExecutionMessage
{
SecurityId = new SecurityId
{
SecurityCode = report.Symbol,
BoardCode = GetBoardCode(report.ExDestination, report.SecurityExchange, report.TradingSessionId),
},
//TransactionId = transactionId ?? 0,
OriginalTransactionId = originalTransactionId ?? 0,
OrderPrice = report.Price ?? 0,
OrderVolume = report.OrderQty,
PortfolioName = GetAccountId(report.Account),
Side = report.Side?.FromFixSide() ?? default,
ServerTime = time,
Balance = (report.OrderQty != null && report.CumQty != null) ? (report.OrderQty - report.CumQty) : report.LeavesQty,
OrderState = GetOrderState(report),
DataTypeEx = DataType.Transactions,
Commission = report.Commission,
CommissionCurrency = report.CommissionCurrency,
ClientCode = report.ClientId,
BrokerCode = report.ExecBroker,
TradePrice = report.LastPx?.DefaultAsNull(),
TradeVolume = report.LastQty?.DefaultAsNull(),
VisibleVolume = report.MaxFloor ?? report.DisplayQty,
OrderStatus = report.ExtendedOrderStatus,
TradeStatus = report.ExtendedTradeStatus,
MarginMode = report.CashMargin?.ToMarginMode(),
AveragePrice = report.AvgPx?.DefaultAsNull(),
Yield = report.Yield,
MinVolume = report.MinQty,
PositionEffect = report.PositionEffect.ToPositionEffect(),
Initiator = report.AggressorIndicator,
IsManual = report.ManualOrderIndicator,
SeqNum = report.MsgSeqNum,
UserOrderId = report.SecondaryOrderId,
StrategyId = report.StrategyTypeId,
Leverage = report.Leverage,
MarketPrice = report.MarketPrice,
};
if (msg.Balance != null || msg.OrderState != null || msg.OrderVolume != null || report.Price != null)
msg.HasOrderInfo = true;
if (report.OrdType != null)
{
msg.OrderType = GetOrderType(report, out var condition);
msg.Condition = condition;
msg.HasOrderInfo = true;
}
if (report.OrderId != null)
{
if (long.TryParse(report.OrderId, out var orderNumId))
msg.OrderId = orderNumId;
else
msg.OrderStringId = GetOrderStringId(report.OrderId);
//msg.HasOrderInfo = true;
}
if (Native.Extensions.IsMarketMaker(report.OrderCapacity, report.OrderRestrictions))
msg.IsMarketMaker = true;
if (isOrderStatus)
msg.TransactionId = clOrdId ?? 0;
//if (_orderStatusTransactions.Contains(msg.OriginalTransactionId))
await foreach (var r in processExecMsg(report, msg, cancellationToken))
{
if (r.OrderState == OrderStates.Failed)
{
r.Error = new InvalidOperationException(report.Text);
r.HasOrderInfo = true;
}
else
r.Comment = report.Text;
r.HasOrderInfo |= ApplyTimeInForce(report, msg);
yield return r;
}
}
static Sides? LastLiquidityIndToSide(Sides? side, int? value)
{
// Which side initiated the trade is read off the order's own side, so a report that
// states none says nothing about the initiator either.
if (side is not Sides orderSide)
return null;
return value switch
{
null => null,
1 => orderSide.Invert(),
2 or 3 => orderSide,
_ => throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.InvalidValue),
};
}
switch (report.ExecType)
{
case ExecType.PendingNew:
case ExecType.PendingReplace:
case ExecType.New:
case ExecType.OrderStatus:
case ExecType.Canceled:
case ExecType.Fill:
case ExecType.PartialFill:
case ExecType.Replaced:
case ExecType.Calculated:
{
if (report.ExecType == ExecType.Canceled && report.LeavesQty == 0)
report.LeavesQty = null;
await foreach (var msg in CreateOrderMsg())
{
//if (msg == null)
// break;
if (report.ExecType == ExecType.Fill || report.ExecType == ExecType.PartialFill)
{
msg.OriginSide ??= LastLiquidityIndToSide(msg.Side, report.LastLiquidityInd);
if (msg.TradeId == null && msg.TradeStringId.IsEmpty() && report.ExecId != null)
{
if (long.TryParse(report.ExecId, out var tradeNumId))
msg.TradeId = tradeNumId;
else
msg.TradeStringId = report.ExecId;
}
}
yield return msg;
}
break;
}
case ExecType.Rejected:
{
//if (originalTransactionId == null)
// originalTransactionId = transactionId;
//if (originalTransactionId != null)
//{
if (originalTransactionId == null && SupportUnknownExecutions)
{
if (_clOrdIds.TryGetKey(report.OrigClOrdId, out temp))
originalTransactionId = temp;
}
var msg = new ExecutionMessage
{
SecurityId = new SecurityId
{
SecurityCode = report.Symbol,
BoardCode = GetBoardCode(report.ExDestination, report.SecurityExchange, report.TradingSessionId),
},
Side = report.Side?.TryFromFixSide(),
PortfolioName = GetAccountId(report.Account),
ServerTime = report.SendingTime,
DataTypeEx = DataType.Transactions,
OrderState = OrderStates.Failed,
Error = new InvalidOperationException(report.Text),
Commission = report.Commission,
CommissionCurrency = report.CommissionCurrency,
ClientCode = report.ClientId,
HasOrderInfo = true,
SeqNum = report.MsgSeqNum,
UserOrderId = report.SecondaryOrderId,
StrategyId = report.StrategyTypeId,
Leverage = report.Leverage,
MarketPrice = report.MarketPrice,
};
if (report.PossDupFlag == true)
{
msg.TransactionId = report.ClOrdId.TryToLong() ?? 0;
}
msg.OriginalTransactionId = originalTransactionId ?? 0;
if (long.TryParse(report.OrderId, out var orderIdNum))
msg.OrderId = orderIdNum;
else
msg.OrderStringId = GetOrderStringId(report.OrderId);
await foreach (var r in processExecMsg(report, msg, cancellationToken))
yield return r;
break;
//}
}
case ExecType.Trade:
{
await foreach (var msg in CreateOrderMsg())
{
msg.OriginSide ??= LastLiquidityIndToSide(msg.Side, report.LastLiquidityInd);
if (msg.TradeId == null && msg.TradeStringId.IsEmpty() && report.ExecId != null)
{
if (long.TryParse(report.ExecId, out var tradeNumId))
msg.TradeId = tradeNumId;
else
msg.TradeStringId = report.ExecId;
}
yield return msg;
}
break;
}
case ExecType.PendingCancel:
break;
default:
throw new InvalidOperationException(LocalizedStrings.UnknownType.Put(report.ExecType));
}
}
///
/// Apply time in force.
///
///
///
///
protected virtual bool ApplyTimeInForce(ExecutionReport report, ExecutionMessage msg, bool throwInvalid = true)
{
switch (report.TimeInForce)
{
case FixTimeInForce.GoodTillCancel:
msg.TimeInForce = Messages.TimeInForce.PutInQueue;
return true;
case FixTimeInForce.Day:
msg.TimeInForce = Messages.TimeInForce.PutInQueue;
msg.ExpiryDate = Messages.Extensions.Today;
return true;
case FixTimeInForce.GoodTillDate:
msg.TimeInForce = Messages.TimeInForce.PutInQueue;
msg.ExpiryDate = report.ExpireTime ?? report.ExpireDate;
return true;
case FixTimeInForce.FillOrKill:
msg.TimeInForce = Messages.TimeInForce.MatchOrCancel;
return true;
case FixTimeInForce.ImmediateOrCancel:
msg.TimeInForce = Messages.TimeInForce.CancelBalance;
return true;
case null:
return false;
default:
if(throwInvalid)
throw new ArgumentOutOfRangeException(nameof(report), report.TimeInForce, LocalizedStrings.InvalidValue);
return false;
}
}
///
/// Convert to value.
///
/// value.
/// value.
protected virtual OrderStates? GetOrderState(ExecutionReport report)
{
return report.OrdStatus?.FromFixStatus();
}
private async IAsyncEnumerable ReadOrderCancelRejectAsync(IFixReader reader, [EnumeratorCancellation]CancellationToken cancellationToken)
{
string clOrdId = null;
string orderId = null;
var sendingTime = default(DateTime);
DateTime? transactTime = null;
string text = null;
var isOk = await reader.ReadMessageAsync(async (tag, ct) =>
{
switch (tag)
{
case FixTags.ClOrdID:
clOrdId = await reader.ReadStringAsync(ct);
return true;
case FixTags.OrderID:
orderId = await reader.ReadStringAsync(ct);
return true;
case FixTags.SendingTime:
sendingTime = await reader.ReadUtcAsync(TimeStampParser, ct);
return true;
case FixTags.TransactTime:
transactTime = await reader.ReadUtcAsync(TimeStampParser, ct);
return true;
case FixTags.Text:
text = await reader.ReadStringAsync(ct);
return true;
default:
return false;
}
}, cancellationToken);
if (!isOk)
yield break;
var msg = new ExecutionMessage
{
OriginalTransactionId = clOrdId.To(),
ServerTime = transactTime ?? sendingTime,
DataTypeEx = DataType.Transactions,
OrderState = OrderStates.Failed,
Error = new InvalidOperationException(LocalizedStrings.ErrorCancellingOrder.Put(orderId, text)),
HasOrderInfo = true,
};
if (orderId != null)
{
if (long.TryParse(orderId, out var orderNumId))
msg.OrderId = orderNumId;
else
msg.OrderStringId = GetOrderStringId(orderId);
}
yield return msg;
}
private static async IAsyncEnumerable ReadRequestForPositionAckAsync(IFixReader reader, [EnumeratorCancellation]CancellationToken cancellationToken)
{
string account = null;
PosReqResult? posReqResult = null;
PosReqStatus? posReqStatus = null;
string text = null;
var isOk = await reader.ReadMessageAsync(async (tag, ct) =>
{
switch (tag)
{
case FixTags.Account:
account = await reader.ReadStringAsync(ct);
return true;
case FixTags.PosReqResult:
posReqResult = (PosReqResult)await reader.ReadIntAsync(ct);
return true;
case FixTags.PosReqStatus:
posReqStatus = (PosReqStatus)await reader.ReadIntAsync(ct);
return true;
case FixTags.Text:
text = await reader.ReadStringAsync(ct);
return true;
default:
return false;
}
}, cancellationToken);
if (!isOk)
yield break;
if (posReqResult != null && posReqResult != 0 && (posReqStatus == PosReqStatus.Rejected || (posReqStatus == null && posReqResult != PosReqResult.ValidRequest)))
yield return LocalizedStrings.RecvPosRejected2.Put(account, posReqResult, text).ToErrorMessage();
}
}