Iceberg Trade Revealer [CHE]Unveiling Iceberg Trades: A Deep Dive into Low Volatility Market Phases 
  Introduction 
In the dynamic world of trading, hidden forces often influence market movements in ways that aren't immediately apparent. One such force is the phenomenon of iceberg trades—large orders that are concealed to prevent significant market impact. This presentation explores the concept of iceberg trades, explains why they are typically hidden during periods of low volatility, and introduces an indicator designed to reveal these elusive trades.
  Agenda 
1. Understanding Iceberg Trades
   - Definition and Purpose
   - Impact on Market Dynamics
2. The Low Volatility Concealment
   - Why Low Volatility Phases?
   - Strategies Behind Hiding Large Orders
3. Introducing the Iceberg Trade Revealer Indicator
   - How the Indicator Works
   - Key Components and Calculations
4. Demonstration and Use Cases
   - Interpreting the Indicator Signals
   - Practical Trading Applications
5. Conclusion
   - Summarizing the Insights
   - Q&A Session
  1. Understanding Iceberg Trades 
 Definition and Purpose
- Iceberg Trades are large single orders divided into smaller lots to disguise the total order quantity.
- Traders use iceberg orders to minimize market impact and avoid unfavorable price movements.
 Impact on Market Dynamics
- Concealed Volume: Iceberg orders hide true supply and demand levels.
- Price Stability: They prevent sudden spikes or drops by releasing orders gradually.
- Market Sentiment: Their presence can influence perceptions of market strength or weakness.
  2. The Low Volatility Concealment 
 Why Low Volatility Phases?
- Less Market Attention: Low volatility periods attract fewer traders, making it easier to conceal large orders.
- Reduced Slippage: Prices are more stable, reducing the risk of executing orders at unfavorable prices.
- Strategic Advantage: Large players can accumulate or distribute positions without tipping off the market.
 Strategies Behind Hiding Large Orders
- Order Splitting: Breaking down large orders into smaller pieces.
- Time Slicing: Executing orders over an extended period.
- Algorithmic Trading: Using sophisticated algorithms to optimize order execution.
  3. Introducing the Iceberg Trade Revealer Indicator 
 How the Indicator Works
- Core Thesis: Iceberg trades can be detected by analyzing periods of unusually low volatility.
- Volatility Analysis: Uses the Average True Range (ATR) and Bollinger Bands to identify low volatility phases.
- Signal Generation: Marks periods where iceberg trades are likely occurring.
 Key Components and Calculations
1. Average True Range (ATR)
   - Measures market volatility over a specified period.
   - Lower ATR values indicate less price movement.
2. Bollinger Bands
   - Creates a volatility envelope around the ATR.
   - Bands tighten during low volatility and widen during high volatility.
3. Timeframe Adjustments
   - Utilizes multiple timeframes to enhance signal accuracy.
   - Options for auto, multiplier, or manual timeframe selection.
4. Signal Conditions
   - Iceberg Trade Detection: ATR falls below the lower Bollinger Band.
   - Revealed Volatility: ATR rises above the upper Bollinger Band, indicating potential market moves after iceberg trades.
  4. Demonstration and Use Cases 
 Interpreting the Indicator Signals
- Iceberg Trade Zones: Highlighted areas where large hidden orders are likely.
- Revealed Volatility Zones: Areas indicating the market's response to the execution of iceberg trades.
 Practical Trading Applications
- Entry and Exit Points: Use signals to time trades alongside institutional activity.
- Risk Management: Adjust strategies during detected low volatility phases.
- Market Analysis: Gain insights into underlying market mechanics.
  5. Conclusion 
 Summarizing the Insights
- Iceberg Trades play a significant role in market movements, especially when concealed during low volatility phases.
- The Iceberg Trade Revealer Indicator provides a tool to uncover these hidden activities, offering traders a strategic edge.
- Understanding and utilizing this indicator can enhance trading decisions by aligning them with the actions of major market players.
Best regards Chervolino ( Volker )
 Q&A Session
- Questions and Discussions: Open the floor for any queries or further explanations.
 Thank You!
By delving into the hidden aspects of market activity, traders can better navigate the complexities of financial markets. The Iceberg Trade Revealer Indicator serves as a bridge between observable market data and the concealed strategies of large institutions.
 References
- Average True Range (ATR): A technical analysis indicator that measures market volatility.
- Bollinger Bands: A volatility indicator that creates a band of three lines which are plotted in relation to a security's price.
- Iceberg Orders: Large orders divided into smaller lots to hide the actual order quantity.
 Note: Always consider multiple factors when making trading decisions. Indicators provide tools, but they do not guarantee results.
Educational Content Disclaimer:
Disclaimer:
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
ค้นหาในสคริปต์สำหรับ "order"
Ranged Volume DCA Strategy - R3c0nTraderUpdate: Republishing this as Public Open-Source script.
Credits:
Thank you "EvoCrypto" for granting me permission to use "Ranged Volume" to create this strategy.
Thank you "junyou0424" for granting me permission to use "DCA Bot with SuperTrend Emulator" which I used for adding bot inputs, calculations, and strategy
What does this do?
This script is mainly used for backtesting a Ranged Volume strategy to see how a 3Commas bot would perform.
I created this script out of necessity and I wanted a way to test a 3Commas DCA bot with a strategy based on “Volume.” 
I came across "EvoCrypto’s" "Ranged Volume" study and strategy in TradingView and I liked it. I wanted to configure it so it can be used for DCA bot backtesting. I used parts from "junyou0424’s" "DCA Bot with SuperTrend Emulator" to add the following:
1.	The Start Time and End Time 
2.	Price deviation to open safety orders (%)
3.	Target Take Profit (%)
4.	Trailing deviation
5.	Base Order and Safety Order
6.	Safety order volume scale
7.	Safety order step scale
8.	Max safety orders
In addition to the above, I also added chart indicators for "Take Profit" as well as "Safety Order" 
Pre-requisites:
You can use this script without a 3Commas account and see how 3Commas DCA Bot and Ranged Volume strategy would perform vs. a non-DCA strategy. However, I highly recommend signing up for their free account and going through their training. This would give you a base understanding on the settings you will see in this strategy and why you will need to know them.
That said these are the pre-requisites I suggest you have:
1.	Base Knowledge of 3Commas DCA bots
2.	Base knowledge of settings such as “Max safety trades count”, “safety order volume scale” and “safety order step scale”. If these are alien to you, I suggest you read up on these.
3.	Knowledge of setting up a Single-pair 3Commas bot for receiving custom TradingView signal.
4.	A paper-bot to test your ideas. (Do not use a real money bot until you have tested it sufficiently with a paper-bot. You alone are responsible for your results!)
5.	Add the study I created called "R3c0nTrader’s Ranged Volume Study” which adds a separate chart in its own pane showing the volume spikes. It will also generate the “buy” signals for your bot. NOTE: The study also has the same color scheme as this strategy and having the colors in both the strategy and the study will make things easier to see. If you use EvoCrypto’s Ranged Volume Study instead, just keep in mind that the colors won’t match, and you will have to manually match them. 
6.	Make your buy signals from your strategy are the same as in your study! To do this, use the same “Volume Range Length” you entered in the STRATEGY and enter that value for the “Volume Range Length” in the STUDY. Also ensure you have the same settings for “Heikin Ashi” (On or Off).
Comparisons of Ranged Volume Strategy vs Ranged Volume DCA Strategy
BTCUSD
  
 
Beware of Strategies that claim super high profits. This can easily be done by lowering the initial capital to something unrealistic. If I did that with this strategy and set the initial capital $100 and base order size to $100, I get a net profit of 2,864% which is not realistic.
How to Use
1.	On the “Inputs” tab:
a.	Set your Start and End Time to backtest against.
b.	Set your “Volume Range Length” (number of bars to look back)
c.	“Heikin Ashi Colors” – Usually I leave this enabled
d.	“Show Bar Colors” – Leave enabled
e.	“Show Break-Out” – Leave enabled
f.	“Show Range” – Leave enabled
g.	Set your other inputs which are those settings you would find in your 3Commas bot that you want to test (e.g., Price deviation to open safety orders, Target Take Profit, Base order, Safety order, etc.). 
h.	Quick Example for BTCUSD on 2hr chart:
   i.	Price deviation to open safety orders (%) = 6
   ii.	Target Take Profit (%) = 14
   iii.	Trailing deviation = 0
   iv.	Base order = 100
   v.	Safety order = 200
   vi.	Safety order volume scale = 2
   vii.	Safety order step scale = 1.4
  viii.	Max safety order = 5
2.	On the “Properties” tab, set your initial capital, base currency, etc. 
   a.	Initial capital – Default is 10,000 (Please use realistic values here. The amount here should be able to cover ALL your safety orders if they were triggered. Ideally, you should have funds left over and not use all trade capital.)
   b.	Base currency – Select your currency
   c.	Order Size - Not used. Use the “Inputs” tab to change your base order size.
   d.	Leave “Pyramiding” set to 999. This acts as a ceiling to the “Max safety orders” on the “Inputs” tab. It must always be higher than your “Max safety orders.” For example, if you set your “Max safety orders” to “4” and “Pyramiding” to “4” then it effectively means you have “3” “Max safety orders” and not “4” because it is counting each successive entry including the initial order. 
   e.	“Commission” - Optional 
   f.	 “Verify price for limit orders” – Leave at zero. This does not change anything that I can tell.
   g.	Optional - Enter a value for “Commission”
   h.	Slippage – Optional. Slippage does not occur in backtesting but does occur in real trading but it can be simulated. Example use case for tracking performance of a real money bot: You enter the start date and time of your bot’s trade into this strategy and you notice some values are a little off due to slippage (average price, take profit, safety orders are not lining up) then you would go back here and increase the slippage until those lines up close enough with your actuals.
   i.	Margin for long positions – I don’t use this honestly.
   j.	Margin for short positions – I don’t use this honestly.
   k.	Recalculate “After order is filled” and “On every tick” – I don’t use this honestly.
3.	“Style” tab
   a.	Ranged Volume Bar Coloring - You must disable bar coloring in any studies you added or this may not work properly
      i.	Color 0 – Default Yellow; appears when a volume breakout occurs
      ii.	Color 1 – Default Red; appears when a volume breakdown occurs
      iii.	Color 2 – Light Blue; appears when Close is higher than the Open
      iv.	Color 3 – Dark Blue; appears when the Close is lower than the Open
   b.	Take profit – Default Green; take profit line
   c.	Safety order – Default Light Blue; safety order line
   d.	No Safety Orders left – Default Red; when a trade runs out of safety orders, the line turns red and there is no safety orders left underneath to catch any further falling price movements.
   e.	Avg Position Price – Default Orange; your average position price for any given trade.
   f.	Take Profit Plot Area – Default Green; creates a highlighted area for your take profit
   g.	SO Plot Area – Default Light Blue; creates a highlighted area for your safety orders
   h.	Trades on chart – Show or hide your trades on the chart
   i.	Signal labels – Show or hide the trade signal labels on the chart
   j.	Quantity – Show or hide the trade quantity on the chart
Explanation of Chart lines and colors on chart
   
