Happy Trade,

  1. Intro
  2. What is New
  3. Algebraic/Boolean Equation
  4. Instruction Set for The Algebraic/Boolean Equation
  5. Example
  6. Usage
  7. Settings Menu
  8. Declaration for Tradingview House Rules on Script Publishing
  9. Disclaimer
  10. Conclusion


1. Intro

This is a rich equipped fork of my previous "Backtest any Indicator v5". And serves as the fitting backtester and trade strategy creation tool for my upcoming ANN Indicators (artificial neural network).
As the previous version this script has no trade signal generating code. The trade signals comes in by the five user settable input slots where the user plug-in external indicators. The final trade siganls go long etc are defined by a algebraic/boolean equation typed in as text in 4 terminals as shown in Image 0. With this algebraic/boolean equations input the user can setup any trade logic as complex and fast and easy as never seen before here on TradingView.

لقطة
Image 0

2. What is new

  1. Input algebraic/boolean equations in text-form for go long, go short, exit long & exit short
  2. Five input slots for external indicator signals
  3. Equation tester
  4. User settable signal delay for enter and exit trades
  5. User selectable alternating trades filter
  6. User settable exit long = enter short
  7. Intrabar or trade only on bar closing
  8. Time filter with duration input
  9. User settable UTC Adjustment
  10. Long and short trades possible
  11. Two Take Profits with quantity setting
  12. Trailing Stop
  13. Webhook connection



3. Algebraic/Boolean Equation

This is where the magic happens. Unlike other backtesters that rely on drop-down menus to define trade signal equations—thus limiting the number of input signals and the complexity of logic—this script uses a string interpreter to solve equations. With this, you can develop your trade logic equations and add signals or conditions simply by writing them down in algebraic/boolean form.
The instruction set for this interpreter includes not only external input signals but also several internal values. These include BarTime, BarIndex, Open, High, Low, Close, True Range, Minimal Tick, Volume, and a signal that indicates whether there is an open trade (long, short, or none). You can also reference the values of past bars for all these inputs and, of course, use constant values in your equations. There is a sad limitation: Only one past bar value per equation is practicable. If you use more, errors can occur. It seems to be caused by the pipe line architecture of the parallel computing. In any attempt to solve this issue an older function call result was hand over.
The implemented functions cover a wide range of algebraic and boolean operations. A boolean "true" is represented by all values greater than zero, while "false" is represented by zero or values less than zero.

4. Instruction set for the Algebraic/Boolean Equation

There are functions that accept either two input values or one input value. The general form is (XandY) or (notX), where X and Y can be any input slot, predefined value, constant, or another sub-equation. Functions are always written in lowercase, while input slots and predefined values use uppercase letters.
Each sub-equation must be enclosed in parentheses, e.g., (A+B). Without proper use of parentheses, the interpreter cannot determine which function to calculate first. Negative constants must be expressed by subtracting from zero (e.g., (0-3.14)), so careful attention is required.
Here are some examples that demonstrate both incorrect and correct notations:

incorrect               correct
(A+B*C)                (A+(B*C))
(A+B+D+E)            (A+(B+(D+E)))
(-20>A)                 ((0-20)>A)
(A*-B)                   (A*(0-B))
(AnotB)                (Aand(notB))
ABS(a-b)               (abs(A-B))


The correct usage ensures the interpreter calculates in the intended order.

And here comes the complete Instruction Set:


Addition:                                             (A+B)
Subtraction:                                        (A-B)
Multiplication:                                     (A*B)
Division:                                              (A/B)
Absolut value:                                     (absA)
Power of:                                            (A^B)
Natural Logarithm:                              (logA)
Lowest value of Low of last x bars:       (lotx)
Highest value of High of last x bars:     (hotx)
Modulo, Remainder of a Division:         (A%B)
Round:                                                (rndA)
round to ceil:                                       (ceiA)
Round to floor:                                    (floA)
Round to next minimal tick:                  (mitA)
EMA of A of last 3 bars:                        (e03A)
EMA of A of last 7 bars:                        (e07A)
EMA of A of last 10 bars:                      (e10A)
EMA of A of last 20 bars:                      (e20A)
EMA of A of last 50 bars:                      (e50A)

