| Overall Statistics |
|
Total Trades 0 Average Win 0% Average Loss 0% Compounding Annual Return 0% Drawdown 0% Expectancy 0 Net Profit 0% Sharpe Ratio 0 Loss Rate 0% Win Rate 0% Profit-Loss Ratio 0 Alpha 0 Beta 0 Annual Standard Deviation 0 Annual Variance 0 Information Ratio 0 Tracking Error 0 Treynor Ratio 0 Total Fees $0.00 |
namespace QuantConnect
{
/*
*/
public class BollingerBandsAlgorithm : QCAlgorithm
{
//Define required variables:
int quantity = 0;
decimal close = 0;
decimal high = 0;
decimal low = 0;
decimal tolerance = 0m; //0.1% safety margin in prices to avoid bouncing.
string symbol = "XAUUSD";
DateTime sampledToday = DateTime.Now;
//Set up the BB
//private AverageDirectionalIndex adx;
private BollingerBands bb;
private RelativeStrengthIndex rsi;
//private AverageTrueRange atr;
//Initialize the data and resolution you require for your strategy:
public override void Initialize()
{
SetStartDate(2017, 01, 01);
SetEndDate(DateTime.Now.Date);//.AddDays(-1));
SetCash(100000);
//Specify the Oanda Brokerage.
SetBrokerageModel(BrokerageName.OandaBrokerage);
//Add as many securities as you like. All the data will be passed into the event handler:
AddSecurity(SecurityType.Cfd, symbol, Resolution.Minute);
//adx = ADX(symbol, 14, Resolution.Daily);
bb = BB(symbol, 20, 2, MovingAverageType.Simple, Resolution.Daily);
rsi = RSI(symbol, 14, MovingAverageType.Simple, Resolution.Daily);
}
public void OnData(TradeBars data)
{
close = Securities[symbol].Close;
high = Securities[symbol].High;
low = Securities[symbol].Low;
//Wait until SMA's are ready:
if (!bb.IsReady || !rsi.IsReady) return;
//Get fresh cash balance: Set purchase quantity to equivalent 10% of portfolio.
decimal cash = Portfolio.Cash;
int holdings = Portfolio[symbol].Quantity;
quantity = Convert.ToInt32((cash * 0.5m) / close);
if (Portfolio.HoldStock)
{
ExitLogic(holdings);
}
else
{
EntryLogic(holdings);
}
}
private void ExitLogic(int holdings)
{
if (Portfolio[symbol].IsLong && !Portfolio[symbol].IsShort && close > (bb.UpperBand * (1+tolerance))) { //rsi > 70) {
Liquidate(symbol);
}
else if (Portfolio[symbol].IsShort && !Portfolio[symbol].IsLong && close < (bb.LowerBand * (1+tolerance))) { //rsi < 30) {
Liquidate(symbol);
}
}
private void EntryLogic(int holdings)
{
//OrderTicket limitOrderTicket;
if (close < (bb.LowerBand * (1+tolerance)) && rsi < 30) {
Order(symbol, Math.Abs(holdings) + quantity);
Log(Time.ToShortDateString() + "> Long > Holdings: " + holdings.ToString() + " Quantity:" + quantity.ToString());
}
else if (close < (bb.UpperBand * (1+tolerance)) && rsi > 70) {
Order(symbol, -(Math.Abs(holdings) + quantity));
Log(Time.ToShortDateString() + " > Go Short > Holdings: " + holdings.ToString() + " Quantity:" + quantity.ToString());
}
}
}
}