Hi guys,
I am trying to write a simple algorithm that buys a stock if it falls a certain amount, and sells it if the price goes above the price at which it was bought by a certain amount. unfortunately cannot work out how to keep purchase price as a constant variable over time. I would be extremely grateful if someone could show me how to do this!
Best
Hugo
namespace QuantConnect.Algorithm.CSharp
{
public class buythedip : QCAlgorithm
{
//Member variables
private static Symbol _google = QuantConnect.Symbol.Create("GOOGL", SecurityType.Equity, Market.USA);
private int ForwardLookingPeriod = 25;
private int BackwardLookingPeriod = 25;
private decimal fallAmount = Convert.ToDecimal(0.1);
private decimal riseAmount = Convert.ToDecimal(0.05);
private int minutesToExecute = 10;
private decimal relevantPrice;
private RollingWindow<decimal> _close_window;
public Boolean cash;
public Boolean buyTrigger;
public Boolean sellTrigger;
public override void Initialize() {
SetStartDate(2013,01,01);
SetEndDate(2018,02,01);
SetCash(30000);
AddEquity(_google, Resolution.Daily);
_close_window = new RollingWindow<decimal>(BackwardLookingPeriod);
IEnumerable<TradeBar> slices = History(_google, BackwardLookingPeriod);
foreach (TradeBar bar in slices) {
_close_window.Add(bar.Close);
}
Debug(_close_window[0]);
Console.WriteLine("Hugo Lu");
Schedule.On(DateRules.EveryDay(_google),
TimeRules.AfterMarketOpen(_google,minutesToExecute), //Execute the function at the start of the day
// x minutes in....
EveryDayOnMarketOpen);
}//Initialize end
public void EveryDayOnMarketOpen(){ //Define the bad boy
//Sanity Check; are there open orders?
if (Transactions.GetOpenOrders().Count > 0) {
return;
}
//Get information about however many periods ago
IEnumerable<TradeBar> slices = History(_google,BackwardLookingPeriod) ;
TradeBar BarOfInterest = slices.First();
decimal relevantClose = BarOfInterest.Close;
decimal yestClose = slices.Last().Close;
decimal fallPercent = 1 - (yestClose/relevantClose);
//Is it time to buy?
if(fallPercent > fallAmount && Portfolio.Cash > 100 ) {
buyTrigger = true;
relevantPrice = yestClose;
} else {
buyTrigger = false;
relevantPrice = 0;
};
if(buyTrigger)
{SetHoldings(_google,1);
}
//Is it time to sell?
if( ((yestClose / relevantPrice)-1)> riseAmount) {
sellTrigger = true;
} else { sellTrigger = false;};
if(sellTrigger) {
Liquidate();
};
}
}
}