Smaller then:                                       (A<B)
Greater then:                                       (A>B)
Equal to:                                              (A==B)
Unequal to:                                          (A!=B)
And:                                                    (AandB)
Or:                                                      (AorB)
Exclusive Or:                                        (AxorB)
Not:                                                     (notA)
Past bar value:                                      (A[x]) ,whereby x can be                                                                     1,2,3,...,barIndex-1

Bar time:                                             (T)
Bar index:                                            (I)
Opening Price of Bar:                           (O)
Highest Price of Bar:                            (H)
Lowest Price of Bar:                             (L)
Closing Price of Bar:                             (C)
Min tick value for the current symbol:   (K)
Trade Volume:                                     (V)
True Range:                                         (R)
Is Money invested:                               (M) ,Long position: M=1,
                                                                 Short position: M=-1,
                                                                 No position: M=0


Reminder: if you wanna replace A or B above don't forget the parentheses. So if you have (logA) and wanna replace A with D+F so the correct replacement would be (log(D+F)).
In the following there are some examples of popular bar patterns and useful filters:


Doji:                         ((abs(O-C))<(10*K))and((H-L)>(100*K))
green Hammer:         (((H-C)<(5000*K))and(((O-L)/2)>(abs(O-C)))
Up trend:                  (C>(e10H))
Down trend:             (C<(e10L))
cool down 7 bars:      ((any buy condition)and((e07(absM))==0))
possible Pivot High:  (H==(hot30))and((C<L[1])or(O>C))
possible Pivot Low:   (L==(lot30))and((C>H[1])or(O<C))



5. Example

To present an easy example we choose the ANN Trend indicator as it is. This example serves only to show how to setup this script. In Image 1 is shown the following decent settings.
Timeframe=5, BTCUSDT, 2024-11-29 11:15am to 1:30pm
Strategy Development Enviroment: input signal A=Ann Trend Predicted_Trend_Signal, goLong ((A<0)and((A[1])>0)), goShort ((A>0)and((A[1])<0)), Enter Signal delay=0, Exit Signal delay=0, Alternate Trades=true
take profit 1 =0.4% (30%), take profit 2 =0.7%, trailing stop loss=0.2%, intrabar, start capital=1000$, qty=5%, fee=0.05%, no Session Filter

لقطة
Image 1


6. Usage

First you need to attach some signals from external Indicators. In the example above we use the Stochastic RSI indicator from TradingView. Load the Stochastic RSI indicator to the chart. Then you go to the settings menu of this script, choose in the drop-down menu of Input A the signal <Stoch RSI: K>.
In case you wanna use a signal which is not in the drop-down menu of Input A do the following:

1) You need to know the name of the boolean (or integer) variable of your indicator which hold the desired signal. Lets say that this boolean variable is called BUY. If this BUY variable is not plotted on the chart you simply add the following code line at the end of your pine script.
For boolean (true/false) BUY variables use this:



And in case your script's BUY variable is an integer or float then use instate the following code line:



2) Probably the name of this BUY variable in your indicator is not BUY. Simply replace in the code line above the BUY with the name of your script's trade condition variable.

3) Do the same procedure for your SELL variable. Then save your changed Indicator script.

4) Then add the changed Indicator script from step before and this backtester script to the chart ...

5) and go to the settings of it. Choose under "Settings -> Input A" your Indicator. So in the example above choose <Stoch RSI: K>.
The form is usually: '<name of your indicator> : BUY'. Then you see something like Image 1

6) Decide about each trade logic for Go Long and Go Short. In this Example we use for GoLong if "Stoch RSI: K" is smaller then 20. The "Stoch RSI: K" we already loaded it in input A. So we set under Go Long (A<20) and set Enter Signal Delay to 0.
Now we setup Go Short if "Stoch RSI: K" is bigger then 80. So we set under Go Short A>80. Enter Signal Delay is already set.

7) For the Exit conditions you can choose (trailing) Stop loss or Take Profit or Exit by Indicator Signal. What ever comes first triggers the exit. If you like to use an EMA Indicator for the Exit by Indicator just load it in a free input slot B, D, E, F or use the inbuild EMA. For this example we use the inbuild EMA of the last 7 values of close. It is called by the following equation: (e07C). So to exit a long trade when the close price crossunder this EMA you have to type in Exit Long ((e07C)>C). For exit a short trade enter in Exit Short ((e07C)<C).


