本文整理匯總了C#中QuantConnect.Orders.OrderEvent類的典型用法代碼示例。如果您正苦於以下問題:C# OrderEvent類的具體用法?C# OrderEvent怎麽用?C# OrderEvent使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
OrderEvent類屬於QuantConnect.Orders命名空間,在下文中一共展示了OrderEvent類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Fill
/********************************************************
* CLASS PROPERTIES
*********************************************************/
/********************************************************
* CLASS METHODS
*********************************************************/
/// <summary>
/// Process a order fill with the supplied security and order.
/// </summary>
/// <param name="vehicle">Asset we're working with</param>
/// <param name="order">Order class to check if filled.</param>
/// <returns>OrderEvent packet with the full or partial fill information</returns>
public virtual OrderEvent Fill(Security vehicle, Order order)
{
var fill = new OrderEvent(order);
try
{
//Based on the order type, select the fill model method.
switch (order.Type)
{
case OrderType.Limit:
fill = LimitFill(vehicle, order);
break;
case OrderType.StopMarket:
fill = StopFill(vehicle, order);
break;
case OrderType.Market:
fill = MarketFill(vehicle, order);
break;
}
}
catch (Exception err)
{
Log.Error("Equity.EquityTransactionModel.Fill(): " + err.Message);
}
return fill;
}
示例2: OnOrderEvent
public override void OnOrderEvent(OrderEvent fill)
{
SymbolData sd;
if (_sd.TryGetValue(fill.Symbol, out sd))
{
sd.OnOrderEvent(fill);
}
}
示例3: OnOrderEvent
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status == OrderStatus.Submitted)
{
Console.WriteLine(Time + ": Submitted: " + Transactions.GetOrderById(orderEvent.OrderId));
}
if (orderEvent.Status.IsFill())
{
Console.WriteLine(Time + ": Filled: " + Transactions.GetOrderById(orderEvent.OrderId));
}
}
示例4: Create
/// <summary>
/// Logs the OrderEvent Transaction
/// </summary>
/// <param name="orderEvent">the OrderEvent being logged</param>
/// <param name="includeHeader">Includes the field names</param>
public OrderTransaction Create(OrderEvent orderEvent, OrderTicket ticket, bool includeHeader = true)
{
var security = _algorithm.Securities[ticket.Symbol];
Order order = _algorithm.Transactions.GetOrderById(orderEvent.OrderId);
OrderTransaction t = new OrderTransaction();
// According to Scottrade a Buy is a negative amount (funds flow from my account to the seller's)
// However the Quantity filled is a negative number for Sell/Short and a positive for Buy/Long
// So multiply by -1 to give order value the correct sign
decimal orderValue = -1 * ticket.QuantityFilled * ticket.AverageFillPrice;
if (order != null)
{
var orderDateTime = _algorithm.Time;
DateTime settleDate = orderDateTime.AddDays(orderDateTime.DayOfWeek < DayOfWeek.Wednesday ? 3 : 5);
// Order Fees are a cost and negative to my account, therefore a negative number
var orderFees = security.TransactionModel.GetOrderFee(security, order) * -1;
#region "Create OrderTransaction"
t.ActionId = orderEvent.Direction.ToString() == "Buy" ? 1 : 13;
t.ActionNameUS = orderEvent.Direction.ToString();
t.Amount = orderValue;
t.Broker = "IB";
t.CUSIP = "CUSIP";
t.Commission = orderFees;
t.Description = string.Format("{0} {1} shares of {2} at ${3}", orderEvent.Direction, ticket.Quantity, orderEvent.Symbol, order.Price);
t.Direction = orderEvent.Direction;
t.Exchange = "";
t.Fees = 0; // need to calculate based upon difference in Portfolio[symbol].HoldingsValue between buy and sell
t.Id = 0;
t.Interest = 0;
t.Net = orderValue + orderFees;
t.OrderId = order.Id;
t.OrderType = ticket.OrderType;
t.Price = ticket.AverageFillPrice;
t.Quantity = ticket.Quantity;
t.RecordType = "Trade";
t.SettledDate = settleDate;
t.Symbol = ticket.Symbol.Value;
t.TaxLotNumber = String.Empty;
t.TradeDate = orderDateTime;
t.TradeNumber = 0;
#endregion
}
return t;
}
示例5: LastTradeProfit_FlatToShort
public void LastTradeProfit_FlatToShort()
{
var reference = new DateTime(2016, 02, 16, 11, 53, 30);
SecurityPortfolioManager portfolio;
var security = InitializeTest(reference, out portfolio);
var fillPrice = 100m;
var fillQuantity = -100;
var orderFee = 1m;
var orderDirection = fillQuantity > 0 ? OrderDirection.Buy : OrderDirection.Sell;
var fill = new OrderEvent(1, security.Symbol, reference, OrderStatus.Filled, orderDirection, fillPrice, fillQuantity, orderFee);
portfolio.ProcessFill(fill);
// zero since we're from flat
Assert.AreEqual(0, security.Holdings.LastTradeProfit);
}
示例6: MarketFill
/// <summary>
/// Default market fill model for the base security class. Fills at the last traded price.
/// </summary>
/// <param name="asset">Security asset we're filling</param>
/// <param name="order">Order packet to model</param>
/// <returns>Order fill information detailing the average price and quantity filled.</returns>
/// <seealso cref="StopMarketFill(Security, StopMarketOrder)"/>
/// <seealso cref="LimitFill(Security, LimitOrder)"/>
public virtual OrderEvent MarketFill(Security asset, MarketOrder order)
{
//Default order event to return.
var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
var orderFee = GetOrderFee(asset, order);
var fill = new OrderEvent(order, utcTime, orderFee);
if (order.Status == OrderStatus.Canceled) return fill;
// make sure the exchange is open before filling
if (!IsExchangeOpen(asset)) return fill;
try
{
//Order [fill]price for a market order model is the current security price
fill.FillPrice = asset.Price;
fill.Status = OrderStatus.Filled;
//Calculate the model slippage: e.g. 0.01c
var slip = GetSlippageApproximation(asset, order);
//Apply slippage
switch (order.Direction)
{
case OrderDirection.Buy:
fill.FillPrice += slip;
break;
case OrderDirection.Sell:
fill.FillPrice -= slip;
break;
}
// assume the order completely filled
if (fill.Status == OrderStatus.Filled) fill.FillQuantity = order.Quantity;
}
catch (Exception err)
{
Log.Error("SecurityTransactionModel.MarketFill(): " + err.Message);
}
return fill;
}
示例7: ReportTransaction
/// <summary>
/// Logs the OrderEvent Transaction
/// </summary>
/// <param name="orderEvent">the OrderEvent being logged</param>
public string ReportTransaction(OrderEvent orderEvent)
{
#region Print
string transmsg = string.Format("Order {0} on not found", orderEvent.OrderId);
Order order = _algorithm.Transactions.GetOrderById(orderEvent.OrderId);
decimal orderValue = orderEvent.FillQuantity*orderEvent.FillPrice;
//if (order != null)
//{
//var orderDateTime = order.Time;
decimal orderFees = 0;
orderFees = _algorithm.Securities[order.Symbol].TransactionModel.GetOrderFee(_algorithm.Securities[order.Symbol], order);
int actionid = orderEvent.Direction.ToString() == "Buy" ? 1 : 13;
transmsg = string.Format(
"{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}",
orderEvent.Symbol,
orderEvent.FillQuantity,
orderEvent.FillPrice,
orderEvent.Direction.ToString(),
order.Time,
order.Time.AddDays(4),
orderValue,
orderFees,
orderValue + orderFees,
"",
orderEvent.Direction + " share of " + orderEvent.Symbol + "at $" + orderEvent.FillPrice.ToString(),
actionid,
order.Id,
"Trade",
"taxlot",
""
);
// }
_logHandler.Debug(transmsg);
return transmsg;
#endregion
}
示例8: OrderEvent
/// <summary>
/// Send a new order event to the browser.
/// </summary>
/// <remarks>In backtesting the order events are not sent because it would generate a high load of messaging.</remarks>
/// <param name="newEvent">New order event details</param>
public void OrderEvent(OrderEvent newEvent)
{
// NOP. Don't do any order event processing for results in backtest mode.
}
示例9: HandleOrderEvent
private void HandleOrderEvent(OrderEvent fill)
{
// update the order status
var order = GetOrderByIdInternal(fill.OrderId);
if (order == null)
{
Log.Error("BrokerageTransactionHandler.HandleOrderEvent(): Unable to locate Order with id " + fill.OrderId);
return;
}
// set the status of our order object based on the fill event
order.Status = fill.Status;
// save that the order event took place, we're initializing the list with a capacity of 2 to reduce number of mallocs
//these hog memory
//List<OrderEvent> orderEvents = _orderEvents.GetOrAdd(orderEvent.OrderId, i => new List<OrderEvent>(2));
//orderEvents.Add(orderEvent);
//Apply the filled order to our portfolio:
if (fill.Status == OrderStatus.Filled || fill.Status == OrderStatus.PartiallyFilled)
{
Log.Debug("BrokerageTransactionHandler.HandleOrderEvent(): " + fill);
Interlocked.Exchange(ref _lastFillTimeTicks, DateTime.Now.Ticks);
// check if the fill currency and the order currency match the symbol currency
var security = _algorithm.Securities[fill.Symbol];
if (fill.FillPriceCurrency != security.SymbolProperties.QuoteCurrency)
{
Log.Error(string.Format("Currency mismatch: Fill currency: {0}, Symbol currency: {1}", fill.FillPriceCurrency, security.SymbolProperties.QuoteCurrency));
}
if (order.PriceCurrency != security.SymbolProperties.QuoteCurrency)
{
Log.Error(string.Format("Currency mismatch: Order currency: {0}, Symbol currency: {1}", order.PriceCurrency, security.SymbolProperties.QuoteCurrency));
}
try
{
_algorithm.Portfolio.ProcessFill(fill);
var conversionRate = security.QuoteCurrency.ConversionRate;
_algorithm.TradeBuilder.ProcessFill(fill, conversionRate);
}
catch (Exception err)
{
Log.Error(err);
_algorithm.Error(string.Format("Order Error: id: {0}, Error in Portfolio.ProcessFill: {1}", order.Id, err.Message));
}
}
// update the ticket and order after we've processed the fill, but before the event, this way everything is ready for user code
OrderTicket ticket;
if (_orderTickets.TryGetValue(fill.OrderId, out ticket))
{
ticket.AddOrderEvent(fill);
order.Price = ticket.AverageFillPrice;
}
else
{
Log.Error("BrokerageTransactionHandler.HandleOrderEvent(): Unable to resolve ticket: " + fill.OrderId);
}
//We have an event! :) Order filled, send it in to be handled by algorithm portfolio.
if (fill.Status != OrderStatus.None) //order.Status != OrderStatus.Submitted
{
//Create new order event:
_resultHandler.OrderEvent(fill);
try
{
//Trigger our order event handler
_algorithm.OnOrderEvent(fill);
}
catch (Exception err)
{
_algorithm.Error("Order Event Handler Error: " + err.Message);
// kill the algorithm
_algorithm.RunTimeError = err;
}
}
}
示例10: OnOrderEvent
/// <summary>
/// Handle order events
/// </summary>
/// <param name="orderEvent">the order event</param>
public override void OnOrderEvent(OrderEvent orderEvent)
{
base.OnOrderEvent(orderEvent);
ProcessOrderEvent(orderEvent);
}
示例11: HandleError
/// <summary>
/// Handles error messages from IB
/// </summary>
private void HandleError(object sender, IB.ErrorEventArgs e)
{
// https://www.interactivebrokers.com/en/software/api/apiguide/tables/api_message_codes.htm
// rewrite these messages to be single lined
e.ErrorMsg = e.ErrorMsg.Replace("\r\n", ". ").Replace("\r", ". ").Replace("\n", ". ");
Log.Trace(string.Format("InteractiveBrokersBrokerage.HandleError(): Order: {0} ErrorCode: {1} - {2}", e.TickerId, e.ErrorCode, e.ErrorMsg));
// figure out the message type based on our code collections below
var brokerageMessageType = BrokerageMessageType.Information;
if (ErrorCodes.Contains((int) e.ErrorCode))
{
brokerageMessageType = BrokerageMessageType.Error;
}
else if (WarningCodes.Contains((int) e.ErrorCode))
{
brokerageMessageType = BrokerageMessageType.Warning;
}
// code 1100 is a connection failure, we'll wait a minute before exploding gracefully
if ((int) e.ErrorCode == 1100 && !_disconnected1100Fired)
{
_disconnected1100Fired = true;
// begin the try wait logic
TryWaitForReconnect();
}
else if ((int) e.ErrorCode == 1102)
{
// we've reconnected
_disconnected1100Fired = false;
OnMessage(BrokerageMessageEvent.Reconnected(e.ErrorMsg));
}
if (InvalidatingCodes.Contains((int)e.ErrorCode))
{
Log.Trace(string.Format("InteractiveBrokersBrokerage.HandleError.InvalidateOrder(): Order: {0} ErrorCode: {1} - {2}", e.TickerId, e.ErrorCode, e.ErrorMsg));
// invalidate the order
var order = _orderProvider.GetOrderByBrokerageId(e.TickerId);
const int orderFee = 0;
var orderEvent = new OrderEvent(order, DateTime.UtcNow, orderFee) { Status = OrderStatus.Invalid };
OnOrderEvent(orderEvent);
}
OnMessage(new BrokerageMessageEvent(brokerageMessageType, (int) e.ErrorCode, e.ErrorMsg));
}
示例12: Scan
/// <summary>
/// Scans all the outstanding orders and applies the algorithm model fills to generate the order events
/// </summary>
public void Scan()
{
lock (_needsScanLock)
{
// there's usually nothing in here
if (!_needsScan)
{
return;
}
var stillNeedsScan = false;
// process each pending order to produce fills/fire events
foreach (var kvp in _pending)
{
var order = kvp.Value;
if (order.Status.IsClosed())
{
// this should never actually happen as we always remove closed orders as they happen
_pending.TryRemove(order.Id, out order);
continue;
}
var fill = new OrderEvent(order, Algorithm.UtcTime, 0);
Security security;
if (!Algorithm.Securities.TryGetValue(order.Symbol, out security))
{
Log.Error("BacktestingBrokerage.Scan(): Unable to process order: " + order.Id + ". The security no longer exists.");
// invalidate the order in the algorithm before removing
OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, 0m){Status = OrderStatus.Invalid});
_pending.TryRemove(order.Id, out order);
continue;
}
// check if we would actually be able to fill this
if (!Algorithm.BrokerageModel.CanExecuteOrder(security, order))
{
continue;
}
// verify sure we have enough cash to perform the fill
bool sufficientBuyingPower;
try
{
sufficientBuyingPower = Algorithm.Transactions.GetSufficientCapitalForOrder(Algorithm.Portfolio, order);
}
catch (Exception err)
{
// if we threw an error just mark it as invalid and remove the order from our pending list
Order pending;
_pending.TryRemove(order.Id, out pending);
order.Status = OrderStatus.Invalid;
OnOrderEvent(new OrderEvent(order, Algorithm.UtcTime, 0, "Error in GetSufficientCapitalForOrder"));
Log.Error(err);
Algorithm.Error(string.Format("Order Error: id: {0}, Error executing margin models: {1}", order.Id, err.Message));
continue;
}
//Before we check this queued order make sure we have buying power:
if (sufficientBuyingPower)
{
//Model:
var model = security.TransactionModel;
//Based on the order type: refresh its model to get fill price and quantity
try
{
switch (order.Type)
{
case OrderType.Limit:
fill = model.LimitFill(security, order as LimitOrder);
break;
case OrderType.StopMarket:
fill = model.StopMarketFill(security, order as StopMarketOrder);
break;
case OrderType.Market:
fill = model.MarketFill(security, order as MarketOrder);
break;
case OrderType.StopLimit:
fill = model.StopLimitFill(security, order as StopLimitOrder);
break;
case OrderType.MarketOnOpen:
fill = model.MarketOnOpenFill(security, order as MarketOnOpenOrder);
break;
case OrderType.MarketOnClose:
fill = model.MarketOnCloseFill(security, order as MarketOnCloseOrder);
break;
}
}
catch (Exception err)
//.........這裏部分代碼省略.........
示例13: SellingShortFromShortAddsToCash
public void SellingShortFromShortAddsToCash()
{
var securities = new SecurityManager(TimeKeeper);
var transactions = new SecurityTransactionManager(securities);
var portfolio = new SecurityPortfolioManager(securities, transactions);
portfolio.SetCash(0);
securities.Add(Symbols.AAPL, new Security(SecurityExchangeHours, CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
securities[Symbols.AAPL].Holdings.SetHoldings(100, -100);
var fill = new OrderEvent(1, Symbols.AAPL, DateTime.MinValue, OrderStatus.Filled, OrderDirection.Sell, 100, -100, 0);
Assert.AreEqual(-100, securities[Symbols.AAPL].Holdings.Quantity);
portfolio.ProcessFill(fill);
Assert.AreEqual(100 * 100, portfolio.Cash);
Assert.AreEqual(-200, securities[Symbols.AAPL].Holdings.Quantity);
}
示例14: UpdateOrder
/// <summary>
/// Updates the order with the same ID
/// </summary>
/// <param name="order">The new order information</param>
/// <returns>True if the request was made for the order to be updated, false otherwise</returns>
public override bool UpdateOrder(Order order)
{
if (true)
{
Order pending;
if (!_pending.TryGetValue(order.Id, out pending))
{
// can't update something that isn't there
return false;
}
lock (_needsScanLock)
{
_needsScan = true;
SetPendingOrder(order);
}
var orderId = order.Id.ToString();
if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(orderId);
// fire off the event that says this order has been updated
const int orderFee = 0;
var updated = new OrderEvent(order, Algorithm.UtcTime, orderFee) { Status = OrderStatus.Submitted };
OnOrderEvent(updated);
return true;
}
}
示例15: CancelOrder
/// <summary>
/// Cancels the order with the specified ID
/// </summary>
/// <param name="order">The order to cancel</param>
/// <returns>True if the request was made for the order to be canceled, false otherwise</returns>
public override bool CancelOrder(Order order)
{
Order pending;
if (!_pending.TryRemove(order.Id, out pending))
{
// can't cancel something that isn't there
return false;
}
var orderId = order.Id.ToString();
if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(order.Id.ToString());
// fire off the event that says this order has been canceled
const int orderFee = 0;
var canceled = new OrderEvent(order, Algorithm.UtcTime, orderFee) { Status = OrderStatus.Canceled };
OnOrderEvent(canceled);
return true;
}