OPEN-SOURCE SCRIPT

SPY 1 Minute Day Trader

מעודכן
When scalping options, users are looking for where breakouts are going to occur instead of sitting thru areas choppy price action that drain delta and cause them to lose value even if price is up trending. This script tries to identify when a trend reversal is expected based on one minute price action on the SPY. It alerts users to prepare for potential breakout when 5 out of the 6 key optimized parameters are discovered by showing a white L or S. Once all six trigger, it informs the user at the close of that candle with a golden triangle with Pivot Up or Pivot Down. As scalping options is something that is expected to be short in duration, a take profit and stop loss of 30 cents of price actions is established. If five or more parameters occur after the pivot is initiated, then stop losses and take profits are adhered to; however, if there are less, then it waits to take profit or stop the trade, as likely it is just noise and it will finish trend with an additional breakout.

This script has been created to take into account how the following variables impact trend for SPY 1 Minute:
ema vs 13 ema : A cross establishes start of trend
MACD (Line, Signal & Slope) : If you have momentum
ADX : if you are trending
RSI : If the trend has strength

The above has been optimized to determine pivot points in the trend using key values for these 6 indicators
bounce up = ema5 > ema13 and macdLine < .5 and adx > 20 and macdSlope > 0 and signalLine > -.1 and rsiSignal > 40
bounce down = ema5 < ema13 and macdLine > -.5 and adx > 20 and signalLine < 0 and macdSlope < 0 and rsiSignal < 60

White L's indicate that 5 of 6 conditions are met due to impending uptrend w/ missing one in green below it
Yellow L's indicate that 6 of 6 conditions still are met
White S's indicate that 5 of 6 conditions are met due to impending downtrend w/ missing condition in red above it
Yellow S's indicate that 6 of 6 conditions still are met

After a downtrend or uptrend is established, once it closes it can't repeat for 10 minutes
Won't open any trades on last two minutes of any hours to avoid volatility
Will close any open trades going into last minute of hour to avoid large overnight random swings.
הערות שחרור
When the bounce up or bounce down is detected it shows yellow tick marks above and below the orange triangle marker so users have an idea where potential run ends or to better understand when the analytic is wrong.
הערות שחרור
Updated chart so it has clean chart vs other indicators.
הערות שחרור
Corrected strategy tester so it used 10% of equity.
הערות שחרור
Updated script to change wait time to 12 minutes between trades.
Since pivot logic runs based on candle close of prior candle. If prior candle had a large change of greater than expected move, then algo waits to initiate. This removes false signals that then closed immediately.
הערות שחרור
Updated exit strategy of trade so if trending is detected via high ADX, Average Directional Index, the .30 take profit is ignored and trade will not close until either the ADX drops, which signals no trending, or if the 5 minute close for a given minute crosses the 5 minute 13 EMA. This avoids a series of closing positions and then waits when to re-enter when trending in a direction. Even though the win % drops slightly, as the winning position is held longer it profits a greater amount. Also, when exiting a position now ensure entering proper exit portion for Pivot Up vs Pivot down. Also, updated entering Pivot Up and Pivot Down logic to only enter if not in a position.
הערות שחרור
If stop loss is breached it now closes trade instead of relying completely on higher degree trend closing trade.
הערות שחרור
By mistake deleted script. Re-adding.
הערות שחרור
Tweaked MACD signal to allow trades to be entered sooner for both Pivot Up and Pivot Down.
הערות שחרור
Updated stop loss logic to percentage so now this will work on any trending stock!
הערות שחרור
Main change further optimized Pivot Up and Pivot Down by including 3 new indicators: Stochastic signal, MACD difference and Root Mean Square of ATR. Also tweaked MACD signal and RSI. This slightly lessoned amounts of trades but improved their ability to enter sooner. Also by tweaking ADX from 25 to 18 was able to hold trades longer. These changes improved backtesting results by about 25%

