本文整理汇总了C#中QuantConnect.Orders.MarketOrder类的典型用法代码示例。如果您正苦于以下问题:C# MarketOrder类的具体用法?C# MarketOrder怎么用?C# MarketOrder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MarketOrder类属于QuantConnect.Orders命名空间,在下文中一共展示了MarketOrder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: MarketFill
public override OrderEvent MarketFill(Security asset, MarketOrder order)
{
// this model randomly fills market orders
decimal absoluteRemaining;
if (!_absoluteRemainingByOrderId.TryGetValue(order.Id, out absoluteRemaining))
{
absoluteRemaining = order.AbsoluteQuantity;
_absoluteRemainingByOrderId.Add(order.Id, order.AbsoluteQuantity);
}
var fill = base.MarketFill(asset, order);
var absoluteFillQuantity = (int) (Math.Min(absoluteRemaining, _random.Next(0, 2*(int)order.AbsoluteQuantity)));
fill.FillQuantity = Math.Sign(order.Quantity) * absoluteFillQuantity;
if (absoluteRemaining == absoluteFillQuantity)
{
fill.Status = OrderStatus.Filled;
_absoluteRemainingByOrderId.Remove(order.Id);
}
else
{
absoluteRemaining = absoluteRemaining - absoluteFillQuantity;
_absoluteRemainingByOrderId[order.Id] = absoluteRemaining;
fill.Status = OrderStatus.PartiallyFilled;
}
_algorithm.Log("CustomFillModel: " + fill);
return fill;
}
示例2: MarketOrderFillsAtBidAsk
public void MarketOrderFillsAtBidAsk(OrderDirection direction)
{
var symbol = Symbol.Create("EURUSD", SecurityType.Forex, "fxcm");
var exchangeHours = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
var quoteCash = new Cash("USD", 1000, 1);
var symbolProperties = SymbolProperties.GetDefault("USD");
var security = new Forex(symbol, exchangeHours, quoteCash, symbolProperties);
var reference = DateTime.Now;
var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
var timeKeeper = new TimeKeeper(referenceUtc);
security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
var brokerageModel = new FxcmBrokerageModel();
var fillModel = brokerageModel.GetFillModel(security);
const decimal bidPrice = 1.13739m;
const decimal askPrice = 1.13746m;
security.SetMarketPrice(new Tick(DateTime.Now, symbol, bidPrice, askPrice));
var quantity = direction == OrderDirection.Buy ? 1 : -1;
var order = new MarketOrder(symbol, quantity, DateTime.Now);
var fill = fillModel.MarketFill(security, order);
var expected = direction == OrderDirection.Buy ? askPrice : bidPrice;
Assert.AreEqual(expected, fill.FillPrice);
}
示例3: GetInitialMarginRequiredForOrderTest
public void GetInitialMarginRequiredForOrderTest()
{
var security = GetSecurity(Symbols.AAPL);
security.MarginModel = new NoMarginCallMarginModel(2);
var order = new MarketOrder(security.Symbol, 100, DateTime.Now);
var actual = security.MarginModel.GetInitialMarginRequiredForOrder(security, order);
Assert.AreEqual(0, actual);
}
示例4: PerformsMarketFillBuy
public void PerformsMarketFillBuy()
{
var model = new SecurityTransactionModel();
var order = new MarketOrder(Symbols.SPY, 100, Noon, type: SecurityType.Equity);
var config = CreateTradeBarConfig(Symbols.SPY);
var security = new Security(SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, 1);
security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101.123m));
var fill = model.MarketFill(security, order);
Assert.AreEqual(order.Quantity, fill.FillQuantity);
Assert.AreEqual(security.Price, fill.FillPrice);
Assert.AreEqual(OrderStatus.Filled, fill.Status);
}
示例5: VerifyOpenMarketLeverage
public void VerifyOpenMarketLeverage()
{
// Market is Open on Tuesday, Feb, 16th 2016 at Noon
var leverage = 4m;
var expected = 100 * 100m / leverage + 1;
var model = new PatternDayTradingMarginModel();
var security = CreateSecurity(Noon);
var order = new MarketOrder(security.Symbol, 100, security.LocalTime);
Assert.AreEqual((double)leverage, (double)model.GetLeverage(security), 1e-3);
Assert.AreEqual((double)expected, (double)model.GetInitialMarginRequiredForOrder(security, order), 1e-3);
}
示例6: PerformsMarketFillSell
public void PerformsMarketFillSell()
{
var model = new SecurityTransactionModel();
var order = new MarketOrder(Symbols.SPY, -100, Noon);
var config = CreateTradeBarConfig(Symbols.SPY);
var security = new Security(SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));
security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101.123m));
var fill = model.MarketFill(security, order);
Assert.AreEqual(order.Quantity, fill.FillQuantity);
Assert.AreEqual(security.Price, fill.FillPrice);
Assert.AreEqual(OrderStatus.Filled, fill.Status);
}
示例7: PerformsMarketFillSell
public void PerformsMarketFillSell()
{
var model = new ForexTransactionModel();
var security = CreateSecurity();
var order = new MarketOrder(Symbols.USDJPY, -100, DateTime.Now, type: SecurityType.Forex);
security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
security.SetMarketPrice(new IndicatorDataPoint(Symbols.USDJPY, DateTime.Now, 101.123m));
var fill = model.MarketFill(security, order);
var slip = model.GetSlippageApproximation(security, order);
Assert.AreEqual(order.Quantity, fill.FillQuantity);
Assert.AreEqual(security.Price - slip, fill.FillPrice);
Assert.AreEqual(OrderStatus.Filled, fill.Status);
}
示例8: TotalCloseProfit
/// <summary>
/// Profit if we closed the holdings right now including the approximate fees.
/// </summary>
/// <remarks>Does not use the transaction model for market fills but should.</remarks>
public override decimal TotalCloseProfit()
{
if (AbsoluteQuantity == 0)
{
return 0;
}
decimal orderFee = 0;
if (AbsoluteQuantity > 0)
{
// this is in the account currency
var marketOrder = new MarketOrder(_cfd.Symbol, -Quantity, _cfd.LocalTime.ConvertToUtc(_cfd.Exchange.TimeZone));
orderFee = _cfd.FeeModel.GetOrderFee(_cfd, marketOrder);
}
// we need to add a conversion since the data is in terms of the quote currency
return (Price - AveragePrice) * Quantity * _cfd.ContractMultiplier * _cfd.QuoteCurrency.ConversionRate - orderFee;
}
示例9: TotalCloseProfit
/// <summary>
/// Profit if we closed the holdings right now including the approximate fees.
/// </summary>
/// <remarks>Does not use the transaction model for market fills but should.</remarks>
public override decimal TotalCloseProfit()
{
if (AbsoluteQuantity == 0)
{
return 0;
}
decimal orderFee = 0;
if (AbsoluteQuantity > 0)
{
// this is in the account currency
var marketOrder = new MarketOrder(_forex.Symbol, -Quantity, _forex.LocalTime.ConvertToUtc(_forex.Exchange.TimeZone), type:_forex.Type);
orderFee = _forex.TransactionModel.GetOrderFee(_forex, marketOrder);
}
// we need to add a conversion since the data is in terms of the quote currency
return (Price - AveragePrice)*Quantity*_forex.QuoteCurrency.ConversionRate - orderFee;
}
示例10: 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;
}
示例11: ConvertOrder
/// <summary>
/// Converts an FXCM order to a QuantConnect order.
/// </summary>
/// <param name="fxcmOrder">The FXCM order</param>
private Order ConvertOrder(ExecutionReport fxcmOrder)
{
Order order;
if (fxcmOrder.getOrdType() == OrdTypeFactory.LIMIT)
{
order = new LimitOrder
{
LimitPrice = Convert.ToDecimal(fxcmOrder.getPrice())
};
}
else if (fxcmOrder.getOrdType() == OrdTypeFactory.MARKET)
{
order = new MarketOrder();
}
else if (fxcmOrder.getOrdType() == OrdTypeFactory.STOP)
{
order = new StopMarketOrder
{
StopPrice = Convert.ToDecimal(fxcmOrder.getPrice())
};
}
else
{
throw new NotSupportedException("FxcmBrokerage.ConvertOrder(): The FXCM order type " + fxcmOrder.getOrdType() + " is not supported.");
}
var securityType = _symbolMapper.GetBrokerageSecurityType(fxcmOrder.getInstrument().getSymbol());
order.Symbol = _symbolMapper.GetLeanSymbol(fxcmOrder.getInstrument().getSymbol(), securityType, Market.FXCM);
order.Quantity = Convert.ToInt32(fxcmOrder.getOrderQty() * (fxcmOrder.getSide() == SideFactory.BUY ? +1 : -1));
order.Status = ConvertOrderStatus(fxcmOrder.getFXCMOrdStatus());
order.BrokerId.Add(fxcmOrder.getOrderID());
order.Duration = ConvertDuration(fxcmOrder.getTimeInForce());
order.Time = FromJavaDate(fxcmOrder.getTransactTime().toDate());
return order;
}
示例12: MarginComputesProperlyWithMultipleSecurities
public void MarginComputesProperlyWithMultipleSecurities()
{
var securities = new SecurityManager(TimeKeeper);
var transactions = new SecurityTransactionManager(securities);
var orderProcessor = new OrderProcessor();
transactions.SetOrderProcessor(orderProcessor);
var portfolio = new SecurityPortfolioManager(securities, transactions);
portfolio.CashBook["USD"].SetAmount(1000);
portfolio.CashBook.Add("EUR", 1000, 1.1m);
portfolio.CashBook.Add("GBP", -1000, 2.0m);
var eurCash = portfolio.CashBook["EUR"];
var gbpCash = portfolio.CashBook["GBP"];
var usdCash = portfolio.CashBook["USD"];
var time = DateTime.Now;
var config1 = CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL);
securities.Add(new Security(SecurityExchangeHours, config1, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
securities[Symbols.AAPL].SetLeverage(2m);
securities[Symbols.AAPL].Holdings.SetHoldings(100, 100);
securities[Symbols.AAPL].SetMarketPrice(new TradeBar{Time = time, Value = 100});
//Console.WriteLine("AAPL TMU: " + securities[Symbols.AAPL].MarginModel.GetMaintenanceMargin(securities[Symbols.AAPL]));
//Console.WriteLine("AAPL Value: " + securities[Symbols.AAPL].Holdings.HoldingsValue);
//Console.WriteLine();
var config2 = CreateTradeBarDataConfig(SecurityType.Forex, Symbols.EURUSD);
securities.Add(new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, usdCash, config2, SymbolProperties.GetDefault(CashBook.AccountCurrency)));
securities[Symbols.EURUSD].SetLeverage(100m);
securities[Symbols.EURUSD].Holdings.SetHoldings(1.1m, 1000);
securities[Symbols.EURUSD].SetMarketPrice(new TradeBar { Time = time, Value = 1.1m });
//Console.WriteLine("EURUSD TMU: " + securities[Symbols.EURUSD].MarginModel.GetMaintenanceMargin(securities[Symbols.EURUSD]));
//Console.WriteLine("EURUSD Value: " + securities[Symbols.EURUSD].Holdings.HoldingsValue);
//Console.WriteLine();
var config3 = CreateTradeBarDataConfig(SecurityType.Forex, Symbols.EURGBP);
securities.Add(new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours, gbpCash, config3, SymbolProperties.GetDefault(gbpCash.Symbol)));
securities[Symbols.EURGBP].SetLeverage(100m);
securities[Symbols.EURGBP].Holdings.SetHoldings(1m, 1000);
securities[Symbols.EURGBP].SetMarketPrice(new TradeBar { Time = time, Value = 1m });
//Console.WriteLine("EURGBP TMU: " + securities[Symbols.EURGBP].MarginModel.GetMaintenanceMargin(securities[Symbols.EURGBP]));
//Console.WriteLine("EURGBP Value: " + securities[Symbols.EURGBP].Holdings.HoldingsValue);
//Console.WriteLine();
//Console.WriteLine(portfolio.CashBook["USD"]);
//Console.WriteLine(portfolio.CashBook["EUR"]);
//Console.WriteLine(portfolio.CashBook["GBP"]);
//Console.WriteLine("CashBook: " + portfolio.CashBook.TotalValueInAccountCurrency);
//Console.WriteLine();
//Console.WriteLine("Total Margin Used: " + portfolio.TotalMarginUsed);
//Console.WriteLine("Total Free Margin: " + portfolio.MarginRemaining);
//Console.WriteLine("Total Portfolio Value: " + portfolio.TotalPortfolioValue);
var acceptedOrder = new MarketOrder(Symbols.AAPL, 101, DateTime.Now) { Price = 100 };
orderProcessor.AddOrder(acceptedOrder);
var request = new SubmitOrderRequest(OrderType.Market, acceptedOrder.SecurityType, acceptedOrder.Symbol, acceptedOrder.Quantity, 0, 0, acceptedOrder.Time, null);
request.SetOrderId(0);
orderProcessor.AddTicket(new OrderTicket(null, request));
var sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, acceptedOrder);
Assert.IsTrue(sufficientCapital);
var rejectedOrder = new MarketOrder(Symbols.AAPL, 102, DateTime.Now) { Price = 100 };
sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, rejectedOrder);
Assert.IsFalse(sufficientCapital);
}
示例13: ComputeMarginProperlyAsSecurityPriceFluctuates
public void ComputeMarginProperlyAsSecurityPriceFluctuates()
{
const decimal leverage = 1m;
const int quantity = (int) (1000*leverage);
var securities = new SecurityManager(TimeKeeper);
var transactions = new SecurityTransactionManager(securities);
var orderProcessor = new OrderProcessor();
transactions.SetOrderProcessor(orderProcessor);
var portfolio = new SecurityPortfolioManager(securities, transactions);
portfolio.CashBook["USD"].SetAmount(quantity);
var config = CreateTradeBarDataConfig(SecurityType.Equity, Symbols.AAPL);
securities.Add(new Security(SecurityExchangeHours, config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)));
var security = securities[Symbols.AAPL];
security.SetLeverage(leverage);
var time = DateTime.Now;
const decimal buyPrice = 1m;
security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, buyPrice, buyPrice, buyPrice, buyPrice, 1));
var order = new MarketOrder(Symbols.AAPL, quantity, time) {Price = buyPrice};
var fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity };
orderProcessor.AddOrder(order);
var request = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, order.Quantity, 0, 0, order.Time, null);
request.SetOrderId(0);
orderProcessor.AddTicket(new OrderTicket(null, request));
Assert.AreEqual(portfolio.CashBook["USD"].Amount, fill.FillPrice*fill.FillQuantity);
portfolio.ProcessFill(fill);
Assert.AreEqual(0, portfolio.MarginRemaining);
Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
Assert.AreEqual(quantity, portfolio.TotalPortfolioValue);
// we shouldn't be able to place a trader
var newOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) {Price = buyPrice};
bool sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, newOrder);
Assert.IsFalse(sufficientCapital);
// now the stock doubles, so we should have margin remaining
time = time.AddDays(1);
const decimal highPrice = buyPrice * 2;
security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, highPrice, highPrice, highPrice, highPrice, 1));
Assert.AreEqual(quantity, portfolio.MarginRemaining);
Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
Assert.AreEqual(quantity * 2, portfolio.TotalPortfolioValue);
// we shouldn't be able to place a trader
var anotherOrder = new MarketOrder(Symbols.AAPL, 1, time.AddSeconds(1)) { Price = highPrice };
sufficientCapital = transactions.GetSufficientCapitalForOrder(portfolio, anotherOrder);
Assert.IsTrue(sufficientCapital);
// now the stock plummets, so we should have negative margin remaining
time = time.AddDays(1);
const decimal lowPrice = buyPrice/2;
security.SetMarketPrice(new TradeBar(time, Symbols.AAPL, lowPrice, lowPrice, lowPrice, lowPrice, 1));
Assert.AreEqual(-quantity/2m, portfolio.MarginRemaining);
Assert.AreEqual(quantity, portfolio.TotalMarginUsed);
Assert.AreEqual(quantity/2m, portfolio.TotalPortfolioValue);
// this would not cause a margin call due to leverage = 1
bool issueMarginCallWarning;
var marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning);
Assert.AreEqual(0, marginCallOrders.Count);
// now change the leverage and buy more and we'll get a margin call
security.SetLeverage(leverage * 2);
order = new MarketOrder(Symbols.AAPL, quantity, time) { Price = buyPrice };
fill = new OrderEvent(order, DateTime.UtcNow, 0) { FillPrice = buyPrice, FillQuantity = quantity };
portfolio.ProcessFill(fill);
Assert.AreEqual(0, portfolio.TotalPortfolioValue);
marginCallOrders = portfolio.ScanForMarginCall(out issueMarginCallWarning);
Assert.AreNotEqual(0, marginCallOrders.Count);
Assert.AreEqual(-security.Holdings.Quantity, marginCallOrders[0].Quantity); // we bought twice
Assert.GreaterOrEqual(-portfolio.MarginRemaining, security.Price * marginCallOrders[0].Quantity);
}
示例14: PerformsMarketFillSell
public void PerformsMarketFillSell()
{
var model = new ForexTransactionModel();
var order = new MarketOrder(Symbol, -100, DateTime.Now, type: SecurityType.Forex);
var config = CreateTradeBarDataConfig(SecurityType.Forex, Symbol);
var security = new Security(SecurityExchangeHours.AlwaysOpen, config, 1);
security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
security.SetMarketPrice(new IndicatorDataPoint(Symbol, DateTime.Now, 101.123m));
var fill = model.MarketFill(security, order);
var slip = model.GetSlippageApproximation(security, order);
Assert.AreEqual(order.Quantity, fill.FillQuantity);
Assert.AreEqual(security.Price - slip, fill.FillPrice);
Assert.AreEqual(OrderStatus.Filled, fill.Status);
Assert.AreEqual(OrderStatus.Filled, order.Status);
}
示例15: InitializeTest
private static DateTime InitializeTest(out BasicTemplateAlgorithm algorithm, out Security security, out PartialMarketFillModel model, out MarketOrder order, out OrderTicket ticket)
{
var referenceTimeNY = new DateTime(2015, 12, 21, 13, 0, 0);
var referenceTimeUtc = referenceTimeNY.ConvertToUtc(TimeZones.NewYork);
algorithm = new BasicTemplateAlgorithm();
algorithm.SetDateTime(referenceTimeUtc);
var transactionHandler = new BacktestingTransactionHandler();
transactionHandler.Initialize(algorithm, new BacktestingBrokerage(algorithm), new TestResultHandler(Console.WriteLine));
Task.Run(() => transactionHandler.Run());
algorithm.Transactions.SetOrderProcessor(transactionHandler);
var config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Second, TimeZones.NewYork, TimeZones.NewYork, false, false, false);
security = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), config);
model = new PartialMarketFillModel(algorithm.Transactions, 2);
algorithm.Securities.Add(security);
algorithm.Securities[Symbols.SPY].FillModel = model;
security.SetMarketPrice(new Tick { Symbol = Symbols.SPY, Value = 100 });
algorithm.SetFinishedWarmingUp();
order = new MarketOrder(Symbols.SPY, 100, referenceTimeUtc) { Id = 1 };
var request = new SubmitOrderRequest(OrderType.Market, security.Type, security.Symbol, order.Quantity, 0, 0, algorithm.UtcTime, null);
ticket = algorithm.Transactions.ProcessRequest(request);
return referenceTimeUtc;
}