namespace QuantConnect
{
public class MACDCross : QCAlgorithm
{
private Symbol _symbol;
private RollingWindow<MacdState> _win =new RollingWindow<MacdState>(2);
private MovingAverageConvergenceDivergence _macd;
private MacdState _macd_hist;
public override void Initialize()
{
SetCash(10000);
SetStartDate(2017, 01, 01);
SetEndDate(2017, 07, 17);
SetBrokerageModel(BrokerageName.OandaBrokerage);
_symbol = AddCfd("XAUUSD", Resolution.Minute).Symbol;
_macd = MACD(_symbol, 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily);
}
public void OnData(QuoteBars data)
{
// If MACD is not ready, return, do no add it to Rollwing Window (RW)
if (!_macd.IsReady) return;
// Add MACD to RW, we need a class to hold its values
_win.Add(new MacdState(_macd));
if (!_win.IsReady) return;
// Current value is index 0, past value index 1.
_macd_hist =_win[1];
var holdings = Portfolio[_symbol].Quantity;
if (holdings <= 0 &&
_macd.Fast > _macd.Slow && _macd_hist.Fast <_macd_hist.Slow)
{
Log("BUY >> " + data[_symbol].Close);
Log("Last Fast: " + _macd_hist.Fast);
Log("Last Slow: " + _macd_hist.Slow);
Log("Curr Fast: " + _macd.Fast);
Log("Curr Slow: " + _macd.Slow);
MarketOrder(_symbol, 200, false, "Buy 100 XAUUSD");
}
if (holdings >= 0 &&
_macd.Fast < _macd.Slow &&_macd_hist.Fast > _macd_hist.Slow)
{
Log("SELL >> " + data[_symbol].Close);
Log("Last Fast: " + _macd_hist.Fast);
Log("Last Slow: " + _macd_hist.Slow);
Log("Curr Fast: " + _macd.Fast);
Log("Curr Slow: " + _macd.Slow);
MarketOrder(_symbol, -200, false, "Sell 100 XAUUSD");
}
Plot("MACD", _macd.Fast, _macd.Slow);
}
}
// class to hold the current state of a MACD instance
public class MacdState
{
public readonly decimal Fast;
public readonly decimal Slow;
public readonly decimal Signal;
public readonly decimal Value;
public MacdState(MovingAverageConvergenceDivergence macd)
{
Fast = macd.Fast;
Slow = macd.Slow;
Signal = macd.Signal;
Value = macd.Current.Value;
}
}
}