You can choose detailed time- and session filters. You can setup two take profit levels with quantity and stop loss, trailing, initial capital, quantity per trade and set the exchange fees. You get an overall result table and even a detailed, scroll-able table with all trades.

لقطة
Image 2

In the Image 2 you see the provided info tables about all Trades and the Result Summary. Further more every trade is marked by a background color, labels and levels. An opening Label with the trade direction and trade number. A closing Label again with the trade number, the trade profit in %, the trade gain in $ and the total amount of $ after all past trades. A green line for each take profit levels and an orange line for the (trail) stop loss. This summary table down left gives you an insign about how good or not so good the trade strategy is and with the trade list you can find those trade which should be avoided. Found those bad trades on the chart by the time or trade number. By seeing a big number of bad trades you may find a pattern and can formulate conditions to avoid those bad trades. Those new conditions you can easily add to the equations for enter or exit trades.

Now you have a backtest with the oppotunity to develope and envolve your trading strategy more and more. And for any iteration from general to detailed you can do it with this backtester. You can add more and more filter signals or may change the setting of your Indicator to the best results and setup the following strategy settings like Time- and Session Filter, Stop Loss, Take Profit etc. With it you find a profitable strategy and it's settings.

7. Settings Menu

In the settings menu you will find the following high-lighted sections. Most of the settings have a attention mark on their right side. Move over it with the cursor to read specific explanation.

Input Signals: This are five input slots A, B, D, E & F which you can load up with your preferred Indicators.

Algebraic Equation for the Trade Signals: Here you setup the definitions for Go Long, Go Short, Ex Long & Ex Short. As shown in Image 3 you can combine the input slots A, B, D, E, F with predefined Variables O, H, L, C, T, I, V, K, M, R or any constant value with the in-build function in the instruction set.


لقطة
Image 3

Additionally, you have the option to delay entry and exit signals. This feature is particularly useful when trade signals exhibit noise and require smoothing.
You can also enable the script to perform alternating trading. In this mode, trades alternate sequentially—after a long trade, a short trade follows, and then another long trade, and so on.


لقطة
Image 4

As shown in Image 4, you can configure the script so that an "exit by signal" also acts as the next entry in the opposite trade direction. To enable this, check the option Exit = Enter Next and set the exit condition as the opposite of the entry condition. With this setting, only one occurrence of the signal is needed to trigger both the exit and the new entry, making the transition seamless.

Equation Tester: Each equation is assigned a checkmark and a color. Activate one like in Image 5 and the chart will highlight bars with a colored background where the corresponding equation result is greater than zero (interpreted as true). At the last bar, a label is displayed showing each equation’s result value. This feature allows you to build your equations and test sub-equations to ensure their results are correct.


لقطة
Image 5

Backtest Results: Check mark the List of Trades to see any single trade with their stats. If there are more trades than can fit in the list, you can scroll down by decreasing the Scroll value.

Timezone Adjustment: In case you wanna use an Chart-UTC that differs from the time scale you can activate Timezone Adjustment. Then you have to setup your location UTC correctly! The Exchange UTC will be set in most cases automatically. Known Exchanges include Amsterdam, Chicago, New_York, Los_Angeles, Calcutta, Colombo, Moscow, St_Petersburg, Tokyo, Shanghai, Hongkong, Berlin, London, Paris, Madrid. Only if you have other exchanges you need to setup it by hand.

Time Filter: You can set a Start time or deactivate it by leave it unhooked. The same with End Time and Duration Days. Duration Days can also count from End time in case you deactivate Start time.

Session Filter: Here, you can choose to activate trading on a weekly basis, specifying which days of the week trading is allowed and which are excluded. Additionally, you can configure trading on a daily basis, setting the start and end times for when trades are permitted. If activated, no new trades will be initiated outside the defined times and sessions.

Long & Short: Here you can enable Longs or Shorts or both trades.

TP & SL Settings: Take Profit 1&2 set the target prices of any trade in relation to the entry price. The TP1 exit a part of the position defined by the quantity value. Stop Loss set the price to step out when a trade goes the wrong direction. You can activate also a trailing SL.
Additionally, you can specify whether trades should be executed intrabar or at the bar's closing.

