Donchian Channel Strategy [for free bot]
I present to you a script for testing the Donchian channel breakout strategy for the Binance_exchange.
This strategy is trending, and is especially effective for trading cryptocurrency futures.
This strategy is very flexible, and you can configure virtually all possible parameters, moreover, separately for longs and separately for shorts.
In the script, you can configure the parameters of the channel for entry and exit, the exit method, enable or disable purchases / sales, specify take profit and stop loss, and more.
On the example of optimization, only 20% of the deposit is used. This is done for diversification, since there are 37 contracts on binance_futures (at the time of writing the script description). That is, by optimizing the parameters for different currencies, you can very well reduce risks.
Представляю Вам скрипт для тестирования стратегии пробоя канала Дончиана для биржи Бинанс.
Данная стратегия относится к трендовым, и особенно эффективная на торговли криптовалютных фьючерсов.
Данная стратегия очень гибкая, и можно настроить фактически все возможные параметры, при чем, отдельно для покупок и отдельно для продаж.
В скрипте можно настроить параметры канала на вход и на выход, метод выхода, разрешить или запретить покупки/проаджи, указать тейк-профит и стоп-лосс и другое.
На примере оптимизации используется всего 20% от депозита. Это сделано для диверсификации, так как на фьючерсах бинансе присутсвует 37 контрактов (на момент написания описания скрипта). Т.е., оптимизировав параметры под разные валюты, можно очень хорошо снизить риски.
Pesquisar nos scripts por "the script"
Low Scanner strategyThis is the strategy I made using low scanner
there is no repaint as there is no security at all
the exit is by using multiple exit point by equity shown in the script of adolgov
so you can set the low low scanner to any position you want by no security MTF (look on the study for detail about it)
the exit you set acording to % and the equity as suggested by adolgov
this scripyt is free you can make the exit diiferent
it just example how to create better non repainting strategies with MTF
look on the same setting on stocks just 1 hour candle look very nice there:)
ADX_TSI_Bol Band Trend ChaserThe idea of this script is to be a low risk strategy on trending stocks (or any other trending market), aiming to achieve minimal draw down (e.g. at time of writing AAPL only had ~1.36% draw down, FB ~1.93% draw down and the SPY was 0.80% draw down and all remained profitable).
Testing proved it shouldn't be used in choppy stocks and best period was on daily charts. The back test filter goes back until 2010 so you can obtain 10 years of data.
The strategy utilizes the 200 Moving Average, a Custom Bollinger Band, a TSI with 52 period weighted moving average and ADX strength.
Although back test dates are set to 2010 - 2020, all other filters (moving average, ADX, TSI , Bollinger Band) are not locked so they can be user amended if desired. However the current settings have been tested with manual trading for quite some time to get this combination correct.
Buy signal is given when trading above the 200 moving average + 5 candles have closed above the upper custom Bollinger + the TSI is positive + ADX is above 20.
As back testing proved that this traded better only in tends then some Sell/Short conditions have been removed from the script and this only takes Long orders.
Only requires 2 additional lines of code to add shorting order and then remove the "buy" condition and this could be used for a downward trending stock instead.
Close for either long or short trades is signaled once the TSI crosses in the opposite direction indicating change in trend strength.
Further optimization could be achieved by adding a stop loss, which I may do in the future.
NOTE: This only shows the lower indicators however for visualization you can use my script "CUSTOM BOLLINGER WITH SMA", which is the upper indicators in this strategy.
This is my first attempt at coding a strategy so I'm happy to receive any feedback or hints on how this could be written better from any experienced coders!
NASDAQ:AAPL AMEX:SPY
Volume Based Buy/SellThis is my very first scrip on this platform. It's the first version of the script, It works on the volume-based moving averages and exponential moving average.
I have added the buy/sell signals for educational purposes only. While adding the buy/sell signal I have an additional check on the strength of the trend to reduce loss to a minimum.
How to use:
1. Use with Heikin Ashi Chart.
2. Use 15 Min timeframe for intraday.
Some improvements I am working in the near future is:
1. Exit tread with the maximum profit.
2. Reduce down false trad to 0%.
To encourage and support please like the script try using for your own paper trading.
Dont forget to leave a comment on if you see any improvement in the script or any idea you have. Happy treading together.
XProfit Strategy BacktesterHello,
This Script is a Backtesting Strategy tester of XProfit and allows users to clearly define a profitable strategy.
To Define a profitable strategy, there is the option to modify the parameters "XR" and "Sensitivity".
The Script in itself is build on ATR which gives Long or Short signal.
Note: The strategy script does not allow alerts. It does only allow backtesting.
How To Get Access: DM me for a Trial or use the links below this post to purchase the Indicator which will automatically come with XProfit
Happy Trading.
Wunder DCA BotThe bot is based on the DCA system.
1. DCA is the investment method in which you buy a certain portion of the asset after the determined price deviation.
2. For entry, we evaluate the maximum and minimum levels for a given period that you can adjust in the script. The bot enters when price rebound from the specified levels.
3. For the exit, the bot will use the take profit percentage that you will specify in settings.
It is also possible to choose how the take profit is calculated either from the average entry price or from the entry order (first order).
4. DCA uses the following settings:
- Base order Volume: Volume of your first order on entry signal
- Subsequent orders volume: The volume of all subsequent orders except the first
- DCA orders count: This parameter will determine how many entries your overall strategy will have. For example: If you will put 3, that will mean that including your initial position you will have 2 additional orders.
- DCA order price deviation:
This is the value in % which determines the deviation of the additional entries from the entry price. Example: If you go long and the price of the asset is 100$ and you put an order price deviation of 1% that will mean that the first additional entry will occur when the price will drop by 1%, and the second entry will be triggered when the overall price will drop by 2% (as the interval between the first and the second additional entry will be 1%).
- DCA Order Volume Multiplier:
This parameter will determine the amount that you put into each additional position. If this parameter is equal to 1 that means that each additional entry will be equal to the initial amount. The extra volume will be added to your position from the second DCA entry. Example: Your initial position was 10$ and your Volume Multiplier is set to 2. When you reach your 1st DCA target your additional order will have the same volume of 10$. When you reach your 2nd DCA target your additional order will be 20$ (previous position volume * multiplier). Your 3rd DCA target will place the order of 40$.
- DCA order price Deviation Multiplier:
This value will increase the price deviation between each additional entry. It is calculated as the price deviation multiplied by the deviation multiplier. For example: if you enter long at the price 100$ and have a price deviation of 1% with the price deviation multiplier of 2 that will mean that the first additional entry will occur when the price will drop to 99$ however the second will occur when the price will go to 97$. The third additional position will be entered at 94$
5. For full automation of the bot, you should set your comments to the input in the bot settings in the "LONG" and "SHORT" fields. You also need to create an alert signal and set a Webhook to send signals.
IMPORTANT!!!
1. Position calculation should take into account several factors: your deposit, leverage, the number of DCA orders, the distance to the last DCA order;
2. When choosing leverage, it is important to correctly calculate the possible drawdown. If you set a high leverage value, then liquidation awaits and the bot will not be able to take profits and will exit the position ahead of time;
3. The size of the position must be determined in accordance with all risks and take into account the size of your deposit;
4. This DCA Bot is able to earn consistently with the correct calculated money management.
GoldMode On (Triple compromise strategy) TF 60-240BINANCE:BTCUSDT
Greetings.
I am publishing this script in order to get feedback for further work on it.
The script combines a compromise between several classic strategies, and each of them uses modifications of classic indicators on specially selected averaging sliding indicators.
1. The script uses an ATR-based filter (it's off by default, as it's better on BTCUSD , but you can enable it in the settings if you want to use it on EURUSD , for example, or on other symbols).
2. A strategy based on crossing the moving.
3. A strategy based on determining the direction of movement of the modified slow and fast RSI .
4. A strategy based on the modified ADX +DI -DI .
The essence of the strategy in finding a compromise decision on the signals coming from each of these three strategies.
=====
Приветствую.
Данный скрипт публикую с целью получить обратную связь для дальнейшей работы над ним.
Скрипт сочетает в себе компромисс между несколькими классическими стратегиями, причём каждая из них использует модификации классических индикаторов на специальным образом подобранные усредняющие скользящие.
1. В скрипте используется фильтр на основе ATR (по умолчанию выключен, т.к. на BTCUSD так лучше, но можно включить в настройках, если хотите использовать его на EURUSD , например, или на других инструментах).
2. Стратегия основанная на пересечении скользящих.
3. Стратегия основанная на определении направления движения модифицированных медленной и быстрой RSI .
4. Стратегия основанная на модифицированном ADX +DI -DI .
Суть стратегии в поиске компромиссного принятия решения по сигналам поступающим от каждой из этих трёх стратегий.
sma dipsparity and sdvFXBTCJPY 1min contrarian script (2020/1/30)
1分足の逆張りです.
If you want to use other timescale, need to change disparity rate and sdv.
To display disparity(sma) and standard deviation, and to draw a hline(pine function) a certain valu. And lets think. I thought disparity rate 1~1.3 or -1~-1.3 are able to use constrarian trade (and sdv>600).
In bottom, disparity index is auxiliary. It is different from the multiple in the script to make the value easier to understand.
Sorry if the expiration date of the script has expired.
Multi RIS Length RSI Strategy calibrated to 20min timeframeI have been working on many itterations of this script, on multiple time frames, with multiple settings.
It's not exactly how I want it, but if used on the 20 min timeframe (I chose this one to publish, not because it's the most profitable, or percent profitable , but for multiple other reasons.
1) From my back testing, this seems to be the most stable (gives the greatest margin for error). By that I mean, I am not a bot, I am a human trader, so I actually have to sleep, and work, and can't always trade all the time when I when I get my signals. So I need some margin of error.
The 20min time frame gives me this, it's still decently profitable (52K), and allows me some margin of error for being human.
2) It not exactly how I want it, because you have to use it in conjunction with the strategy tester to see if it is in longs or shorts (open trades). You can't see that on the app, or even if you are logged in to TV on a browser on a smart phone. At least I cant, I can only see the strategy tester when I am logged in on my computer, which obviously I can not be all the time.
3) It's also not exactly how I want it because it doesn't tell you when it is switching from buying additional longs (or shorts), and closing them out, and reversing. You can figure this out from the strategy tester, but I would like my script to make it more clear in real time.
4) The alerts on the script only fire after the current bar is closed. So really to use this you need to be a non free member or TV, because then you can add the appropriate RSIs to your chart, and set up real time alerts on them that will fire in real time, as opposed to displaying on the chart after the bar closes (a lot can happen in 20 minutes). Which is sad, and not my intent, I want this to be useful to free members, I just don't know how to do that given they don't have custom time frames (like 20 min), and multiple real time alerts. I can't fix that, that's a limitation of TV.
MoneyBible QTUMUSDT BacktesterMoneybible BINANCE:QTUMUSDT backtester on 15m candlestick . It will be re-optimized monthly.
The script is written in PineScript V.3, makes no use of the security() function and does not use the Trailing Stop-Loss function from TradingView. No repainting issue.
DM me for joining discord and getting a trial.
Alert script here :
MoneyBible ETHUSD BacktesterMoneybible BITMEX:ETHUSD backtester on 15m candlestick . It will be re-optimized monthly.
The script is written in PineScript V.3, makes no use of the security() function and does not use the Trailing Stop-Loss function from TradingView. No repainting issue.
Alert script here :
MoneyBible XBTUSD BacktesterMoneybible BITMEX:XBTUSD backtester on 10m candlestick . It will be re-optimized monthly.
The script is written in PineScript V.3, makes no use of the security() function and does not use the Trailing Stop-Loss function from TradingView. No repainting issue.
Alert script here :
[M10] Ichimoku Keltner Channel Scalper [Backtest]Hey all,
This script combines a couple of popular indicators to create a reliable yet versatile opportunity to automate trades based on the Ichimoku Cloud. The idea is to use bullish/bearish Ichimoku crossovers to enter positions whilst taking advantage of a modified Keltner Channel to exit these positions at maximum profit.
The script has been backtested on various timeframes and proves effective in both trending and ranging markets.
I have also added the ability to limit your positions to only long, or short, if this is of preference.
An alerts version of this script is also available at no cost on my page - enjoy!
Any questions? Let me know!
FREE BACKTEST STRATEGY BTC/USDT 15m Binance LONGA long only strategy for trading BINANCE:BTCUSDT in a 15m timeframe built upon Donchian Channels.
The script is already configured for this market /timeframe.
I built it using my generic version that you can request access by leaving a comment:
To get access to the alert setup version and automate the strategy, you need to purchase a subscription on my website .
Thanks for the feedback/support !
CryptoWise4hETHstrategyCrypto Wise 4h ETH Trading Script with Alerts
ETH is very volatile, and that's what makes this script great: Being able to catch the next Move Up or Down.
No repainting.
Better to be used on a 4hr Chart.
No indicator is perfect, but when it gets integrated into a great strategy, and used together with other indicators like the Stoch RSI , you can easily make great trades.
You can get access to the script for $20 / month. Payments accepted in BTC, ETH, LTC, BCH.
72hr Trial given upon request.
Crypto Reversal Scalper DEMO / FREE BacktesterCrypto Reversal Scalper Lite
This is a lite version of:
This script allows anyone to try out the capability of the script with restrictions to some features. If you want to unlock all the features, consider upgrading.
Full version also includes alerts for automated trading.
Market Sniper V1 [Strategy]Market Sniper is a trend-based script born and created with leverage trading in mind. I created this to trade automatically with leverage using AutoView Chrome Extension on BitMex XBTUSD.
Features:
• Trend-Based: use higher timeframe to check the trend of the coin, and a threshold to evaluate the trend strength.
• Dual-Behavior: different settings are used when the trend is strong and when it is weak. With a strong trend it can catch big trades, with a stable trend it can act like a scalper with smaller and faster trades.
• Smart Profit: you can set a percentage gain and a trail setting. The script will try to trail the price if the trend is strong, otherwise it will exit at the specified gain.
• Loss Control: you can set a percentage stop-loss to cover bad entries. The market is unpredictable, no script is perfect, sooner or later it will take a bad choice.
The chart shows the result for the full month of August using leverage 10.
If you want to try it just contact me.
Prometheus Trend SurferPrometheus Trend Surfer is a strategy built to follow trends and make the best use of it by giving you long and short entries.
It works on all time frames and has a tight tolerance for non-profitable entries so you won’t get stuck in losing positions.
Gives you an option to set trend length so you can fit it to your style of trading.
You also have the option to backtest from the date you set in the options dialog.
Instructions
1. Load the script
2. Use Heikin-Ashi candles
Did we get your attention? If you wish to buy our script, shoot us a PM.
We are not analysts, investment advisors or anything of that sort. Everything that we provide with this script is purely for guidance, informational and educational purposes. All information contained herein should be independently verified and confirmed. We do not accept any liability for any loss or damage whatsoever caused in reliancee upon such information or services. Please be aware of the risks involved with any trading done in any financial market. Do not trade with money that you cannot afford to lose. When in doubt, you should consult a qualified financial advisor before making any investment decisions.
Bollinger Bear SniperThis script uses Bollinger Band but with different interpretation. The upper Bollinger Band is the resistant level, the lower Bollinger Band is the base or support level. The Commodity Channel Index (CCI) and the Bollinger Bandwidth helps us avoid high risk.
The script identifies candles that are marking bold upward moves in prices and fires buy signal. Sales signals are fired when the candle closes in positive. The idea is to buy and sell on the same candle or next positively closed candle. This is anti-bear-anti-bags strategy. You either make profit or loss holding no bag. When you gain more than lose you are in business. This script is set to gain more than lose. We however offer no guarantee, expressed or implied. We are NOT responsible.
NGRN MACD-X & RSI v3.1 STRATEGYMACD-X, RSI & Volume Indicator Strategy - Version 3.1
Overview
This strategy and it's associated study were modeled after the famous Philakone described algorithms on his now defunct instructional video series.
This indicator allows for full customisation of parameters and interaction between three indicators that allow users to shape their trading methods to their desired goals. This associated strategy also allows users to backtest the study alerts script and find the best settings towards that end.
MACD + RSI + VOLUME - are of the most powerful and widely usded indicators, MACD/Histogram crosses, coupled with RSI & Volume increases/decreases will detects areas of deeply oversold / overbought and buys/sells on the reversal
Features
Full customisation - All parameters are open for customising to allow the trader to build their own strategy and adapt from market to market.
Clean/Simple UI - Facilitating ease of use.
Enable Buying or Selling, - or have them both active at the same time.
Toggle off and on ALTERNATING Buy and Sell feature (pyramiding) - to allow for consecutive dollar cost averaging style buys or SCALING out of an entry (partial sell).
Customizable Stop-Loss plot - to enable users to create a STOP-LOSS alert option or other alert(s) based on the plot location. See settings screenshot.
Study and associated Strategy - to use the TradingView ‘Strategy Tester’ back-testing features to find the best alert settings for specific coins in bear, bull and sideways markets.
Changes Version 3.1
UI consolidates reduntant script inputs making the script easier to use.
Fixes STOP-LOSS algorithm.
Adds a STOP-LOSS Plot (red line) to enable users to create a STOP-LOSS alert option or other alert(s) based on the plot location. See settings screenshot.
Access
Full Access is 0.1 ETH , one time fee for LIFETIME access to the STUDY indicator, STRATEGY and future updates as well as support and SETTINGS for various markets on the Binance Exchange.
Settings
BUY SETTINGS: prntscr.com
SELL SETTINGS: prntscr.com
STOP-LOSS SETTINGS : prntscr.com
Volume & Intraday ScriptI am still learning pinescript, and part of this was created using the Pine Script language reference manual. This includes looking at the time series, a fixed length, and the default intraday_loss variables. This also includes the basic fixed lengths for an swma (Symmetrically weighted moving average) and the script to start creating a strategy. All in all this is just a basic sample of pinescript that you can customize for your trading needs. This can work with Cryptocurrency but these moving averages usually work more efficiently for forex.
FTSE FridaysThis code snippet below is a quick and dirty follow up to some statistical analysis performed on the FTSE 100. It showed that over the long run, (since 1995) going long on a Friday appeared to have a statistical edge (53%). As a bit of fun, I wanted to create a quick pine script backtest to test this and see if it is possible to profit from it. After all, the index might finish up 53% of the time, but that doesn't mean one can profit from it.
A full commentary to the script and FTSE analysis post can be found on the Backtest-Rookies website. To comply with house rules, I cannot post a direct link here.
Important Note
The script must run on the 4H time frame…..Why? It is a quick and dirty implementation and it relies on entering a long position on the 4H bar before the market opens. This way the position will enter at the open of the market. (Since positions are always opening on the bar following an entry signal).
System 0530 - Stoch RSI Strategy with ATR filterStrategy Description: System 0530 - Multi-Timeframe Stochastic RSI with ATR Filter
Overview:
This strategy, "System 0530," is designed to identify trading opportunities by leveraging the Stochastic RSI indicator across two different timeframes: a shorter timeframe for initial signal triggers (assumed to be the chart's current timeframe, e.g., 5-minute) and a longer timeframe (15-minute) for signal confirmation. It incorporates an ATR (Average True Range) filter to help ensure trades are taken during periods of adequate market volatility and includes a cooldown mechanism to prevent rapid, successive signals in the same direction. Trade exits are primarily handled by reversing signals.
How It Works:
1. Signal Initiation (e.g., 5-Minute Timeframe):
Long Signal Wait: A potential long entry is considered when the 5-minute Stochastic RSI %K line crosses above its %D line, AND the %K value at the time of the cross is at or below a user-defined oversold level (default: 30).
Short Signal Wait: A potential short entry is considered when the 5-minute Stochastic RSI %K line crosses below its %D line, AND the %K value at the time of the cross is at or above a user-defined overbought level (default: 70). When these conditions are met, the strategy enters a "waiting state" for confirmation from the 15-minute timeframe.
2. Signal Confirmation (15-Minute Timeframe):
Once in a waiting state, the strategy looks for confirmation on the 15-minute Stochastic RSI within a user-defined number of 5-minute bars (wait_window_5min_bars, default: 5 bars).
Long Confirmation:
The 15-minute Stochastic RSI %K must be greater than or equal to its %D line.
The 15-minute Stochastic RSI %K value must be below a user-defined threshold (stoch_15min_long_entry_level, default: 40).
Short Confirmation:
The 15-minute Stochastic RSI %K must be less than or equal to its %D line.
The 15-minute Stochastic RSI %K value must be above a user-defined threshold (stoch_15min_short_entry_level, default: 60).
3. Filters:
ATR Volatility Filter: If enabled, trades are only confirmed if the current ATR value (converted to ticks) is above a user-defined minimum threshold (min_atr_value_ticks). This helps to avoid taking signals during periods of very low market volatility. If the ATR condition is not met, the strategy continues to wait for the condition to be met within the confirmation window, provided other conditions still hold.
Signal Cooldown Filter: If enabled, after a signal is generated, the strategy will wait for a minimum number of bars (min_bars_between_signals) before allowing another signal in the same direction. This aims to reduce overtrading.
4. Entry and Exit Logic:
Entry: A strategy.entry() order is placed when all trigger, confirmation, and filter conditions are met.
Exit: This strategy primarily uses reversing signals for exits. For example, if a long position is open, a confirmed short signal will close the long position and open a new short position. There are no explicit take profit or stop loss orders programmed into this version of the script.
Key User-Adjustable Parameters:
Stochastic RSI Parameters: RSI Length, Stochastic RSI Length, %K Smoothing, %D Smoothing.
Signal Trigger & Confirmation:
5-minute %K trigger levels for long and short.
15-minute %K confirmation thresholds for long and short.
Wait window (in 5-minute bars) for 15-minute confirmation.
Filters:
Enable/disable and configure the Signal Cooldown filter (minimum bars between signals).
Enable/disable and configure the ATR Volatility filter (ATR period, minimum ATR value in ticks).
Strategy Parameters:
Leverage Multiplier (Note: This primarily affects theoretical position sizing for backtesting calculations in TradingView and does not simulate actual leveraged trading risks).
Recommendations for Users:
Thorough Backtesting: Test this strategy extensively on historical data for the instruments and timeframes you intend to trade.
Parameter Optimization: Experiment with different parameter settings to find what works best for your trading style and chosen markets. The default values are starting points and may not be optimal for all conditions.
Understand the Logic: Ensure you understand how each component (Stochastic RSI on different timeframes, ATR filter, cooldown) interacts to generate signals.
Risk Management: Since this version does not include explicit stop-loss orders, ensure you have a clear risk management plan in place if trading this strategy live. You might consider manually adding stop-loss orders through your broker or using TradingView's separate strategy order settings for stop-loss if applicable.
Disclaimer:
This strategy description is for informational purposes only and does not constitute financial advice. Past performance is not indicative of future results. Trading involves significant risk of loss. Always do your own research and understand the risks before trading.
The Z-score The Z-score, also known as the standard score, is a statistical measurement that describes a value's relationship to the mean of a group of values. It's measured in terms of standard deviations from the mean. If a Z-score is 0, it indicates that the data point's score is identical to the mean score. Z-scores may be positive or negative, with a positive value indicating the score is above the mean and a negative score indicating it is below the mean.
The concept of Z-score was introduced by statistician Carl Friedrich Gauss as part of his "method of the least squares," which was an important step in the development of the normal distribution and Z-score tables. It's a key concept in statistics and is used in various statistical tests.
In financial analysis, Z-scores are used to determine whether a data point is usual or unusual. You can think of it as a measure of how many standard deviations an element is from the mean. For instance, a Z-score of 1.0 would denote a value that is one standard deviation from the mean. Z-scores are also used to predict probabilities, with Z-scores having a distribution that is expected to be normal.
In trading, a Z-score is used to determine how often a trading system may produce a string of winners or losers. It can help a trader to understand whether the losses or profits they see are something that the system would most likely produce, or if it's a once in a blue moon situation. This helps traders make decisions about when to start or stop a system.
I just wanted to play a bit with the Z-score I guess.
Feel free to share your findings if you discover additional applications for this strategy or identify timeframes where it appears to perform more optimally.
How it works:
This strategy is based on a statistical concept called Z-score, which measures the number of standard deviations a data point is from the mean. In other words, it helps determine how unusual or usual a data point is.
In the context of this strategy, Z-score is applied to a 10-period EMA (Exponential Moving Average) of Heikin-Ashi candlestick close prices. The Z-score is calculated over a look-back period of 25 bars.
The EMA of the Z-score is then calculated over a 20-bar period, and the upper and lower thresholds (bounds for buy and sell signals) are defined using the 90th and 10th percentiles of this EMA score.
Long positions are taken when the Z-score crosses above the lower threshold or crosses above the mid-line (50th percentile). An additional long entry is made when the Z-score crosses above the highest value the EMA has been in the past 100 periods.
Short positions are initiated when the EMA crosses below the upper threshold, lower threshold or the highest value the EMA has been in the past 100 periods.
Positions are closed when opposing entry conditions are met, for example, a long position is closed when the short entry condition is true, and vice versa.
Set your desired start date for the strategy. This can be modified in the timestamp("YYYY MM DD") function at the top of the script.