namespace QuantConnect
{
public class ScheduledEventPractice : QCAlgorithm
{
public string symbol = "SPY";
public decimal dailyLevel;
//Initialize the data and resolution you require for your strategy:
public override void Initialize()
{
SetStartDate(2016, 1, 1);
SetEndDate(DateTime.Now.Date.AddDays(-1));
SetCash(25000);
//Add as many securities as you like. All the data will be passed into the event handler:
AddSecurity(SecurityType.Equity, symbol , Resolution.Minute);
}
//Data Event Handler: New data arrives here.
public void OnData(TradeBars data)
{
// Schedule event to fire daily and capture Close of first bar
Schedule.On(DateRules.EveryDay(symbol), TimeRules.At(9, 31, 01), () =>
{
Log("Scheduled Event fired at : " + Time);
dailyLevel = data[symbol].Close;
Log("dailyLevel = " + dailyLevel );
});
// If not holding stock, order if price drops to 50 cents below captured dailyLevel
if (!Portfolio.HoldStock && data[symbol].Close < dailyLevel - 0.50m)
{
int quantity = (int)Math.Floor(Portfolio.Cash / data[symbol].Close);
Order(symbol, quantity);
Log("Purchased " + symbol + " : " + quantity + " at " + data[symbol].Close + " on " + Time);
}
// If holding stock, sell if price rises to 75 cents above purchased price
if (Portfolio.HoldStock && data[symbol].Close >= Portfolio[symbol].AveragePrice + 0.75m)
{
int _holdings = Portfolio[symbol].Quantity;
decimal _sellPrice = Securities[symbol].Price;
Liquidate();
Log("Sold " + symbol + " : " + _holdings + " at " + _sellPrice + " on " + Time);
}
}
}
}