72s Strat: Backtesting Adaptive HMA+ pt.1This is a follow up to my previous publication of  Adaptive HMA+  few months ago, as a mean to provide some kind of initial backtesting tools. Which can be use to explore many possible strategies, optimise its settings to better conform user's pair/tf, and hopefully able to help tweaking your general strategy.
If you haven't read the study or use the indicator, kindly go  here  first to get the overall idea.
The first strategy introduce in this backtest is one most basic already described in the study; buy/sell is when movement is there and everything is on the right side; When RSI has turned to other side, we can use it as exit point (if in profit of course, else just let it hit our TP/SL, why would we exit before profit). Also, base on RSI when we make entry, we can further differentiate type of signals. --Please check all comments in code directly where the  signals ,  entries , and  exits  section are. 
Second additional strategy to check; is when we also use second faster Adaptive HMA+ for exit. So this is like a double orders on a signal but with different exit-rule (/more on this on snapshots below). Alternatively, you can also work the code so to only use this type of exit. 
There's also an additional feature which you can enable its visuals, the  Distance Zone , is to help measuring price distance to our xHMA+. It's just a simple atr based envelope really, I already put the sample code in study's comment section, but better gonna update it there directly for non-coder too, after this.
In this sample I use  Lot  for order quantity size just because that's what I use on my broker. Also what few friends use while we forward-testing it since the study is published, so we also checked/compared each profit/loss report by real number. To use default or other unit of measurement, change the entry code accordingly.
If you change your order size, you should also change the  commission  in Properties Tab. My broker commission is 5 USD per order/lot, so in there with example order size 0.1 lot I put commission 0.5$ per order (I'll put 2.5$ for 0.5 lot, 10$ for 2 lot, and so on). Crypto usually has higher charge. --It is important that you should fill it base on your broker. 
 SETTINGS 
I'm trying to keep it short. Please explore it further again. (Beginner should also first get acquaintance with terms use here.)
 
 ORDERS:  
 Base Minimum Profit Before Exit:  
The number is multiplier of ongoing ATR. Means that when basic exit condition is met, algo will check whether you're already in minimum profit or not, if not, let it still run to TP or SL, or until it meets subsequent exit condition, then it will check again.  
 Default Target Profit:  
Multiplier of ATR at signal. If reached before any  eligible exit condition  is met, exit TP.
 Base StopLoss Point:  
You can change directly in code to use other like ATR Trailing SL, fix percent SL, or whatever. In the sample, 4 options provided.
 Maximum StopLoss:  
This is like a safety-net, that if at some point your chosen SL point from input above happens to be exceeding this maximum input that you can tolerate, then this max point is the one will be use as SL.
 Activate 2nd order...:  
The additional doubling of certain buy/sell with different exits as described above. If enable, you should also set pyramiding to at least: 2. If not, it does nothing.
 ADAPTIVE HMA+ PERIOD 
Many users already have their own settings for these. So in here I only sample the default as first presented in the study. Make it to your adaptive.
 MARKET MOVEMENT 
(1) Now you can check in realtime how much slope degree is best to define your specific pair/tf is out of congestion (yellow) area. And (2) also able to check directly what ATR lengths are more suitable defining your pair's volatility.
 DISTANCE ZONE 
Distance Multiplier. Each pair/tf has its own best distance zone (in xHMA+ perspective). The zone also determine whether a signal should appear or not. (Or what  type  of signal, if you wanna go more detail in constructing your strategy)
 
 USAGE 
(Provided you already have your own comfortable settings for minimum-maximum period of Adaptive HMA+. Best if you already have backtested it manually too and/or apply as an add-on to your working strategy)
1. In our experiences, first most important to define is both elements in the  Market Movement Settings . These also tend to be persistent for whole season since it's kinda describing that pair/tf overall behaviour. Don't worry if you still get a low Profit Factor here, but by tweaking you should start to see positive changes in one of Max Drawdown and Net Profit, or Percent Profitable.
2. Afterwards, find your pair/tf  Distance Zone . When optimising this, what we seek is just a "not to bad" equity curves to start forming. At least Max Drawdown should lessen more. Doesn't have to be great already, but should be better, no red in Net Profit. 
3. Then go manage the "Trailing Minimum Profit", TP, SL, and max SL. 
4. Repeat 1,2,3. 👻
5. Manage order size, commission, and/or enable double-order (need pyramiding) if you like. Check if your equity can handle max drawdown before margin call.
6. After getting an acceptable backtest result, go to  List of Trades  tab and find the biggest loss or when many sequencing loss in a row happened. Click on it to go to exact point on chart,  observe why the signal failed and get at least general idea how it can be prevented . The rest is yours, you should know your pair/tf more than other.
You can also re-explore your minimum-maximum period for both Major and minor xHMA+.
Keep in mind that all numbers in Setting are conceptually in a form of  range . You don't want to get superb equity curves but actually a "fragile" , means one can easily turn it to disaster just by changing only a fraction in one/two of the setting. 
---
If you just wanna test the strength of the indicator alone, you can disable "Use StopLoss" temporarily while optimising settings. 
Using no SL might be tempting in overall result data in some cases, but NOTE: It is  not  recommended to not using SL, don't forget that we deliberately enter when it's in high volatility. If want to add flexibility or trading for long-term, just maximise your SL. ie.: chose SL Point>ATR only and set it maximum. (Check your max drawdown after this).
      I think this is quite important specially for beginners, so here's an example; Hypothetically in below scenario, because of some settings, the buy order after the loss sell signal didn't appear. Let's say if our initial capital only 1000$ using leverage and order size 0,5 lot (risky position sizing already), moreover if this happens at the beginning of your trading season,  that's half of account gone already in one trade . Your max SL should've made you exit after that pumping bar.
  
The Trailing Minimum Profit is actually look like this. Search in the code if you want to plot it. I just don't like too many lines on chart.
  
To maximise profit we can try enabling double-order. The only added rule coded is: RSI should rising when buy and falling when sell. 2nd signal will appears above or below default buy/sell signal. (Of course it's also prone to double-loss, re-check your max drawdown after. Profit factor play its part in here for a long run). Snapshot in comparison:
  
Two default sell signals on left closed at RSI exit, the additional sell signal closed later on when price crossover minor xHMA+. On buy side, price haven't met our minimum profit when first crossunder minor xHMA+. If later on we hit SL on this "+buy" signal, at least we already profited from default buy signal. You can also consider/treat this as multiple TP points. 
For longer-term trading, what you need to maximise is the  Minimum Profit , so it won't exit whenever an exit condition happened, it can happen several times before reaching minimum profit. Hopefully this snapshot can explain:
  
Notice in comparison default sell and buy signal now close in average after 3 days. What's best is when we also have confirmation from higher TF. It's like targeting higher TF by entering from smaller TF. 
As also mention in the study, we can still experiment via original HMA by putting same value for minimum-maximum period setting. This is experimental EU 1H with Major xHMA+: 144-144, Flat market 13, Distance multiplier 3.6, with 2nd order activated.
  
Kiwi was a bit surprising for me. It's flat market is effectively below 6, with quite far distance zone of 3.5. Probably because I'm using big numbers in adaptive period.
  
---
The result you see in strategy tester report below for EURUSD 15m is using just default settings you see in code, as follow:
 
  0,1 lot for each order (which is the smallest allowed by my broker).
  No pyramiding. Commission: 0.5 usd per order. Slippage: 3
  Opening position is only using basic strategy #1 (RSI exit). Additional exit not activated.
  Minimum Profit: 1. TP: 3. 
  SL use: Half-distance zone. Max SL: 4.5.
  Major xHMA+: 172-233. minor xHMA+: 89-121
  Distance Zone Multiplier: 2.7
  RSI: Standard 14.
 
(From our forward-testing, the difference we get from net profit is because of the spread, our entry isn't exactly at the close/open price. Not so much though, but not the same. If somebody can direct me to any example where we can code our entry via current bid/ask price, that would be awesome!)
It's already a long post (sorry), think I'm gonna pause here. Check out the code :)
---
DISCLAIMER:  Past performance is no guarantee of future results , and so on.. you know the drill ;)
Please read whole description first before using, don't take 1-2 paragraph and claim it's the whole logic, you are responsible of your own actions and understanding.
LEGEND IsoPulse Fusion Universal Volume Trend Buy Sell RadarLEGEND IsoPulse Fusion • Universal Volume Trend Buy Sell Radar 
 One line summary 
LEGEND IsoPulse Fusion reads intent from price and volume together, learns which features matter most on your symbol, blends them into a single signed Fusion line in a stable unit range, and emits clear Buy Sell Close events with a structure gate and a liquidity safety gate so you act only when the tape is favorable.
 What this script is and why it exists 
Many traders keep separate windows for trend, volume, volatility, and regime filters. The result can feel fragmented. This script merges two complementary engines into one consistent view that is easy to read and simple to act on.
 
 LEGEND Tensor  estimates directional quality from five causally computed features that are normalized for stationarity. The features are Flow, Tail Pressure with Volume Mix, Path Curvature, Streak Persistence, and Entropy Order.
 IsoPulse  transforms raw volume into two decaying reservoirs for buy effort and sell effort using body location and wick geometry, then measures price travel per unit volume for efficiency, and detects volume bursts with a recency memory.
 
Both engines are mapped into the same unit range and fused by a regime aware mixer. When the tape is orderly the mixer leans toward trend features. When the tape is messy but a true push appears in volume efficiency with bursts the mixer allows IsoPulse to speak louder. The outcome is a single Fusion line that lives in a familiar range with calm behavior in quiet periods and expressive pushes when energy concentrates.
 What makes it original and useful 
 
 Two reservoir volume split . The script assigns a portion of the bar volume to up effort and down effort using body location and wick geometry together. Effort decays through time using a forgetting factor so memory is present without becoming sticky.
 Efficiency of move . Price travel per unit volume is often more informative than raw volume or raw range. The script normalizes both sides and centers the efficiency so it becomes signed fuel when multiplied by flow skew.
 Burst detection with recency memory . Percent rank of volume highlights bursts. An exponential memory of how recently bursts clustered converts isolated blips into useful context.
 Causal adaptive weighting . The LEGEND features do not receive static weights. The script learns, causally, which features have correlated with future returns on your symbol over a rolling window. Only positive contributions are allowed and weights are normalized for interpretability.
 Regime aware fusion . Entropy based order and persistence create a mixer that blends IsoPulse with LEGEND. You see a single line rather than two competing panels, which reduces decision conflict.
 
 How to read the screen in seconds 
 
 Fusion area . The pane fills above and below zero with a soft gradient. Deeper fill means stronger conviction. The white Fusion line sits on top for precise crossings.
 Entry guides and exit guides . Two entry guides draw symmetrically at the active fused entry level. Two exit guides sit inside at a fraction of the entry. Think of them as an adaptive envelope.
 Letters . B prints once when the script flips from flat to long. S prints once when the script flips from flat to short. C prints when a held position ends on the appropriate side. T prints when the structure gate first opens. A prints when the liquidity safety flag first appears.
 Price bar paint . Bars tint green while long and red while short on the chart to mirror your virtual position.
 HUD . A compact dashboard in the corner shows Fusion, IsoPulse, LEGEND, active entry and exit levels, regime status, current virtual position, and the vacuum z value with its avoid threshold.
 
 What signals actually mean 
 
 Buy . A Buy prints when the Fusion line crosses above the active entry level while gates are open and the previous state was flat.
 Sell . A Sell prints when the Fusion line crosses below the negative entry level while gates are open and the previous state was flat.
 Close . A Close prints when Fusion cools back inside the exit envelope or when an opposite cross would occur or when a gate forces a stop, and the previous state was a hold.
 Gates . The Trend gate requires sufficient entropy order or significant persistence. The Avoid gate uses a liquidity vacuum z score. Gates exist to protect you from weak tape and poor liquidity.
 
 Inputs and practical tuning 
Every input has a tooltip in the script. This section provides a concise reference that you can keep in mind while you work.
 Setup 
 
 Core window . Controls statistics across features. Scalping often prefers the thirties or low fifties. Intraday often prefers the fifties to eighties. Swing often prefers the eighties to low hundreds. Smaller responds faster with more noise. Larger is calmer.
 Smoothing . Short EMA on noisy features. A small value catches micro shifts. A larger value reduces whipsaw.
 
 Fusion and thresholds 
 
 Weight lookback . Sample size for weight learning. Use at least five times the horizon. Larger is slower and more confident. Smaller is nimble and more reactive.
 Weight horizon . How far ahead return is measured to assess feature value. Smaller favors quick reversion impulses. Larger favors continuation.
 Adaptive thresholds . Entry and exit levels from rolling percentiles of the absolute LEGEND score. This self scales across assets and timeframes.
 Entry percentile . Eighty selects the top quintile of pushes. Lower to seventy five for more signals. Raise for cleanliness.
 Exit percentile . Mid fifties keeps trades honest without overstaying. Sixty holds longer with wider give back.
 Order threshold . Minimum structure to trade. Zero point fifteen is a reasonable start. Lower to trade more. Raise to filter chop.
 Avoid if Vac z . Liquidity safety level. One point two five is a good default on liquid markets. Thin markets may prefer a slightly higher setting to avoid permanent avoid mode.
 
 IsoPulse 
 
 Iso forgetting per bar . Memory for the two reservoirs. Values near zero point nine eight to zero point nine nine five work across many symbols.
 Wick weight in effort split . Balance between body location and wick geometry. Values near zero point three to zero point six capture useful behavior.
 Efficiency window . Travel per volume window. Lower for snappy symbols. Higher for stability.
 Burst percent rank window . Window for percent rank of volume. Around one hundred to three hundred covers most use cases.
 Burst recency half life . How long burst clusters matter. Lower for quick fades. Higher for cluster memory.
 IsoPulse gain . Pre compression gain before the atan mapping. Tune until the Fusion line lives inside a calm band most of the time with expressive spikes on true pushes.
 Continuation and Reversal guides . Visual rails for IsoPulse that help you sense continuation or exhaustion zones. They do not force events.
 
 Entry sensitivity and exit fraction 
 
 Entry sensitivity . Loose multiplies the fused entry level by a smaller factor which prints more trades. Strict multiplies by a larger factor which selects fewer and cleaner trades. Balanced is neutral.
 Exit fraction . Exit level relative to the entry level in fused unit space. Values around one half to two thirds fit most symbols.
 
 Visuals and UX 
 
 Columns and line . Use both to see context and precise crossings. If you present a very clean chart you can turn columns off and keep the line.
 HUD . Keep it on while you learn the script. It teaches you how the gates and thresholds respond to your market.
 Letters . B S C T A are informative and compact. For screenshots you can toggle them off.
 Debug triggers . Show raw crosses even when gates block entries. This is useful when you tune the gates. Turn them off for normal use.
 
 Quick start recipes 
 Scalping one to five minutes 
 
 Core window in the thirties to low fifties.
 Horizon around five to eight.
 Entry percentile around seventy five.
 Exit fraction around zero point five five.
 Order threshold around zero point one zero.
 Avoid level around one point three zero.
 Tune IsoPulse gain until normal Fusion sits inside a calm band and true squeezes push outside.
 
 Intraday five to thirty minutes 
 
 Core window around fifty to eighty.
 Horizon around ten to twelve.
 Entry percentile around eighty.
 Exit fraction around zero point five five to zero point six zero.
 Order threshold around zero point one five.
 Avoid level around one point two five.
 
 Swing one hour to daily 
 
 Core window around eighty to one hundred twenty.
 Horizon around twelve to twenty.
 Entry percentile around eighty to eighty five.
 Exit fraction around zero point six zero to zero point seven zero.
 Order threshold around zero point two zero.
 Avoid level around one point two zero.
 
 How to connect signals to your risk plan 
This is an indicator. You remain in control of orders and risk.
 
 Stops . A simple choice is an ATR multiple measured on your chart timeframe. Intraday often prefers one point two five to one point five ATR. Swing often prefers one point five to two ATR. Adjust to symbol behavior and personal risk tolerance.
 Exits . The script already prints a Close when Fusion cools inside the exit envelope. If you prefer targets you can mirror the entry envelope distance and convert that to points or percent in your own plan.
 Position size . Fixed fractional or fixed risk per trade remains a sound baseline. One percent or less per trade is a common starting point for testing.
 Sessions and news . Even with self scaling, some traders prefer to skip the first minutes after an open or scheduled news. Gate with your own session logic if needed.
 
 Limitations and honest notes 
 
 No look ahead . The script is causal. The adaptive learner uses a shifted correlation, crosses are evaluated without peeking into the future, and no lookahead security calls are used. If you enable intrabar calculations a letter may appear then disappear before the close if the condition fails. This is normal for any cross based logic in real time.
 No performance promises . Markets change. This is a decision aid, not a prediction machine. It will not win every sequence and it cannot guarantee statistical outcomes.
 No dependence on other indicators . The chart should remain clean. You can add personal tools in private use but publications should keep the example chart readable.
 Standard candles only for public signals . Non standard chart types can change event timing and produce unrealistic sequences. Use regular candles for demonstrations and publications.
 
 Internal logic walkthrough 
 LEGEND feature block 
 
 Flow . Current return normalized by ATR then smoothed by a short EMA. This gives directional intent scaled to recent volatility.
 Tail pressure with volume mix . The relative sizes of upper and lower wicks inside the high to low range produce a tail asymmetry. A volume based mix can emphasize wick information when volume is meaningful.
 Path curvature . Second difference of close normalized by ATR and smoothed. This captures changes in impulse shape that can precede pushes or fades.
 Streak persistence . Up and down close streaks are counted and netted. The result is normalized for the window length to keep behavior stable across symbols.
 Entropy order . Shannon entropy of the probability of an up close. Lower entropy means more order. The value is oriented by Flow to preserve sign.
 Causal weights . Each feature becomes a z score. A shifted correlation against future returns over the horizon produces a positive weight per feature. Weights are normalized so they sum to one for clarity. The result is angle mapped into a compact unit.
 
 IsoPulse block 
 
 Effort split . The script estimates up effort and down effort per bar using both body location and wick geometry. Effort is integrated through time into two reservoirs using a forgetting factor.
 Skew . The reservoir difference over the sum yields a stable skew in a known range. A short EMA smooths it.
 Efficiency . Move size divided by average volume produces travel per unit volume. Normalization and centering around zero produce a symmetric measure.
 Bursts and recency . Percent rank of volume highlights bursts. An exponential function of bars since last burst adds the notion of cluster memory.
 IsoPulse unit . Skew multiplied by centered efficiency then scaled by the burst factor produces the raw IsoPulse that is angle mapped into the unit range.
 
 Fusion and events 
 
 Regime factor . Entropy order and streak persistence form a mixer. Low structure favors IsoPulse. Higher structure favors LEGEND. The blend is convex so it remains interpretable.
 Blended guides . Entry and exit guides are blended in the same way as the line so they stay consistent when regimes change. The envelope does not jump unexpectedly.
 Virtual position . The script maintains state. Buy and Sell require a cross while flat and gates open. Close requires an exit or force condition while holding. Letters print once at the state change.
 
 Disclosures 
 This script and description are educational. They do not constitute investment advice. Markets involve risk. You are responsible for your own decisions and for compliance with local rules. The logic is causal and does not look ahead. Signals on non standard chart types can be misleading and are not recommended for publication. When you test a strategy wrapper, use realistic commission and slippage, moderate risk per trade, and enough trades to form a meaningful sample, then document those assumptions if you share results. 
 Closing thoughts 
Clarity builds confidence. The Fusion line gives a single view of intent. The letters communicate action without clutter. The HUD confirms context at a glance. The gates protect you from weak tape and poor liquidity. Tune it to your instrument, observe it across regimes, and use it as a consistent lens rather than a prediction oracle. The goal is not to trade every wiggle. The goal is to pick your spots with a calm process and to stand aside when the tape is not inviting.
Divergence Strategy [Trendoscope®]🎲 Overview 
 The Divergence Strategy   is a sophisticated TradingView strategy that enhances the  Divergence Screener   by adding automated trade signal generation, risk management, and trade visualization. It leverages the screener’s robust divergence detection to identify bullish, bearish, regular, and hidden divergences, then executes trades with precise entry, stop-loss, and take-profit levels. Designed for traders seeking automated trading solutions, this strategy offers customizable trade parameters and visual feedback to optimize performance across various markets and timeframes.
For core divergence detection features, including oscillator options, trend detection methods, zigzag pivot analysis, and visualization, refer to the Divergence Screener   documentation. This description focuses on the strategy-specific enhancements for automated trading and risk management.
 🎲 Strategy Features 
 🎯Automated Trade Signal Generation 
 
 Trade Direction Control : Restrict trades to long-only or short-only to align with market bias or strategy goals, preventing conflicting orders.
 Divergence Type Selection : Choose to trade regular divergences (bullish/bearish), hidden divergences, or both, targeting reversals or trend continuations.
 Entry Type Options :
 Cautious : Enters conservatively at pivot points and exits quickly to minimize risk exposure.
 Confident : Enters aggressively at the latest price and holds longer to capture larger moves.
 Mixed : Combines conservative entries with delayed exits for a balanced approach. 
 Market vs. Stop Orders:  Opt for market orders for instant execution or stop orders for precise price entry.
 
 🎯 Enhanced Risk Management 
 
 Risk/Reward Ratio : Define a risk-reward ratio (default: 2.0) to set profit targets relative to stop-loss levels, ensuring consistent trade sizing.
 Bracket Orders : Trades include entry, stop-loss, and take-profit levels calculated from divergence pivot points, tailored to the entry type and risk-reward settings.
 Stop-Loss Placement : Stops are strategically set (e.g., at recent pivot or last price point) based on entry type, balancing risk and trade validity.
 Order Cancellation : Optionally cancel pending orders when a divergence is broken (e.g., price moves past the pivot in the wrong direction), reducing invalid trades. This feature is toggleable for flexibility.
 
 🎯 Trade Visualization 
 
 Target and Stop Boxes : Displays take-profit (lime) and stop-loss (orange) levels as boxes on the price chart, extending 10 bars forward for clear visibility.
 Dynamic Trade Updates : Trade visualizations are added, updated, or removed as trades are executed, canceled, or invalidated, ensuring accurate feedback.
 Overlay Integration : Trade levels overlay the price chart, complementing the screener’s oscillator-based divergence lines and labels.
 
 🎯 Strategy Default Configuration 
 
 Capital and Sizing : Set initial capital (default: $1,000,000) and position size (default: 20% of equity) for realistic backtesting.
 Pyramiding : Allows up to 4 concurrent trades, enabling multiple divergence-based entries in trending markets.
 Commission and Margin : Accounts for commission (default: 0.01%) and margin (100% for long/short) to reflect trading costs.
 Performance Optimization : Processes up to 5,000 bars dynamically, balancing historical analysis and real-time execution.
 
 🎲 Inputs and Configuration 
 🎯Trade Settings 
 
 Direction : Select Long or Short (default: Long).
 Divergence : Trade Regular, Hidden, or Both divergence types (default: Both).
 Entry/Exit Type : Choose Cautious, Confident, or Mixed (default: Cautious).
 Risk/Reward : Set the risk-reward ratio for profit targets (default: 2.0).
 Use Market Order : Enable market orders for immediate entry (default: false, uses limit orders).
 Cancel On Break : Cancel pending orders when divergence is broken (default: true).
 
  
 🎯Inherited Settings 
The strategy inherits all inputs from the Divergence Screener, including:
 
 Oscillator Settings : Oscillator type (e.g., RSI, CCI), length, and external oscillator option.
 Trend Settings : Trend detection method (Zigzag, MA Difference, External), MA type, and length.
 Zigzag Settings : Zigzag length (fixed repaint = true).
 
  
 🎲 Entry/Exit Types for Divergence Scenarios 
 The Divergence Strategy    offers three Entry/Exit Type options—Cautious, Confident, and Mixed—which determine how trades are entered and exited based on divergence pivot points. This section explains how these settings apply to different divergence scenarios, with placeholders for screenshots to illustrate each case.
The divergence pattern forms after 3 pivots.  The stop and entry levels are formed on one of these levels based on Entry/Exit types.
 🎯Bullish Divergence (Reversal) 
A bullish divergence occurs when price forms a lower low, but the oscillator forms a higher low, signaling a potential upward reversal.
 💎 Cautious: 
 
 Entry : At the pivot high point for a conservative entry.
 Exit : Stop-loss at the last pivot point (previous low that is higher than the current pivot low); take-profit at risk-reward ratio. Canceled if price breaks below the pivot (if Cancel On Break is enabled).
 Behavior : Enters after confirmation and exits quickly to limit downside risk.
 
 💎Confident: 
 
 Entry : At the last pivot low, (previous low which is higher than the current pivot low) for an aggressive entry.
 Exit : Stop-loss at recent pivot low, which is the lowest point; take-profit at risk-reward ratio. Canceled if price breaks below the pivot. (lazy exit)
 Behavior : Enters early to capture trend continuation, holding longer for gains.
 
 💎Mixed: 
 
 Entry : At the pivot high point (conservative).
 Exit : Stop-loss at the recent pivot point that has resulted in lower low (lazy exit). Canceled if price breaks below the pivot.
 Behavior : Balances entry caution with extended holding for trend continuation.
 
  
 🎯Bearish Divergence (Reversal) 
A bearish divergence occurs when price forms a higher high, but the oscillator forms a lower high, indicating a potential downward reversal.
 💎Cautious: 
 
 Entry : At the pivot low point (lower high) for a conservative short entry.
 Exit : Stop-loss at the previous pivot high point (previous high); take-profit at risk-reward ratio. Canceled if price breaks above the pivot (if Cancel On Break is enabled).
 Behavior : Enters conservatively and exits quickly to minimize risk.
 
 💎Confident: 
 
 Entry : At the last price point (previous high) for an aggressive short entry.
 Exit : Stop-loss at the pivot point; take-profit at risk-reward ratio. Canceled if price breaks above the pivot.
 Behavior : Enters early to maximize trend continuation, holding longer.
 
 💎Mixed: 
 
 Entry : At the previous piot high point (conservative).
 Exit : Stop-loss at the last price point (delayed exit). Canceled if price breaks above the pivot.
 Behavior : Combines conservative entry with extended holding for downtrend gains.
 
  
 🎯Bullish Hidden Divergence (Continuation) 
A bullish hidden divergence occurs when price forms a higher low, but the oscillator forms a lower low, suggesting uptrend continuation. In case of Hidden bullish divergence, b]Entry  is always on the previous pivot high (unless it is a market order)
 💎Cautious: 
 
 Exit : Stop-loss at the recent pivot low point (higher than previous pivot low); take-profit at risk-reward ratio. Canceled if price breaks below the pivot (if Cancel On Break is enabled).
 Behavior : Enters after confirmation and exits quickly to limit downside risk.
 
 💎Confident: 
 
 Exit : Stop-loss at previous pivot low, which is the lowest point; take-profit at risk-reward ratio. Canceled if price breaks below the pivot. (lazy exit)
 Behavior : Enters early to capture trend continuation, holding longer for gains.
 
  
 🎯Bearish Hidden Divergence (Continuation) 