Also did some basic house cleaning on stale duplicate code and initial header explanation.
הערות שחרור
Got rid of noisy trades by taking absolute difference between 5 & 13 ema on higher degree and ensuring it was > .11. This allowed the time between successful trades shrink to 7 minutes since not taking noisy trades. Now also only closing trades right before 10AM & 4PM (eliminated 1PM and 3PM). Backtest results indicated that trades shrunk by more than 50% but profits close to doubled and percent profitable jumped to over 70% due to noisy trades being removed.
הערות שחרור
Now including 5 min 5 EMA (blue) and 13 EMA (orange). These are used on 1 min to exit trades which are trending and not take trades when the difference is less than 0.12. If less than 0.12 and only parameter not hitting, you will see a 5 below/above the L or S that is prepping you to get ready for pivot point.
הערות שחרור
There are 10 parameters not 9 so needed to update for Pivot Signals and letters to show properly.
הערות שחרור
Prior release was correct plus needed to remove unnecessary indicators.
הערות שחרור
Discovered a couple inconsistencies with macdLine letter colors so updated.
הערות שחרור
Removed candle spike logic as noisy trades have been removed.
הערות שחרור
Updating description. Now that this works with any trending stock, stops and take profits are 0.00075%
Tweaked bounce up and bounce down logic with a
Updated description about wait period for trades as none is enabled due to removing noisy trades
הערות שחרור
Only cleaned-up notes in code. Reload not necessary for this version.
הערות שחרור
Only now entering long trades if close > open and short trades if close < open. This was added as a new condition for white and gold L's and S's as well.
Also not entering trades during first five minutes. It can enter if still trending in 6th minute. Also, now only not taking trades in last two minutes of day instead of last two minutes of every hour.
הערות שחרור
Released with extra unnecessary stuff. Re-releasing clean version.
הערות שחרור
With fuchsia line now indicate high low price of day and will not Pivot Up when within 0.05% of high of day and will not Pivot Down when within 0.05% of low of day.
Will now suggest protecting trades when longs achieve 2x take profit and shorts achieve 1.8x take profits. Stops are then set to break-even.
These changes have boosted win percentage to over 80% as indicated by backtesting.
הערות שחרור
Tweaked HOD / LOD logic so that won't take if within 0.1% instead of 0.05%
הערות שחרור
Updated to give some leeway on entering trade only if Pivot Up and Pivot Down by comparing prior candle and 3 cent buffer.
הערות שחרור
Changed Protect Longs to Exit Partial Longs and same with Shorts so it is more understandable
Remove extra MACD indicator added by mistake in last release.
הערות שחרור
Critical update as discovered issue with short stop loss that was causing it to sometimes close trade too early
Prepping tool for VWAP inclusion
הערות שחרור
Will now only take partial profit for Pivot Up once above 2x when a candle closes below the 5 minute 13 EMA and for Pivot Down once below 2x when a candle closes above the 5 minute 13 EMA
Added 2x Take Profit Indicators as an orange tick mark
הערות שחרור
Critical Update
Please note that in order to use this script Extended Hours trading must be turned off
Updated strategy and backtested/optimized 5 different trading periods throughout the day and color coordinated triangles based on best trading times of day for this script. Wasn't much of a surprise that first 90 minutes of day is best time to trade. Also lunchtime looks like good time as well for this script.
First 90 minutes: 94% win rate (green triangles)
Next hour: 80% win rate (orange triangles)
Lunchtime: 90% (green triangles)
After lunch until Power Hour: 80% (orange triangles)
Power Hour: 70% (red triangles)

