//On each data event, buy a few of each one: public void OnData(TradeBars data) { Debug("REALTIME: " + DateTime.Now.ToString("o") + " DATATIME: " + data.Time.ToString("o") + " REALTIME DELTA: " + (DateTime.Now - data.Time).TotalSeconds.ToString("0.000") + "sec COUNT: " + data.Count + " FILLFORWARD: " + data.Count(x => x.Value.IsFillForward)); foreach (var symbol in AllSymbols) { if (!Portfolio.ContainsKey(symbol)) { continue; } if (!Portfolio[symbol].Invested) { //Not invested, get invested: Order(symbol, 10); } else { if (Time.Second % 15 == 0) { var holdings = Portfolio[symbol].Quantity; Order(symbol, holdings * -2); } } } //Log timer: if (Time.Second % 15 == 0) { Log("Time: " + Time.ToShortTimeString()); } }
/// <summary> /// Submit a new order for quantity of symbol using type order. /// </summary> /// <param name="type">Buy/Sell Limit or Market Order Type.</param> /// <param name="symbol">Symbol of the MarketType Required.</param> /// <param name="quantity">Number of shares to request.</param> public int Order(string symbol, int quantity, OrderType type = OrderType.Market) { //Add an order to the transacion manager class: int orderId = -1; decimal price = 0; string orderRejected = "Order Rejected at " + Time.ToShortDateString() + " " + Time.ToShortTimeString() + ": "; //Internals use upper case symbols. symbol = symbol.ToUpper(); //Ordering 0 is useless. if (quantity == 0) { return(orderId); } if (type != OrderType.Market) { Debug(orderRejected + "Currently only market orders supported."); } //If we're not tracking this symbol: throw error: if (!Securities.ContainsKey(symbol)) { Debug(orderRejected + "You haven't requested " + symbol + " data. Add this with AddSecurity() in the Initialize() Method."); } //Set a temporary price for validating order for market orders: if (type == OrderType.Market) { price = Securities[symbol].Price; } try { orderId = Transacions.AddOrder(new Order(symbol, quantity, type, Time, price), Portfolio); if (orderId < 0) { //Order failed validaity checks and was rejected: Debug(orderRejected + OrderErrors.ErrorTypes[orderId]); } } catch (Exception err) { Error("Algorithm.Order(): Error sending order. " + err.Message); } return(orderId); }