Random Entry and ExitStrategy for Researching Whether It Is Possible to Earn Consistently by Opening Random Trades
The essence of the strategy lies in generating random entries and exits based on pseudorandom numbers. The generation of pseudorandom numbers is performed by the function random_number based on the value of the seed variable. The variables entry_threshold and exit_threshold control the frequency of entries and exits. Lower values mean less frequent trades. To increase the number of trades, increase the values of these variables.
The strategy was created as part of research into whether it is possible to earn randomly in financial markets by making chaotic actions of opening and closing trades. However, it adheres to a few rules: open only long positions (in the direction of the global trend) and do not use leverage. Positions are opened with the entire available capital.
100 generations of the strategy on the daily chart of the S&P 500 (seed 1-101) give 100% positive mathematical expectations. Similar results are observed on higher timeframes of assets that are in a global uptrend.
There is also the possibility of opening only short positions for the research. Note that the logic of the strategy is built in such a way that only one trading direction can operate simultaneously (either longs or shorts). On higher timeframes, random shorts show negative results. Positive mathematical expectations for short positions can be found on lower timeframes (1 min, etc.), where a large amount of noise is observed.
---------------------------------------------------------------------------------------------------
Стратегия для исследования, можно ли стабильно зарабатывать при открытии случайных сделок
Суть стратегии заключается в генерации случайных входов и выходов на основе псевдослучайных чисел. Генерация псевдослучайных чисел происходит функцией random_number на основе значения переменной seed. Переменные entry_threshold и exit_threshold контролируют частоту входов и выходов. Более низкие значения означают менее частые сделки. Для увеличения количества сделок - увеличивайте значения переменных.
Стратегия создавалась в рамках исследования вопроса, можно ли случайным образом зарабатывать на фин. рынках, совершая хаотичные открытия и закрытия сделок. НО, придерживаясь нескольких правил: открывать только длинные позиции (в сторону глобального тренда) и не использовать кредитные плечи. Открытие позиций происходит на весь доступный капитал.
100 генераций стратегии на дневном графике S&P500 (seed 1-101) дают 100% положительных математических ожиданий. Похожие результаты наблюдаются на высоких таймфреймах активов, которые глобально находятся в восходящем тренде.
Также для исследования предусмотрена возможность открытия только коротких позиций. Обратите внимание, что логика стратегии построена таким образом, что одновременно может работать только одно направление торговли (либо лонги, либо шорты). На старших таймфреймах случайные шорты показывают негативные результаты. Положительное математическое ожидание для коротких позиций можно обнаружить на младших таймфреймах (1 min, etc), где наблюдается большое количество шумов.
Random
Random Market «NoaTrader»This is a simple script for generating random data shown as candles. The purpose of it is the following:
1- To see what works here. If everything is random and something is working, is there really any reason behind it?
2- To see what NOT works here! this is probably the most interesting part. Human behaviors are more likely to generate bubbles so theories like Elliot waves don't work here but do work on real charts! that is an interesting thing!
3- To find out the exact parameters defining a market which is a bit more complicated and deeper. If you look closely to candles you can say that it is not natural like other candle charts. If you have watched different timeframes enough, you have a sense of the difference between them. Why? What is natural? The volume? The wicks? The seasonality? The amount of randomness? The cycle of momentum change? ... If you can generate candles more similar to real ones it means you know the details of market much better!
P.S: the random function of trading view works differently on different symbols and timeframes..
Random Signal Generator
Random Signals Indicator generates random long and short signals on the chart. Please note that these signals are purely random and should not be used for actual trading decisions. The indicator allows you to set the minimum number of bars between signals and adjust the sensitivity of the random generation. Use this indicator for educational or testing purposes only, and always rely on proper trading strategies and analysis for real trading.
---
Индикатор случайных сигналов генерирует случайные сигналы на покупку и продажу на графике. Обратите внимание, что эти сигналы полностью случайные и не должны использоваться для принятия реальных торговых решений. Индикатор позволяет установить минимальное количество баров между сигналами и настроить чувствительность генерации случайных значений. Используйте этот индикатор только для образовательных или тестовых целей, а при реальной торговле полагайтесь на надлежащие торговые стратегии и анализ.
Random Price Action Visible Chartplots randomly generated price (closing basis) from LHS of the chart. Re-plots each time you scroll
-just a curiosity really; perhaps a lesson in seeing patterns where there are none; 'fooled by randomness' etc.
-always anchors/starts from the real close of the asset on the visible Left hand side of the chart.
-adjust ATR as you like (bigger = probably more reliable/realistic).
-adjust ATRmultiple as you like (discretionary; basically how many ATR ranges above/below last bar's random close, will the maximum random value above/below be; default is 1.5x (arbitrary).
Chop and explode (ps5)Description : This is a renovated version of my previous mod that was based on the original script from fhenry0331.
Added are:
a data cleaning function
a seasonal random index function
an updated scaler and
a signalling procedure.
-
The following description is moved here from the old script.
The purpose of this script is to decipher chop zones from runs/movement/explosion spans. The chop is RSI movement between 40 and 60. Tight chop is RSI movement between 45 and 55. There should be an explosion after RSI breaks through 60 (long) or 40 (short). Tight chop bars are colored gray, a series of gray bars indicates a tight consolidation and should explode imminently. The longer the chop the longer the explosion will go for. The tighter the better. Loose chop (jig saw/gray bars on the silver background) will range between 40 and 60. The move begins with green and red bars.
Couple it with your trading system to help stay out of chop and enter when there is a movement.
FunctionGenerateRandomPointsInShapeLibrary "FunctionGenerateRandomPointsInShape"
Generate random vector points in geometric shape (parallelogram, triangle)
random_parallelogram(vector_a, vector_b) Generate random vector point in a parallelogram shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
random_triangle(vector_a, vector_b) Generate random vector point in a triangle shape.
Parameters:
vector_a : float array, vector of (x, y) shape.
vector_b : float array, vector of (x, y) shape.
Returns: float array, vector of (x, y) shape.
FunctionProbabilityDistributionSamplingLibrary "FunctionProbabilityDistributionSampling"
Methods for probability distribution sampling selection.
sample(probabilities) Computes a random selected index from a probability distribution.
Parameters:
probabilities : float array, probabilities of sample.
Returns: int.
FunctionSMCMCLibrary "FunctionSMCMC"
Methods to implement Markov Chain Monte Carlo Simulation (MCMC)
markov_chain(weights, actions, target_path, position, last_value) a basic implementation of the markov chain algorithm
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
target_path : float array, target path array.
position : int, index of the path.
last_value : float, base value to increment.
Returns: void, updates target array
mcmc(weights, actions, start_value, n_iterations) uses a monte carlo algorithm to simulate a markov chain at each step.
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
start_value : float, base value to start simulation.
n_iterations : integer, number of iterations to run.
Returns: float array with path.
FunctionDecisionTreeLibrary "FunctionDecisionTree"
Method to generate decision tree based on weights.
decision_tree(weights, depth) Method to generate decision tree based on weights.
Parameters:
weights : float array, weights for decision consideration.
depth : int, depth of the tree.
Returns: int array
Random Entries Work!" tHe MaRkEtS aRe RaNdOm ", say moron academics.
The purpose of this study is to show that most markets are NOT random! Most markets show a clear bias where we can make such easy money, that a random number generator can do it.
=== HOW THE INDICATOR WORKS ===
The study will randomly enter the market
The study will randomly exit the market if in a trade
You can choose a Long Only, Short Only, or Bidirectional strategy
=== DEFAULT VALUES AND THEIR LOGIC ===
Percent Chance to Enter Per Bar: 10%
Percent Chance to Exit Per Bar: 3%
Direction: Long Only
Commission: 0
Each bar has a 10% chance to enter the market. Each bar has a 3% to exit the market . It will only enter long.
I included zero commission for simplification. It's a good exercise to include a commission/slippage to see just how much trading fees take from you.
=== TIPS ===
Increasing "Percent Chance to Exit" will shorten the time in a trade. You can see the "Avg # Bars In Trade" go down as you increase. If "Percent Chance to Exit" is too high, the study won't be in the market long enough to catch any movement, possibly exiting on the same bar most of the time.
If you're getting the red screen, that means the strategy lost so much money it went broke. Try reducing the percent equity on the Properties tab.
Switch the start year to avoid/minimize black swan events like the covid drop in 2020.
=== FINDINGS ===
Most markets lose money with a "Random" direction strategy.
Most markets lose ALL money with a "Short Only" strategy.
Most markets make money with a "Long Only" strategy.
Try this strategy on: Bitcoin (BTCUSD) and the NASDAQ (QQQ).
There are two popular memes right now: "Bitcoin to the moon" and "Stocks only go up". Both are seemingly true. Bitcoin was the best performing asset of the 2010's, gaining several billion percent in gains. The stock market is on a 100 year long uptrend. Why? BECAUSE FIAT CURRENCIES ALWAYS GO DOWN! This is inflation. If we measure the market in terms of others assets instead of fiat, the Long Only strategy doesn't work anymore (or works less well).
Try this strategy on: Bitcoin/GLD (BTCUSD/GLD), the Eurodollar (EURUSD), and the S&P 500 measured in gold (SPY/GLD).
Bitcoin measured in gold (BTCUSD/GLD) still works with a Long Only strategy because Bitcoin increased in value over both USD and gold.
The Eurodollar (EURUSD) generally loses money no matter what, especially if you add any commission. This makes sense as they are both fiat currencies with similar inflation schedules.
Gold and the S&P 500 have gained roughly the same amount since ~2000. Some years will show better results for a long strategy, while others will favor a short strategy. Now look at just SPY or GLD (which are both measured in USD by default!) and you'll see the same trend again: a Long Only strategy crushes even when entering and exiting randomly.
=== " JUST TELL ME WHAT TO DO, YOU NERD! " ===
Bulls always win and Bears always lose because fiat currencies go to zero.
You're not underperforming a random number generator, are you?
Function - Probability Chebyshev Inequalityfunction to calculate Chebyshev Inequality. wich can be used to compute the probability that we will diverge from what we expect to obtain.
reference:
- www.omnicalculator.com
- github.com
- statisticstopics.wordpress.com
- en.wikipedia.org
Coin Flipper Pro with strategy testerConverted the script "Coin Flipper Pro" into a Strategy. The same random "Coin Flip" trading fun with new features. Now users can run back test on the random trades and see how adjusting the risk to reward ratio affects the over all win rate and the profit of each trade. The Back test can be enabled or disabled in the settings along with the option to choose specific dates to run the test. Enjoy!
Coin Flipper ProHave you ever wondered how your win rate compares with flipping a coin? Well now you can check with Coin Flipper Pro!
This script produces a random position direction like flipping a coin and sets up a long or short trade based on you desired risk % and target ratio.
Have fun!
Random Walk ReversalUses the Random Walk script as a tool for predicting trend reversals instead of trend strength.
Random Synthetic Asset GenerationThis script generates pseudo-random asset data . Due to the nature of the random generator, it is impossible to use this indicator as input for other indicators because the instance of the script that the indicator is applied to will automatically be different from the instance that is plotted on the chart. Therefore, the idea is to use this script in other scripts (to make it possible to backtest on random data, for example).
The script has four main input parameters.
Random Number Generator Method: It supports two methods for generating the pseudo-random numbers (one by Ricardo Santos and one by Wichmann-Hill).
Seed: You can specify the seed to use. Each unique seed will generate a unique set of pseudo-random data.
Intrabar Volatility: This basically sets how volatile the generated wicks will be (0 = no wicks).
Price Multiplier: This is just a multiplier for the generated price data, so that you can scale up or down the generated price data.
You can also change the colors of the bars.
In addition to this, the indicator also generates random volume. In order to make it possible to show both volume and price, you need to have two identical instances of the indicator. One on the chart, and one in its own panel. Then, go into the Style tab in the indicator settings on the instance in the panel. Untick Up-Candles and Down-Candles boxes, and tick the Volume box.
In a similar manner, you can also plot the true range data and the candle change data as well, by ticking one of those boxes instead.
Example: Monte Carlo SimulationExperimental:
Example execution of Monte Carlo Simulation applied to the markets(this is my interpretation of the algo so inconsistencys may appear).
note:
the algorithm is very demanding so performance is limited.
Pseudo-Random Number Generators via Pine ScriptThese are my "Pseudo-Random Number Generators via Pine Script", having uniform distribution between 0 and 1. In my quest for sequential pseudo-random numbers in Pine, tinkering with mathematical chaos, I have come up with these three simple yet handy generators. I believe these may be useful in the future by developers of the Tradingview community.
NOTICE: Use it as you please, this is free code to implement into your new Pine projects. You don't have to ask for my permission to reuse these functions in your published scripts, simply because I have better things to do than answer requests for the reuse of these simplistic PRNG functions. I don't require accreditation for members to reuse these functions either. I simply don't want any credit. I only require that you respectfully put it to "good and proper use" complimenting the elaborate script you have in mind. I would however like to see some great ideas utilizing these when I randomly and accidentally come across them in the public library. I didn't know where to put this script, so I just tossed it into the "Trend Analysis" category.
The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... regarding only this indicator, not others. When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section, should you have any questions or comments regarding this indicator. When my indicators achieve more prevalent use by TV members, I may implement more ideas when they present themselves as worthy additions. As always, "Like" it if you simply just like it with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
[RS]Function - Normaly Distributed Pseudo Random GeneratorEXPERIMENTAL:
Function to generate a normally distributed pseudo random value.
if you find that something doesn't add up, please leave a message bellow.
Optimized Random Average (Linear) mcbw_This is a moving average with a customizable random kernel. You can shape your kernel by selecting your parameters in the settings window. This is not something that is immediately ready to mess with by just applying it on the chart, it is very useful for people who are researching indicators and developing new tools. To see the shape of your kernel you can plug it into google or wolfram. This indicator and the related ones are rather technical in nature, so feel free to comment any questions you may have and to see if anyone has asked your question.
Read more here:
Happy studying and enjoy your life!
2019 will be absolutely insane!