public void OnData(TradeBars tradeBars) { TradeBar bar; if (!tradeBars.TryGetValue(_symbol, out bar)) { return; } if (!Portfolio.Invested && Time.Date == EndDate.Date) { Buy(_symbol, 1); } }
public void OnData(TradeBars data) { // wait for slowest indicator to fully initialize if (!emaShort.IsReady) { return; } TradeBar b = null; data.TryGetValue(symbol, out b); price = b.Close; holdings = Portfolio[symbol].Quantity; // EXIT if (b.Time.Minute == 45 && b.Time.Hour == endHour && holdings > 0 ) // exit long positions 1-2 hours after market open { Liquidate(); } if (holdings < 0 && (roc2 > 0 || price > stopLoss) ) // exit short positions with trailing stop or two-day uptrend { Liquidate(); } // On market open if (b.Time.Hour == 9 && b.Time.Minute == 30) { dayOpen = b.Open; } // ENTRY if (b.Time.Hour == 9 && b.Time.Minute == 30 // SAFETY -- only enter a new position if in cash // && Portfolio.Invested == false ) { // check for long entry if ((roc1 > 0 && // last trading day closed higher than the previous trading day roc2 > 0 && roc3 > 0) && roc4 > 0 && dayOpen < close0 * 1.00m && // today opened below last trading day's close price > emaShort ) { SetHoldings(symbol, 1.0m, false, "open"); // stopLoss = price*longSL; } // check for short entry if (roc2 < 0) // two-day downtrend { SetHoldings(symbol, -1.0m, false, "open"); stopLoss = price * shortSL; } } // if // update trailing stop loss if (holdings < 0 && price * shortSL < stopLoss) { stopLoss = price * shortSL; } } // OnData
/// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">TradeBars IDictionary object with your stock data</param> public void OnData(TradeBars data) { try { TradeBar b; if (!data.TryGetValue(Symbol, out b) || b == null) { return; } if (_history.IsReady) { if (IsFirstTradingMin(b)) { _firstBar = b; // enable entry on the first bar if not invested yet if (!Portfolio.Invested) { _enableEntry = true; } } decimal price = 0; if (IsExit(b, out price)) { Liquidate(Symbol); Log(">>Close>> " + b.Time + " " + Symbol + " @" + price); } else { bool isLong = true; if (IsEntry(b, out price, out isLong)) { int qnt = (int)(Portfolio.Cash / price); if (isLong) { SetHoldings(Symbol, 1.0); } else { qnt = -qnt; SetHoldings(Symbol, -1.0); } _trlStop = new TrailingStop(price, 2, isLong); _enableEntry = false; Log(">>BUY/sell>> " + b.Time + " " + qnt + " " + Symbol + " @" + price); } } } if (IsLastTradingMin(b)) { _history.Add(b); } } catch (Exception ex) { Error("OnData: " + ex.Message + "\r\n\r\n" + ex.StackTrace); } }