Here is my alert system code that I have setup in ThinkorSwim that gives visual/audio alerts when to enter/exit positions.
How to turn this into a trading algorithm trading the following:
FB, AAPL, NFLX, GOOG/GOOGL, AMZN, BABA, TSLA, PCLN
It alerts to buy when price is above 11 moving average, and sell when below
Code is tailored to a daytrader setting, but for Robinhood intergration, would be looking for a 4 hour/1 day charting time frame
Purpose: Plot signals when Price crosses above and below a
moving average
Notes
barNumber() is initialized to 0
Before the calculation, the rec value is set to 0 for all moments of time.
Inputs
input price = close;
input length = 11;
input maType = {default Weighted, Exponential, Simple, Wilders, Hull};
Input Moving Average types
plot ma;
ma.SetDefaultColor(color.YELLOW);
switch (maType) {
case Simple:
ma = Average(price, length);
case Exponential:
ma = ExpAverage(price, length);
case Weighted:
ma = wma(price, length);
case Wilders:
ma = WildersAverage(price, length);
case Hull:
ma = HullMovingAvg(price, length);
}
Set crossthreshold according to aggregationPeriod
def thrUp =
if getAggregationPeriod() == AggregationPeriod.HOUR
then 0.0001
else if getAggregationPeriod() == AggregationPeriod.FIFTEEN_MIN
then 0.0001
else if getAggregationPeriod() == AggregationPeriod.MIN
then 0.0001
else 0.000125;
def thrDn =
if getAggregationPeriod() == AggregationPeriod.HOUR
then 0.005
else if getAggregationPeriod() == AggregationPeriod.FIFTEEN_MIN
then 0.0025
else if getAggregationPeriod() == AggregationPeriod.MIN
then 0.0015
else 0.00125;
Price CrossOver
def up = close > ((1 + thrUp) * ma) and close[1] <= ((1 + thrUp) * ma[1]);
rec barUp = if up then barNumber() else if isNaN(barUp[1]) then barNumber() else barUp[1];
Price CrossUnder
def down = close < ((1 - thrDn) * ma) and close[1] >= ((1 - thrDn) * ma[1]);
rec barDown = if down then barNumber() else if isNaN(barDown[1]) then barNumber() else barDown[1];
Buy Signal
plot buy = if up and (if isNaN(barUp[1]) then 1 else if barUp[1] <= barDown then 1 else 0) then 1 else 0;
buy.setDefaultColor(color.GREEN);
buy.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Sell Signal
plot sell = if down and (if isNaN(barDown[1]) then 1 else if barDown[1] <= barUp then 1 else 0) then 1 else 0;
sell.setDefaultColor(color.RED);
sell.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);