Removed the following parameters from Pivot Up / Pivot Down signals: Stoichastic Signal, MACD Signal, MACD Difference between Line and Signal, RSI Signal
Removed low ADX from closing trade
הערות שחרור
Per other users feedback updated first line of code to stop repaint from occurring and improperly positively impacting backtest results. By add the following line backtest results were minimally impacted and first hour still rocks at 94% for last 38 days of trading.
strategy(title="SPY 1 Minute Day Trader", overlay=true, calc_on_every_tick=false, process_orders_on_close=true)
הערות שחרור
Removed lookahead=barmerge.lookahead_on from request.security in script to avoid repaint at end of day. Tweaked values to get backtest clean.
הערות שחרור
Had to remove volume or I get in trouble!
הערות שחרור
Updated colors based on new backtesting and determined that for this strategy
First 90 minutes and After lunch until power hour are good (green)
After first 90 minutes until lunch is bad (red)
1PM until power hour is great! (lime)
הערות שחרור
Added ADX to stay in trending trades that pop above 2x and tweaked 5 minute 5/13 ema difference.
הערות שחרור
Stay out of more trades before lunch!
הערות שחרור
Tweaked power hour to take less trades.
הערות שחרור
Fixed when one parameter short, now shows which one missing with silver L or S and Gold L or S when everything is there and trade is ongoing.
Also added barstate.isconfirmed so trades don't change at close of day. Didn't impact backtest.
הערות שחרור
Added 3x pin bar reversals with the ability to toggle them in inputs (positive impact to backtest with limited additional trades). Also cleaned up other inputs.
הערות שחרור
Updated to only take pin bar if not in that type of long/short position already and can take opposite position and close on trend reversal.
הערות שחרור
Updated so that pin bar has meaningful size to remove small signals that aren't true reversals. Improved win rate and lessened trades.
הערות שחרור
Optimized pin bar height for reversal signal
Added VWAP to stop trying to short when above VWAP 2 standard deviations and long when below VWAP 2 standard deviations. Reversals are unlikely at that point!
Show VWAP with basic 2 standard deviations
Cleaned-up function bar to remove unnecessary string of zeros
הערות שחרור
Disabled trading from 11 until 12 by default. Can enable in settings.
Changed 5 min difference of 5 & 13 EMA to reference percentage instead of fixed values to work with more stocks. This is however optimized for SPY.
Also optimized pin bar exit height strategy.
הערות שחרור
Turned off pin bar exits as closing trades too early
הערות שחרור
Fixed missing indicator to work on % instead of fixed value.
הערות שחרור
Now can see Pin Bar pivot signals vs typical pivot signal
הערות שחרור
Optimized Stochastic to minimize trades (Pivot Down > 0 and Pivot Up <90)
Won't close trade in first 3 minutes if 5 min EMA < 13 EMA for Pivot Up or 5 min 5 EMA > 13 EMA for Pivot Down
No trades in first 10 minutes of day and last 5 minutes of day
Close all positions in last 3 minutes of day
From 1PM until 3PM will now take HOD & LOD trades
Now showing Exit Longs if stopped as Exit Longs Stopped and if Exist Shorts if stopped as Exit Shorts Stopped
הערות שחרור
Now give flexibility to enable and disable trading times in Inputs. They are broken into 5 segments:
9:30 until 11 (default on)
11 until noon (default off)
Lunchtime (default on)
1 until 3 (default on)
Power Hour (default off)
This way if you don't want alerts you won't get bothered during these times.
Improved logic exiting trades to take profit sooner but if trending to allow it to run
הערות שחרור
Had to remove Stoichastic... ugh.
הערות שחרור
Cleaned-up bug in 1 to 3 5 min 5/13 diff
הערות שחרור
Had to remove volume.
הערות שחרור
Enabled all timeframes for trading by default. Can disable in Inputs. 11-12 and Power Hour are typically bad times to trade.
Made one parameters missing descriptive and on by default. Can disable in Inputs if clutters screen with ability to toggle if interested.
הערות שחרור
Critical Update:
Discovered that exiting partial positions weren't occurring properly unless users had proper strategy of percent of equity selected vs the default. Updated strategy in order to approx. tune for a pair of 1 DTE ATM option contracts being bought/sold on SPY. Exit Partial refers to selling one contract and holding runner until Exit flashes for remaining.
initial_capital=1800000, default_qty_type=strategy.percent_of_equity, default_qty_value=15, pyramiding=0, commission_type=strategy.commission.cash_per_order, commission_value=1.3
הערות שחרור
Default state of missing 1 parameter from Pivot Up and Pivot Down signals, silver Ls and Ss, will now only show recent reasons with ability to hover over and have tool tip explain why position wasn't initiated.
To see reasons for all time, simply check option box in Input (default is unchecked to show as stated above).
הערות שחרור
Critical Update:
Discovered a few repaints occurring so added barstate.isconfirmed to eliminate.
Also check out new SPY 4 Hour Swing Trader! It works great with SPXL!!!
הערות שחרור
Switched First 90 minutes of trading following one set of conditions to first 60 minutes. This in turn has next 30 minutes follow new conditions which now make 10: 30 until lunch profitable time period. Suggest not trading during power hour as this is still loses money. Also, forcing trades once over 2x to take profits vs adhere to limit order which improves profitability as well. Updated first hour of trading to lime and next 90 minutes to green.
הערות שחרור
Fixed partial profit logic.
הערות שחרור
After re-evaluating, removed partial logic as now able to re-enter if continuing trend after counter-trend.
הערות שחרור
Critical Update:
Was not detecting long properly and was shorting on false signals. Fixed parameters.
הערות שחרור
Tweaked exiting trade to improve profit
הערות שחרור
Updated trading pivot triangle colors for pivot signals based on how successful:
9:30 until 10:30 -> Green
10:30 until Noon -> Red (In backtesting didn't benefit)
1:00 until 3:00 -> Lime
3:00 until 4:00 -> Lime

Removed unnecessary notes
הערות שחרור
Updated to take more high and low of day trades first thing in morning (until noon) and during 1PM until 3PM as well.
Will start trading after first 5 minutes after open.
הערות שחרור
Added Stop Loss & Take Profit to Inputs
Added Configurable date that is now tuned for 4 SPY 1 DTE option contracts that are to see profit or loss for day
Found missing barstate.isconfirmed's that should correct any repaints
הערות שחרור
Tweaked 5 minute differences between 5 and 13 EMAs. Eventually may rethink this part of strategy as it seems to change. Maybe this will be the last time for the tweak?
הערות שחרור
Simplified getting into long trades by only including 5 ema > than 13 ema with 5 min 5 ema > 5 min 13 ema and RSI Signal < 49
and simplified getting into long trades by only including 5 ema < 13 ema with 5 min 5 ema < 5 min 13 ema and RSI Signal > 60

No longer need to show prep signals!
הערות שחרור
Added alert messages to strategies so when alerts appear they can be more descriptive and show message indicating what action to take.

Add the following code to your alert:
{{ticker}} @ {{time}}
{{strategy.order.action}}
{{strategy.order.alert_message}}
הערות שחרור
Forgot to remove indicators and lines.
הערות שחרור
Trying to see if removing plotshape fixes alerts. Also removed excess commenting.
options

סקריפט קוד פתוח

ברוח TradingView אמיתית, מחבר הסקריפט הזה פרסם אותו בקוד פתוח, כך שסוחרים יוכלו להבין ולאמת אותו. כל הכבוד למחבר! אתה יכול להשתמש בו בחינם, אבל השימוש החוזר בקוד זה בפרסום כפוף לכללי הבית. אתה יכול להכניס אותו למועדפים כדי להשתמש בו בגרף.

רוצה להשתמש בסקריפ זה בגרף?

כתב ויתור