A bearish hidden divergence occurs when price forms a lower high, but the oscillator forms a higher high, suggesting downtrend continuation. In case of Hidden Bearish divergence, b]Entry  is always on the previous pivot low (unless it is a market order)
 💎Cautious: 
 
 Exit : Stop-loss at the latest pivot high point (which is a lower high); take-profit at risk-reward ratio. Canceled if price breaks above the pivot (if Cancel On Break is enabled).
 Behavior : Enters conservatively and exits quickly to minimize risk.
 
 💎Confident/Mixed: 
 
 Exit : Stop-loss at the previous pivot high point; take-profit at risk-reward ratio. Canceled if price breaks above the pivot.
 Behavior : Uses the late exit point to hold longer.
 
  
 🎲 Usage Instructions 
 🎯Add to Chart: 
 
 Add the Divergence Strategy   to your TradingView chart.
 The oscillator and divergence signals appear in a separate pane, with trade levels (target/stop boxes) overlaid on the price chart.
 
 🎯Configure Settings: 
 
 Adjust trade settings (direction, divergence type, entry type, risk-reward, market orders, cancel on break).
 Modify inherited Divergence Screener settings (oscillator, trend method, zigzag length) as needed.
 Enable/disable alerts for divergence notifications.
 
 🎯Interpret Signals: 
 
 Long Trades: Triggered on bullish or bullish hidden divergences (if allowed), shown with green/lime lines and labels.
 Short Trades: Triggered on bearish or bearish hidden divergences (if allowed), shown with red/orange lines and labels.
 Monitor lime (target) and orange (stop) boxes for trade levels.
 Review strategy performance metrics (e.g., profit/loss, win rate) in the strategy tester.
 
 🎯Backtest and Optimize: 
 
 Use TradingView’s strategy tester to evaluate performance on historical data.
 Fine-tune risk-reward, entry type, position sizing, and cancellation settings to suit your market and timeframe.
 
For questions, suggestions, or support, contact Trendoscope via TradingView or official support channels. Stay tuned for updates and enhancements to the Divergence Strategy!
PVSRA  v5Overview of the PVSRA Strategy
This strategy is designed to detect and capitalize on volume-driven threshold breaches in price candles. It operates on the premise that when a high-volume candle breaks a critical price threshold, not all orders are filled within that candle’s range. This creates an imbalance—similar to a physical system being perturbed—causing the price to revert toward the level where the breach occurred to “absorb” the residual orders.
Key Features and Their Theoretical Underpinnings
Dynamic Volume Analysis and Threshold Detection
Volume Surges as Market Perturbations:
The script computes a moving average of volume over a short window and flags moments when the current volume significantly exceeds this average. These surges act as a perturbation—injecting “energy” into the market.
Adaptive Abnormal Volume Threshold:
By calculating a dynamic abnormal threshold using a daily volume average (via an 89-period VWMA) and standard deviation, the strategy identifies when the current volume is abnormally high. This mechanism mirrors the idea that when a system is disturbed (here, by a volume surge), it naturally seeks to return to equilibrium.
Candle Coloring and Visual Signal Identification
Differentiation of Candle Types:
The script distinguishes between bullish (green) and bearish (red) candles. It applies different colors based on the strength of the volume signal, providing a clear, visual representation of whether a candle is likely to trigger a price reversion.
Implication of Unfilled Orders:
A red (bearish) candle with high volume implies that sell pressure has pushed the price past a critical threshold—yet not all buy orders have been fulfilled. Conversely, a green (bullish) candle indicates that aggressive buying has left pending sell orders. In both cases, the market is expected to reverse toward the breach point to restore balance.
Trade Execution Logic: Normal and Reversal Trades
Normal Trades:
When a high-volume candle breaches a threshold and meets the directional conditions (e.g., a red candle paired with price above a daily upper band), the strategy enters a trade anticipating a reversion. The underlying idea is that the market will move back to the level where the threshold was crossed—clearing the residual orders in a manner analogous to a system following the path of least resistance.
Reversal Trades:
The strategy also monitors for clusters of consecutive signals within a short lookback period. When multiple signals accumulate, it interprets this as the market having overextended and, in a corrective move, reverses the typical trade direction. This inversion captures the market’s natural tendency to “correct” itself by moving in discrete, quantized steps—each step representing the absorption of a minimum quantum of order imbalance.
Risk and Trade Management
Stop Loss and Take Profit Buffers:
Both normal and reversal trades include predetermined buffers for stop loss and take profit levels. This systematic risk management approach is designed to capture the anticipated reversion while minimizing potential losses, aligning with the idea that market corrections follow the most energy-efficient path back to equilibrium.
Symbol Flexibility:
An option to override the chart’s symbol allows the strategy to be applied consistently across different markets, ensuring that the volume and price dynamics are analyzed uniformly.
Conceptual Bridge: From Market Dynamics to Trade Execution
At its core, the strategy treats market price movements much like a physical system that seeks to minimize “transactional energy” or inefficiency. When a price candle breaches a key threshold on high volume, it mimics an injection of energy into the system. The subsequent price reversion is the market’s natural response—moving in the most efficient path back to balance. This perspective is akin to the principle of least action, where the system evolves along the trajectory that minimizes cumulative imbalance, and it acknowledges that these corrections occur in discrete steps reflective of quantized order execution.
This unified framework allows the PVSRA strategy to not only identify when significant volume-based threshold breaches occur but also to systematically execute trades that benefit from the expected corrective moves.
Extreme Trend Reversal Points [HeWhoMustNotBeNamed]Using moving average crossover for identifying the change in trend is very common. However, this method can give lots of false signals during the ranging markets. In this algorithm, we try to find the extreme trend by looking at fully aligned multi-level moving averages and only look at moving average crossover when market is in the extreme trend - either bullish or bearish. These points can mean long term downtrend or can also cause a small pullback before trend continuation. In this discussion, we will also check how to handle different scenarios.
 🎲 Components 
🎯 Recursive Multi Level Moving Averages
Multi level moving average here refers to applying moving average on top of base moving average on multiple levels. For example,
Level 1 SMA = SMA(source, length)
Level 2 SMA = SMA(Level 1 SMA, length)
Level 3 SMA = SMA(Level 2 SMA, length)
..
..
..
Level n SMA = SMA(Level (n-1) SMA, length)
In this script, user can select how many levels of moving averages need to be calculated. This is achieved through " recursive moving average " algorithm. Requirement for building such algorithm was initially raised by @loxx
While I was able to develop them in minimal code with the help of some of the existing libraries built on  arrays  and  matrix , I also thought why not extend this to find something interesting.
Note that since we are using variable levels - we will not be able to plot all the levels of moving average. (This is because plotting cannot be done in the loop). Hence, we are using lines to display the latest moving average levels in front of the last candle. Lines are color coded in such a way that least numbered levels are greener and higher levels are redder.
🎯 Finding the trend and range
Strength of fully aligned moving average is calculated based on position of each level with respect to other levels.
For example, in a complete uptrend, we can find
 source > L(1)MA > L(2)MA > L(3)MA ...... > L(n-1)MA > L(n)MA 
Similarly in a complete downtrend, we can find
 source < L(1)MA < L(2)MA < L(3)MA ...... < L(n-1)MA < L(n)MA 
Hence, the strength of trend here is calculated based on relative positions of each levels. Due to this, value of strength can range from  0 to Level*(Level-1)/2 
0 represents the complete downtrend
Level*(Level-1)/2 represents the complete uptrend.
Range and Extreme Range are calculated based on the percentile from median. The brackets are defined as per input parameters -  Range Percentile  and  Extreme Range Percentile  by using  Percentile History  as reference length.
Moving average plot is color coded to display the trend strength.
Green - Extreme Bullish
Lime - Bullish
Silver - range
Orange - Bearish
Red - Extreme Bearish
  
🎯 Finding the trend reversal
Possible trend reversals are when price crosses the moving average while in complete trend with all the moving averages fully aligned. Triangle marks are placed in such locations which can help observe the probable trend reversal points. But, there are possibilities of trend overriding these levels. An example of such thing, we can see here:
In order to overcome this problem, we can employ few techniques.
1. After the signal, wait for trend reversal (moving average plot color to turn silver) before placing your order.
2. Place stop orders on immediate pivot levels or support resistance points instead of opening market order. This way, we can also place an order in the direction of trend. Whichever side the price breaks out, will be the direction to trade.
3. Look for other confirmations such as extremely bullish and bearish candles before placing the orders.
🎯 An example of using stop orders
Let us take this scenario where there is a signal on possible reversal from complete uptrend.
Create a box joining high and low pivots at reasonable distance. You can also chose to add 1 ATR additional distance from pivots.
Use the top of the box as stop-entry for long and bottom as stop-entry for short. The other ends of the box can become stop-losses for each side.
After few bars, we can see that few more signals are plotted but, the price is still within the box. There are some candles which touched the top of the box. But, the candlestick patterns did not represent bullishness on those instances. If you have placed stop orders, these orders would have already filled in. In that case, just wait for position to hit either stop or target.
For bullish side, targets can be placed at certain risk reward levels. In this case, we just use 1:1 for bullish (trend side) and 1:1.5 for bearish side (reversal side)
In this case, price hit the target without any issue: 
Wait for next reversal signal to appear before placing another order :)
FiniteStateMachine🟩  OVERVIEW 
A flexible framework for creating, testing and implementing a Finite State Machine (FSM) in your script. FSMs use rules to control how states change in response to events. 
This is the first Finite State Machine library on TradingView and it's quite a different way to think about your script's logic. Advantages of using this vs hardcoding all your logic include: 
 •  Explicit logic : You can see all rules easily side-by-side.
 •  Validation : Tables show your rules and validation results right on the chart.
 •  Dual approach : Simple matrix for straightforward transitions; map implementation for concurrent scenarios. You can combine them for complex needs.
 •  Type safety : Shows how to use enums for robustness while maintaining string compatibility.
 •  Real-world examples : Includes both conceptual (traffic lights) and practical (trading strategy) demonstrations.
 •  Priority control : Explicit control over which rules take precedence when multiple conditions are met.
 •  Wildcard system : Flexible pattern matching for states and events.
The library seems complex, but it's not really. Your conditions, events, and their potential interactions are complex. The FSM makes them all explicit, which is some work. However, like all "good" pain in life, this is front-loaded, and *saves* pain later, in the form of unintended interactions and bugs that are very hard to find and fix.
🟩  SIMPLE FSM (MATRIX-BASED) 
The simple FSM uses a matrix to define transition rules with the structure: state > event > state. We look up the current state, check if the event in that row matches, and if it does, output the resulting state.
Each row in the matrix defines one rule, and the first matching row, counting from the top down, is applied.
A limitation of this method is that you can supply only ONE event.
You can design layered rules using widlcards. Use an empty string "" or the special string "ANY" for any state or event wildcard.
The matrix FSM is foruse where you have clear, sequential state transitions triggered by single events. Think traffic lights, or any logic where only one thing can happen at a time.
The demo for this FSM is of traffic lights.
🟩  CONCURRENT FSM (MAP-BASED) 
The map FSM uses a more complex structure where each state is a key in the map, and its value is an array of event rules. Each rule maps a named condition to an output (event or next state).
This FSM can handle multiple conditions simultaneously. Rules added first have higher priority.
Adding more rules to existing states combines the entries in the map (if you use the supplied helper function) rather than overwriting them.
This FSM is for more complex scenarios where multiple conditions can be true simultaneously, and you need to control which takes precedence. Like trading strategies, or any system with concurrent conditions.
The demo for this FSM is a trading strategy.
🟩  HOW TO USE 
Pine Script libraries contain reusable code for importing into indicators. You do not need to copy any code out of here. Just import the library and call the function you want.
For example, for version 1 of this library, import it like this:
 
import SimpleCryptoLife/FiniteStateMachine/1
 
See the EXAMPLE USAGE sections within the library for examples of calling the functions.
For more information on libraries and incorporating them into your scripts, see the  Libraries  section of the Pine Script User Manual. 
🟩  TECHNICAL IMPLEMENTATION 
Both FSM implementations support wildcards using blank strings "" or the special string "ANY". Wildcards match in this priority order:
 • Exact state + exact event match
 • Exact state + empty event (event wildcard)  
 • Empty state + exact event (state wildcard)
 • Empty state + empty event (full wildcard)
