namespace QuantConnect
{
public class BasicTemplateAlgorithm : QCAlgorithm
{
private readonly string Symbol = "DRWI";
private StrategicAction LastAction;
public DateTime PrimedDate = new DateTime(2016, 1, 11);
private RollingWindow<decimal> CloseHistory = new RollingWindow<decimal>(19);
public override void Initialize()
{
SetStartDate(2016, 1, 1);
SetEndDate(2016, 3, 6);
this.SetBrokerageModel(BrokerageName.TradierBrokerage, AccountType.Margin);
this.SetCash(25000);
this.AddSecurity(SecurityType.Equity, this.Symbol, Resolution.Second);
}
public void OnData(TradeBars data)
{
TradeBar tradeBar = null;
data.TryGetValue(this.Symbol, out tradeBar);
if (Time >= this.PrimedDate)
{
decimal movingAverage = this.CloseHistory.Average();
var action = this.Recommend(tradeBar, movingAverage);
switch (action)
{
case StrategicAction.BuyLong:
SellAndBuyLong(tradeBar, action);
break;
case StrategicAction.BuyShort:
SellAndBuyShort(tradeBar, action);
break;
}
this.LastAction = action;
}
this.CloseHistory.Add(tradeBar.Close);
}
public StrategicAction Recommend(TradeBar latestTradeBar, decimal movingAverage)
{
if (movingAverage > latestTradeBar.Close)
{
return StrategicAction.BuyLong;
}
else if (movingAverage < latestTradeBar.Close)
{
return StrategicAction.BuyShort;
}
else
{
return StrategicAction.Hold;
}
}
private void SellAndBuyLong(TradeBar tradeBar, StrategicAction action)
{
int optimalUnits = Convert.ToInt32(Math.Floor(this.Portfolio.TotalPortfolioValue / tradeBar.Close));
SellAll(tradeBar, OrderType.Short, action);
TryBuy(tradeBar, OrderType.Long, optimalUnits);
}
private void SellAndBuyShort(TradeBar tradeBar, StrategicAction action)
{
int optimalUnits = Convert.ToInt32(Math.Floor(this.Portfolio.TotalPortfolioValue / tradeBar.Close));
SellAll(tradeBar, OrderType.Long, action);
TryBuy(tradeBar, OrderType.Short, optimalUnits);
}
private void SellAll(TradeBar tradeBar, OrderType orderType, StrategicAction action)
{
if (this.LastAction != action && action != StrategicAction.Hold)
{
this.Liquidate(tradeBar.Symbol);
}
}
private void TryBuy(TradeBar tradeBar, OrderType orderType, int units)
{
if (this.GetHoldingBalance(tradeBar.Symbol) == 0)
{
switch (orderType)
{
case OrderType.Long:
this.Order(tradeBar.Symbol, units);
break;
case OrderType.Short:
this.Order(tradeBar.Symbol, -units);
break;
}
}
}
public decimal GetHoldingBalance(string symbol)
{
Security security = this.Securities.Values.SingleOrDefault(m => string.Compare(m.Symbol, symbol) == 0);
return security.Holdings.AbsoluteHoldingsCost;
}
}
public enum StrategicAction
{
Hold,
BuyShort,
BuyLong
}
public enum OrderType
{
Long,
Short
}
}