本文整理汇总了C#中StockSharp.Messages.ExecutionMessage类的典型用法代码示例。如果您正苦于以下问题:C# ExecutionMessage类的具体用法?C# ExecutionMessage怎么用?C# ExecutionMessage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ExecutionMessage类属于StockSharp.Messages命名空间,在下文中一共展示了ExecutionMessage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ProcessOrderRegisterMessage
private void ProcessOrderRegisterMessage(OrderRegisterMessage message)
{
var condition = (OandaOrderCondition)message.Condition;
string type;
if (condition == null)
type = message.Price == 0 ? "market" : "limit";
else
type = condition.IsMarket ? _orderImit : "stop";
var response = _restClient.CreateOrder(GetAccountId(message.PortfolioName),
message.SecurityId.ToOanda(), (int)message.Volume, message.Side.To<string>().ToLowerInvariant(),
type,
GetExpiryTime(message),
message.Price,
condition?.LowerBound,
condition?.UpperBound,
condition?.StopLossOffset,
condition?.TakeProfitOffset,
condition?.TrailingStopLossOffset);
var execMsg = new ExecutionMessage
{
OriginalTransactionId = message.TransactionId,
ServerTime = response.Time.FromOanda(),
ExecutionType = ExecutionTypes.Transaction,
PortfolioName = message.PortfolioName,
HasOrderInfo = true,
};
var tradeData = response.TradeOpened;
if (tradeData != null)
{
execMsg.OrderState = OrderStates.Done;
execMsg.OrderId = tradeData.Id;
}
else
{
execMsg.OrderState = OrderStates.Active;
execMsg.OrderId = response.OrderOpened.Id;
}
SendOutMessage(execMsg);
if (tradeData != null)
{
SendOutMessage(new ExecutionMessage
{
OriginalTransactionId = message.TransactionId,
ExecutionType = ExecutionTypes.Transaction,
TradePrice = (decimal)tradeData.Price,
TradeVolume = tradeData.Units,
ServerTime = tradeData.Time.FromOanda(),
TradeId = tradeData.Id,
HasTradeInfo = true,
});
}
}
示例2: ProcessExecution
/// <summary>
/// Рассчитать комиссию.
/// </summary>
/// <param name="message">Сообщение, содержащее информацию по заявке или собственной сделке.</param>
/// <returns>Комиссия. Если комиссию рассчитать невозможно, то будет возвращено <see langword="null"/>.</returns>
public decimal? ProcessExecution(ExecutionMessage message)
{
var commission = OnProcessExecution(message);
if (commission != null)
Commission += commission.Value;
return commission;
}
示例3: PnLInfo
/// <summary>
/// Initializes a new instance of the <see cref="PnLInfo"/>.
/// </summary>
/// <param name="trade">Own trade.</param>
/// <param name="closedVolume">The volume of position, which was closed by own trade.</param>
/// <param name="pnL">The profit, realized by this trade.</param>
public PnLInfo(ExecutionMessage trade, decimal closedVolume, decimal pnL)
{
if (trade == null)
throw new ArgumentNullException(nameof(trade));
if (closedVolume < 0)
throw new ArgumentOutOfRangeException(nameof(closedVolume), closedVolume, LocalizedStrings.Str946);
Trade = trade;
ClosedVolume = closedVolume;
PnL = pnL;
}
示例4: ProcessExecution
/// <summary>
/// To calculate commission.
/// </summary>
/// <param name="message">The message containing the information about the order or own trade.</param>
/// <returns>The commission. If the commission can not be calculated then <see langword="null" /> will be returned.</returns>
public virtual decimal? ProcessExecution(ExecutionMessage message)
{
if (_rules.Count == 0)
return null;
var commission = _rules.Cache.Sum(rule => rule.ProcessExecution(message));
if (commission != null)
Commission += commission.Value;
return commission;
}
示例5: ProcessMyTrade
/// <summary>
/// Рассчитать прибыльность сделки. Если сделка уже ранее была обработана, то возвращается предыдущая информация.
/// </summary>
/// <param name="trade">Сделка.</param>
/// <returns>Информация о новой сделке.</returns>
public virtual PnLInfo ProcessMyTrade(ExecutionMessage trade)
{
if (trade == null)
throw new ArgumentNullException("trade");
lock (_portfolioManagers.SyncRoot)
{
var manager = _portfolioManagers.SafeAdd(trade.PortfolioName, pf => new PortfolioPnLManager(pf));
PnLInfo info;
if (manager.ProcessMyTrade(trade, out info))
_realizedPnL += info.PnL;
return info;
}
}
示例6: ProcessMyTrade
/// <summary>
/// To calculate trade profitability. If the trade was already processed earlier, previous information returns.
/// </summary>
/// <param name="trade">Trade.</param>
/// <param name="info">Information on new trade.</param>
/// <returns><see langword="true" />, if new trade received, otherwise, <see langword="false" />.</returns>
public bool ProcessMyTrade(ExecutionMessage trade, out PnLInfo info)
{
if (trade == null)
throw new ArgumentNullException(nameof(trade));
var tradeId = trade.GetTradeId();
if (_tradeInfos.TryGetValue(tradeId, out info))
return false;
var queue = _securityPnLs.SafeAdd(trade.SecurityId, security => new PnLQueue(security));
info = queue.Process(trade);
_tradeInfos.Add(tradeId, info);
_realizedPnL += info.PnL;
return true;
}
示例7: ClientOnOrderRegisterResult
/// <summary>
/// Callback of the order (re)registration.
/// </summary>
/// <param name="transId">Transaction ID.</param>
/// <param name="data">(Re)registration result.</param>
/// <param name="ex">(Re)registration error.</param>
private void ClientOnOrderRegisterResult(long transId, PlaceEquityOrderResponse2 data, Exception ex)
{
if (ex != null)
{
this.AddWarningLog("RegisterOrder: {0}", ex);
SendOutMessage(new ExecutionMessage
{
OriginalTransactionId = transId,
OrderState = OrderStates.Failed,
Error = new InvalidOperationException(LocalizedStrings.Str2258Params.Put(transId, ex)),
OrderStatus = OrderStatus.RejectedBySystem,
ExecutionType = ExecutionTypes.Transaction,
HasOrderInfo = true,
});
return;
}
var msg = new ExecutionMessage
{
SecurityId = new SecurityId { SecurityCode = data.symbol, BoardCode = AssociatedBoardCode },
PortfolioName = data.accountId.To<string>(),
Side = data.orderAction.ETradeActionToSide(),
OriginalTransactionId = transId,
OrderState = OrderStates.Active,
OrderId = data.orderNum,
ExecutionType = ExecutionTypes.Transaction,
ServerTime = ETradeUtil.ETradeTimestampToUTC(data.orderTime),
HasOrderInfo = true,
};
SaveOrder(transId, msg.OrderId ?? 0);
if (data.messageList != null)
{
foreach (var m in data.messageList)
this.AddDebugLog("ord #{0}: ({1}) {2}", data.orderNum, m.msgCode, m.msgDesc);
}
SendOutMessage(msg);
}
示例8: ProcessMyTradeMessage
public Tuple<MyTrade, bool> ProcessMyTradeMessage(Security security, ExecutionMessage message)
{
if (security == null)
throw new ArgumentNullException(nameof(security));
if (message == null)
throw new ArgumentNullException(nameof(message));
var originalTransactionId = _orderStatusTransactions.Contains(message.OriginalTransactionId)
? 0 : message.OriginalTransactionId;
if (originalTransactionId == 0 && message.OrderId == null && message.OrderStringId.IsEmpty())
throw new ArgumentOutOfRangeException(nameof(message), originalTransactionId, LocalizedStrings.Str715);
var securityData = GetData(security);
var myTrade = securityData.MyTrades.TryGetValue(Tuple.Create(originalTransactionId, message.TradeId ?? 0));
if (myTrade != null)
return Tuple.Create(myTrade, false);
var order = GetOrder(security, originalTransactionId, message.OrderId, message.OrderStringId);
if (order == null)
return null;
var trade = message.ToTrade(EntityFactory.CreateTrade(security, message.TradeId, message.TradeStringId));
var isNew = false;
myTrade = securityData.MyTrades.SafeAdd(Tuple.Create(order.TransactionId, trade.Id), key =>
{
isNew = true;
var t = EntityFactory.CreateMyTrade(order, trade);
if (t.ExtensionInfo == null)
t.ExtensionInfo = new Dictionary<object, object>();
if (message.Commission != null)
t.Commission = message.Commission;
if (message.Slippage != null)
t.Slippage = message.Slippage;
message.CopyExtensionInfo(t);
//trades.Add(t);
_myTrades.Add(t);
return t;
});
return Tuple.Create(myTrade, isNew);
// mika
// http://stocksharp.com/forum/yaf_postst1072_Probliemy-so-sdielkami--pozitsiiami.aspx
// из-за того, что сделки по заявке иногда приходит быстрее события NewOrders, неправильно расчитывается поза по стратегиям
//var raiseOrderChanged = false;
//trades.SyncDo(d =>
//{
// var newBalance = order.Volume - d.Sum(t => t.Trade.Volume);
// if (order.Balance > newBalance)
// {
// raiseOrderChanged = true;
// order.Balance = newBalance;
// if (order.Balance == 0)
// order.State = OrderStates.Done;
// }
//});
//if (raiseOrderChanged)
// RaiseOrderChanged(order);
}
示例9: ProcessOrderMessage
public Tuple<Order, bool, bool> ProcessOrderMessage(Security security, ExecutionMessage message)
{
if (security == null)
throw new ArgumentNullException(nameof(security));
if (message == null)
throw new ArgumentNullException(nameof(message));
if (message.Error != null)
throw new ArgumentException(LocalizedStrings.Str714Params.PutEx(message));
bool isNew;
var transactionId = message.TransactionId;
if (transactionId == 0)
{
// ExecMsg.OriginalTransactionId == OrderStatMsg.TransactionId when orders info requested by OrderStatMsg
transactionId = _orderStatusTransactions.Contains(message.OriginalTransactionId) ? 0 : message.OriginalTransactionId;
}
var securityData = GetData(security);
var orderInfo = GetOrderInfo(securityData, message.OrderType, transactionId, message.OrderId, message.OrderStringId, trId =>
{
var o = EntityFactory.CreateOrder(security, message.OrderType, trId);
o.Time = message.ServerTime;
o.Price = message.OrderPrice;
o.Volume = message.OrderVolume ?? 0;
o.Direction = message.Side;
o.Comment = message.Comment;
o.ExpiryDate = message.ExpiryDate;
o.Condition = message.Condition;
o.UserOrderId = message.UserOrderId;
o.Portfolio = message.PortfolioName.IsEmpty()
? _portfolios.FirstOrDefault().Value
: ProcessPortfolio(message.PortfolioName).Item1;
o.ClientCode = message.ClientCode;
return o;
}, out isNew, true);
if (orderInfo == null)
return null;
var order = orderInfo.Item1;
var isCancelled = orderInfo.Item2;
//var isReReregisterCancelled = orderInfo.Item3;
var raiseNewOrder = orderInfo.Item3;
var isPending = order.State == OrderStates.Pending;
//var isPrevIdSet = (order.Id != null || !order.StringId.IsEmpty());
bool isChanged;
if (order.State == OrderStates.Done)
{
// данные о заявке могут приходить из маркет-дата и транзакционного адаптеров
isChanged = false;
//throw new InvalidOperationException("Изменение заявки в состоянии Done невозможно.");
}
else
{
if (message.OrderId != null)
order.Id = message.OrderId.Value;
if (!message.OrderStringId.IsEmpty())
order.StringId = message.OrderStringId;
if (!message.OrderBoardId.IsEmpty())
order.BoardId = message.OrderBoardId;
//// некоторые коннекторы не транслируют при отмене отмененный объем
//// esper. при перерегистрации заявок необходимо обновлять баланс
//if (message.Balance > 0 || !isCancelled || isReReregisterCancelled)
//{
// // BTCE коннектор не транслирует баланс заявки
// if (!(message.OrderState == OrderStates.Active && message.Balance == 0))
// order.Balance = message.Balance;
//}
if (message.Balance != null)
order.Balance = message.Balance.Value;
// IB коннектор не транслирует состояние заявки в одном из своих сообщений
if (message.OrderState != null)
order.State = message.OrderState.Value;
if (order.Time == DateTimeOffset.MinValue)
order.Time = message.ServerTime;
// для новых заявок используем серверное время,
// т.к. заявка получена первый раз и не менялась
// ServerTime для заявки - это время регистрации
order.LastChangeTime = isNew ? message.ServerTime : message.LocalTime;
order.LocalTime = message.LocalTime;
//нулевой объем может быть при перерегистрации
if (order.Volume == 0 && message.OrderVolume != null)
//.........这里部分代码省略.........
示例10: ReadOrderStatus
private void ReadOrderStatus(IBSocket socket, ServerVersions version)
{
var id = socket.ReadInt();
var status = socket.ReadOrderStatus();
/* filled */
socket.ReadInt();
var balance = socket.ReadDecimal();
var avgPrice = socket.ReadDecimal();
var permId = version >= ServerVersions.V2 ? socket.ReadInt() : (int?)null;
var parentId = version >= ServerVersions.V3 ? socket.ReadInt() : (int?)null;
var lastTradePrice = version >= ServerVersions.V4 ? socket.ReadDecimal() : (decimal?)null;
var clientId = version >= ServerVersions.V5 ? socket.ReadInt() : (int?)null;
var whyHeld = version >= ServerVersions.V6 ? socket.ReadStr() : null;
var execMsg = new ExecutionMessage
{
ExecutionType = ExecutionTypes.Transaction,
OriginalTransactionId = id,
Balance = balance,
OrderStatus = status,
OrderState = status.ToOrderState(),
HasOrderInfo = true,
};
execMsg.SetAveragePrice(avgPrice);
if (permId != null)
execMsg.SetPermId(permId.Value);
if (parentId != null)
execMsg.Condition = new IBOrderCondition { ParentId = parentId.Value };
if (lastTradePrice != null)
execMsg.SetLastTradePrice(lastTradePrice.Value);
if (clientId != null)
execMsg.SetClientId(clientId.Value);
if (whyHeld != null)
execMsg.SetWhyHeld(whyHeld);
SendOutMessage(execMsg);
}
示例11: WriterFixOrderCondition
protected override void WriterFixOrderCondition(IFixWriter writer, ExecutionMessage message)
{
writer.WriteOrderCondition((QuikOrderCondition)message.Condition, TransactionSession.DateTimeFormat);
}
示例12: SendOutErrorExecution
private void SendOutErrorExecution(ExecutionMessage execMsg, Exception ex)
{
execMsg.ServerTime = CurrentTime;
execMsg.Error = ex;
execMsg.OrderState = OrderStates.Failed;
SendOutMessage(execMsg);
}
示例13: OnProcess
/// <summary>
/// Process message.
/// </summary>
/// <param name="message">Message.</param>
/// <returns>The result of processing. If <see langword="null" /> is returned, then generator has no sufficient data to generate new message.</returns>
protected override Message OnProcess(Message message)
{
DateTimeOffset time;
switch (message.Type)
{
case MessageTypes.Board:
return null;
case MessageTypes.Level1Change:
{
var l1Msg = (Level1ChangeMessage)message;
var value = l1Msg.Changes.TryGetValue(Level1Fields.LastTradePrice);
if (value != null)
_lastTradePrice = (decimal)value;
time = l1Msg.ServerTime;
break;
}
case MessageTypes.Execution:
{
var execMsg = (ExecutionMessage)message;
switch (execMsg.ExecutionType)
{
case ExecutionTypes.Tick:
case ExecutionTypes.Trade:
_lastTradePrice = execMsg.TradePrice.Value;
break;
case ExecutionTypes.OrderLog:
if (execMsg.TradePrice != null)
_lastTradePrice = execMsg.TradePrice.Value;
break;
default:
return null;
}
time = execMsg.ServerTime;
break;
}
case MessageTypes.Time:
{
var timeMsg = (TimeMessage)message;
time = timeMsg.ServerTime;
break;
}
default:
return null;
}
if (!IsTimeToGenerate(time))
return null;
var trade = new ExecutionMessage
{
SecurityId = SecurityId,
TradeId = IdGenerator.GetNextId(),
ServerTime = time,
LocalTime = time.LocalDateTime,
OriginSide = GenerateDirection ? RandomGen.GetEnum<Sides>() : (Sides?)null,
Volume = Volumes.Next(),
ExecutionType = ExecutionTypes.Tick
};
var priceStep = SecurityDefinition.PriceStep ?? 0.01m;
_lastTradePrice += RandomGen.GetInt(-MaxPriceStepCount, MaxPriceStepCount) * priceStep;
if (_lastTradePrice <= 0)
_lastTradePrice = priceStep;
trade.TradePrice = _lastTradePrice;
LastGenerationTime = time;
return trade;
}
示例14: OnProcessExecution
/// <summary>
/// To calculate commission.
/// </summary>
/// <param name="message">The message containing the information about the order or own trade.</param>
/// <returns>The commission. If the commission can not be calculated then <see langword="null" /> will be returned.</returns>
protected override decimal? OnProcessExecution(ExecutionMessage message)
{
if (message.ExecutionType != ExecutionTypes.Trade)
return null;
if (++_currentCount < Count)
return null;
_currentCount = 0;
return (decimal)Value;
}
示例15: OnProcessOrders
private void OnProcessOrders(string[] data)
{
var f = Wrapper.FieldsOrders;
if (data.Length > 0)
this.AddLog(LogLevels.Debug, () => "OnProcessOrders:\n" + data.Join("\n"));
foreach (var str in data)
{
var cols = str.ToColumns();
// 83487901|41469-000|42550|M|B|8356|1|1|0:00:00||FORTS|0|
// ...
// 83487901|41469-000|42550|M|B|8356|1|0|12.12.2011 16:31:41|2198931532|FORTS|0|
// NOTE: когда в первый раз приходит апдейт по заявке в нем нет ни времени, ни комментария.
// 84352688|41469-000|12910|M|S|80.13|10|0|22.12.2011 17:16:58||MICEX_SHR|0|0|
// 84352688|41469-000|12910|M|S|80.13|10|0|22.12.2011 17:16:58|2968835969|MICEX_SHR|0|80.408|
// NOTE: на ММВБ заявка сперва приходит с пустым комментарием!
var orderId = f.OrdNo.GetValue(cols);
var transId = f.Comments.GetValue(cols);
if (transId == 0)
{
var alfaTransactionId = _alfaIds.TryGetKey(orderId);
transId = _localIds.TryGetKey(alfaTransactionId);
if (transId == 0)
{
this.AddWarningLog("transaction id for order #{0} not found. creating new one.", orderId);
transId = TransactionIdGenerator.GetNextId();
if (alfaTransactionId == 0)
{
alfaTransactionId = --_lastFakeAlfaTransactionId;
_alfaIds.Add(alfaTransactionId, orderId);
}
_localIds.Add(transId, alfaTransactionId);
}
}
var msg = new ExecutionMessage
{
SecurityId = new SecurityId { Native = f.PaperNo.GetValue(cols) },
PortfolioName = GetPortfolioName(f.AccCode.GetValue(cols), this.GetBoardCode(f.PlaceCode.GetValue(cols))),
Side = f.BuySellStr.GetValue(cols),
OrderPrice = f.Price.GetValue(cols),
Volume = f.Qty.GetValue(cols),
Balance = f.Rest.GetValue(cols),
OriginalTransactionId = transId,
OrderId = orderId,
ExecutionType = ExecutionTypes.Order,
};
var orderTime = f.TsTime.GetValue(cols);
if (orderTime.TimeOfDay != TimeSpan.Zero)
msg.ServerTime = orderTime.ApplyTimeZone(TimeHelper.Moscow);
var stopPrice = f.StopPrice.GetValue(cols);
var orderType = f.Blank.GetValue(cols);
switch (orderType)
{
case "S":
{
var updateToPrice = f.UpdateNewPrice.GetValue(cols);
if (updateToPrice != 0) // Stop + TargetProfit
{
var updGrowPrice = f.UpdateGrowPrice.GetValue(cols);
var updDownPrice = f.UpdateDownPrice.GetValue(cols);
msg.Condition = new AlfaOrderCondition
{
StopPrice = stopPrice,
TargetPrice = msg.OrderPrice,
Slippage = msg.Side == Sides.Buy
? updateToPrice - updGrowPrice
: updDownPrice - updateToPrice
};
}
else // Stop
{
msg.Condition = new AlfaOrderCondition
{
StopPrice = stopPrice,
Slippage = stopPrice == 0
? 0
: msg.Side == Sides.Buy
? msg.OrderPrice - stopPrice
: stopPrice - msg.OrderPrice
};
}
msg.OrderType = OrderTypes.Conditional;
break;
}
case "T":
{
//.........这里部分代码省略.........