namespace QuantConnect.Algorithm.CSharp {
public class BasicTemplateAlgorithm : QCAlgorithm {
String symbol = "SPY";
decimal price;
decimal stopLossPercent = 0.0002m;
decimal takeProfitPercent = 0.0002m;
private OrderTicket stopLoss;
private OrderTicket takeProfit;
int size = 100;
RelativeStrengthIndex rsi;
ExponentialMovingAverage ema100;
ExponentialMovingAverage ema200;
AverageDirectionalIndex adx;
public override void Initialize() {
AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);
rsi = RSI(symbol, 14, MovingAverageType.Simple, Resolution.Minute);
ema100 = EMA(symbol, 100, Resolution.Minute);
ema200 = EMA(symbol, 200, Resolution.Minute);
adx = ADX(symbol, 14, Resolution.Hour);
SetStartDate(2017, 10, 01);
SetEndDate(2017, 12, 01);
SetCash(100000);
}
public override void OnData(Slice data) {
price = data[symbol].Close;
if (!Portfolio.Invested && rsi > 70 && ema100 > ema200 && adx > 30){
longOrder(price);
}
if(!Portfolio.Invested && rsi < 30 && ema200 > ema100 && adx > 30){
shortOrder(price);
}
}
public override void OnOrderEvent(OrderEvent orderEvent){
var filledOrderId = orderEvent.OrderId;
if (takeProfit != null && stopLoss != null){
if (takeProfit.OrderId == filledOrderId){
Log(Time+": Cancelling stop loss");
stopLoss.Cancel();
} if (stopLoss.OrderId == filledOrderId){
Log(Time+": Cancelling proffit target");
takeProfit.Cancel();
}
}
}
private void longOrder(decimal currentPrice) {
var price = Securities[symbol].Price;
Order(symbol, size);
takeProfit = LimitOrder(symbol, -size, price*(1m + takeProfitPercent));
stopLoss = StopMarketOrder(symbol, -size, price*(1m - stopLossPercent));
}
private void shortOrder(decimal currentPrice) {
var price = Securities[symbol].Price;
Order(symbol, -size);
takeProfit = LimitOrder(symbol, size, price*(1m - takeProfitPercent));
stopLoss = StopMarketOrder(symbol, size, price*(1m + stopLossPercent));
}
}
}