namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Basic template algorithm simply initializes the date range and cash. This is a skeleton
/// framework you can use for designing an algorithm.
/// </summary>
public class BasicTemplateAlgorithm : QCAlgorithm
{
private Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
private int roundTrades = 0;
private OrderEvent _lastOrderEvent;
/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2018, 10, 3); //Set Start Date
SetEndDate(2018, 10, 3); //Set End Date
SetCash(100000); //Set Strategy Cash
// Find more symbols here: http://quantconnect.com/data
// Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
// Futures Resolution: Tick, Second, Minute
// Options Resolution: Minute Only.
AddEquity("SPY", Resolution.Minute);
// There are other assets with similar methods. See "Selecting Options" etc for more details.
// AddFuture, AddForex, AddCfd, AddOption
}
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public override void OnData(Slice data)
{
if (!data.Bars.ContainsKey("SPY")) return;
if (roundTrades > 20) return;
if (!Portfolio.Invested)
{
SetHoldings(_spy, 1);
return;
}
if (_lastOrderEvent != null &&
_lastOrderEvent.Status == OrderStatus.Submitted)
{
var ticket = Transactions.GetOrderTicket(_lastOrderEvent.OrderId);
ticket.Cancel();
}
if (Portfolio[_spy].IsLong)
// SetHoldings(_spy, -1);
PlaceOrder(-1, data.Bars["SPY"].Close);
else if (Portfolio[_spy].IsShort)
// SetHoldings(_spy, 1);
PlaceOrder(1, data.Bars["SPY"].Close);
roundTrades++;
}
private void PlaceOrder(double percentage, decimal limitPrice)
{
var quantity = CalculateOrderQuantity(_spy, percentage);
if (Math.Abs(quantity) > 0)
LimitOrder(_spy, quantity, limitPrice);
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
_lastOrderEvent = orderEvent;
Log($"{orderEvent} :: {Transactions.GetOrderById(orderEvent.OrderId)}");
}
}
}