Hedging: The Hedging is basic as shown in the following Image 6 and serves as a catch if price moves fast in the wrong direction.


لقطة
Image 6

You can activate a hedging mechanism, which opens a trade in the opposite direction if the price moves x% against the entry price. If both the Stop Loss and Hedging are triggered within the same bar, the hedging action will always take precedence.

Invest Settings: Here, you can set the initial amount of cash to start with. The Quantity Percentage determines how much of the available cash is allocated to each trade, while the Fee Percentage specifies the trading fee applied to both opening and closing positions.

Webhooks: Here, you configure the License ID and the Comment. This is particularly useful if you plan to use multiple instances of the script, ensuring the webhooks target the correct positions. The Take Profit and Stop Loss values are displayed as prices.


لقطة

8. Declaration for Tradingview House Rules on Script Publishing

This Backtester also serves as Strategy Development Tool by offering the user a fast and easy opportunity to test, enhance and manipulate the definitions for enter and exit trades. The unique feature "algebraic/boolean equation input" provides users with a significant edge over other backtest scripts. Unlike any other backtesting tool available with few drop-down menus for enter the equation, this script allows users to define an extensive range of trade equation definitions without setup of numerous specific parameters. This is reached by four terminals where the user type in the equation as text. Those equations in text-form are send intern to a context-depending touring machine that interprets the string. So with this tool, users can implement their trading ideas—even those involving complex definitions for trade entries and exits based on huge number of variables and indicators—without hiring a developer.

This script is closed-source and invite-only to support and compensate for over a year of development work. Unlike traditional backtest scripts, this one does not rely on TradingView's strategy functions. Instead, it is designed as an indicator, utilizing TradingView's "Indicator-on-Indicator" functionality.

9. Disclaimer

Trading is risky, and traders do lose money, eventually all. This script is for informational and educational purposes only. All content should be considered hypothetical, selected post-factum to demonstrate the upcoming ANN scripts and is not to be construed as financial advice. Decisions to buy, sell, hold, or trade in securities, commodities, and other investments involve risk and are best made based on the advice of qualified financial professionals. Past performance does not guarantee future results. Using this script on your own risk. This script may have bugs and I declare don't be responsible for any losses.

10. Conclusion

Now it’s your turn! Connect your promising Artificial Neural Networks (ANN) and standard indicators to this feature-rich Backtest/Strategy script. This tool allows you to quickly evaluate how well your indicators perform in trading scenarios and easily compare different trading logics defined by algebraic/boolean equations. You can refine your trading strategy step by step without needing a coder. Let it incorporate numerous variables and indicators—simply write the algebraic/boolean equations for trade entries and exits directly into the script’s settings.

Additionally, you can utilize the Time Filter to identify the market conditions where your setups perform best—or where they fall short. The Session Filter helps you isolate recurring favorable conditions to optimize your strategy further. Once you find a promising configuration, you can set up alerts to send webhooks directly. Configure all parameters, test and validate them in paper trading, and if results align with your expectations, deploy the script as your trading bit.

Cheers
backtesteducationalequation_inputPine utilitiesstrategy_adapterstrategy_as_indicatorstrategy_developmentstring_interpreterwebhook

نص برمجي للمستخدمين المدعوين فقط

الوصول إلى هذا النص مقيد للمستخدمين المصرح لهم من قبل المؤلف وعادة ما يكون الدفع مطلوباً. يمكنك إضافته إلى مفضلاتك، لكن لن تتمكن من استخدامه إلا بعد طلب الإذن والحصول عليه من مؤلفه. تواصل مع BerlinCode42 للحصول على مزيد من المعلومات، أو اتبع إرشادات المؤلف أدناه.

لا تقترح TradingView الدفع مقابل النصوص البرمجية واستخدامها حتى تثق بنسبة 100٪ في مؤلفها وتفهم كيفية عملها. في كثير من الحالات، يمكنك العثور على بديل جيد مفتوح المصدر مجانًا في نصوص مجتمع الخاصة بنا .

تعليمات المؤلف

You can get access to this Script for 10$ per month or 100$ per year. Just write me a message here on TradingView.

هل تريد استخدام هذا النص البرمجي على الرسم البياني؟

تحذير: ‎‎‎يرجى القراءة‎‎ قبل طلب الوصول.

إخلاء المسؤولية