When multiple rules match the same state + event combination, the FIRST rule encountered takes priority. In the matrix FSM, this means row order determines priority. In the map FSM, it's the order you add rules to each state.
The library uses user-defined types for the map FSM:
 •  o_eventRule : Maps a condition name to an output
 •  o_eventRuleWrapper : Wraps an array of rules (since maps can't contain arrays directly)
Everything uses strings for maximum library compatibility, though the examples show how to use enums for type safety by converting them to strings.
Unlike normal maps where adding a duplicate key overwrites the value, this library's `m_addRuleToEventMap()` method *combines* rules, making it intuitive to build rule sets without breaking them.
🟩  VALIDATION & ERROR HANDLING 
The library includes comprehensive validation functions that catch common FSM design errors:
 Error detection: 
 • Empty next states
 • Invalid states not in the states array  
 • Duplicate rules
 • Conflicting transitions
 • Unreachable states (no entry/exit rules)
 Warning detection: 
 • Redundant wildcards
 • Empty states/events (potential unintended wildcards)
 • Duplicate conditions within states
You can display validation results in tables on the chart, with tooltips providing detailed explanations. The helper functions to display the tables are exported so you can call them from your own script.
🟩  PRACTICAL EXAMPLES 
The library includes four comprehensive demos:
 Traffic Light Demo (Simple FSM) : Uses the matrix FSM to cycle through traffic light states (red → red+amber → green → amber → red) with timer events. Includes pseudo-random "break" events and repair logic to demonstrate wildcards and priority handling.
 Trading Strategy Demo (Concurrent FSM) : Implements a realistic long-only trading strategy using BOTH FSM types:
 • Map FSM converts multiple technical conditions (EMA crosses, gaps, fractals, RSI) into prioritised events
 • Matrix FSM handles state transitions (idle → setup → entry → position → exit → re-entry)
 • Includes position management, stop losses, and re-entry logic
 Error Demonstrations : Both FSM types include error demos with intentionally malformed rules to showcase the validation system's capabilities.
🟩  BRING ON THE FUNCTIONS 
 f_printFSMMatrix(_mat_rules, _a_states, _tablePosition) 
  Prints a table of states and rules to the specified position on the chart. Works only with the matrix-based FSM.
  Parameters:
     _mat_rules (matrix) 
     _a_states (array) 
     _tablePosition (simple string) 
  Returns: The table of states and rules.
 method m_loadMatrixRulesFromText(_mat_rules, _rulesText) 
  Loads rules into a rules matrix from a multiline string where each line is of the form "current state | event | next state" (ignores empty lines and trims whitespace).
This is the most human-readable way to define rules because it's a visually aligned, table-like format.
  Namespace types: matrix
  Parameters:
     _mat_rules (matrix) 
     _rulesText (string) 
  Returns: No explicit return. The matrix is modified as a side-effect.
 method m_addRuleToMatrix(_mat_rules, _currentState, _event, _nextState) 
  Adds a single rule to the rules matrix. This can also be quite readble if you use short variable names and careful spacing.
  Namespace types: matrix
  Parameters:
     _mat_rules (matrix) 
     _currentState (string) 
     _event (string) 
     _nextState (string) 
  Returns: No explicit return. The matrix is modified as a side-effect.
 method m_validateRulesMatrix(_mat_rules, _a_states, _showTable, _tablePosition) 
  Validates a rules matrix and a states array to check that they are well formed. Works only with the matrix-based FSM.
Checks: matrix has exactly 3 columns; no empty next states; all states defined in array; no duplicate states; no duplicate rules; all states have entry/exit rules; no conflicting transitions; no redundant wildcards. To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the rules and states are ready.
  Namespace types: matrix
  Parameters:
     _mat_rules (matrix) 
     _a_states (array) 
     _showTable (bool) 
     _tablePosition (simple string) 
  Returns: `true` if the rules and states are valid; `false` if errors or warnings exist.
 method m_getStateFromMatrix(_mat_rules, _currentState, _event, _strictInput, _strictTransitions) 
  Returns the next state based on the current state and event, or `na` if no matching transition is found. Empty (not na) entries are treated as wildcards if `strictInput` is false.
Priority: exact match > event wildcard > state wildcard > full wildcard.
  Namespace types: matrix
  Parameters:
     _mat_rules (matrix) 
     _currentState (string) 
     _event (string) 
     _strictInput (bool) 
     _strictTransitions (bool) 
  Returns: The next state or `na`.
 method m_addRuleToEventMap(_map_eventRules, _state, _condName, _output) 
  Adds a single event rule to the event rules map. If the state key already exists, appends the new rule to the existing array (if different). If the state key doesn't exist, creates a new entry.
  Namespace types: map
  Parameters:
     _map_eventRules (map) 
     _state (string) 
     _condName (string) 
     _output (string) 
  Returns: No explicit return. The map is modified as a side-effect.
 method m_addEventRulesToMapFromText(_map_eventRules, _configText) 
  Loads event rules from a multiline text string into a map structure.
Format: "state | condName > output | condName > output | ..." . Pairs are ordered by priority. You can have multiple rules on the same line for one state.
Supports wildcards: Use an empty string ("") or the special string "ANY" for state or condName to create wildcard rules.
Examples: " | condName > output" (state wildcard), "state |  > output" (condition wildcard), " |  > output" (full wildcard).
Splits lines by \n, extracts state as key, creates/appends to array with new o_eventRule(condName, output).
Call once, e.g., on barstate.isfirst for best performance.
  Namespace types: map
  Parameters:
     _map_eventRules (map) 
     _configText (string) 
  Returns: No explicit return. The map is modified as a side-effect.
 f_printFSMMap(_map_eventRules, _a_states, _tablePosition) 
  Prints a table of map-based event rules to the specified position on the chart.
  Parameters:
     _map_eventRules (map) 
     _a_states (array) 
     _tablePosition (simple string) 
  Returns: The table of map-based event rules.
 method m_validateEventRulesMap(_map_eventRules, _a_states, _a_validEvents, _showTable, _tablePosition) 
  Validates an event rules map to check that it's well formed.
Checks: map is not empty; wrappers contain non-empty arrays; no duplicate condition names per state; no empty fields in o_eventRule objects; optionally validates outputs against matrix events.
NOTE: Both "" and "ANY" are treated identically as wildcards for both states and conditions.
To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the map is ready.
  Namespace types: map
  Parameters:
     _map_eventRules (map) 
     _a_states (array) 
     _a_validEvents (array) 
     _showTable (bool) 
     _tablePosition (simple string) 
  Returns: `true` if the event rules map is valid; `false` if errors or warnings exist.
 method m_getEventFromConditionsMap(_currentState, _a_activeConditions, _map_eventRules) 
  Returns a single event or state string based on the current state and active conditions.
Uses a map of event rules where rules are pre-sorted by implicit priority via load order.
Supports wildcards using empty string ("") or "ANY" for flexible rule matching.
Priority: exact match > condition wildcard > state wildcard > full wildcard.
  Namespace types: series string, simple string, input string, const string
  Parameters:
     _currentState (string) 
     _a_activeConditions (array) 
     _map_eventRules (map) 
  Returns: The output string (event or state) for the first matching condition, or na if no match found.
 o_eventRule 
  o_eventRule defines a condition-to-output mapping for the concurrent FSM.
  Fields:
     condName (series string) : The name of the condition to check.
     output (series string) : The output (event or state) when the condition is true.
 o_eventRuleWrapper 
  o_eventRuleWrapper wraps an array of o_eventRule for use as map values (maps cannot contain collections directly).
  Fields:
     a_rules (array) : Array of o_eventRule objects for a specific state.
Bot Analyzer📌 Script Name: Bot Analyzer
This TradingView Pine Script v5 indicator creates a dashboard table on the chart that helps you analyze any asset for running a martingale grid bot on futures.
🔧 User Inputs
TP % (tpPct): Take Profit percentage.
SO step % (soStepPct): Step size between safety orders.
SO n (soCount): Number of safety orders.
M mult (martMult): Martingale multiplier (how much each next order increases in size).
Lev (leverage): Leverage used in futures.
BB len / BB mult: Bollinger Bands settings for measuring channel width.
ATR len: ATR period for volatility.
HV days: Lookback window (days) for Historical Volatility calculation.
📐 Calculations
ATR % (atrPct): Normalized ATR relative to price.
Bollinger Band width % (bbPct): Market channel width as percentage of basis.
Historical Volatility (hvAnn): Annualized volatility, calculated from daily log returns.
Dynamic Step % (dynStepPct): Step size for safety orders, automatically adjusted from ATR and clamped between 0.3% and 5%.
Covered Move % (coveredPct): Total percentage move the bot can withstand before last safety order.
Martingale Size Factor (sizeFactor): Total position size multiplier after all safety orders, based on martingale multiplier.
Risk Score (riskLabel): Simple risk estimate:
Low if risk < 30
Mid if risk < 60
High if risk ≥ 60
📊 Output (Table on Chart)
At the top-right of the chart, the script draws a table with 9 rows:
Metric	Value
BB %	Bollinger Band width in %
HV %	Historical Volatility (annualized %)
TP %	Take profit setting
SO step %	Safety order step size
SO n	Number of safety orders
M mult	Martingale multiplier
Dyn step %	Dynamic step based on ATR
Size x	Total position size factor (e.g., 4.5x)
Risk	Risk label (Low / Mid / High)
⚙️ Use Case
Helps choose coins for a martingale bot:
If BB% is wide and HV% is high → the asset is volatile enough.
If Risk shows "High" → parameters are aggressive, you may need to adjust step size, SO count, or leverage.
The dashboard lets you compare assets quickly without switching between multiple indicators.
Bullish and Bearish Breakout Alert for Gold Futures PullbackBelow is a Pine Script (version 6) for TradingView that includes both bullish and bearish breakout conditions for my intraday trading strategy on micro gold futures (MGC). The strategy focuses on scalping two-legged pullbacks to the 20 EMA or key levels with breakout confirmation, tailored for the Apex Trader Funding $300K challenge. The script accounts for the Daily Sentiment Index (DSI) at 87 (overbought, favoring pullbacks). It generates alerts for placing stop-limit orders for 175 MGC contracts, ensuring compliance with Apex’s rules ($7,500 trailing threshold, $20,000 profit target, 4:59 PM ET close).
Script Requirements
Version: Pine Script v6 (latest for TradingView, April 2025).
Purpose:
Bullish: Alert when price breaks above a rejection candle’s high after a two-legged pullback to the 20 EMA in a bullish trend (price above 20 EMA, VWAP, higher highs/lows).
Bearish: Alert when price breaks below a rejection candle’s low after a two-legged pullback to the 20 EMA in a bearish trend (price below 20 EMA, VWAP, lower highs/lows).
Context: 5-minute MGC chart, U.S. session (8:30 AM–12:00 PM ET), avoiding overbought breakouts above $3,450 (DSI 87).
Output: Alerts for stop-limit orders (e.g., “Buy: Stop=$3,377, Limit=$3,377.10” or “Sell: Stop=$3,447, Limit=$3,446.90”), quantity 175 MGC.
Apex Compliance: 175-contract limit, stop-losses, one-directional news trading, close by 4:59 PM ET.
How to Use the Script in TradingView
1. Add Script:
Open TradingView (tradingview.com).
Go to “Pine Editor” (bottom panel).
Copy the script from the  content.
Click “Add to Chart” to apply to your MGC 5-minute chart  .
2. Configure Chart:
Symbol: MGC (Micro Gold Futures, CME, via Tradovate/Apex data feed).
Timeframe: 5-minute (entries), 15-minute (trend confirmation, manually check).
Indicators: Script plots 20 EMA and VWAP; add RSI (14) and volume manually if needed  .
3. Set Alerts:
Click the “Alert” icon (bell).
Add two alerts:
Bullish Breakout: Condition = “Bullish Breakout Alert for Gold Futures Pullback,” trigger = “Once Per Bar Close.”
Bearish Breakout: Condition = “Bearish Breakout Alert for Gold Futures Pullback,” trigger = “Once Per Bar Close.”
Customize messages (default provided) and set notifications (e.g., TradingView app, SMS).
Example: Bullish alert at $3,377 prompts “Stop=$3,377, Limit=$3,377.10, Quantity=175 MGC”  .
4. Execute Orders:
Bullish:
Alert triggers (e.g., stop $3,377, limit $3,377.10).
In TradingView’s “Order Panel,” select “Stop-Limit,” set:
Stop Price: $3,377.
Limit Price: $3,377.10.
Quantity: 175 MGC.
Direction: Buy.
Confirm via Tradovate.
Add bracket order (OCO):
Stop-loss: Sell 175 at $3,376.20 (8 ticks, $1,400 risk).
Take-profit: Sell 87 at $3,378 (1:1), 88 at $3,379 (2:1)  .
Bearish:
Alert triggers (e.g., stop $3,447, limit $3,446.90).
Select “Stop-Limit,” set:
Stop Price: $3,447.
Limit Price: $3,446.90.
Quantity: 175 MGC.
Direction: Sell.
Confirm via Tradovate.
Add bracket order:
Stop-loss: Buy 175 at $3,447.80 (8 ticks, $1,400 risk).
Take-profit: Buy 87 at $3,446 (1:1), 88 at $3,445 (2:1)  .
5. Monitor:
Green triangles (bullish) or red triangles (bearish) confirm signals.
Avoid bullish entries above $3,450 (DSI 87, overbought) or bearish entries below $3,296 (support)  .
Close trades by 4:59 PM ET (set 4:50 PM alert)  .
Supertrend TP SL (PRO)2. Main Components:
Supertrend Indicator:
Theoretical basis: The Supertrend indicator is based on two main concepts: Average True Range (ATR) and Factor. ATR measures the extent of price fluctuations in a given period of time, while Factor determines the sensitivity of the indicator to price changes.
Mechanism of operation: The indicator calculates two possible lines: one line representing the potential support level and another line representing the potential resistance level. The selection of the appropriate line depends on the current price direction. When the price is above the line, the indicator is considered to be in an uptrend, and vice versa.
Customizable inputs:
atrPeriod: Allows the trader to specify the time period for calculating the ATR. Shorter periods make the indicator more sensitive to price changes, while longer periods reduce its sensitivity.
factor: Allows the adjustment of the factor. Higher values make the indicator less likely to give false signals, but they may also delay entry signals.
Risk Management:
Take Profit and Stop Loss Orders:
TPPoints: Specifies the distance between the entry price and the take profit level. This distance is expressed in points, and is converted to an actual price value using syminfo.mintick (the smallest possible price movement of the traded asset).
SLPoints: Specifies the distance between the entry price and the stop loss level.
Importance: These orders allow the trader to specify the maximum loss he is willing to take and the profit target he is aiming to achieve, which helps in effective risk management.
Activate/Disable Trades:
isLongEnabled: Allows buy trades to be enabled or disabled, which allows the trader to trade in one direction only (for example, only trade in the uptrend during a bull market).
isShortEnabled: Allows sell trades to be enabled or disabled.
isTakeProfitEnabled: Allows take profit orders to be enabled or disabled. The trader may wish to disable them if he prefers to manage his trades manually.
isStopLossEnabled: Allows you to enable or disable stop loss orders. Although disabling them may seem tempting in some cases, it is a very risky move.
Visual Customization:
Line Style and Width:
lineStyle: Allows the trader to choose the style of lines used to draw TP and SL levels (Solid, Dashed, Dotted).
lineWidth: Sets the thickness of the lines.
Label Size:
labelSize: Allows you to set the size of the labels that display TP and SL levels (Small, Normal, Large).
Colors:
bullColor, bearColor, tpColor, slColor: Allows the trader to customize the colors of the different elements on the chart, making visual analysis easier.
3. Strategy Logic:
Determining Entry Signals: The strategy relies on the Supertrend indicator to determine entry signals. When the Supertrend trend changes from bearish to bullish, a buy trade is triggered (if isLongEnabled is enabled). When the trend changes from bullish to bearish, a sell trade is triggered (if isShortEnabled is enabled).
Order Execution: Once the entry signal is triggered, the strategy automatically places buy or sell orders.
Trade Management: After opening a trade, the strategy monitors the price and automatically triggers Take Profit and Stop Loss orders if the price reaches the specified levels.
Visualization: The strategy displays useful information on the chart, such as TP and SL lines, entry and exit signals, which helps the trader understand the strategy’s behavior and evaluate its performance.
4. Advanced Tips:
Optimizing Settings: The strategy’s performance can be improved by adjusting different input values. For example, the trader can experiment with different values for atrPeriod and factor to improve the accuracy of Supertrend signals.
Combining Indicators: This strategy can be combined with other indicators to improve the accuracy of entry signals. For example, the Relative Strength Index (RSI) can be used to confirm Supertrend signals.
Time Analysis: The strategy’s performance can be analyzed over different time periods to evaluate its effectiveness in various market conditions.
Strategy Testing: Before using the strategy in real trading, it should be tested on historical data (Backtesting) to evaluate its performance and determine the optimal settings.
5. Associated Risks:
False Signals: The Supertrend indicator may sometimes give false signals, especially in volatile markets.
Losses: Even with the use of stop loss orders, the trader may be exposed to significant losses.
Over-optimization: Over-optimization of settings on historical data may lead to misleading results. The trader should be careful about generalizing the results to future data.
Over-reliance on automation: The automated strategy should not be relied upon completely. The trader should monitor the trades and make appropriate decisions when necessary.
6. Disclaimer:
I am not a licensed financial advisor. This strategy is provided for educational and illustrative purposes only and should not be considered as investment advice. Trading in financial markets involves significant risks and you may lose your invested capital. Before making any investment decisions, consult a qualified financial advisor and conduct your own research. You alone are responsible for your trading decisions and their results. By using this strategy, you acknowledge and agree that I am not responsible for any losses or damages you may incur.
2. المكونات الرئيسية:
مؤشر Supertrend:
الأساس النظري: يعتمد مؤشر Supertrend على مفهومين رئيسيين هما: متوسط المدى الحقيقي (Average True Range - ATR) ومعامل الضرب (Factor). ATR يقيس مدى تقلبات الأسعار في فترة زمنية محددة، بينما Factor يحدد مدى حساسية المؤشر لتغيرات الأسعار.
آلية العمل: يقوم المؤشر بحساب خطين محتملين: خط يمثل مستوى الدعم المحتمل وخط آخر يمثل مستوى المقاومة المحتمل. يعتمد اختيار الخط المناسب على اتجاه السعر الحالي. عندما يكون السعر أعلى من الخط، يعتبر المؤشر في اتجاه صاعد، والعكس صحيح.
المدخلات القابلة للتخصيص:
atrPeriod: يتيح للمتداول تحديد الفترة الزمنية لحساب ATR. الفترات الأقصر تجعل المؤشر أكثر حساسية لتغيرات الأسعار، بينما الفترات الأطول تقلل من حساسيته.
factor: يسمح بتعديل معامل الضرب. القيم الأعلى تجعل المؤشر أقل عرضة لإعطاء إشارات خاطئة، ولكنها قد تؤخر أيضًا إشارات الدخول.
إدارة المخاطر:
أوامر جني الأرباح وإيقاف الخسارة:
TPPoints: يحدد المسافة بين سعر الدخول ومستوى جني الأرباح. يتم التعبير عن هذه المسافة بالنقاط (Points)، ويتم تحويلها إلى قيمة سعرية فعلية باستخدام syminfo.mintick (أصغر حركة سعرية ممكنة للأصل المتداول).
SLPoints: يحدد المسافة بين سعر الدخول ومستوى إيقاف الخسارة.
الأهمية: تتيح هذه الأوامر للمتداول تحديد الحد الأقصى للخسارة التي يرغب في تحملها والهدف الربحي الذي يسعى لتحقيقه، مما يساعد على إدارة المخاطر بشكل فعال.
تفعيل/تعطيل الصفقات:
isLongEnabled: يسمح بتفعيل أو تعطيل صفقات الشراء، مما يمكن المتداول من التداول في اتجاه واحد فقط (على سبيل المثال، التداول فقط في الاتجاه الصاعد خلال سوق صاعدة).
isShortEnabled: يسمح بتفعيل أو تعطيل صفقات البيع.
isTakeProfitEnabled: يسمح بتفعيل أو تعطيل أوامر جني الأرباح. قد يرغب المتداول في تعطيلها إذا كان يفضل إدارة صفقاته يدويًا.
isStopLossEnabled: يسمح بتفعيل أو تعطيل أوامر إيقاف الخسارة. على الرغم من أن تعطيلها قد يبدو مغريًا في بعض الحالات، إلا أنه يعتبر خطوة محفوفة بالمخاطر للغاية.
التخصيص المرئي:
نمط وعرض الخطوط:
lineStyle: يتيح للمتداول اختيار نمط الخطوط المستخدمة لرسم مستويات TP و SL (Solid, Dashed, Dotted).
lineWidth: يحدد سمك الخطوط.
حجم الملصقات:
labelSize: يسمح بتحديد حجم الملصقات التي تعرض مستويات TP و SL (Small, Normal, Large).
الألوان:
bullColor, bearColor, tpColor, slColor: تتيح للمتداول تخصيص ألوان العناصر المختلفة على الرسم البياني، مما يسهل عملية التحليل البصري.
3. منطق عمل الاستراتيجية:
تحديد إشارات الدخول: تعتمد الاستراتيجية على مؤشر Supertrend لتحديد إشارات الدخول. عندما يتغير اتجاه Supertrend من هابط إلى صاعد، يتم تفعيل صفقة شراء (إذا كانت isLongEnabled مفعلة). وعندما يتغير الاتجاه من صاعد إلى هابط، يتم تفعيل صفقة بيع (إذا كانت isShortEnabled مفعلة).
تنفيذ الأوامر: بمجرد تفعيل إشارة الدخول، تقوم الاستراتيجية بوضع أوامر الشراء أو البيع تلقائيًا.
إدارة الصفقات: بعد فتح الصفقة، تقوم الاستراتيجية بمراقبة السعر وتفعيل أوامر جني الأرباح وإيقاف الخسارة تلقائيًا في حالة وصول السعر إلى المستويات المحددة.
التمثيل المرئي: تعرض الاستراتيجية معلومات مفيدة على الرسم البياني، مثل خطوط TP و SL وإشارات الدخول والخروج، مما يساعد المتداول على فهم سلوك الاستراتيجية وتقييم أدائها.
4. نصائح متقدمة:
تحسين الإعدادات: يمكن تحسين أداء الاستراتيجية من خلال تعديل قيم المدخلات المختلفة. على سبيل المثال، يمكن للمتداول تجربة قيم مختلفة لـ atrPeriod و factor لتحسين دقة إشارات Supertrend.
الجمع بين المؤشرات: يمكن دمج هذه الاستراتيجية مع مؤشرات أخرى لتحسين دقة إشارات الدخول. على سبيل المثال، يمكن استخدام مؤشر القوة النسبية (RSI) لتأكيد إشارات Supertrend.
التحليل الزمني: يمكن تحليل أداء الاستراتيجية على مدى فترات زمنية مختلفة لتقييم مدى فعاليتها في ظروف السوق المتنوعة.
اختبار الاستراتيجية: قبل استخدام الاستراتيجية في التداول الحقيقي، يجب اختبارها على بيانات تاريخية (Backtesting) لتقييم أدائها وتحديد الإعدادات المثلى.
5. المخاطر المرتبطة:
الإشارات الخاطئة: قد يعطي مؤشر Supertrend إشارات خاطئة في بعض الأحيان، خاصة في الأسواق المتقلبة.
الخسائر: حتى مع استخدام أوامر إيقاف الخسارة، قد يتعرض المتداول لخسائر كبيرة.
التحسين المفرط: قد يؤدي التحسين المفرط للإعدادات على بيانات تاريخية إلى نتائج مضللة. يجب أن يكون المتداول حذرًا بشأن تعميم النتائج على البيانات المستقبلية.
الاعتماد الزائد على الأتمتة: يجب عدم الاعتماد بشكل كامل على الاستراتيجية الآلية. يجب على المتداول مراقبة الصفقات واتخاذ القرارات المناسبة عند الضرورة.
6. إخلاء المسؤولية:
أنا لست مستشارًا ماليًا مرخصًا. هذه الاستراتيجية مقدمة لأغراض تعليمية وتوضيحية فقط، ولا ينبغي اعتبارها نصيحة استثمارية. التداول في الأسواق المالية ينطوي على مخاطر كبيرة، وقد تخسر رأس المال المستثمر. قبل اتخاذ أي قرارات استثمارية، استشر مستشارًا ماليًا مؤهلاً وقم بإجراء بحثك الخاص. أنت وحدك المسؤول عن قراراتك التجارية ونتائجها. باستخدام هذه الاستراتيجية، فإنك تقر وتوافق على أنني لست مسؤولاً عن أي خسائر أو أضرار قد تتكبدها.
PineConnectorLibrary   "PineConnector" 
This library is a comprehensive alert webhook text generator for PineConnector. It contains every possible alert syntax variation from the documentation, along with some debugging functions.
To use it, just import the library (eg. "import ZenAndTheArtOfTrading/PineConnector/1 as pc") and use pc.buy(licenseID) to send an alert off to PineConnector - assuming all your webhooks etc are set up correctly.
View the PineConnector documentation for more information on how to send the commands you're looking to send (all of this library's function names match the documentation).
 all() 
  Usage: pc.buy(pc_id, freq=pc.all())
  Returns: "all"
 once_per_bar() 
  Usage: pc.buy(pc_id, freq=pc.once_per_bar())
  Returns: "once_per_bar"
 once_per_bar_close() 
  Usage: pc.buy(pc_id, freq=pc.once_per_bar_close())
  Returns: "once_per_bar_close"
 na0(value) 
  Checks if given value is either 'na' or 0. Useful for streamlining scripts with float user setting inputs which default values to 0 since na is unavailable as a user input default.
  Parameters:
     value (float) : The value to check
  Returns: True if the given value is 0 or na
 getDecimals() 
  Calculates how many decimals are on the quote price of the current market.
  Returns: The current decimal places on the market quote price
 truncate(number, decimals) 
  Truncates the given number. Required params: mumber.
  Parameters:
     number (float) : Number to truncate
     decimals (int) : Decimal places to cut down to
  Returns: The input number, but as a string truncated to X decimals
 getPipSize(multiplier) 
  Calculates the pip size of the current market.
  Parameters:
     multiplier (int) : The mintick point multiplier (1 by default, 10 for FX/Crypto/CFD but can be used to override when certain markets require)
  Returns: The pip size for the current market
 toWhole(number) 
  Converts pips into whole numbers. Required params: number.
  Parameters:
     number (float) : The pip number to convert into a whole number
  Returns: The converted number
 toPips(number) 
  Converts whole numbers back into pips. Required params: number.
  Parameters:
     number (float) : The whole number to convert into pips
  Returns: The converted number
 debug(txt, tooltip, displayLabel) 
  Prints to console and generates a debug label with the given text. Required params: txt.
  Parameters:
     txt (string) : Text to display
     tooltip (string) : Tooltip to display (optional)
     displayLabel (bool) : Turns on/off chart label (default: off)
  Returns: Nothing
 order(licenseID, command, symbol, parameters, accfilter, comment, secret, freq, debug) 
  Generates an alert string. Required params: licenseID, command.
  Parameters:
     licenseID (string) : Your PC license ID
     command (string) : Command to send
     symbol (string) : The symbol to trigger this order on
     parameters (string) : Other optional parameters to include
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: An alert string with valid PC syntax based on supplied parameters
 market_order(licenseID, buy, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Generates a market entry alert with relevant syntax commands. Required params: licenseID, buy, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     buy (bool) : true=buy/long, false=sell/short
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A market order alert string with valid PC syntax based on supplied parameters
 buy(licenseID, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Generates a market buy alert with relevant syntax commands. Required params: licenseID, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A market order alert string with valid PC syntax based on supplied parameters
 sell(licenseID, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Generates a market sell alert with relevant syntax commands. Required params: licenseID, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A market order alert string with valid PC syntax based on supplied parameters
 closeall(licenseID, comment, secret, freq, debug) 
  Closes all open trades at market regardless of symbol. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closealleaoff(licenseID, comment, secret, freq, debug) 
  Closes all open trades at market regardless of symbol, and turns the EA off. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closelong(licenseID, symbol, comment, secret, freq, debug) 
  Closes all long trades at market for the given symbol. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     symbol (string) : Symbol to act on (defaults to current symbol)
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closeshort(licenseID, symbol, comment, secret, freq, debug) 
  Closes all open short trades at market for the given symbol. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     symbol (string) : Symbol to act on (defaults to current symbol)
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closelongshort(licenseID, symbol, comment, secret, freq, debug) 
  Closes all open trades at market for the given symbol. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     symbol (string) : Symbol to act on (defaults to current symbol)
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closelongbuy(licenseID, risk, symbol, comment, secret, freq, debug) 
  Close all long positions and open a new long at market for the given symbol with given risk/contracts. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     risk (float) : Risk or contracts (according to EA settings)
     symbol (string) : Symbol to act on (defaults to current symbol)
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closeshortsell(licenseID, risk, symbol, comment, secret, freq, debug) 
  Close all short positions and open a new short at market for the given symbol with given risk/contracts. Required params: licenseID, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     risk (float) : Risk or contracts (according to EA settings)
     symbol (string) : Symbol to act on (defaults to current symbol)
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 newsltplong(licenseID, sl, tp, symbol, accfilter, comment, secret, freq, debug) 
  Updates the stop loss and/or take profit of any open long trades on the given symbol with the given values. Required params: licenseID, sl and/or tp.
  Parameters:
     licenseID (string) : Your PC license ID
     sl (float) : Stop loss pips or price (according to EA settings)
     tp (float) : Take profit pips or price (according to EA settings)
     symbol (string) : Symbol to act on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 newsltpshort(licenseID, sl, tp, symbol, accfilter, comment, secret, freq, debug) 
  Updates the stop loss and/or take profit of any open short trades on the given symbol with the given values. Required params: licenseID, sl and/or tp.
  Parameters:
     licenseID (string) : Your PC license ID
     sl (float) : Stop loss pips or price (according to EA settings)
     tp (float) : Take profit pips or price (according to EA settings)
     symbol (string) : Symbol to act on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closelongpct(licenseID, symbol, comment, secret, freq, debug) 
  Close a percentage of open long positions (according to EA settings). Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     symbol (string) : Symbol to act on (defaults to current symbol)
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closeshortpct(licenseID, symbol, comment, secret, freq, debug) 
  Close a percentage of open short positions (according to EA settings). Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     symbol (string) : Symbol to act on (defaults to current symbol)
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closelongvol(licenseID, risk, symbol, comment, secret, freq, debug) 
  Close all open long contracts on the current symbol until the given risk value is remaining. Required params: licenseID, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     risk (float) : The quantity to leave remaining
     symbol (string) : Symbol to act on (defaults to current symbol)
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 closeshortvol(licenseID, risk, symbol, comment, secret, freq, debug) 
  Close all open short contracts on the current symbol until the given risk value is remaining. Required params: licenseID, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     risk (float) : The quantity to leave remaining
     symbol (string) : Symbol to act on (defaults to current symbol)
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 limit_order(licenseID, buy, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Generates a limit order alert with relevant syntax commands. Required params: licenseID, buy, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     buy (bool) : true=buy/long, false=sell/short
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A limit order alert string with valid PC syntax based on supplied parameters
 buylimit(licenseID, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Generates a buylimit order alert with relevant syntax commands. Required params: licenseID, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A limit order alert string with valid PC syntax based on supplied parameters
 selllimit(licenseID, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Generates a selllimit order alert with relevant syntax commands. Required params: licenseID, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A limit order alert string with valid PC syntax based on supplied parameters
 stop_order(licenseID, buy, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Generates a stop order alert with relevant syntax commands. Required params: licenseID, buy, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     buy (bool) : true=buy/long, false=sell/short
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A stop order alert string with valid PC syntax based on supplied parameters
 buystop(licenseID, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Generates a buystop order alert with relevant syntax commands. Required params: licenseID, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A stop order alert string with valid PC syntax based on supplied parameters
 sellstop(licenseID, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Generates a sellstop order alert with relevant syntax commands. Required params: licenseID, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A stop order alert string with valid PC syntax based on supplied parameters
 cancel_neworder(licenseID, order, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Cancel + place new order template function.
  Parameters:
     licenseID (string) : Your PC license ID
     order (string) : Cancel order type
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A stop order alert string with valid PC syntax based on supplied parameters
 cancellongbuystop(licenseID, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Cancels all long orders with the specified symbol and places a new buystop order. Required params: licenseID, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A stop order alert string with valid PC syntax based on supplied parameters
 cancellongbuylimit(licenseID, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Cancels all long orders with the specified symbol and places a new buylimit order. Required params: licenseID, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A stop order alert string with valid PC syntax based on supplied parameters
 cancelshortsellstop(licenseID, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Cancels all short orders with the specified symbol and places a sellstop order. Required params: licenseID, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A stop order alert string with valid PC syntax based on supplied parameters
 cancelshortselllimit(licenseID, price, risk, sl, tp, betrigger, beoffset, spread, trailtrig, traildist, trailstep, atrtimeframe, atrperiod, atrmultiplier, atrshift, atrtrigger, symbol, accfilter, comment, secret, freq, debug) 
  Cancels all short orders with the specified symbol and places a selllimit order. Required params: licenseID, price, risk.
  Parameters:
     licenseID (string) : Your PC license ID
     price (float) : Price or pips to set limit order (according to EA settings)
     risk (float) : Risk quantity (according to EA settings)
     sl (float) : Stop loss distance in pips or price
     tp (float) : Take profit distance in pips or price
     betrigger (float) : Breakeven will be activated after the position gains this number of pips
     beoffset (float) : Offset from entry price. This is the amount of pips you'd like to protect
     spread (float) : Enter the position only if the spread is equal or less than the specified value in pips
     trailtrig (float) : Trailing stop-loss will be activated after a trade gains this number of pips
     traildist (float) : Distance of the trailing stop-loss from current price
     trailstep (float) : Moves trailing stop-loss once price moves to favourable by a specified number of pips
     atrtimeframe (int) : ATR Trailing Stop timeframe, only updates once per bar close. Options: 1, 5, 15, 30, 60, 240, 1440
     atrperiod (int) : ATR averaging period
     atrmultiplier (float) : Multiple of ATR to utilise in the new SL computation, default = 1
     atrshift (int) : Relative shift of price information, 0 uses latest candle, 1 uses second last, etc. Default = 0
     atrtrigger (int) : Activate the trigger of ATR Trailing after market moves favourably by a number of pips. Default = 0 (instant)
     symbol (string) : The symbol to trigger this order on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment (maximum 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A stop order alert string with valid PC syntax based on supplied parameters
 cancellong(licenseID, symbol, accfilter, comment, secret, freq, debug) 
  Cancels all pending long orders with the specified symbol. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     symbol (string) : Symbol to act on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A cancel long alert command
 cancelshort(licenseID, symbol, accfilter, comment, secret, freq, debug) 
  Cancels all pending short orders with the specified symbol. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     symbol (string) : Symbol to act on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: A cancel short alert command
 newsltpbuystop(licenseID, sl, tp, symbol, accfilter, comment, secret, freq, debug) 
  Updates the stop loss and/or take profit of any pending buy stop orders on the given symbol. Required params: licenseID, sl and/or tp.
  Parameters:
     licenseID (string) : Your PC license ID
     sl (float) : Stop loss pips or price (according to EA settings)
     tp (float) : Take profit pips or price (according to EA settings)
     symbol (string) : Symbol to act on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 newsltpbuylimit(licenseID, sl, tp, symbol, accfilter, comment, secret, freq, debug) 
  Updates the stop loss and/or take profit of any pending buy limit orders on the given symbol. Required params: licenseID, sl and/or tp.
  Parameters:
     licenseID (string) : Your PC license ID
     sl (float) : Stop loss pips or price (according to EA settings)
     tp (float) : Take profit pips or price (according to EA settings)
     symbol (string) : Symbol to act on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 newsltpsellstop(licenseID, sl, tp, symbol, accfilter, comment, secret, freq, debug) 
  Updates the stop loss and/or take profit of any pending sell stop orders on the given symbol. Required params: licenseID, sl and/or tp.
  Parameters:
     licenseID (string) : Your PC license ID
     sl (float) : Stop loss pips or price (according to EA settings)
     tp (float) : Take profit pips or price (according to EA settings)
     symbol (string) : Symbol to act on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 newsltpselllimit(licenseID, sl, tp, symbol, accfilter, comment, secret, freq, debug) 
  Updates the stop loss and/or take profit of any pending sell limit orders on the given symbol. Required params: licenseID, sl and/or tp.
  Parameters:
     licenseID (string) : Your PC license ID
     sl (float) : Stop loss pips or price (according to EA settings)
     tp (float) : Take profit pips or price (according to EA settings)
     symbol (string) : Symbol to act on (defaults to current symbol)
     accfilter (float) : Optional minimum account balance filter
     comment (string) : Optional comment to include (max 20 characters)
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 eaoff(licenseID, secret, freq, debug) 
  Turns the EA off. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
 eaon(licenseID, secret, freq, debug) 
  Turns the EA on. Required params: licenseID.
  Parameters:
     licenseID (string) : Your PC license ID
     secret (string) : Optional secret key (must be enabled in dashboard)
     freq (string) : Alert frequency. Default = "all", options = "once_per_bar", "once_per_bar_close" and "none"
     debug (bool) : Turns on/off debug label
  Returns: The required alert syntax as a string
Strategy / Connectable [Azullian]The  connectable strategy  serves as a foundational component in our  indicator system  on TradingView, designed for intuitive testing, visualization, and construction of trading strategies. In concert with the  connectable signal filter , it forms a cohesive unit that allows for efficient signal processing and strategy implementation. This integration enables the strategy to receive and act on weighted signals from various connectable indicators, making it a versatile tool for both novice and experienced traders.
Let's review the separate parts of this indicator.
█  STRATEGY INPUTS 
We've provided an input to connect a signal filter or indicators or chains (→) which is set to 'Close' by default. 
  
An input has several controls: 
 •  Input:  Connect indicators or signal filter here, choose indicators with a compatible : Signal connector.
 •  SM - Signal Mode:  Choose a trading direction compatible with the settings in your signal filter
█  POSITION INVESTMENT 
Determine the percentage of your trading budget you would like to use in each position based on the strategy's profit or loss.
  
 •  LINVB - Loss Investment Base:  Choose which base to use to determine the investment percentage when the strategy is in a loss.
    ○ Equity: Use the equity as the base for percentage calculation.
    ○ Initial capital: Use the initial capital as the base for percentage calculation.
 •  LINV% - Loss Investment Percentage:  Set a percentage of the chosen investment base as the investment for a new position. 
    ○ For example, when 10% in loss, and a initial capital of $100, and the investment base is set to equity with a percentage of 50%, your investment will be 50% of $90, $45.
 •  PINVB - Profit Investment Base:  Choose which base to use to determine the investment percentage when the strategy is in profit.
    ○ Equity: Use the equity as the base for percentage calculation.
    ○ Initial capital: Use the initial capital as the base for percentage calculation.
 •  PINV% - Profit Investment Percentage:  Set a percentage of the chosen investment base as the investment for a new position. 
    ○ For example, when 10% in profit, and an initial capital of $100, and the investment base is set to equity with a percentage of 100%, your investment will be 100% of $110, $110.
 •  RISK% - Risk Percentage: 
    ○ Determine how much of the calculated position investment is at risk when the stop-loss is hit. 
        - For example, 1% of $45 represents a maximum loss of $0.45.
    ○ Risk percentage works together with the stop loss and the max leverage.
 •  MXLVG - Maximum Leverage: 
    ○ Investigate the trading rules for your trading pair and use the maximum allowed amount of leverage.
    ○ To determine the number of contracts to be bought or sold, considering the stop loss and the specified risk percentage, the maximum leverage available will constrain the amount of leverage utilized to ensure that the maximum risk threshold is not exceeded. For instance, suppose the stop loss is set at 1%, and the risk percentage is defined as 10%. Initially, the calculated leverage to be used would be 10. However, if there is a maximum leverage cap set at 5, it would constrain the calculated leverage of 10 to adhere to the maximum limit of 5.
█  EXIT STOP LOSS 
Determine the Stop Loss price based on your selected configuration. 
As the stop loss is an integral part of the ordered contracts calculation used in conjunction with the Risk and Max leverage, you'll always need to provide a stop loss price.  
  
 •  SLB - Stop Loss Base:  Choose a stop loss mode for calculating stop loss prices.
    ○ Risk: Determines the price using the Risk parameter (RISK%) and maximum leverage (MXLVG). In this case, SLB% will not have any impact.
    ○ Price Entry + Offset: Calculates the stop loss price based on a offset percentage (SLB%) from the entry price of the position.
 •  SLB% - Stop Loss Base Percentage:  Define an offset percentage that will be applied in the price entry + offset stop loss mode.
 •  SLT - Stop Loss Trailing: 
    ○ Fixed: The initial stop loss will be kept and no trailing stop loss will be applied.
    ○ Trail Price: Computes the trailing stop loss price based on an offset percentage (SLT%) from the closing price of the current candle. 
        - If a better stop loss price is calculated, it will be set as the new stop loss price.
    ○ Trail Incr: Adapts the trailing stop loss price based on the offset percentage (SLT%). 
        - Each price change in favor of your position will incrementally adapt the trailing stop loss with SLT%.
 •  SLT% - Stop Loss Trailing Percentage:  This percentage serves as an offset or increment depending on your chosen trailing mode.
█  EXIT TAKE PROFIT 
Determine the Take Profit price based on your selected configuration. 
  
 •  TPB - Take Profit Base:  Choose a take profit mode for calculating take profit prices.
    ○ Reward: Determines the take profit price using the Risk parameter (RISK%) and the calculated Stop Loss price and the set reward percentage (TPB%). 
        -  For example: Risk 1%, Calculated Stop loss price: $90, Entry price: $100, Reward (TPB%): 2%, will result in a take profit price on $120.
    ○ Price Entry + Offset: Calculates the take profit price based on a offset percentage (TPB%) from the entry price of the position. 
        -  For example: Entry price: $100, Offset (TPB%): 2%, will result in a take profit price on $102.
 •  TPB% - Take Profit Base Percentage:  Define an offset percentage that will be applied in the price entry + offset take profit mode.
 •  TPT - Take Profit Trailing: 
    ○ Fixed: The initial take profit will be kept and no trailing take profit will be applied.
    ○ Trail Price: Computes the trailing take profit price based on an offset percentage (TPT%) from the closing price of the current candle. 
        -  If an applicable take profit price is calculated, it will be set as the new take profit price.
    ○ Trail Incr: Adapts the trailing take profit price based on the offset percentage (TPT%). Each price change against your position will incrementally adapt the trailing take profit with TPT%.
 •  TPT% - Take Profit Trailing Percentage:  This percentage serves as an offset or increment depending on your chosen trailing mode.
█  STRATEGY CONDITIONS 
Specify when the strategy is permitted to execute trades.
  
 •  DATE:  Enable the Date Range filter to restrict entries to a specific date range.
    ○ START: Set a start date and hour to commence trading.
    ○ END: Set an end date and hour to conclude trading within the defined range.
■  VISUALS 
  
 •  LINE:  Activate a colored dashed diagonal line to visually connect the entry and exit points of positions.
 •  SLTP:  Enable visualization of stop loss, take profit, and break-even levels.
 •  PNL:  Enable Break-Even and Close Lines along with a colored area in between to visualize profit and loss.
 •  ☼: Brightness % :  Adjust the opacity of the plotted trading visuals. 
 •  P - Profit Color :  Choose the color for profit-related elements.
 •  L - Loss Color:  Choose the color for loss-related elements.
 •  B - Breakeven Color :  Select the color for break-even points.
 •  EL - Long Color:  Specify the color for long positions.
 •  ES - Short Color:  Specify the color for short positions.
 •  TRADE LABELING:  For better analysis we've labeled all entries and exits conform with the type of order your strategy has executed, some examples: 
    ○ XL-TP-150: Exit Long - Take Profit - Position 150
    ○ XS-TP-154: Exit Short - Take Profit - Position 154
    ○ XL-SL-160: Exit Long - Stop Loss - Position 160
    ○ XS-SL-164: Exit Short - Stop Loss - Position 164
█  USAGE OF CONNECTABLE INDICATORS 
 ■  Connectable chaining mechanism 
Connectable indicators can be connected directly to the  signal monitor, signal filter or strategy , or they can be daisy chained to each other while the last indicator in the chain connects to the signal monitor, signal filter or strategy. When using a  signal filter  you can chain the filter to the strategy input to make your chain complete.
    
   •  Direct chaining:  Connect an indicator directly to the  signal monitor, signal filter or strategy  through the provided inputs (→).
   •  Daisy chaining:  Connect indicators using the indicator input (→). The first in a daisy chain should have a flow (⌥) set to 'Indicator only'. Subsequent indicators use 'Both' to pass the previous weight. The final indicator connects to the  signal monitor, signal filter, or strategy. 
 ■  Set up the strategy with a signal filter and an RSI indicator 
  Let's connect the Strategy to a connectable  signal filter   and a  connectable RSI indicator : 
  1.  Load all relevant indicators  
   • Load RSI / Connectable
   • Load Signal filter / Connectable
   • Load Strategy / Connectable
  2.  Signal Filter: Connect the RSI to the Signal Filter  
   • Open the signal filter settings
   • Choose one of the three input dropdowns (1→, 2→, 3→) and choose : RSI / Connectable: Signal Connector
   • Toggle the enable box before the connected input to enable the incoming signal
  3.  Signal Filter: Update the filter signals settings if needed  
   • The default settings of the filter enable EL (Enter Long), XL (Exit Long), ES (Enter Short) and XS (Exit Short).
  4.  Signal Filter: Update the weight threshold settings if needed  
   • All connectable indicators load by default with a score of 6 for each direction (EL, XL, ES, XS)
   • By default, weight threshold (TH) is set at 5. This allows each occurrence to score, as the default score in each connectable indicator is 1 point above the threshold. Adjust to your liking.
  5.  Strategy: Connect the strategy to the signal filter in the strategy settings  
   • Select the strategy input → and select the Signal filter: Signal connector
  6.  Strategy: Enable filter compatible directions  
   • Set the signal mode of the strategy to a compatible direction with the signal filter. 
   
 
  Now that everything is connected, you'll notice green spikes in the  signal filter  representing long signals, and red spikes indicating short signals. Trades will also appear on the chart, complemented by a performance overview. Your journey is just beginning: delve into different scoring mechanisms, merge diverse connectable indicators, and craft unique chains. Instantly test your results and discover the potential of your configurations. Dive deep and enjoy the process!
 
█  BENEFITS 
 •  Adaptable Modular Design:  Arrange indicators in diverse structures via direct or daisy chaining, allowing tailored configurations to align with your analysis approach.
 •  Streamlined Backtesting:  Simplify the iterative process of testing and adjusting combinations, facilitating a smoother exploration of potential setups.
 •  Intuitive Interface:  Navigate TradingView with added ease. Integrate desired indicators, adjust settings, and establish alerts without delving into complex code.
 •  Signal Weight Precision:  Leverage granular weight allocation among signals, offering a deeper layer of customization in strategy formulation.
 •  Advanced Signal Filtering:  Define entry and exit conditions with more clarity, granting an added layer of strategy precision.
 •  Clear Visual Feedback:  Distinct visual signals and cues enhance the readability of charts, promoting informed decision-making.
 •  Standardized Defaults:  Indicators are equipped with universally recognized preset settings, ensuring consistency in initial setups across different types like momentum or volatility.
 •  Reliability:   Our indicators are meticulously developed to prevent repainting. We strictly adhere to TradingView's coding conventions, ensuring our code is both performant and clean.
█  COMPATIBLE INDICATORS 
  Each indicator that incorporates our open-source 'azLibConnector' library and adheres to our conventions can be effortlessly integrated and used as detailed above. 
  For clarity and recognition within the TradingView platform, we append the suffix ' / Connectable' to every compatible indicator. 
█  COMMON MISTAKES AND CLARIFICATIONS 
 •  Removing an indicator from a chain:  Deleting a linked indicator and confirming the "remove study tree" alert will also remove all underlying indicators in the object tree. Before removing one, disconnect the adjacent indicators and move it to the object stack's bottom.
 •  Point systems:  The azLibConnector provides 500 points for each direction (EL: Enter long, XL: Exit long, ES: Enter short, XS: Exit short) Remember this cap when devising a point structure.
 •  Flow misconfiguration:  In daisy chains the first indicator should always have a flow (⌥) setting of 'indicator only' while other indicator should have a flow (⌥) setting of 'both'.
 •  Recalculate:  While this strategy has undergone extensive testing, enabling recalculation options like 'After order is filled' or 'On every tick' may lead to unexpected behavior.
 •  Fill orders:  The strategy is thoroughly tested, yet enabling fill order options such as 'Using bar magnifier', 'On bar close', or 'Using standard OHLC' might result in unexpected outcomes.
 •  Layout and abbreviations:  To maintain a consistent structure, we use abbreviations for each input. While this may initially seem complex, you'll quickly become familiar with them. Each abbreviation is also explained in the inline tooltips.
 •  Optimized for crypto trading:  While many principles are common across markets, this strategy is specifically optimized and tested for crypto trading.
 •  Inputs:  Connecting a connectable indicator directly to the strategy delivers the raw signal without a weight threshold, meaning every signal will trigger a trade.
█  A NOTE OF GRATITUDE 
  Through years of exploring TradingView and Pine Script, we've drawn immense inspiration from the community's knowledge and innovation. Thank you for being a constant source of motivation and insight.
█  RISK DISCLAIMER 
  Azullian's content, tools, scripts, articles, and educational offerings are presented purely for educational and informational uses. Please be aware that past performance should not be considered a predictor of future results.
Hammers & Stars StrategyOverview 
This script trades basic hammer and shooting star candlestick patterns.
It's an extremely simple strategy with minimal filters, and according to my personal manual backtesting and automated trading results, performs best on the Daily chart on certain forex pairs.
It is intended to be traded on the forex markets but theoretically should work on all markets (especially if you optimize the settings).
The script also comes with complete AutoView automation for Oanda. 
Make sure you've connected AutoView to TradingView and Oanda, then simply set an alert using the "alert() function calls only" condition and it will automatically execute trades based on whatever settings you've selected (only recommended for experienced traders - use at your own risk!)
If you're not sure how to set up AutoView, search "The Art of Trading AutoView Guide" on YouTube to find my detailed video guide.
Check out my website and YouTube channel for more information, scripts, resources and free Pine Script & trading lessons (link in my profile).
Best of luck with your trading!
- Matt / The Art of Trading
 Settings Menu 
 Tooltips are included explaining what the various settings do, but here's a quick summary: 
 Strategy Settings 
>= ATR Filter: Minimum size of entry candle compared to ATR
<= ATR Filter: Maximum size of entry candle compared to ATR
Stop Loss ATR: Stop loss multiplier (x ATR)
R:R: Risk:Reward profile
Fib Level: Used to calculate upper/lower third of candle. (For example, setting it to 0.5 will mean hammers must close >= 50% mark of the total candle size)
Start Date Filter: Date & time to begin trading from
End Date Filter: Date & time to stop trading
 AutoView Oanda Settings 
Use Oanda Demo: If turned on then oandapractice broker prefix will be used for AutoView alerts (demo account). If turned off then live account will be used
Use Limit Order: If turned on then AutoView will use limit orders. If turned off then market orders will be used (recommended to use limit order to mitigate spread issues)
Days To Leave Limit Order: This is your GTD setting (good til day)
Account Balance: Your account balance (used for calculating position size)
Account Currency: Your account balance currency (used for calculating position size)
Risk Per Trade %: Your risk per trade as a % of your account balance
Ribbon — multi-MA trend bandsRibbon  paints five translucent bands between six moving averages to visualize trend structure and regime at a glance. You can choose the MA type (EMA/SMA/WMA), customize lengths, and switch the coloring logic between an anchor-based mode and strict alignment.
 What it shows 
 
 Six MAs on the current timeframe  (defaults: 5 / 34 / 55 / 89 / 144 / 233).
 Five bands  filled between consecutive MAs:
 5–34, 34–55, 55–89, 89–144, 144–233.
 Optional plotting of MA lines (hidden by default to keep the chart clean).
 
 Coloring modes 
 1. By EMA233 (Anchor mode) 
Each band is colored  Up  or  Down  by comparing its upper MA to the anchor (the  6th MA  in inputs, default length 233).
 
 If MA > anchor → Up color (supportive regime).
 If MA < anchor → Down color (resistive regime).
 
 2. By Alignment 
 
 All bands share one color depending on strict ordering:
 Up  if MA1 > MA2 > MA3 > MA4 > MA5 > MA6
 Down  if MA1 < MA2 < MA3 < MA4 < MA5 < MA6
 Gray  otherwise (no clean alignment).
 
 Inputs (key) 
 
 MA Type : EMA / SMA / WMA (applies to all six MAs).
 MA 1…MA 6 (anchor) : lengths for each average (defaults form a classic ribbon up to 233).
 Up/Down colors : band palette.
 Base transparency / step : controls band opacity gradient (top band uses Base, each next band adds Step).
 Show MA lines + Lines transparency : optionally draw the six MA curves.
 
 How to read it 
 
 Directional bias : when most bands are green (anchor mode) or the whole ribbon is green (alignment mode), momentum favors the upside; red implies downside pressure.
 Quality of trend : a persistent alignment (all ordered) signals a cleaner trend. Mixed/gray suggests chop or transition.
 Pullback zones : price returning toward inner bands can mark areas to watch for continuation vs. failure.
 
 Implementation notes 
 
 No higher-timeframe data, no lookahead — this is a non-repainting, current-TF visualization.
 Bands still render even when MA lines are hidden (the script uses hidden plot anchors under the hood).
 This is an  indicator , not a strategy — it does not open/close trades or calculate P&L.
 
 Disclaimer 
This script is for educational and informational purposes only and does not constitute financial advice. Always test on historical data and manage risk appropriately.
Reversal Point Dynamics⇋ Reversal Point Dynamics (RPD) 
 This is not an indicator; it is a complete system for deconstructing the mechanics of a market reversal.  Reversal Point Dynamics (RPD) moves far beyond simplistic pattern recognition, venturing into a deep analysis of the underlying forces that cause trends to exhaust, pause, and turn. It is engineered from the ground up to identify high-probability reversal points by quantifying the confluence of market dynamics in real-time.
 Where other tools provide a static signal, RPD delivers a dynamic probability.  It understands that a true market turning point is not a single event, but a cascade of failing momentum, structural breakdown, and a shift in market order. RPD's core engine meticulously analyzes each of these dynamic components—the market's underlying state, its velocity and acceleration, its degree of chaos (entropy), and its structural framework. These forces are synthesized into a single, unified Probability Score, offering you an unprecedented, transparent view into the conviction behind every potential reversal.
 This is not a "black box" system.  It is an open-architecture engine designed to empower the discerning trader. Featuring real-time signal projection, an integrated Fibonacci R2R Target Engine, and a comprehensive dashboard that acts as your  Dynamics Control Center , RPD gives you a complete, holistic view of the market's state.
 The Theoretical Core: Deconstructing Market Dynamics 
 RPD's analytical power is born from the intelligent synthesis of multiple, distinct theoretical models.  Each pillar of the engine analyzes a different facet of market behavior. The convergence of these analyses—the "Singularity" event referenced in the dashboard—is what generates the final, high-conviction probability score.
 1. Pillar One: Quantum State Analysis (QSA) 
 This is the foundational analysis of the market's current state within its recent context.  Instead of treating price as a random walk, QSA quantizes it into a finite number of discrete "states."
 Formulaic Concept:  The engine establishes a price range using the highest high and lowest low over the Adaptive Analysis Period. This range is then divided into a user-defined number of Analysis Levels. The current price is mapped to one of these states (e.g., in a 9-level system, State 0 is the absolute low, and State 8 is the absolute high).
 Analytical Edge:  This acts as a powerful foundational filter. The engine will only begin searching for reversal signals when the market has reached a statistically stretched, extreme state (e.g., State 0 or 8). The Edge Sensitivity input allows you to control exactly how close to this extreme edge the price must be, ensuring you are trading from points of maximum potential exhaustion.
 2. Pillar Two: Price State Roc (PSR) - The Dynamics of Momentum 
 This pillar analyzes the kinetic forces of the market: its velocity and acceleration.  It understands that it’s not just where the price is, but how it got there that matters.
 Formulaic Concept:  The psr function calculates two derivatives of price.
 Velocity:  (price - price ). This measures the speed and direction of the current move.
 Acceleration:  (velocity - velocity ). This measures the rate of change in that speed. A negative acceleration (deceleration) during a strong rally is a critical pre-reversal warning, indicating momentum is fading even as price may be pushing higher.
 Analytical Edge:  The engine specifically hunts for exhaustion patterns where momentum is clearly decelerating as price reaches an extreme state. This is the mechanical signature of a weakening trend.
 3. Pillar Three: Market Entropy Analysis - The Dynamics of Order & Chaos 
 This is RPD's chaos filter, a concept borrowed from information theory.  Entropy measures the degree of randomness or disorder in the market's price action.
 Formulaic Concept:  The calculateEntropy function analyzes recent price changes. A market moving directionally and smoothly has low entropy (high order). A market chopping back and forth without direction has high entropy (high chaos). The value is normalized between 0 and 1.
 Analytical Edge:  The most reliable trades occur in low-entropy, ordered environments. RPD uses the Entropy Threshold to disqualify signals that attempt to form in chaotic, unpredictable conditions, providing a powerful shield against whipsaw markets.
 4. Pillar Four: The Synthesis Engine & Probability Calculation 
 This is where all the dynamic forces converge.  The final probability score is a weighted calculation that heavily rewards confluence.
 Formulaic Concept:  The calculateProbability function intelligently assembles the final score:
A  Base Score  is established from trend strength and entropy.
An  Entropy Score  adds points for low entropy (order) and subtracts for high entropy (chaos).
A significant  Divergence Bonus  is awarded for a classic momentum divergence.
 RSI & Volume Bonuses  are added if momentum oscillators are in extreme territory or a volume spike confirms institutional interest.
 MTF & Adaptive Bonuses  add further weight for alignment with higher timeframe structure.
 Analytical Edge:  A signal backed by multiple dynamic forces (e.g., extreme state + decelerating momentum + low entropy + volume spike) will receive an exponentially higher probability score.  This is the very essence of analyzing reversal point dynamics. 
 The Command Center: Mastering the Inputs 
 Every input is a precise lever of control, allowing you to fine-tune the RPD engine to your exact trading style, market, and timeframe. 
 🧠 Core Algorithm 
 Predictive Mode (Early Detection): 
 What It Is:  Enables the engine to search for potential reversals on the current, unclosed bar.
 How It Works:  Analyzes intra-bar acceleration and state to identify developing exhaustion. These signals are marked with a ' ? ' and are tentative.
 How To Use It:  Enable for scalping or very aggressive day trading to get the earliest possible indication. Disable for swing trading or a more conservative approach that waits for full bar confirmation.
 Live Signal Mode (Current Bar): 
 What It Is:  A highly aggressive mode that plots tentative signals with a ' ! ' on the live bar based on projected price and momentum. These signals repaint intra-bar.
 How It Works:  Uses a linear regression projection of the close to anticipate a reversal.
 How To Use It:  For advanced users who use intra-bar dynamics for execution and understand the nature of repainting signals.
 Adaptive Analysis Period: 
 What It Is:  The main lookback period for the QSA, PSR, and Entropy calculations. This is the engine's "memory."
 How It Works:  A shorter period makes the engine highly sensitive to local price swings. A longer period makes it focus only on major, significant market structure.
 How To Use It:   Scalping (1-5m):  15-25.  Day Trading (15m-1H):  25-40.  Swing Trading (4H+):  40-60.
 Fractal Strength (Bars): 
 What It Is:  Defines the strength of the pivot detection used for confirming reversal events.
 How It Works:  A value of '2' requires a candle's high/low to be more extreme than the two bars to its left and right.
 How To Use It:  '2' is a robust standard. Increase to '3' for an even stricter definition of a structural pivot, which will result in fewer signals.
 MTF Multiplier: 
 What It Is:  Integrates pivot data from a higher timeframe for confluence.
 How It Works:  A multiplier of '4' on a 15-minute chart will pull pivot data from the 1-hour chart (15 * 4 = 60m).
 How To Use It:  Set to a multiple that corresponds to your preferred higher timeframe for contextual analysis.
 🎯 Signal Settings 
 Min Probability %: 
 What It Is:  Your master quality filter. A signal is only plotted if its score exceeds this threshold.
 How It Works:  Directly filters the output of the final probability calculation.
 How To Use It:   High-Quality (80-95):  For A+ setups only.  Balanced (65-75):  For day trading.  Aggressive (50-60):  For scalping.
 Min Signal Distance (Bars): 
 What It Is:  A noise filter that prevents signals from clustering in choppy conditions.
 How It Works:  Enforces a "cooldown" period of N bars after a signal.
 How To Use It:  Increase in ranging markets to focus on major swings. Decrease on lower timeframes.
 Entropy Threshold: 
 What It Is:  Your "chaos shield." Sets the maximum allowable market randomness for a signal.
 How It Works:  If calculated entropy is above this value, the signal is invalidated.
 How To Use It:   Lower values (0.1-0.5):  Extremely strict.  Higher values (0.7-1.0):  More lenient. 0.85 is a good balance.
 Adaptive Entropy & Aggressive Mode: 
 What It Is:  Toggles for dynamically adjusting the engine's core parameters.
 How It Works:  Adaptive Entropy can slightly lower the required probability in strong trends. Aggressive Mode uses more lenient settings across the board.
 How To Use It:  Keep Adaptive on. Use Aggressive Mode sparingly, primarily for scalping highly volatile assets.
 📊 State Analysis 
 Analysis Levels: 
 What It Is:  The number of discrete "states" for the QSA.
 How It Works:  More levels create a finer-grained analysis of price location.
 How To Use It:  6-7 levels are ideal. Increasing to 9 can provide more precision on very volatile assets.
 Edge Sensitivity: 
 What It Is:  Defines how close to the absolute top/bottom of the range price must be.
 How It Works:  '0' means price must be in the absolute highest/lowest state. '3' allows a signal within the top/bottom 3 states.
 How To Use It:  '3' provides a good balance. Lower it to '1' or '0' if you only want to trade extreme exhaustion.
 The Dashboard: Your Dynamics Control Center 
 The dashboard provides a transparent, real-time view into the engine's brain.  Use it to understand the context behind every signal and to gauge the current market environment at a glance.
 🎯 UNIFIED PROB SCORE 
 TOTAL SCORE:  The highest probability score (either Peak or Valley) the engine is currently calculating. This is your main at-a-glance conviction metric. The "Singularity" header refers to the event where market dynamics align—the event RPD is built to detect.
 Quality:  A human-readable interpretation of the Total Score.  "EXCEPTIONAL" (🌟)  is a rare, A+ confluence event.  "STRONG" (💪)  is a high-quality, tradable setup.
 📊 ORDER FLOW & COMPONENT ANALYSIS 
 Volume Spike:  Shows if the current volume is significantly higher than average (YES/NO). A 'YES' adds major confirmation.
 Peak/Valley Conf:  This breaks down the probability score into its directional components, showing you the separate confidence levels for a potential top (Peak) versus a bottom (Valley).
 🌌 MARKET STRUCTURE 
 HTF Trend:  Shows the direction of the underlying trend based on a Supertrend calculation.
 Entropy:  The current market chaos reading.  "🔥 LOW"  is an ideal, ordered state for trading.  "😴 HIGH"  is a warning of choppy, unpredictable conditions.
 🔮 FIB & R2R ZONE (Large Dashboard) 
 This section gives you the status of the Fibonacci Target Engine.  It shows if an Active Channel (entry zone) or Stop Zone (invalidation zone) is active and displays the precise price levels for the static entry, target, and stop calculated at the time of the signal.
 🛡️ FILTERS & PREDICTIVES (Large Dashboard) 
 This panel provides a status check on all the bonus filters.  It shows the current RSI Status, whether a Divergence is present, and if a Live Pending signal is forming.
 The Visual Interface: A Symphony of Data 
 Every visual element is designed for instant, intuitive interpretation of market dynamics. 
 Signal Markers:  These are the primary outputs of the engine.
▼/▲ b:  A fully confirmed signal that has passed all filters.
? b:  A tentative signal generated in Predictive Mode, indicating developing dynamics.
◈ b:  This diamond icon replaces the standard triangle when the signal is confirmed by a strong momentum divergence, highlighting it as a superior setup where dynamics are misaligned with price.
 Harmonic Wave:  The flowing, colored wave around the price.
 What It Represents:  The market's "flow dynamic" and volatility.
 How to Interpret It:  Expanding waves show increasing volatility. The color is tied to the "Quantum Color" in your theme, representing the underlying energy field of the market.
 Entropy Particles:  The small dots appearing above/below price.
 What They Represent:  A direct visualization of the "order dynamic."
 How to Interpret Them:   Their presence  signifies a low-entropy, ordered state ideal for trading.  Their color  indicates the direction of momentum (PSR velocity).  Their absence  means the market is too chaotic (high entropy).
 The Fibonacci Target Engine:  The dynamic R2R system appearing post-signal.
 Static Fib Levels:  Colored horizontal lines representing the market's "structural dynamic."
 The Green "Active Channel" Box:  Your  zone of consideration.  An area to manage a potential entry.
 Development Philosophy 
 Reversal Point Dynamics was engineered to answer a fundamental question: can we objectively measure the forces behind a market turn?  It is a synthesis of concepts from market microstructure, statistics, and information theory. The objective was never to create a "perfect" system, but to build a robust decision-support tool that provides a measurable, statistical edge by focusing on the principle of confluence.
 By demanding that multiple, independent market dynamics align simultaneously, RPD filters out the vast majority of market noise.  It is designed for the trader who thinks in terms of probability and risk management, not in terms of certainties. It is a tool to help you discount the obvious and bet on the unexpected alignment of market forces.
 "Markets are constantly in a state of uncertainty and flux and money is made by discounting the obvious and betting on the unexpected." 
—  George Soros 
Trade with insight. Trade with anticipation.
— Dskyz, for DAFE Trading Systems
Tetuan SniperThe TEMA and EMA Crossover Alert with SL, TP, and Order Signal strategy combines the power of Triple Exponential Moving Average (TEMA) and Exponential Moving Average (EMA) to generate high-quality trading signals. This strategy is designed to provide clear entry and exit points, manage risk through dynamic Stop Loss (SL) and Take Profit (TP) levels, and optimize trade sizes based on account balance and risk tolerance.
Key Features:
EMA and TEMA Crossover:
The strategy identifies potential buy and sell signals based on the crossover of EMA and TEMA. A buy signal is generated when TEMA crosses above EMA, and a sell signal is generated when TEMA crosses below EMA.
Dynamic Stop Loss (SL) and Take Profit (TP):
Stop Loss levels are dynamically set based on a user-defined number of pips below (for buy orders) or above (for sell orders) the lowest or highest point since the crossover.
Take Profit levels are dynamically adjusted using another TEMA, providing a flexible exit strategy that adapts to market conditions.
Lot Size Calculation:
The strategy calculates the optimal lot size based on the account balance, risk percentage per trade, and the number of maximum open orders. For JPY pairs, the lot size is adjusted by dividing by 100 to account for the different pip value.
The lot size is rounded to two decimal places for better readability and precision.
Visual Alerts and Labels:
Clear visual alerts and labels are provided for each buy and sell signal, including the recommended SL, TP, and lot size. The labels are placed in a way to avoid overlapping important chart elements.
Trend Visualization:
The area between the TEMA and EMA is colored to indicate the trend, with green for bullish trends and red for bearish trends, making it easy to visualize the market direction.
Inputs:
SL Points: Number of pips for the Stop Loss.
EMA Period: Period for the Exponential Moving Average.
TEMA Period: Period for the Triple Exponential Moving Average.
Account Balance: The total account balance for calculating the lot size.
Risk Percentage: The percentage of the account balance to risk per trade.
Take Profit TEMA Period: Period for the TEMA used to set Take Profit levels.
Lot per Pip Value: The value of 1 pip per lot.
Maximum Open Orders: The maximum number of open orders to split the balance among.
Example Usage
This strategy is suitable for traders who want to automate their trading signals and manage risk effectively. By combining TEMA and EMA crossovers with dynamic SL and TP levels and precise lot size calculation, traders can achieve a disciplined and methodical approach to trading.
PercentX Trend Follower [Trendoscope]"Trendoscope" was born from our trading journey, where we first delved into the world of trend-following methods. Over time, we discovered the captivating allure of pattern analysis and the exciting challenges it presented, drawing us into exploring new horizons. However, our dedication to trend-following methodologies remains steadfast and continues to be an integral part of our core philosophy.
Here we are, introducing another effective trend-following methodology, employing straightforward yet powerful techniques.
 🎲 Concepts 
Introducing the innovative  PercentX Oscillator , a representation of Bollinger PercentB and Keltner Percent K. This powerful tool offers users the flexibility to customize their PercentK oscillator, including options for the type of moving average and length.
 The Oscillator Range  is derived dynamically, utilizing two lengths - inner and outer. The inner length initiates the calculation of the oscillator's highest and lowest range, while the outer length is used for further calculations, involving either a moving average or the opposite side of the highest/lowest range, to obtain the oscillator ranges.
Next, the  Oscillator Boundaries  are derived by applying another round of high/low or moving average calculations on the oscillator range values.
 Breakouts  occur when the close price crosses above the upper boundary or below the lower boundary, signaling potential trading opportunities.
 🎲 How to trade a breakout? 
To reduce false signals, we employ a simple yet effective approach. Instead of executing market trades, we use stop orders on both sides at a certain distance from the current close price.
In case of an upper side breakout, a long stop order is placed at 1XATR above the close, and a short stop order is placed at 2XATR below the close. Conversely, for a lower side breakout, a short stop order is placed at 1XATR below the close, and a long stop order is placed at 2XATR above the ATR. As a trend following method, our first inclination is to trade on the side of breakout and not to find the reversals. Hence, higher multiplier is used for the direction opposite to the breakout.
The script provides users with the option to specify ATR multipliers for both sides.
Once a trade is initiated, the opposite side of the trade is converted into a stop-loss order. In the event of a breakout, the script will either place new long and short stop orders (if no existing trade is present) or update the stop-loss orders if a trade is currently running.
As a trend-following strategy, this script does not rely on specific targets or target levels. The objective is to run the trade as long as possible to generate profits. The trade is only stopped when the stop-loss is triggered, which is updated with every breakout to secure potential gains and minimize risks.
 🎲 Default trade parameters 
Script uses 10% equity per trade and up to 4 pyramid orders. Hence, the maximum invested amount at a time is 40% of the equity. Due to this, the comparison between buy and hold does not show a clear picture for the trade.
Feel free to explore and optimize the parameters further for your favorite symbols.
 🎲 Visual representation  
The blue line represents the PercentX Oscillator, orange and lime colored lines represent oscillator ranges. And red/green lines represent oscillator boundaries. Oscillator spikes upon breakout are highlighted with color fills.
Per Volume Price ImpactLiquidity, Information and Market Timing 
* Market Liquidity
The term liquidity can refer to many things in finance. In this article, we will limit the scope of discussion to the market’s ability to transact without incurring a significant increase in volatility.
As we know, liquidity and volatility have an inversed relationship — the more ample the liquidity, the lower the volatility (attributed to transaction cost, price movement and, so on). With this understanding, we can say large movements in the market are driven by low liquidity. This does not seem to make sense because the markets are huge, how can it possibly be illiquid? Now, this has to do with how the market operates and how exchanges occur (This topic concerns the area of market microstructure).
* Order Book & the Trading Process
So how does a transaction actually occur in the market? Let’s assume we open a position with a market order. In this case, you will get the price on your quote board if there are enough units of assets people are willing to sell at that price. If there are not enough units, you will buy from the second-best price and so on until your order is filled. Now in the second case, as the order is being filled, the change in price is recorded. Therefore, if someone wishes to move the market, theoretically, they just need to buy up or sell up but it is problematic to do so.
Here is why: 
while dry up the liquidity can make huge moves, it is inefficient to do so.
it takes a lot of money to do that
your position will be exposed, someone more resourceful than you may go against you and that is a huge risk
market manipulation charges
when you open a position, the entry price of the position is essentially a VWAP (volume-weighted average price). If you attempt to move the market and open a buy position at the same time, you will have a higher VWAP, eating into your own profit.
I think these reasons are sufficient in establishing why opening a position and drying up liquidity to profit is a dumb idea. But of course, the institutions are not stupid, the alternative is to enter your position first then move the market.
To measure liquidity one of the tools people use is the order book. It can offer an overview of the sentiment (by looking at the orders and changes in volume) and how people are positioned (if the broker offers such data). In my opinion, open interest is a much better tool than order as it records the transactions that have occurred, hence less prone to manipulations (google: “Navinder Singh Sarao”, the trader who used fake orders to manipulate algorithms to crash the market).
But to quantify the order book is so much work as well (there are ways, just difficult), what we can do is to make things simpler.
* Quantify Market Impact
We know price and volume reflect information, while the past technical information has no predictive power per semi-strong form of EMH, empirical studies have often tested this theory over a longer time horizon. In our case, precisely due to the mechanism of exchange and human behavior (The lack of incentive to move the market right away) we can, in the very short term (often intraday), foresee if the market is going to move or not. Back to the very definition of liquidity being the ability to transact without moving the market significantly, we can take this definition and quantify it with this formula:
Market Impact = (High — Low) / Volume
Why specifically “high — low”, because that’s the complete information in that moment and it is corresponding to the volume. A little crude but it is the simplest form.
A few things to take note of here:
We can only know the complete picture once the candle is complete. This is fine in most markets because it takes time to gather money and orders.
We often see high liquidity during certain time of the day, for example, when the market opens and so on. As a result, we need to take some scientific approaches to transform the data.
Now, this looks much better. To interpret this graph, the lower the value, the lower the market impact, the deeper the liquidity.
* Generate Tradable Insights
To generate trade ideas isn’t a difficult task, we all know the RSI, MOM, STOC, etc. all the indicators attempt to draw boundaries, and we can do the same but we need to be a little more advanced and critical.
step 1: we first need to normalize the data. To do that we will take the log of the values to make the skewed distribution normal. The result isn’t ideal if you zoom out but I think this is decent enough to work with. Here is 
This is still not a stationary time series, but it looks stable enough and it mean-reverts. So we turn to our lovely standard deviation bands for help.
Step 2: Because this is not a stationary process (visually, you can test it statistically if you wish), we cannot just take sample mean and SD and also because we want to show off our data skills, so we turn to move averages and regressions. I’m going to use moving regression here because I think it is better (mean can be distorted by large values by a larger margin and it lags)
I’m using the moving regression band on TradingView and 1.5 SD here for convenience, you can try to optimize the parameters with codes or other regression models if you wish. But I think it is more important to understand the rationale here.
This step is essentially trying to figure out the anomalies in liquidity so that we can see when there is deep liquidity. This is also why choosing the parameter is crucial because you are essentially approximating how much informed trading is taking place (This is a concept in market microstructure for brokerages to set their spreads but it is not a good tool in a liquid market). By setting the level at 1.5 we are assuming about 86% of the time the market is in what we consider a normal liquid state. (again it is arbitrary, but based on the 68–95–99.7 rule of normal distribution). The rest of the time will be either low or high liquidity, When liquidity is deep, it perhaps, signals institutional money is pouring into the market and big moves may follow.
* Conclusion
There you have it, how to enter the market with the big bucks. But do take note there are plenty of assumptions and a lot to improve on here.
StocksDeveloper_AutoTraderWebLibrary   "StocksDeveloper_AutoTraderWeb" 
AutoTrader Web trading API functions implementation for Trading View.
 preparePlaceOrderJson(account, symbol, group, variety)  Prepare a place order json
  Parameters:
     account : Pseudo or group account number
     symbol : AutoTrader Web's stock/derivative symbol
     group : Set it to true to use group account (Default: false)
     variety : Variety   (Default: REGULAR)
  Returns: A json message for the given order data
 preparePlaceOrderAlertUsingOrderJson(orderJsonArray)  Prepare a place order alert message using order json array
  Parameters:
     orderJsonArray : Order json can contain one or more orders
  Returns: A complete alert message to place orders
 preparePlaceOrderAlertMessage(account, symbol, group, variety, validity)  Prepare a place order alert json message
  Parameters:
     account : Pseudo or group account number
     symbol : AutoTrader Web's stock/derivative symbol
     group : Set it to true to use group account (Default: false)
     variety : Variety   (Default: REGULAR)
     validity : Validity   (Default: DAY)
  Returns: A complete alert message to place orders
Backtesting on Non-Standard Charts: Caution! - PineCoders FAQMuch confusion exists in the TradingView community about backtesting on non-standard charts. This script tries to shed some light on the subject in the hope that traders make better use of those chart types.
Non-standard charts are:
 Heikin Ashi (HA)
 Renko
 Kagi
 Point & Figure
 Range 
These chart types are called non-standard because they all transform market prices into synthetic views of price action. Some focus on price movement and disregard time. Others like HA use the same division of bars into fixed time intervals but calculate artificial open, high, low and close (OHLC) values.
Non-standard chart types can provide traders with alternative ways of interpreting price action, but they are not designed to test strategies or run automated traded systems where results depend on the ability to enter and exit trades at precise price levels at specific times, whether orders are issued manually or algorithmically. Ironically, the same characteristics that make non-standard chart types interesting from an analytical point of view also make them ill-suited to trade execution. Why? Because of the dislocation that a synthetic view of price action creates between its non-standard chart prices and real market prices at any given point in time. Switching from a non-standard chart price point into the market always entails a translation of time/price dimensions that results in uncertainty—and uncertainty concerning the level or the time at which orders are executed is detrimental to all strategies.
The delta between the chart’s price when an order is issued (which is assumed to be the expected price) and the price at which that order is filled is called  slippage . When working from normal chart types, slippage can be caused by one or more of the following conditions:
• Time delay between order submission and execution. During this delay the market may move normally or be subject to large orders from other traders that will cause large moves of the bid/ask levels.
• Lack of bids for a market sell or lack of asks for a market buy at the current price level.
• Spread taken by middlemen in the order execution process.
• Any other event that changes the expected fill price.
When a market order is submitted, matching engines attempt to fill at the best possible price at the exchange. TradingView strategies usually fill market orders at the opening price of the next candle. A non-standard chart type can produce misleading results because the open of the next candle may or may not correspond to the real market price at that time. This creates artificial and often beneficial slippage that would not exist on standard charts.
Consider an HA chart. The open for each candle is the average of the previous HA bar’s open and close prices. The open of the HA candle is a synthetic value, but the real market open at the time the new HA candle begins on the chart is the unrelated, regular open at the chart interval. The HA open will often be lower on long entries and higher on short entries, resulting in unrealistically advantageous fills.
Another example is a Renko chart. A Renko chart is a type of chart that only measures price movement. The purpose of a Renko chart is to cluster price action into regular intervals, which consequently removes the time element. Because Trading View does not provide tick data as a price source, it relies on chart interval close values to construct Renko bricks. As a consequence, a new brick is constructed only when the interval close penetrates one or more brick thresholds. When a new brick starts on the chart, it is because the previous interval’s close was above or below the next brick threshold. The open price of the next brick will likely not represent the current price at the time this new brick begins, so correctly simulating an order is impossible.
Some traders have argued with us that backtesting and trading off HA charts and other non-standard charts is useful, and so we have written this script to show traders what happens when order fills from backtesting on non-standard charts are compared to real-world fills at market prices.
Let’s review how TV backtesting works. TV backtesting uses a broker emulator to execute orders. When an order is executed by the broker emulator on historical bars, the price used for the fill is either the close of the order’s submission bar or, more often, the open of the next. The broker emulator only has access to the chart’s prices, and so it uses those prices to fill orders. When backtesting is run on a non-standard chart type, orders are filled at non-standard prices, and so backtesting results are non-standard—i.e., as unrealistic as the prices appearing on non-standard charts. This is not a bug; where else is the broker emulator going to fetch prices than from the chart?
This script is a strategy that you can run on either standard or non-standard chart types. It is meant to help traders understand the differences between backtests run on both types of charts. For every backtest, a label at the end of the chart shows two global net profit results for the strategy:
• The net profits (in currency) calculated by TV backtesting with orders filled at the chart’s prices.
• The net profits (in currency) calculated from the same orders, but filled at market prices (fetched through  security()  calls from the underlying real market prices) instead of the chart’s prices.
If you run the script on a non-standard chart, the top result in the label will be the result you would normally get from the TV backtesting results window. The bottom result will show you a more realistic result because it is calculated from real market fills.
If you run the script on a normal chart type (bars, candles, hollow candles, line, area or baseline) you will see the same result for both net profit numbers since both are run on the same real market prices. You will sometimes see slight discrepancies due to occasional differences between chart prices and the corresponding information fetched through  security()  calls.
 Features 
• Results shown in the Data Window (third icon from the top right of your chart) are:
— Cumulative results
— For each order execution bar on the chart, the chart and market previous and current fills, and the trade results calculated from both chart and market fills.
• You can choose between 2 different strategies, both elementary.
• You can use HA prices for the calculations determining entry/exit conditions. You can use this to see how a strategy calculated from HA values can run on a normal chart. You will notice that such strategies will not produce the same results as the real market results generated from HA charts. This is due to the different environment backtesting is running on where for example, position sizes for entries on the same bar will be calculated differently because HA and standard chart close prices differ.
• You can choose repainting/non-repainting signals.
• You can show MAs, entry/exit markers and market fill levels.
• You can show candles built from the underlying market prices.
• You can color the background for occurrences where an order is filled at a different real market price than the chart’s price.
 Notes 
• On some non-standard chart types you will not obtain any results. This is sometimes due to how certain types of non-standard types work, and sometimes because the script will not emit orders if no underlying market information is detected.
• The script illustrates how those who want to use HA values to calculate conditions can do so from a standard chart. They will then be getting orders emitted on HA conditions but filled at more realistic prices because their strategy can run on a standard chart.
• On some non-standard chart types you will see market results surpass chart results. While this may seem interesting, our way of looking at it is that it points to how unreliable non-standard chart backtesting is, and why it should be avoided.
• In order not to extend an already long description, we do not discuss the particulars of executing orders on the realtime bar when using non-standard charts. Unless you understand the minute details of what’s going on in the realtime bar on a particular non-standard chart type, we recommend staying away from this.
• Some traders ask us: Why does TradingView allow backtesting on non-standard chart types if it produces unrealistic results? That’s somewhat like asking a hammer manufacturer why it makes hammers if hammers can hurt you. We believe it’s a trader’s responsibility to understand the tools he is using.
 Takeaways 
• Non-standard charts are not bad per se, but they can be badly used.
• TV backtesting on non-standard charts is not broken and doesn’t require fixing. Traders asking for a fix are in dire need of learning more about trading. We recommend they stop trading until they understand why.
• Stay away from—even better, report—any vendor presenting you with strategies running on non-standard charts and implying they are showing reliable results.
• If you don’t understand everything we discussed, don’t use non-standard charts at all.
• Study carefully how non-standard charts are built and the inevitable compromises used in calculating them so you can understand their limitations.
Thanks to @allanster and @mortdiggiddy for their help in editing this description.
 Look first. Then leap.  
Harmonic Patterns Library [TradingFinder]🔵 Introduction 
Harmonic patterns blend geometric shapes with Fibonacci numbers, making these numbers fundamental to understanding the patterns.
One person who has done a lot of research on harmonic patterns is Scott Carney.Scott Carney's research on harmonic patterns in technical analysis focuses on precise price structures based on Fibonacci ratios to identify market reversals. 
Key patterns include the Gartley, Bat, Butterfly, and Crab, each with specific alignment criteria. These patterns help traders anticipate potential market turning points and make informed trading decisions, enhancing the predictability of technical analysis.
🟣 Understanding 5-Point Harmonic Patterns 
In the current library version, you can easily draw and customize most XABCD patterns. These patterns often form M or W shapes, or a combination of both. By calculating the Fibonacci ratios between key points, you can estimate potential price movements. 
All five-point patterns share a similar structure, differing only in line lengths and Fibonacci ratios. Learning one pattern simplifies understanding others.
  
🟣 Exploring the Gartley Pattern 
The Gartley pattern appears in both bullish (M shape) and bearish (W shape) forms. In the bullish Gartley, point X is below point D, and point A surpasses point C. Point D marks the start of a strong upward trend, making it an optimal point to place a buy order. 
The bearish Gartley mirrors the bullish pattern with inverted Fibonacci ratios. In this scenario, point D indicates the start of a significant price drop. Traders can place sell orders at this point and buy at lower prices for profit in two-way markets.
🟣 Analyzing the Butterfly Pattern 
The Butterfly pattern also manifests in bullish (M shape) and bearish (W shape) forms. It resembles the Gartley pattern but with point D lower than point X in the bullish version. 
The Butterfly pattern involves deeper price corrections than the Gartley, leading to more significant price fluctuations. Point D in the bullish Butterfly indicates the beginning of a sharp price rise, making it an entry point for buy orders. 
The bearish Butterfly has inverted Fibonacci ratios, with point D marking the start of a sharp price decline, ideal for sell orders followed by buying at lower prices in two-way markets.
🟣 Insights into the Bat Pattern 
The Bat pattern, appearing in bullish (M shape) and bearish (W shape) forms, is one of the most precise harmonic patterns. It closely resembles the Butterfly and Gartley patterns, differing mainly in Fibonacci levels. 
The bearish Bat pattern shares the Fibonacci ratios with the bullish Bat, with an inverted structure. Point D in the bearish Bat marks the start of a significant price drop, suitable for sell orders followed by buying at lower prices for profit.
🟣 The Crab Pattern Explained 
The Crab pattern, found in both bullish (M shape) and bearish (W shape) forms, is highly favored by analysts. Discovered in 2000, the Crab pattern features a larger final wave correction compared to other harmonic patterns. 
The bearish Crab shares Fibonacci ratios with the bullish version but in an inverted form. Point D in the bearish Crab signifies the start of a sharp price decline, making it an ideal point for sell orders followed by buying at lower prices for profitable trades.
🟣 Understanding the Shark Pattern 
The Shark pattern appears in bullish (M shape) and bearish (W shape) forms. It differs from previous patterns as point C in the bullish Shark surpasses point A, with unique level measurements. 
The bearish Shark pattern mirrors the Fibonacci ratios of the bullish Shark but is inverted. Point D in the bearish Shark indicates the start of a sharp price drop, ideal for placing sell orders and buying at lower prices to capitalize on the pattern.
🟣 The Cypher Pattern Overview 
The Cypher pattern is another that appears in both bullish (M shape) and bearish (W shape) forms. It resembles the Shark pattern, with point C in the bullish Cypher extending beyond point A, and point D forming within the XA line. 
The bearish Cypher shares the Fibonacci ratios with the bullish Cypher but in an inverted structure. Point D in the bearish Cypher marks the start of a significant price drop, perfect for sell orders followed by buying at lower prices.
🟣 Introducing the Nen-Star Pattern 
The Nen-Star pattern appears in both bullish (M shape) and bearish (W shape) forms. In the bullish Nen-Star, point C extends beyond point A, and point D, the final point, forms outside the XA line, making CD the longest wave. 
The bearish Nen-Star has inverted Fibonacci ratios, with point D indicating the start of a significant price drop. Traders can place sell orders at point D and buy at lower prices to profit from this pattern in two-way markets.
The 5-point harmonic patterns, commonly referred to as XABCD patterns, are specific geometric price structures identified in financial markets. These patterns are used by traders to predict potential price movements based on historical price data and Fibonacci retracement levels. 
 Here are the main 5-point harmonic patterns :
 
 Gartley Pattern
 Anti-Gartley Pattern
 Bat Pattern
 Anti-Bat Pattern
 Alternate Bat Pattern
 Butterfly Pattern
 Anti-Butterfly Pattern
 Crab Pattern	
 Anti-Crab Pattern
 Deep Crab Pattern
 Shark Pattern
 Anti- Shark Pattern
 Anti Alternate Shark Pattern
 Cypher Pattern
 Anti-Cypher Pattern
 
 
🔵 How to Use 
To add "Order Block Refiner Library", you must first add the following code to your script.
 import TFlab/Harmonic_Chart_Pattern_Library_TradingFinder/1 as HP 
🟣 Parameters 
 XABCD(Name, Type, Show, Color, LineWidth, LabelSize, ShVF, FLPC, FLPCPeriod, Pivot, ABXAmin, ABXAmax, BCABmin, BCABmax, CDBCmin, CDBCmax, CDXAmin, CDXAmax) =>
Parameters: 
Name (string) 
Type (string) 
Show (bool) 
Color (color) 
LineWidth (int) 
LabelSize (string) 
ShVF (bool) 
FLPC (bool) 
FLPCPeriod (int) 
Pivot (int) 
ABXAmin (float) 
ABXAmax (float) 
BCABmin (float) 
BCABmax (float) 
CDBCmin (float) 
CDBCmax (float) 
CDXAmin (float) 
CDXAmax (float)
 
🟣 Genaral Parameters 
 Name : The name of the pattern.
 Type:  Enter "Bullish" to draw a Bullish pattern and "Bearish" to draw an Bearish pattern.
 Show : Enter "true" to display the template and "false" to not display the template.
 Color : Enter the desired color to draw the pattern in this parameter.
 LineWidth : You can enter the number 1 or numbers higher than one to adjust the thickness of the drawing lines. This number must be an integer and increases with increasing thickness.
 LabelSize : You can adjust the size of the labels by using the "size.auto", "size.tiny", "size.smal", "size.normal", "size.large" or "size.huge" entries.
🟣 Logical Parameters 
 ShVF : If this parameter is on "true" mode, only patterns will be displayed that they have exact format and no noise can be seen in them. If "false" is, the patterns displayed that maybe are noisy and do not exactly correspond to the original pattern.
  
 FLPC : if Turned on, you can see this ability of patterns when their last pivot is formed. If this feature is off, it will see the patterns as soon as they are formed. The advantage of this option being clear is less formation of fielded patterns, and it is accompanied by the lateest pattern seeing and a sharp reduction in reward to risk.
 FLPCPeriod : Using this parameter you can determine that the last pivot is based on Pivot period.
  
 Pivot : You need to determine the period of the zigzag indicator. This factor is the most important parameter in pattern recognition.
 ABXAmin : Minimum retracement of "AB" line compared to "XA" line.
 ABXAmax : Maximum retracement of "AB" line compared to "XA" line.
 BCABmin : Minimum retracement of "BC" line compared to "AB" line.
 BCABmax : Maximum retracement of "BC" line compared to "AB" line.
 CDBCmin : Minimum retracement of "CD" line compared to "BC" line.
 CDBCmax : Maximum retracement of "CD" line compared to "BC" line.
 CDXAmin : Minimum retracement of "CD" line compared to "XA" line.
 CDXAmax : Maximum retracement of "CD" line compared to "XA" line.
  
  
🟣 Function Outputs 
This library has two outputs. The first output is related to the alert of the formation of a new pattern. And the second output is related to the formation of the candlestick pattern and you can draw it using the "plotshape" tool.
 Candle Confirmation Logic :
  
 Example :
 import TFlab/Harmonic_Chart_Pattern_Library_TradingFinder/1 as HP
PP = input.int(3, 'ZigZag Pivot Period')
ShowBull = input.bool(true, 'Show Bullish Pattern')
ShowBear = input.bool(true, 'Show Bearish Pattern')
ColorBull = input.color(#0609bb, 'Color Bullish Pattern')
ColorBear = input.color(#0609bb, 'Color Bearish Pattern')
LineWidth = input.int(1 , 'Width Line')
LabelSize = input.string(size.small , 'Label size' , options =  )
ShVF = input.bool(false , 'Show Valid Format')
FLPC = input.bool(false , 'Show Formation Last Pivot Confirm')
FLPCPeriod =input.int(2, 'Period of Formation Last Pivot')
//Call function
  = HP.XABCD('Bullish Bat', 'Bullish', ShowBull, ColorBull , LineWidth, LabelSize ,ShVF,  FLPC, FLPCPeriod, PP, 0.382, 0.50, 0.382, 0.886, 1.618, 2.618, 0.85, 0.9)
  = HP.XABCD('Bearish Bat', 'Bearish', ShowBear, ColorBear , LineWidth, LabelSize ,ShVF,  FLPC, FLPCPeriod, PP, 0.382, 0.50, 0.382, 0.886, 1.618, 2.618, 0.85, 0.9)
//Alert
if BearAlert
    alert('Bearish Harmonic')
if BullAlert
    alert('Bulish Harmonic')
//CandleStick Confirm
plotshape(BearCandleConfirm, style = shape.arrowdown, color = color.red)
plotshape(BullCandleConfirm, style = shape.arrowup, color = color.green, location = location.belowbar )
 
3Commas BotBjorgum 3Commas Bot 
 A strategy in a box to get you started today 
With 3rd party API providers growing in popularity, many are turning to automating their strategies on their favorite assets. With so many options and layers of customization possible, TradingView offers a place no better for young or even experienced coders to build a platform from to meet these needs. 3Commas has offered easy access with straight forward TradingView compatibility. Before long many have their brokers hooked up and are ready to send their alerts (or perhaps they have been trying with mixed success for some time now) only they realize there might just be a little bit more to building a strategy that they are comfortable letting out of their sight to trade their money while they eat, sleep, etc. Many may have ideas for entry criteria they are excited to try,  but further questions arise... "What about risk mitigation?" "How can I set stop or limit orders?" "Is there not some basic shell of a strategy that has laid some of this out for me to get me going?"
Well now there is just that. This strategy is meant for those that have begun to delve into the world of algorithmic trading providing a template that offers risk defined positions complete with stops, limit orders, and even trailing stops should one so choose to employ any of these criteria. It provides a framework that is easily manipulated (with some basic working knowledge of pine coding) to encompass ones own ideas and entry criteria, while also providing an already functioning strategy. 
  
The default settings have a basic 1:1 risk to reward ratio, which sets a limit and a stop equal distance from the entry. The entry is a simple MA cross (up for long, down for short). There a variety of MA's to choose from and the user can define the lengths of the averages. The ratio can be adjusted from the menu along with a volatility based adder (ATR) that helps to distance a stop from support or resistance. These values are calculated off the swing low/high of the user defined lookback period. Risk is calculated from position entry to stop, and projected upwards to the limit as a function of the desired risk to reward ratio. Of note: the default settings include 0.05% commissions. Competitive commissions of the leading cryptocurrency exchanges are .1% round trip (one buy and one sell) for market orders. There is also some slippage to allow time for alerts to be sent and orders to fill giving the back test results a more accurate representation of real time conditions. Its recommended to research the going rates for your exchange and set them to default for the strategy you use or build. 
 To get started a user would: 
1) Make a copy of the code and paste in their bot keys in the area provided under the "3Comma Keys" section
         - eg. Long bot "start deal" copied from 3commas in to define "Long" etc. (code is commented)
2) Place alert on desired asset with desired settings ensuring to select "Order fills and alert() function calls"
3) Paste webhook into the webhook box and select webhook URL alerts (3rd party provided webhook)
3) Delete contents of alert message box and replace with {{strategy.order.alert_message}} and nothing else
       - the codes will be sent to the webhook appropriately as the strategy enters and exits positions. Only 1 alert is needed  
 settings used for the display image:  
1hr chart on BTCUSD 
-ATR stop
-Risk adjustment 1.2
-ATR multiplier 1.3
-RnR 0.6
-MAs HEMA/SMA
-MA Length 50/100
-Order size percent of equity 
-Trail trigger 60% of target
Experiment with your own settings on your crypto of choice or implement your own code!
  
 Implementing your trailing stop (optional) 
Among the options for possible settings is a trailing stop. This stop will ratchet higher once triggered as a function of the Average True Range (ATR). There is a variable level to choose where the user would like to begin trailing the stop during the trade. The level can be assigned with a decimal between 0 and 1 (eg. 0.5 = 50% of the distance between entry and the target which must be exceeded before the trail triggers to begin). This can allow for some dips to occur during the trade possibly keeping you in the trade for longer, while potentially reducing risk of drawdown over time. The default for this setting is 0 meaning unless adjusted, the trail will trigger on entry if the trailing stop exit method is selected.  An example can be seen below: 
  
Again, optional as well is the choice to implement a limit order. If one were to select a trailing stop they could choose not to set a limit, which could allow a trail to run further until hit. Drawdowns of this strategy would be foregoing locking gains at highs on target on other trades. This is a trade-off the user can decide on and test. An example of this working in favor can be observed below:
  
 Conclusion 
Although a simple strategy is implemented here, the benefits of this script allow a user a starting platform to build their strategies from with built in risk mitigation. This allows the user to sidestep some of the potential difficulties' that can arise while learning Pine and taking on the endeavor of automating their trading strategies. It is meant as an aid, a structure, and an educational piece that can be seen as a "pick-up-and-go" strategy with easy 3Commas compatibility. Additionally, this can help users become more comfortable with strategy alert messages and sending strings in the form of alerts from Pine. As well, FAQs are often littered with questions regarding "strategy.exit" calls, how to implement stops. how to properly set a trailing stop based on ATR, and more. The time this can save an individual to get started is likely of the best "take-aways" here. 
Happy trading 






















